// Fix for date validator 
$(function () {
    $.validator.methods.date = function (value, element) {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        if (isChrome) {
            var d = new Date();
            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toString($("#DateFormat").val())));
        } else {
            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        }
    };
});

$(document).ready(function () {
    if ($("#isLicenseCM").val() === "True") {
        setGlobalHelpUrl($("#EmployeesLicenseCMHelpUrl").val())

        if ($("#isEdit").val() === "False") {
            $.ajax({
                type: "GET",
                url: $("#GetActiveEmployeesCountUrl").val(),
                success: function (activeEmployees) {
                    if (activeEmployees >= 5) {
                        openEmployeesIRISModal();
                    }
                },
                error: function (error) {
                    console.error(error);
                }
            });
        }

        var focusDateOfEntry = decodeURI(url.searchParams.get("focusDateOfEntry"));
        if (focusDateOfEntry === "true") {
            $('#Begin').focus();
            $('#Begin').val('');
        }
    }
});

function setIsActive() {
    if ($("#UserCanNotUpdateWorker").val() === 'True') {
        return;
    }
    let worker = decodeURI(url.searchParams.get("id"));

    if ($("#isActive").val() === 'True') {
        $("#isActive").removeAttr("checked");
        $("#isActive").attr("value", "False");
    }
    else {
        $("#isActive").attr("checked", true);
        $("#isActive").attr("value", "True");
    }

    $.ajax({
        type: "GET",
        url: $("#CheckUserStatus").val(),
        data: {
            worker: worker
        },
        async: false,
        success: function (userStatus) {
            if (userStatus === "T") {
                displayUserActivationModal($("#DoYouWantToDeactivateUserForEmployee").val());
            } else if (userStatus === "F") {
                displayUserActivationModal($("#DoYouWantToActivateUserForEmployee").val());
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function displayUserActivationModal(text) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: text,
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                action: function () {
                    $("#ChangeUserStatus").val(false);
                },
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#YesLoc").val(),
                action: function () {
                    $("#ChangeUserStatus").val(true);
                    return checkAndHandleNewEmployeeClick('false', 'submitEmployee');
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function checkAndHandleNewEmployeeClick(redirectToCreate = "", submitButtonId = "") {
    $.ajax({
        type: "GET",
        url: $("#GetActiveEmployeesCountUrl").val(),
        data: {
            acWorker: $('#Worker').val()
        },
        success: function (activeEmployees) {
            if ($('#isLicenseCM').val() === "True" &&
                (($('#isEdit').val() === "False" && activeEmployees >= 5) ||
                ($('#isEdit').val() === "True" && activeEmployees > 5 && $('#isActive').val() === "True"))) {
                openEmployeesIRISModal();
            }
            else {
                return handleNewEmployeeClick(redirectToCreate, submitButtonId);
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function handleNewEmployeeClick(redirectToCreate = "", submitButtonId = "") {
    let currentWorker = $("#ModelId").val();
    
    if (currentWorker !== "0") {
        if (redirectToCreate === 'true') {
            window.location.href = $("#CreateWorkerUrl").val();
            return;
        }

        saveEmployee(redirectToCreate, submitButtonId);
        return;
    }

    if (redirectToCreate === 'false') {
        setQuestionWorker($("#Name").val(), $("#Surname").val());

        $().customModal({
            showCloseButton: true,
            type: "question",
            title: $("#Question").val(),
            help: $("#CreateUserHelpUrl").val(),
            id: "createUserFromEmployeeModal",
            text: $("#DoYouWantToCreateUserForEmployee").val(),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#Cancel").val(),
                    action: async function () {
                        checkContactAndCreate(redirectToCreate, submitButtonId);
                    },
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#Create").val(),
                    action: async function () {
                        checkUsersCount(null, redirectToCreate, submitButtonId);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
    else {
        checkContactAndCreate(redirectToCreate, submitButtonId);
    }
}

function checkContactAndCreate(redirectToCreate, submitButtonId){
    if (redirectToCreate !== "") {
        $.ajax({
            type: 'GET',
            url: $("#GetWorkerContactUrl").val(),
            dataType: 'json',
            data: { worker: $("#Worker").val() },
            success: function (response) {
                if (response.AcSubject) {
                    openWorkerHasContactModal(response.AnUserId);
                } else {
                    saveEmployee(redirectToCreate, submitButtonId);
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    } else {
        window.location.href = $("#CreateWorkerUrl").val();
    }
}

function saveEmployee(redirectToCreate, submitButtonId) {
    $.ajax({
        type: "GET",
        url: $("#GetActiveEmployeesCountUrl").val(),
        data: {
            acWorker: $('#Worker').val()
        },
        success: function (activeEmployees) {
            if ($('#isLicenseCM').val() === "True" && activeEmployees >= 5 && ($('#isActive').val() === undefined || $('#isActive').val() === "True")) {
                openEmployeesIRISModal();
            }
            else if (redirectToCreate.length > 0 && submitButtonId.length > 0) {
                return submitForm(redirectToCreate, submitButtonId);
            }
            else {
                window.location.href = $("#CreateWorkerUrl").val();
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function checkActiveEmployeesCount() {
    $.ajax({
        type: "GET",
        url: $("#GetActiveEmployeesCountUrl").val(),
        success: function (activeEmployees) {
            if ($('#isLicenseCM').val() === "True" && activeEmployees >= 5) {
                openEmployeesIRISModal();
            } else {
              window.location.href = $("#CreateWorkerUrl").val();
            }
        }
    });
}

function openWorkerHasContactModal(contactUserId) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        help: true,
        type: "alert",
        title: $("#WarningLoc").val(),
        text: $("#ContactAlreadyExistsLoc").val() + " " + " " + contactUserId,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function openEmployeesIRISModal() {
    $('#iris-header').text($('#MaxFiveEmployeesTitle').val());
    $('#iris-message').text($('#MaxFiveEmployeesDescription').val());
    $('#option-1-header').text($('#OrderWebLightLicence').val());
    $('#option-1-text').text($('#OrderHigherWebLightLicence').val());
    $('#option-2-header').text($('#CancelIRIS').val());
    $('#option-2-text').text($('#CancelEmployeeCreate').val());
    $('#option-3-header').text($('#PoIrisHelp').val());
    $('#option-3-text').text($('#ViewInstructionsDescription').val());

    let locCode = $('#locCode').val();
    let domain = locCode;
    switch (locCode) {
        case "en":
            locCode = "eu";
            domain = "eu";
            break;

        case "mk":
            locCode = "mk";
            domain = "com.mk";
            break;

        case "xk":
            locCode = "eu";
            domain = "eu";
            break;

        case "al":
            locCode = "eu";
            domain = "eu";
            break;
    }

    $('#option-1-clickable').click(function () {
        window.open(`https://www.datalab.${domain}/pantheon-web/?popup=open_popup_${locCode}_pantheon_web`, '_blank')
    });

    $('#option-3-clickable').click(function () {
        window.open($('#maxFiveEmployeesHelpUrl').val(), '_blank')
    });

    var parentElement = $('#option-1-section');

    if (!parentElement.children('.fa-phone').length && !parentElement.children('.fa-envelope').length) {
        var phoneElement = $('<i>').addClass('fa fa-phone m-r-xs');
        parentElement.append(phoneElement);

        var phoneText = $('<span>').text($('#contactPhone').val()).addClass('m-r-sm');
        parentElement.append(phoneText);

        var envelopeElement = $('<i>').addClass('fa fa-envelope m-r-xs m-l-sm');
        parentElement.append(envelopeElement);

        var envelopeText = $('<span>').text($('#contactEmail').val());
        parentElement.append(envelopeText);
    }

    $('#blank-iris').modal('show');
}

function initializeEmployees() {
    let currentLoc = $("#CurrentLoc").val();
    let locBA = $("#LocBA").val();
    let locRS = $("#LocRS").val();
    let locMK = $("#LocMK").val();
    let locME = $("#LocME").val().replace("_", "-");
    let hiddenOnBAMKRSME = '';
    let isLicenseCM = $("#isLicenseCM").val();

    if (currentLoc == locBA || currentLoc == locRS || currentLoc == locMK || currentLoc == locME) {
        hiddenOnBAMKRSME = 'hidden';
    }

    let dtColumns = [
        {
            data: function (data) {
                return "value=" + data.Worker;
            },
            orderable: false,
            className: 'dt-body-center',
            render: function (data) {
                data = data.replace("value=", "").replace('"', '');
                return "<input name='employeeSelection' class='checkForStatus' type='checkbox' onclick=checkBoxSelectionChanged('" + encodeURIComponent(data) + "'); />";
            }
        },
        {
            data: function (data) {
                if (data.ProfilePhoto) {
                    return "<img class='dt-image-circle' src='" + data.ProfilePhoto + "' />";
                }
                else {
                    return "<div class='dt-text-avatar'>" + data.Avatar + "</div>";
                }
            },
            orderable: false,
            className: 'dt-col-no-padding',
            render: function (data) {
                return data;
            }
        },
        { data: "Worker", name: "AcWorker", filtertype: "text", render: $.fn.dataTable.render.link("Worker") },
        { data: "FullName", name: "AcSurname", filtertype: "text" },
        { data: "Job", name: "AcJob", filtertype: "text" },
        { data: "Address", name: "AcStreet", filtertype: "text" },
        { data: "Post", name: "AcPost", filtertype: "text" },
        { data: "TaxId", name: "AcTaxId", filtertype: "number", className: hiddenOnBAMKRSME },
        { data: "Active", name: "AcActive", render: $.fn.dataTable.render.toggle(true, true), className: 'dt-body-center' }
    ]

    if (isLicenseCM === 'False') {
        dtColumns.splice(4, 0, { data: "Department", name: "AcDept", filtertype: "text" });
        dtColumns.splice(9, 0, { data: "RegNo", name: "AcRegNo", filtertype: "text" });
    }

    $('.datepicker').datepicker()
        .on('click', function (e) {
            $(this).select();
        })
        .on('changeDate', function () {
            $(this).datepicker('hide');
            $.fn.dataTable.reload($dataTable);
        });

    $dataTable = $('#mainGrid');

    $(".selectpicker-dropdown").on("hide.bs.dropdown", function () {
        $dataTable.DataTable().ajax.reload();
    });

    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.EmploymentStatuses = $("#EmploymentStatuses").val();
                d.WorkingPlaces = $("#WorkingPlaces").val();
                d.Departments = $("#Departments").val();
                d.WorkingStatuses = $("#WorkingStatuses").val();
            }
        },
        columns: dtColumns,
        colReorder: {
            fixedColumnsLeft: 2,
        },
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
}

function expandEmployeeTableRow(tableId, index, isOnChange = false) {
    if (window.screen.width < 768) {
        var rowId = "#" + tableId + " .collapse-table-row-" + index;
        var expandIconObj = $("#" + tableId).find("#expand-icon-" + index);
        var borderClass = "border-left-success";
        var iconRight = "fa-caret-right";
        var iconDown = "fa-caret-down";

        $(rowId).find('td').each(function (column, td) {
            if ($(td).css('display') == 'none') {
                $(td).css("display", "flex");

                $(rowId).addClass(borderClass);
                expandIconObj.removeClass(iconRight);
                expandIconObj.addClass(iconDown);
            }
            else if ($(td).css('display') == 'flex' && !isOnChange) {
                $(td).css("display", "none");

                $(rowId).removeClass(borderClass);
                expandIconObj.addClass(iconRight);
                expandIconObj.removeClass(iconDown);
            }
        });
    }
}

function initializeEmployeesEdit() {
    initializePostTypeahead($('#Post').attr('dataUrl'), $('#Post'), $("#Post"));
    initializePostTypeahead($('#BirthPlace').attr('dataUrl'), $('#BirthPlace'), $("#BirthPlace"));

    $("#VehicleRegistrationNumber").on("change", function () {
        if ($("#VehicleRegistrationNumber").val()) {
            $.ajax({
                url: $("#GetCompanyVehicleUrl").val() + '?registrationNumber=' + $("#VehicleRegistrationNumber").val(),
                type: 'GET',
                success: function (response) {
                    if (response !== null) {
                        $('#IsCompanyVehicleDisplay').prop('checked', true);
                    } else {
                        $('#IsCompanyVehicleDisplay').prop('checked', false);
                    }
                },
                error: function (result) {
                    $('#IsCompanyVehicleDisplay').prop('checked', false);
                }
            });
        }
    });

    $('#saveemployee').on('click', function () {
        SubmitEmployeeForm(this);
    });

    $('#saveAndRedirect').on('click', function () {
        SubmitEmployeeForm(this);
    });

    var modelValid = $('#ModelValid').val();

    if ($("#ActionMethod").val() === "Create") {

        if (modelValid === "False")
            return;

        $("#Worker").on("blur", function () {
            fillNameDetails(this.value);
        });
    }
}

function initializeEmployeesCreate() {
    initializeEmployeesEdit();
    dropifyUpload();
}

function fillEmployeeDetails(emso) {

    if (emso.length < 1)
        return;

    $.ajax({
        url: $("#EmployeeAdditionalInfoUrl").val(),
        dataType: 'json',
        data: { uid: emso },
        method: "GET",
        success: function (data) {
            if (data.IsValidUin) {

                $('#BirthCountry').val(data.CountryId);

                if (data.IsFemale === true) {
                    $('#Gender').val(2);
                    $('#Gender').trigger('change');
                }
                else {
                    $('#Gender').val(1);
                    $('#Gender').trigger('change');
                }

                var birthDate = new Date(data.Birthday);
                var bDay = formatDate(birthDate);

                $('#Birth').val(bDay);
            }
        },
        fail: function (error) {
            alert(error);
        }
    });
}

function fillNameDetails(name) {

    if (name.length < 1)
        return;

    $.getJSON($("#GetNameConfiguration").val(),
        function (data) {

            var nameSplitted = name.split(" ");

            if (data === "A") {
                if (nameSplitted.length > 2) {
                    $("#Name").val(nameSplitted[0]);
                    $("#Surname").val(nameSplitted[1] + " " + nameSplitted[2]);
                } else {
                    $("#Name").val(nameSplitted[0]);
                    $("#Surname").val(nameSplitted[1]);
                }
            }
            else if (data === "B") {
                if (nameSplitted.length > 2) {
                    $("#Surname").val(nameSplitted[0] + " " + nameSplitted[1]);
                    $("#Name").val(nameSplitted[2]);
                } else {
                    $("#Surname").val(nameSplitted[0]);
                    $("#Name").val(nameSplitted[1]);
                }
            }
        });
}

function SetCitizenship() {
    $.getJSON($("#GetCitizenship").val(), { country: $("#BirthCountry").val() },
        function (data) {
            $('#CountryCitizenship').val(data.Value).change();
        });
}


function SetDepartment() {
    $.getJSON($("#GetDepartmentUrl").val(), { jobId: $("#Job").val() },
        function (data) {
            if (data.department) {
                var newDepartment = new Option(data.department, data.department, false, true);
                $('#Department').append(newDepartment).trigger('change');
            }
        });
}

function checkBoxSelectionChanged(checkboxValue) {

    if (!selectedAcKeys.includes(checkboxValue)) {
        selectedAcKeys.push(checkboxValue);
    } else {
        var index = selectedAcKeys.indexOf(checkboxValue);
        selectedAcKeys.splice(index, 1);
    }

    if (selectedAcKeys.length > 0) {
        $('#deleteButton').removeClass('disabled');
    }
    else {
        $('#deleteButton').addClass('disabled');
    }
}

function SetCountry(num) {
    var value = $("#RPost-" + num).val();
    var url = $("#RPost-" + num).data('change-url');

    $.getJSON(url, { id: value },
        function (data) {
            if (data) {
                var item = new Option(data.Country, data.Country, false, true);
                $('#RCountry-' + num).append(item).trigger('change');
            }
        });
}

//#region DELETE

function DeleteEmployee(url) {
    var deleteWorkerText = $("#DeleteWorkerText").val();
    var deleteTitle = $("#DeleteTitle").val();
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        title: deleteTitle,
        text: deleteWorkerText,
        buttons: [
            {
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    GetSubjectDeleteSwal(url);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function GetSubjectDeleteSwal(url) {
    var deleteSubjectText = $("#DeleteSubjectText").val();
    var deleteTitle = $("#DeleteTitle").val();
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        title: deleteTitle,
        text: deleteSubjectText,
        buttons: [
            {
                icon: 'fa fa-times',
                text: cancelText,
                action: async function () {
                    PerformDelete(url, false);
                },
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    PerformDelete(url, true);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function PerformDelete(url, isSubjectConfirmed) {
    var confirmText = $("#TextConfirm").val();

    $.ajax({
        cache: false,
        type: "post",
        url: url,
        data: {
            keys: selectedAcKeys,
            isSubjectConfirmed: isSubjectConfirmed
        },
        success: function (result) {
            selectedAcKeys = [];
            $.fn.dataTable.reload($dataTable);

            var output = "";
            for (var i = 0; i < result.length; i++) {
                output += "<p>" + result[i] + "</p>";
            }

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: output,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: confirmText,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            $("#deleteButton").addClass('btn-outline disabled').removeClass('btn-danger');
        },
        error: function (error) {

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#GeneralErrorMessage").val() + error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: confirmText,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

//#endregion DELETE


function openModal(id) {
    $('#' + id).find('input[type="checkbox"]').customCheckbox();
    $('#' + id).modal('show');
}

function dropifyUpload() {
    var dr = $('.dropify').dropify({
        messages: {
            'default': $("#DragAndDropOrClick").val(),
            'replace': $("#DragAndDropOrClick").val(),
            'remove': $("#Remove").val(),
            'error': $("#GeneralErrorMessage").val()
        },
        error: {
            'imageFormat': $("#WrongImageFormat").val(),
            'fileExtension': $("#WrongImageFormat").val(),
            'fileSize': $("#FileSizeMessage").val()
        }
    });

    var allowSubmit = true;
    dr.on('dropify.errors', function (event, element) {
        allowSubmit = false;
    });

    $('.dropify').on('change', function () {
        if (allowSubmit) {
            setTimeout(function () { $('.dropify-loader').css('display', 'block'); }, 600);
            $('#employee-image-form').submit();
        }
        else {
            allowSubmit = true;
        }
    });
}

$(".employee-picture").hover(
    function () {
        $(".edit-photo-icon").removeClass("hidden");
        $(".edit-photo").removeClass("hidden");
    },
    function () {
        $(".edit-photo-icon").addClass("hidden");
        $(".edit-photo").addClass("hidden");
    }
);

function initializeSidebarEmployees(activeWorker) {
    $dataTable = $('#side-employee-table');

    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
            }
        },
        columns: [
            {
                data: function (data) {
                    var rowDiv = "<div onclick=openWorkerUrl('" + encodeURIComponent(data.Worker) + "'); class='row dt-worker-row' data-worker='" + data.Worker + "'>";

                    var subtext = '';
                    if (data.Department && data.Job) {
                        subtext = data.Job + " • " + data.Department;
                    } else if (data.Job) {
                        subtext = data.Job;
                    } else if (data.Department) {
                        subtext = data.Department;
                    }

                    let name = "";
                    let surname = "";

                    if (data.Name) {
                        name = data.Name;
                    }

                    if (data.Surname) {
                        surname = data.Surname;
                    }

                    var showData = "<div class='col-md-10 col-sm-11 col-xs-10 emp-data'>" + surname + " " + name + "<br/><span class='text-muted'>" + subtext + "</span></div>";

                    if (data.ProfilePhoto) {
                        return rowDiv + "<div class='col-md-2 col-sm-1 col-xs-2 emp-avatar'><img class='dt-image-circle' src='" + data.ProfilePhoto + "' /></div>" + showData + "</div > ";
                    }
                    else {
                        return rowDiv + "<div class='col-md-2 col-sm-1 col-xs-2 emp-avatar'><div class='dt-text-avatar'>" + data.Avatar + "</div></div>" + showData + "</div>";
                    }
                },
                orderable: false,
                className: 'dt-employee-side-col',
                render: function (data) {
                    return data;
                }
            }
        ],
        "createdRow": function (row, data, dataIndex) {
            if (data.Worker === activeWorker) {
                $(row).children().addClass('side-menu-item-active');
            }
        }
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
}

function openWorkerUrl(worker) {
    window.location.href = $("#EmployeeSideContentUrl").val() + "?id=" + worker;
}

function addNewResidence() {
    if ($("#ResidenceType--1").val() === "" ||
        $("#RDateFrom--1").val() === "" ||
        $("#RStreet--1").val() === "" ||
        $("#RPost--1").val() === "" ||
        $("#RCountry--1").val() === "")
    {
        return;
    }

    var tableId = "residence-table";
    var tableRows = $('table#residence-table > tbody > tr');
    var cloneCount = tableRows.not(':first').length;
    var newAnNo = cloneCount++;
    var residenceRow = '#residence-row-' + newAnNo;

    tableRows.find(".select2withAPI").each(function (index) {
        if ($(this).data('select2')) {
            $(this).select2('destroy');
        }
    });

    $('#residence-new-row').clone().attr('id', 'residence-row-' + newAnNo).appendTo("#residence-table > tbody");
    $(residenceRow).find('#btn-col').empty().append("<td><a class='a-outline' onclick=deleteResidence('" + newAnNo + "')><i class='far fa-trash-alt'></i></a></td>").removeAttr("id").removeClass("add-btn-td");

    var baseAnNo = newAnNo + 1;

    $(residenceRow).removeClass("collapse-table-row--1").addClass("collapse-table-row-" + newAnNo);
    $(residenceRow + ' #expand-icon--1').attr('onclick', 'expandEmployeeTableRow(\'' + tableId + '\', \'' + newAnNo + '\')').attr('id', 'expand-icon-' + newAnNo);
    $(residenceRow + ' #RAnNo--1').attr('name', 'Residences[' + newAnNo + '].AnNo').attr('value', baseAnNo).attr('id', 'RAnNo-' + newAnNo);
    $(residenceRow + ' #RAnQid--1').attr('name', 'Residences[' + newAnNo + '].AnQid').attr('id', 'RAnQid-' + newAnNo);
    $(residenceRow + ' #ResidenceType--1').attr('name', 'Residences[' + newAnNo + '].ResidenceType').attr('id', 'ResidenceType-' + newAnNo).val($("#ResidenceType--1").val());
    $(residenceRow + ' #RDateFrom--1').attr('name', 'Residences[' + newAnNo + '].DateFrom').attr('id', 'RDateFrom-' + newAnNo);
    $(residenceRow + ' #RDateTo--1').attr('name', 'Residences[' + newAnNo + '].DateTo').attr('id', 'RDateTo-' + newAnNo);
    $(residenceRow + ' #RStreet--1').attr('name', 'Residences[' + newAnNo + '].Street').attr('id', 'RStreet-' + newAnNo);
    $(residenceRow + ' #RPost--1').attr('name', 'Residences[' + newAnNo + '].Post').attr("onchange", "SetCountry('" + newAnNo + "')").attr('id', 'RPost-' + newAnNo);
    $(residenceRow + ' #RCountry--1').attr('name', 'Residences[' + newAnNo + '].Country').attr('id', 'RCountry-' + newAnNo);
    $(residenceRow).find('#RDateTo-' + newAnNo).removeAttr("placeholder");

    clearResidenceRow();
    select2withAPI();
    initializeDateTimePicker();
}

function clearResidenceRow() {
    $("#ResidenceType--1").val(null).trigger('change');
    $("#RDateFrom--1").val('');
    $("#RDateTo--1").val('');
    $("#RStreet--1").val('');
    $("#RPost--1").val('');
    $("#RCountry--1").val(null).trigger('change');
}

function deleteResidence(num) {
    let tableRows = $('#residence-table tbody tr:nth-child(n+2)');
    let totalRows = tableRows.length;
    var intNum = parseInt(num);

    $('#residence-row-' + num).remove();

    for (var i = intNum; i < totalRows; i++) {
        $("#residence-row-" + (i + 1) + " #AnNo-" + (i + 1)).attr("id", "AnNo-" + i).attr("Name", "Residences[" + i + "].AnNo").attr("Value", (i + 1));
        $("#residence-row-" + (i + 1) + " #AnQId-" + (i + 1)).attr("id", "AnQId-" + i).attr("Name", "Residences[" + i + "].AnQId");
        $("#residence-row-" + (i + 1) + " #ResidenceType-" + (i + 1)).attr("id", "ResidenceType-" + i).attr("Name", "Residences[" + i + "].ResidenceType");
        $("#residence-row-" + (i + 1) + " #RDateFrom-" + (i + 1)).attr("id", "RDateFrom-" + i).attr("Name", "Residences[" + i + "].DateFrom");
        $("#residence-row-" + (i + 1) + " #RDateTo-" + (i + 1)).attr("id", "RDateTo-" + i).attr("Name", "Residences[" + i + "].DateTo");
        $("#residence-row-" + (i + 1) + " #RStreet-" + (i + 1)).attr("id", "RStreet-" + i).attr("Name", "Residences[" + i + "].Street");
        $("#residence-row-" + (i + 1) + " #RPost-" + (i + 1)).attr("id", "RPost-" + i).attr("Name", "Residences[" + i + "].Post");
        $("#residence-row-" + (i + 1) + " #RCountry-" + (i + 1)).attr("id", "RCountry-" + i).attr("Name", "Residences[" + i + "].Country");
        $("#residence-row-" + (i + 1) + " a").attr("onclick", "deleteResidence('" + i + "')");

        $("#residence-row-" + (i + 1)).attr("id", "residence-row-" + i)
            .removeClass("collapse-table-row-" + (i + 1)).addClass("collapse-table-row-" + i);
    }
}

$('#Birth').datetimepicker({
    format: 'DD.MM.YYYY',
    locale: 'sl-SI'
});

function addNewContactAddress() {
    if ($("#CaType--1").val() === "" || $("#CaValue--1").val() === "") {
        return;
    }

    var tableId = "contactaddress-table";
    var tableRows = $('table#contactaddress-table > tbody > tr');
    var cloneCount = tableRows.not(':first').length;
    var newSubNo = cloneCount++;
    var residenceRow = '#contactaddress-row-' + newSubNo;

    tableRows.find(".select2withAPI").each(function (index) {
        if ($(this).data('select2')) {
            $(this).select2('destroy');
        }
    });

    $('#contactaddress-new-row').clone().attr('id', 'contactaddress-row-' + newSubNo).appendTo("#contactaddress-table > tbody")
        .find('input').removeAttr('placeholder');

    $(residenceRow).find('#btn-col-contact-addr').empty().append("<td><a class='a-outline' onclick=deleteContactAddress('" + newSubNo + "')><i class='far fa-trash-alt'></i></a></td>").removeAttr("id").removeClass("add-btn-td");

    var baseSubNo = newSubNo + 1;

    $(residenceRow).removeClass("collapse-table-row--1").addClass("collapse-table-row-" + newSubNo);
    $(residenceRow + ' #expand-icon--1').attr('onclick', 'expandEmployeeTableRow(\'' + tableId + '\', \'' + newSubNo + '\')').attr('id', 'expand-icon-' + newSubNo);
    $(residenceRow + ' #CaAnSubNo--1').attr('name', 'ContactAddresses[' + newSubNo + '].AnSubNo').attr('id', 'RAnNo-' + newSubNo);
    $(residenceRow + ' #CaAnQid--1').attr('name', 'ContactAddresses[' + newSubNo + '].AnQid').attr('id', 'CaAnQid-' + newSubNo);
    $(residenceRow + ' #CaAnNo--1').attr('name', 'ContactAddresses[' + newSubNo + '].AnNo').attr('id', 'CaAnNo-' + newSubNo);
    $(residenceRow + ' #CaType--1').attr('name', 'ContactAddresses[' + newSubNo + '].Type').attr('id', 'CaType-' + newSubNo).val($("#CaType--1").val());
    $(residenceRow + ' #CaValue--1').attr('name', 'ContactAddresses[' + newSubNo + '].Value').attr('id', 'CaValue-' + newSubNo);
    $(residenceRow + ' #CaNote--1').attr('name', 'ContactAddresses[' + newSubNo + '].Note').attr('id', 'CaNote-' + newSubNo);

    clearContactAddressRow();
    select2withAPI();
}

function clearContactAddressRow() {
    $("#CaType--1").val(null).trigger('change');
    $("#CaValue--1").val('');
    $("#CaNote--1").val('');
}

function deleteContactAddress(num) {
    let tableRows = $('#contactaddress-table tbody tr:nth-child(n+2)');
    let totalRows = tableRows.length;
    var intNum = parseInt(num);

    $('#contactaddress-row-' + num).remove();

    for (var i = intNum; i < totalRows; i++) {
        $("#contactaddress-row-" + (i + 1) + " #AnNo-" + (i + 1)).attr("id", "AnNo-" + i).attr("Name", "ContactAddresses[" + i + "].AnNo");
        $("#contactaddress-row-" + (i + 1) + " #AnQId-" + (i + 1)).attr("id", "AnQId-" + i).attr("Name", "ContactAddresses[" + i + "].AnQId");
        $("#contactaddress-row-" + (i + 1) + " #AnSubNo-" + (i + 1)).attr("id", "AnSubNo-" + i).attr("Name", "ContactAddresses[" + i + "].AnSubNo");
        $("#contactaddress-row-" + (i + 1) + " #CaType-" + (i + 1)).attr("id", "CaType-" + i).attr("Name", "ContactAddresses[" + i + "].Type");
        $("#contactaddress-row-" + (i + 1) + " #CaValue-" + (i + 1)).attr("id", "CaValue-" + i).attr("Name", "ContactAddresses[" + i + "].Value");
        $("#contactaddress-row-" + (i + 1) + " #CaNote-" + (i + 1)).attr("id", "CaNote-" + i).attr("Name", "ContactAddresses[" + i + "].Note");
        $("#contactaddress-row-" + (i + 1) + " a").attr("onclick", "deleteContactAddress('" + i + "')");

        $("#contactaddress-row-" + (i + 1)).attr("id", "contactaddress-row-" + i)
            .removeClass("collapse-table-row-" + (i + 1)).addClass("collapse-table-row-" + i);
    }
}

$('#residence-table tbody tr').each(function (index) {
    var num = index - 1;

    $('#Residence-' + num).on('select2:opening', function (e) {
        if (!$(".collapse-table-row-" + num).hasClass("border-left-success")) {
            expandEmployeeTableRow('residence-table', num);
        }
    });
});

function initGoogleMapsSearches() {
    $(".google-input").each(function () {
        var id = $(this).attr("id");
        var idSuffix = id.split("RStreet")[1];
        
        google.maps.event.addDomListener(window, 'load', function () {

            var input = document.getElementById(id);
            var autocomplete = new google.maps.places.Autocomplete(input);

            selectFirstOnEnter(input);

            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var postalCode;
                var postalCodePrefix;
                var country;
                var place = autocomplete.getPlace();
                var address = place.name;
                $(input).val(address);
                
                for (var i = 0; i < place.address_components.length; i++) {
                    for (var j = 0; j < place.address_components[i].types.length; j++) {
                        if (place.address_components[i].types[j] == "country") postalCodePrefix = place.address_components[i].short_name;
                        if (place.address_components[i].types[j] == "postal_code") postalCode = place.address_components[i].long_name;
                        if (place.address_components[i].types[j] == "country") country = place.address_components[i].long_name;
                    }
                }

                // Set post
                if (postalCode) {
                    $('#RPost' + idSuffix).val(postalCodePrefix + "-" + postalCode);
                } else {
                    $('#RPost' + idSuffix).val("");
                }

                // Set country
                var item = new Option(country, country, false, true);
                $('#RCountry' + idSuffix).append(item).trigger('change');
            });
        });
    });

    $(".check-api-key").blur(function () {
        setTimeout(() => {
            if ($(".check-api-key").hasClass("gm-err-autocomplete")) {
                $("#IRISContinueClickable").attr("onclick", "switchToPlainSearch()");
                $("#IRISContinueText").text($("#ContinueUsingExpiredGoogleMapKeyEmployee").val());
                $('#google-api-key-expired-iris').modal('show');
            }
        }, "100")
    });

}

function switchToPlainSearch() {
    var googleSearch = $(".employees-google-search");
    var plainSearch = $(".employees-plain-search");

    if (plainSearch.is(":hidden")) {
        googleSearch.hide();
        plainSearch.show();
    }
}

function initContactTypeAhead(element, localization) {
    let url = element.attr('dataUrl');

    element.typeahead({
        value: "Post",
        display: "Post",
        width: "20%",
        minSearchLength: 0,
        focusOpen: true,
        columns: [
            { name: localization.post, value: "Post", width: "50%" },
            { name: localization.name, value: "Name", width: "50%" }
        ],
        localization: { noResults: localization.noResults },
        url: url,
        urlRequestMethod: "POST",
        onSelect: function (item) {
            //console.log(item)
        }
    });
}

function initContactTypeahead() {
    $(".input-post").each(function () {
        initContactTypeAhead($(this), { noResults: $("#NoResults").val(), name: $("#NameLoc").val(), post: $("#CodeLoc").val() });
    });
}

$(function () {
    $('#contact-data-form').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (data) {
                if (data.Success == false) {
                    let text = data.errors.join(', ');

                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: $("#PostDoesNotExist").val() + ": " + text,
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            }
        });
        return false;
    });
});

function createUserFromEmployee() {
    let worker = $("#ModelWorker").val();

    $.ajax({
        type: 'GET',
        url: $("#UserExistsForEmployeeUrl").val(),
        dataType: 'json',
        data: { worker: worker },
        success: function (response) {
            if (response === true) {
                $().customModal({
                    showCloseButton: true,
                    type: "alert",
                    title: $("#Information").val(),
                    id: "userExistsModal",
                    text: $("#UserAlreadyExists").val(),
                    buttons: [
                        {
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                return;
            }
            else {
                setQuestionWorker($("#Name").val(), $("#Surname").val());

                $().customModal({
                    showCloseButton: true,
                    type: "question",
                    title: $("#Question").val(),
                    help: $("#CreateUserHelpUrl").val(),
                    id: "createUserFromEmployeeModal",
                    text: $("#DoYouWantToCreateUserForEmployee").val(),
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: $("#Cancel").val(),
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: $("#Create").val(),
                            action: async function () {
                                checkUsersCount(worker, null, null);
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        }
    })
}

function checkUsersCount(worker, redirectToCreate, submitButtonId) {
    if ($("#isLicenseCM").val() === "True") {
        $.ajax({
            type: "GET",
            url: $("#VerifyAddingUserUrl").val(),
            success: function (response) {
                if (response !== "") {
                    $("#iris-placeholder").html(response);
                    $('#blank-iris').modal('show');
                    return;
                } else {
                    if (worker) {
                        window.location.href = $("#UsersUrl").val() + "?worker=" + worker;
                    } else {
                        $("#redirectToUserCreate").val(true);
                        checkContactAndCreate(redirectToCreate, submitButtonId);
                    }
                }
            }
        });
    } else {
        if (worker) {
            window.location.href = $("#UsersUrl").val() + "?worker=" + worker;
        } else {
            $("#redirectToUserCreate").val(true);
            checkContactAndCreate(redirectToCreate, submitButtonId);
        }
    }
}

function setQuestionWorker(name, surname) {
    $("#DoYouWantToCreateUserForEmployee").val(function (index, currentValue) {
        return currentValue.replace("{0}", name + " " + surname);
    });
}

function selectCountryField(e, fieldId) {
    if (e.key === "Tab") {
        e.preventDefault();
        $("#" + fieldId).select2('open');
    }
}

function setHolidayLoc(localization) {
    if (localization == $("#localizationBA").val()) {
        $("#employee-legislation").removeClass("hidden");
    }
    else if ($("#isLocalizationBA").val() == 'False') {
        $("#employee-legislation").addClass("hidden");
    }
}

function toggleAffiliationField(localization) {
    if ($("#isLocalizationSI").val() == 'True' && localization == $("#localizationSI").val()) {
        $("#Affiliation").val(null).trigger("change");
        $("#employee-religion").addClass("hidden");
    }
    else {
        $("#employee-religion").removeClass("hidden");
    }
}