var receiversIndex = 0;
var receiversContainer;
var receivers = [];

function receiversFiltering() {
    $.expr[":"].contains = $.expr.createPseudo(function (arg) {
        return function (elem) {
            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
    $('#receivers-filter').keyup(function () {
        var filter = $(this).val();
        console.log(filter);
        if (filter.length > 0) {
            $('#addresses-list > div').hide();
            $('#addresses-list > div:contains(' + filter + ')').show();
        } else {
            $('#addresses-list > div').show();
        }
    });
}

function receiversListInit() {
    receiversContainer = $('.msg-receivers-container');
    receiversIndex = getReceiversIndex();
    $.each($(receiversContainer).children('.msg-receiver'), function (index, value) {
        receivers.push($(this).find('input.receiver-gid-input').val());
    })
}

function getReceiversIndex() {
    return $(receiversContainer).children('.msg-receiver').length;
}
function addReceiver(name, email, gid) {
    if ($.inArray(gid, receivers) == -1) {
        var inputName = "data[pWiadomosc][b:Odbiorcy][" + receiversIndex + "][b:Adres]";
        var inputNameName = inputName + "[b:Nazwa]";
        var inputNameEmail = inputName + "[b:Email]";
        var inputNameGid = inputName + "[b:Gid]";
        var msg_receiver = $('<div class="msg-receiver"></div>');
        var span_delete = $('<span class="remove-button delete-receiver"><i class="fa fa-times"></i></span>');
        var span_name = $('<span class="receiver-name">' + name + '</span>');
        var input_name = $('<input type="hidden" class="receiver-name-input" name="' + inputNameName + '" value="' + name + '"/>');
        var input_email = $('<input type="hidden" class="receiver-email-input" name="' + inputNameEmail + '" value="' + email + '"/>');
        var input_gid = $('<input type="hidden" class="receiver-gid-input" name="' + inputNameGid + '" value="' + gid + '"/>');
        msg_receiver.append(span_delete).append(span_name).append(input_name).append(input_email).append(input_gid);
        $(receiversContainer).append(msg_receiver);
        receivers.push(gid);
        receiversIndex++;
    }
}
function findReceivers() {
    var input = $('#receiver-search');
    var loader = $(input).data('loader');
    var trigger = $('#receiver-search-trigger');
    var options = {
        source: 'daj_adresy_ac',
        appendTo: '#receiver-search-holder',
        disabled: false,
        select: function (event, ui) {
            addReceiver(ui.item.bNazwa, ui.item.bEmail, ui.item.bGid);
        },
        close: function () {
            // $(input).autocomplete('disable', true);
            $(input).val('');
        },
        search: function () {
            // showLoader(loader);
        },
        response: function () {
            // hideLoader(loader);
        },
        open: function () {
            // hideLoader(loader);
        }
    };
    $(input).autocomplete(options);

    // $(trigger).click(function (e) {
    //     e.preventDefault();
    //     var value = $(input).val();
    //     $(input).autocomplete('enable');
    //     $(input).autocomplete('search', value);
    // });
}
// $(document).on('click', '#receivers-list-submit', function () {
$('#receivers-list-submit').not('[data-module="appliactions"]').unbind('click').bind('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    _receiversListModalSubmit();
});
var receiversListModal,
    receiversListBody,
    receiversListLoader,
	receiversListType;
function getReceiversList(zmetody) {
    var url = local_url + 'ajax_daj_adresy/' + zmetody;
    receiversListModal.modal('show');
    receiversListType = zmetody;
    $.ajax({
        url: url,
        type: 'POST',
        data: {},
        dataType: 'HTML',
        async: true,
        beforeSend: function () {
            showLoader(receiversListLoader);
        },
        success: function (response) {
            if (response != 'empty') {
                receiversListBody.html(response);
                receiversListLoader = receiversListBody.find('#receivers-list-loader');
                checkboxesInit('#receivers-list-modal');
                if (receivers.length > 0) {
                    $.each(receivers, function (index, value) {
                        receiversListBody.find('#' + value).iCheck('check');
                    });
                }
            }
            receiversFiltering();
            hideLoader(receiversListLoader);
        },
        error: function (response) {
            console.log(response);
        }
    });
}
function _receiversListModalSubmit() {
    // var checkedReceivers = receiversListModal.find('input[type=checkbox]:checked');
    var checkedReceivers = [];
    receiversListModal.find('input[type="checkbox"]').each(function () {
        if ($(this).parent('[class*="icheckbox"]').hasClass("checked")) {
            checkedReceivers.push($(this));
        }
    })

    if(checkedReceivers.length != 1) {
        if (is_single_message) {
            alert('Wymagana liczba odbiorców: 1');
        }
        return;
    } else {
        $.each(checkedReceivers, function (index) {
            var $this = $(this);
            if (receiversListType) {
				$($('#receivers-list-trigger[data-zmetody="' + receiversListType + '"]').data('holder-gid')).val($this.attr('id'));
				$($('#receivers-list-trigger[data-zmetody="' + receiversListType + '"]').data('holder-name')).val($this.data('display-name'));
			} else {
				$($('#receivers-list-trigger').data('holder-gid')).val($this.attr('id'));
				$($('#receivers-list-trigger').data('holder-name')).val($this.data('display-name'));
			}

        });
        receiversListModal.find('input[type=checkbox]').each(function () {
           $(this).attr('checked', false);
        });
        receiversListModal.modal('hide');
    }
}

function receiversList() {
    $('#receivers-list-trigger').click(function (e) {
        e.preventDefault();
        receiversListModal = $('#receivers-list-modal');
        receiversListBody = receiversListModal.find('#receivers-list-body');
        receiversListLoader = receiversListBody.find('#receivers-list-loader');
        var zmetody = $(this).data('zmetody');
        getReceiversList(zmetody);
    });
}

function deleteReceiver(msg_receiver, gid) {
    var index = receivers.indexOf(gid);
    if (index > -1) {
        receivers.splice(index, 1);
    }
    getRidOf($(msg_receiver), 'parent', 'slideUp');
}
function deleteReceivers() {
    $(document).on('click', '.delete-receiver', function (e) {
        e.preventDefault();
        if (confirm('Usunąć odbiorcę?')) {
            deleteReceiver($(this), $(this).siblings('.receiver-gid-input').val());
        }
    });
}

$(document).ready(function () {
    receiversListInit();
    receiversIndex = getReceiversIndex();
    findReceivers();
    deleteReceivers();
    receiversList();
});
