function workersFiltering() {
    $.expr[":"].contains = $.expr.createPseudo(function (arg) {
        return function (elem) {
            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
    $('#workers-filter').keyup(function () {
        var filter = $(this).val();
        console.log(filter);
        if (filter.length > 0) {
            $('#workers-list > div').hide();
            $('#workers-list > div:contains(Wszystkie)').show();
            $('#workers-list > div:contains(' + filter + ')').show();
        } else {
            $('#workers-list > div').show();
        }
    });
}
function codesFiltering() {
    $.expr[":"].contains = $.expr.createPseudo(function (arg) {
        return function (elem) {
            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
    $('#codes-filter').keyup(function () {
        var filter = $(this).val();
        console.log(filter);
        if (filter.length > 0) {
            $('#codes-list > div').hide();
            $('#codes-list > div:contains(Wszystkie)').show();
            $('#codes-list > div:contains(' + filter + ')').show();
        } else {
            $('#codes-list > div').show();
        }
    });
}
function sortablePaths() {
    $('.path-rows').sortable({
        axis: 'y',
        helper: "original",
        forcePlaceholderSize: true,
        stop: function (event, ui) {
            reorderPaths();
        }
    });
}

function deletePath(gid, row) {
    var index = addresses.indexOf(gid);
    if (index > -1) {
        addresses.splice(index, 1);
    }
    $(row).remove();
    reorderPaths();
}
var addresses = [];
var addressesIndex = 0;
var pathGid = "";
function findAddress() {
    addressesIndex = $('.path-row').length;
    pathGid = $('#gid-sciezki').val();
    $('.path-row').each(function () {
        var addressGid = $(this).find('.address-gid').val();
        addresses.push(addressGid);
    });
    var input = $('#address-search');
    var trigger = $('#address-search-trigger');
    var loader = $(input).data('loader');
    var options = {
        source: '/daj_adresy_ac',
        appendTo: '#address-search-holder',
        disabled: false,
        select: function (event, ui) {
            addAddress(ui.item.bNazwa, ui.item.bEmail, ui.item.bGid, ui.item.bNazwaWyswietlana, ui.item.bImie, ui.item.bNazwisko);
        },
        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);
    // });
}
function addAddress(name, email, gid, displayName, imie, nazwisko) {
    if ($.inArray(gid, addresses) == -1) {
        var row = "data[pSciezkaAkceptacji][dat:Sciezka][dat:ElementSciezkiAkceptacji][" + addressesIndex + "]";
        var rowIndex = row + "[dat:Indeks]";
        var rowParentGid = row + "[dat:GidRodzica]";
        var rowAddressEmail = row + "[dat:Akceptujacy][dat1:Email]";
        var rowAddressGid = row + "[dat:Akceptujacy][dat1:Gid]";
        var rowAddressName = row + "[dat:Akceptujacy][dat1:Nazwa]";
        var rowMustAccept = row + "[dat:CzyMusiZaakceptowac]";
        var rowAcceptAll = row + "[dat:CzyMozeAkceptowacZaPozostalych]";

        var path_row = $('<div class="row path-row" id="' + addressesIndex + '"></div>');
        var path_row_info = $('<div class="col-xs-6"><span class="path-index">' + addressesIndex + '</span>' + imie + " " + nazwisko + '</div>');
        var path_row_parent_gid = $('<input type="hidden" name="' + rowParentGid + '" value="' + pathGid + '">');
        var path_row_index = $('<input type="hidden" name="' + rowIndex + '" value="' + addressesIndex + '">');
        var path_row_adr_email = $('<input type="hidden" name="' + rowAddressEmail + '" value="' + email + '">');
        var path_row_adr_gid = $('<input type="hidden" class="address-gid" name="' + rowAddressGid + '" value="' + gid + '">');
        var path_row_adr_name = $('<input type="hidden" name="' + rowAddressName + '" value="' + imie + " " + nazwisko + '">');

        var path_row_actions = $('<div class="col-xs-3"></div>');
        var path_row_must_accept = $('<input type="checkbox" name="' + rowMustAccept + '"/><label>Akceptacja wymagana</label>');
        var path_row_actions_2 = $('<div class="col-xs-3"></div>');
        var path_row_accept_all = $('<input type="checkbox" name="' + rowAcceptAll + '"/><label>Akceptuje za wszystkich</label>');
        var path_row_remove = $('<a href="#" class="delete-path-element btn btn-flat btn-danger pull-right"><i class="fa fa-trash"></i></a>');

        path_row.append(path_row_parent_gid).append(path_row_index).append(path_row_adr_email).append(path_row_adr_gid).append(path_row_adr_name);
        path_row_actions_2.append(path_row_accept_all).append(path_row_remove);
        path_row_actions.append(path_row_must_accept);
        path_row.append(path_row_info).append(path_row_actions).append(path_row_actions_2);
        $('#path-rows').append(path_row);
        checkboxesInit();
        addresses.push(gid);
        addressesIndex++;
        reorderPaths();
    }
}
function reorderPaths() {
    $('.path-rows .path-row').each(function (index, value) {
        $(this).attr('id', index);
        $(this).find('.element-index').val(index);
        $(this).find('.path-index').text(index);
    });
}
var codeListModal,
    codeListBody,
    codeListLoader;
var workersListModal,
    workersListBody,
    workersListLoader,
    workersCounter;
var selectedValues = [],
    $listActiveInput;

function _prepareCodeList() {
    codeListModal = $('#code-list-modal');
    codeListBody = codeListModal.find('#code-list-body');
    codeListLoader = codeListBody.find('#code-list-loader');
}

function _prepareWorkersList() {
    workersListModal = $('#workers-list-modal');
    workersListBody = workersListModal.find('#workers-list-body');
    workersListLoader = workersListBody.find('#workers-list-loader');
}


function getCodeList(codeNumber) {
    var url = local_url + 'ajax/api/daj_liste_kodow',
        data = {};
    if (typeof codeNumber != "undefined") {
        data.code = codeNumber
    }
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType: 'HTML',
        async: true,
        beforeSend: function () {
            showLoader(codeListLoader);
        },
        success: function (response) {
            if(trim(response) == 'login') {
                window.location = local_url + 'login';
            } else {
                if (response != 'empty') {
                    codeListBody.html(response);
                    codeListLoader = codeListBody.find('#code-list-loader');
                    $(document).find('#ALL').on('ifToggled', function () {
                        var is_checked = $(this).is(':checked');
                        $(document).find('#codes-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('#code-list-modal');
                    if (selectedValues.length > 0) {
                        $.each(selectedValues, function (index, value) {
                            codeListBody.find('#' + value).iCheck('check');
                        });
                    }
                    codesFiltering();
                }
                hideLoader(codeListLoader);
            }
        },
        error: function (err) {
            if(err.status == 403) {
                window.location = local_url + 'login';
            }
        }
    });
}

function getWorkersList(all) {
    var url = local_url + 'ajax/api/daj_liste_pracownikow/' + all;
    $.ajax({
        url: url,
        type: 'POST',
        data: {},
        dataType: 'HTML',
        async: true,
        beforeSend: function () {
            showLoader(workersListLoader);
        },
        success: function (response) {
            if(trim(response) == 'login') {
                window.location = local_url + 'login';
            } else {
                if (response != 'empty') {
                    workersListBody.html(response);
                    if(workersCounter == 1) workersListBody.find('.check-all').remove();
                    workersListLoader = workersListBody.find('#workers-list-loader');
                    $(document).find('#ALL').on('ifToggled', function () {
                        var is_checked = $(this).is(':checked');
                        $(document).find('#workers-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('#workers-list-modal');
                    if (selectedValues.length > 0) {
                        $.each(selectedValues, function (index, value) {
                            workersListBody.find('#' + value).iCheck('check');
                        });
                    }
                    workersFiltering();
                }
                hideLoader(workersListLoader);
            }
        },
        error: function (err) {
            if(err.status == 403) {
                window.location = local_url + 'login';
            }
        }
    });
}

function _codeListModalSubmit() {
    $listActiveInput.val('');
    var counter = 0;
    var checkedCodes = codeListModal.find('input[type=checkbox]:checked');
    $.each(checkedCodes, function (index) {
        var $this = $(this);
        if($this.attr('id') != 'ALL') {
            if (counter > 0) {
                $listActiveInput.val($listActiveInput.val() + ';' + $this.attr('id'));
            } else {
                $listActiveInput.val($listActiveInput.val() + $this.attr('id'));
            }
            counter++;
        }
    });
    codeListModal.modal('hide');
}

function _workersListModalSubmit() {
    $listActiveInput.val('');
    var counter = 0;
    var checkedWorkers = workersListModal.find('input[type=checkbox]:checked');
    $.each(checkedWorkers, function (index) {
        var $this = $(this);
        if($this.attr('id') != 'ALL') {
            if (counter > 0) {
                $listActiveInput.val($listActiveInput.val() + ';' + $this.attr('id'));
            } else {
                $listActiveInput.val($listActiveInput.val() + $this.attr('id'));
            }
            counter++;
        }
    });

    if(workersCounter != undefined && workersCounter != null) {
        if(workersCounter < checkedWorkers.length) {
            alert('Proszę wybrać dokładnie jednego pracownika');
        } else {
            workersListModal.modal('hide');
        }
    } else {
        workersListModal.modal('hide');
    }
}

$(document).on('click', '#code-list-submit', function () {
    _codeListModalSubmit();
});

$(document).on('click', '#workers-list-submit', function () {
    _workersListModalSubmit();
});

function codeList() {
    _prepareCodeList();
    $('.codes-modal-trigger').click(function (e) {
        e.preventDefault();
        var loader = codeListBody.find('.loader');
        codeListBody.html('');
        codeListBody.append($(loader));
        $listActiveInput = $(this).siblings('input[type=text]');
        if ($listActiveInput.val().length > 0) {
            selectedValues = $listActiveInput.val().split(";");
        } else {
            selectedValues = []
        }
        codeListModal.modal('show');
        getCodeList($(this).data('code-list-number'));
    });
}

function workersList() {
    _prepareWorkersList();
    $('.workers-modal-trigger').click(function (e) {
        e.preventDefault();
        var loader = workersListBody.find('.loader');
        workersListBody.html('');
        workersListBody.append($(loader));
        workersCounter = $(this).data('count');
        $listActiveInput = $(this).siblings('input[type=text]');
        if ($listActiveInput.val().length > 0) {
            selectedValues = $listActiveInput.val().split(";");
        } else {
            selectedValues = [];
        }
        checkboxesInit('#workers-list-modal');

        workersListModal.find('input[type="checkbox"]').each(function () {
            $(this).iCheck('uncheck');
        });

        workersListModal.modal('show');
        var all = $(this).data('getall');
        getWorkersList(all);
    });
}

$(document).ready(function () {
    sortablePaths();
    deletePath();
    findAddress();
    codeList();
    workersList();

});

/**
 * RECEIVERS LIST
 */

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

function getReceiversList(zmetody) {
	var url = local_url + 'ajax/api/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('#ALL').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 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(Wszystkie)').show();
            $('#addresses-list > div:contains(' + filter + ')').show();
        } else {
            $('#addresses-list > div').show();
        }
    });
}

$(document).on('click', '#receivers-list-submit', function () {
    _receiversListModalSubmit();
});

function _receiversListModalSubmit() {
    var checkedReceivers = receiversListModal.find('input[type=checkbox]:checked');
    $.each(checkedReceivers, function (index) {
        var $this = $(this);
        addAddress($this.data('name'), $this.data('email'), $this.attr('id'), $(this).data('display-name'), $(this).data('imie'), $(this).data('nazwisko'));
    });
    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) {
            deleteReceiver($input, gid);
        }
    });
    receiversListModal.modal('hide');
}

function receiversList() {
    $('#address-search-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);
    });
}

receiversList();
