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

function findSubstitutes() {
    var input = $('#substitute-search');
    var options = {
        source: '/daj_adresy_ac',
        appendTo: '#substitutes-search-holder',
        disabled: false,
        select: function (event, ui) {
            selectSubstitute(ui.item.bNazwa, ui.item.bEmail, ui.item.bGid, ui.item.bNazwaWyswietlana);
        },
        search: function () {
            // showLoader(loader);
        },
        response: function () {
            // hideLoader(loader);
        },
        open: function () {
            // hideLoader(loader);
        }
    };
    input.autocomplete(options);
}
function selectSubstitute(name, email, gid, displayName) {
    $('#substitute-email').val(email);
    $('#substitute-name').val(name);
    $('#substitute-gid').val(gid);
}
function findEmployee() {
	var input = $('#employee-search');
	var options = {
		source: '/daj_adresy_ac',
		appendTo: '#employee-search-holder',
		disabled: false,
		select: function (event, ui) {
			selectEmployee(ui.item.bNazwa, ui.item.bEmail, ui.item.bGid, ui.item.bNazwaWyswietlana);
		},
		search: function () {
			// showLoader(loader);
		},
		response: function () {
			// hideLoader(loader);
		},
		open: function () {
			// hideLoader(loader);
		}
	};
	input.autocomplete(options);
}
function selectEmployee(name, email, gid, displayName) {
	$('#employee-email').val(email);
	$('#employee-name').val(name);
	$('#employee-gid').val(gid).trigger('change');
}
$(document).ready(function(){
    findSubstitutes();
    findEmployee();
    receiversList();
});


var receiversListModal,
    receiversListBody,
    receiversListLoader;

function _receiversListAppliactionsModalSubmit() {
    var checkedReceivers = receiversListModal.find('input[type=checkbox]:checked');

    if (receiversListModal.data('single') == '1') {
        checkedReceivers = [];
        receiversListModal.find('input[type="checkbox"]').each(function() {
            if ($(this).parent('[class*="icheckbox"]').hasClass("checked")) {
                checkedReceivers.push($(this));
            }
        });
    }

    if(checkedReceivers.length != 1) {
        alert('Wymagana liczba odbiorców: 1');
    } else {
        $.each(checkedReceivers, function (index) {
            var $this = $(this);
			switch($('#receivers-list-submit').data('from'))
			{
				case 'substitute':
					selectSubstitute($this.data('name'), $this.data('email'), $this.attr('id'), $this.data('display-name'));
					$('#substitute-search').val($this.data('display-name'));
					break;
				case 'employee':
					selectEmployee($this.data('name'), $this.data('email'), $this.attr('id'), $this.data('display-name'));
					$('#employee-search').val($this.data('display-name'));
					break;
			}

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

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 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);
                    receiversListBody.find('.blue-text').remove();
                    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 (err) {
            if(err.status == 403) {
                window.location = local_url + 'login';
            }
        }
    });
}

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