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;
        };
    });
    $(document).on('keyup', '#receivers-filter', function () {
        var filter = $(this).val();
        console.log(filter);
        if (filter.length > 0) {
            $('#addresses-list > div').hide();
            $('#addresses-list > div:contains(Wszystkie)').show();
            $('#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, displayName) {
    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-message"><i class="fa fa-times"></i></span>');
        var span_name = $('<span class="receiver-name">' + displayName + '</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 addReceiverOnEditEnter(name, email, gid, displayName) {
    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-message"><i class="fa fa-times"></i></span>');
    var span_name = $('<span class="receiver-name">' + displayName + '</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) {
            if (ui.item.bGid !== 'ALL' && ui.item.bGid !== 'AllAdrress') {
                addReceiver(ui.item.bNazwa, ui.item.bEmail, ui.item.bGid, ui.item.bNazwaWyswietlana);
            }
        },
        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 () {
    _receiversListModalSubmit();
});
var receiversListModal,
    receiversListBody,
    receiversListLoader;

function getReceiversList(zmetody) {
    var url = local_url + 'ajax_daj_adresy/' + zmetody;
    receiversListModal.modal('show');
    $.ajax({
        url: url,
        type: 'POST',
        data: {},
        dataType: 'HTML',
        async: true,
        beforeSend: function () {
            showLoader(receiversListLoader);
        },
        success: function (response) {
            if (trim(response) == 'login') {
                window.location = local_url + 'login';
            } else {
                if (response != 'empty') {
                    receiversListBody.html(response);
                    receiversListLoader = receiversListBody.find('#receivers-list-loader');

                    $(document).find('#AllAdrress').on('ifToggled', function () {
                        var is_checked = $(this).is(':checked');
                        $(document).find('#addresses-list .checkboxes-right:not(.check-all):visible').each(function () {
                            if (is_checked) {
                                $(this).find('input[type="checkbox"]').iCheck('check');
                            } else {
                                $(this).find('input[type="checkbox"]').iCheck('uncheck');
                            }
                        });
                    });

                    checkboxesInit('#receivers-list-modal');
                    if (receivers.length > 0) {
                        $.each(receivers, function (index, value) {
                            receiversListBody.find('#' + value).iCheck('check');
                        });
                    }
                }
                receiversFiltering();
                hideLoader(receiversListLoader);
            }
        },
        error: function (err) {
            if (err.status == 403) {
                window.location = local_url + 'login';
            }
        }
    });
}

function _receiversListModalSubmit() {
    var checkedReceivers = receiversListModal.find('input[type=checkbox]:checked');
    $.each(checkedReceivers, function (index) {
        var $this = $(this);
        if ($this.attr('id') !== 'ALL' && $this.attr('id') !== 'AllAdrress') {
            addReceiver($this.data('name'), $this.data('email'), $this.attr('id'), $this.data('display-name'));
        }
    });
    var uncheckedReceivers = receiversListModal.find('input[type=checkbox]:not(:checked)');
    $.each(uncheckedReceivers, function (index) {
        var $this = $(this),
            gid = $this.attr('id');
        var $input = $('.receiver-gid-input[value="' + gid + '"]');
        if ($input.length > 0) {
            deleteReceiverMessage($input, gid);
        }
    });
    receiversListModal.modal('hide');
}

function deleteReceiverMessage(msg_receiver, gid) {
    var index = receivers.indexOf(gid);
    if (index > -1) {
        receivers.splice(index, 1);
    }
    getRidOf($(msg_receiver), 'parent', 'slideUp');
    setTimeout(function () {
        $(msg_receiver).parents('.msg-receiver').remove();
    });
}

$(document).on('click', '.show-sent-receivers', function (e) {
    e.preventDefault();
    var sent_receivers = $(this).data('receivers').split(','),
        $sent_receivers_modal = $('#sent-receivers-modal'),
        $sent_receivers_modal_body = $sent_receivers_modal.find('.modal-body');
    $sent_receivers_modal_body.html('');
    $.each(sent_receivers, function (index, value) {
        $sent_receivers_modal_body.append('<p>' + value + '</p>');
    });
    $sent_receivers_modal.modal('show');
});

/** OBSŁUGA WIDOKU LISTY WIADOMOŚCI **/

var message_active = "Odbiorcza",
    message_url = 'daj_wiadomosci',
    message_prior = 'x',
    localActiveMessageListKey = "last_message_listy_type",
    localShowHiddenMessages = 'show_hidden_messages',
    messages_hidden = 'false',
    messagesRequest,
    messagesRequestRunning = false;

if (localStorage.getItem(localActiveMessageListKey) != undefined) message_active = localStorage.getItem(localActiveMessageListKey);

function initialMessagesList() {
    if (typeof (Storage) !== "undefined" && localStorage.getItem(localActiveMessageListKey) !== "undefined") {
        $('#message_list_filters a[data-message]').attr('data-active', 0);
        $('#message_list_filters').find('[data-type="' + localStorage.getItem(localActiveMessageListKey) + '"]').attr('data-active', 1);
        if (localStorage.getItem(localShowHiddenMessages) == null) {
            localStorage.setItem(localShowHiddenMessages, messages_hidden);
        } else {
            messages_hidden = localStorage.getItem(localShowHiddenMessages);
        }
        // $('#message_list_filters').find('[data-type="' + localStorage.getItem(localActiveMessageListKey) + '"]').trigger('click');
        if (messages_hidden == 'true') {
            $("#MessageIsHidden").iCheck('toggle');
        }
    }
    if ($('[data-active="1"]').length == 1) {
        var initialTable = $('[data-active="1"]');
        message_url = initialTable.data('message');
        message_active = initialTable.data('type');
    }
}

function messagesList() {
    if ($('#MessageIsHidden').is(':checked')) {
        messages_hidden = 'true';
    } else {
        messages_hidden = 'false';
    }
    localStorage.setItem(localShowHiddenMessages, messages_hidden);
    if (messagesRequestRunning) {
        messagesRequest.abort();
        messagesRequestRunning = false;
    }
    messagesRequest = $.ajax({
        type: "GET",
        url: local_url + "ajax_daj_wiadomosci/?no_cache=" + ((new Date()).getTime()),
        data: {
            hidden: messages_hidden,
            type: message_active,
            prior: message_prior
        },
        dataType: "html",
        beforeSend: function () {
            showLoader($('#table-loading'));
            messagesRequestRunning = true;
        }
    }).done(function (response) {
        messagesRequestRunning = false;
        if (typeof (Storage) !== "undefined") {
            localStorage.setItem(localActiveMessageListKey, message_active);
        }
        $('[data-container="table"]').html(response);
        hideLoader($('#table-loading'));
        setTimeout(function () {
            runDataTable(message_url);
        });
    });
}

function hiddenMessagesToggle() {
    var messagesHiddenCheckbox = $("#MessageIsHidden");
    $('.hidden-messages-toggle').click(function () {
        messagesHiddenCheckbox.iCheck('toggle');
    });
    messagesHiddenCheckbox.on('ifToggled', function () {
        if (event.target.id === 'MessageIsHidden') {
            if (messagesHiddenCheckbox.is(':checked')) {
                messagesHiddenCheckbox.prop('checked', false);
            } else {
                messagesHiddenCheckbox.prop('checked', true);
            }
        }
        messagesList();
    });
}

$(document).ready(function () {
    receiversListInit();
    receiversIndex = getReceiversIndex();
    findReceivers();
    // deleteReceivers();
    // openMessage();

    if (typeof initMsg !== 'undefined' && initMsg == true) {
        initialMessagesList();
        messagesList();
    }

    hiddenMessagesToggle();
    // receiversList();
});
