function initializeCompanyUnits() {
    $dataTable = $('#mainGrid');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.Status = $("#Status").val();
            }
        },
        columns: [
            { data: "IsActive", name: "AcCloseType", render: $.fn.dataTable.render.toggle('True', true), className: 'dt-body-center' },
            { data: "Id", name: "AcWorkPlace", filtertype: "text", render: $.fn.dataTable.render.link("Id") },
            { data: "Description", name: "AcDesc", filtertype: "text", render: $.fn.dataTable.render.link("Id") },
            {
                data: "MobileType", name: "AcMobileType", filtertype: "text", visible: isLocale(siteLocale.SI),
                render: function (data) {
                    var display = "";
                    switch (data) {
                        case "A":
                            display = $("#MovableWorkplace").val();
                            break;
                        case "B":
                            display = $("#FixedMovableWorkplace").val();
                            break;
                        case "C":
                            display = $("#DeviceWorkplace").val();
                            break;
                        default:
                            return "N - " + $("#NonMovabeWorkplace").val();
                    }

                    return data + " - " + display;
                }
            },
            { data: "Address", name: "AcStreet", filtertype: "text", visible: !isLocale(siteLocale.ME) },
            { data: "City", name: "AcCity", filtertype: "text", visible: !isLocale(siteLocale.ME) },
            { data: "Region", name: "AcMunicip", filtertype: "text", visible: !isLocale(siteLocale.ME) },
            { data: "CadastralNumber", name: "AcCadastralNumber", filtertype: "number", visible: !isLocale(siteLocale.HR) && !isLocale(siteLocale.ME) },
            { data: "CadastralBuildingNumber", name: "AcCadastralBuildingNumber", filtertype: "number", visible: !isLocale(siteLocale.ME) },
            { data: "CadastralSectionNumber", name: "AcCadastralSectionNumber", filtertype: "number", visible: !isLocale(siteLocale.HR) && !isLocale(siteLocale.ME) },
            { data: "WorkPlaceCode", name: "AcWorkPlaceCode", filtertype: "text", visible: isLocale(siteLocale.ME) },
            { data: "ENUCode", name: "AcENUCode", filtertype: "text", visible: isLocale(siteLocale.ME) },
            { data: "ERPCode", name: "AcERPCode", filtertype: "text", visible: isLocale(siteLocale.ME) },
            { data: "ERPDeveloperCode", name: "AcERPDeveloperCode", filtertype: "text", visible: isLocale(siteLocale.ME) },
            { data: "TCRCode", name: "AcTCRCode", filtertype: "text", visible: isLocale(siteLocale.ME) }

        ]
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function () {
        $.fn.dataTable.reload($dataTable);
    });

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

//Edit
function initializeCompanyUnitsEdit() {
    $('#Id').focus();

    $('.input-validation-error').parents('.form-group').addClass('has-error');
    $('.field-validation-error').addClass('text-danger');

    initializePostTypeahead($('#PostSelect').attr('dataUrl'), $('#PostSelect'), $("#Post"), function (item) {
        $("#City").val(item.name);
        $("#MunicipId").val(item.municipCode);
        $("#Municip").val(item.municip);
    });

    initializeUserTypeahead($('#ClerkName').attr('dataUrl'), $('#ClerkName'), $("#Clerk"));

    var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
    });

    $(".datepicker").datepicker({
        format: 'dd.mm.yyyy',
        language: $('#siteLocale').val(),
        startDate: "moment().format('DD.MM.YYYY')"
    });

    $('input[type="radio"][name="MobileType"]').on('change', function () {
        SetIsMovableCheckboxState($(this));
    });

    SetIsMovableCheckboxState($('input[type="radio"][name="MobileType"]:checked'));

    $("#btnRegisterCompanyUnit").on("click", function () {
        RaiseCompanyUnitRegistrationPopup();
    });

    $("#btnCloseCompanyUnit").on("click", function () {
        RaiseCompanyUnitClosePopup();
    });

    $("input#Id").on({
        keydown: function (e) {
            if (e.which === 32)
                return false;
        },
        change: function () {
            this.value = this.value.replace(/\s/g, "");
        }
    });

    $("#btnCheckFiscalServiceConnectivity").on("click", function () {
        var $btn = $(this);
        $btn.find("i").removeClass("fa-wifi").addClass("fa-spinner fa-spin");
        $.ajax({
            method: "POST",
            url: $("#UrlCheckFiscalServiceConnectivity").val(),
            success: function (isServiceAvailable) {
                if (isServiceAvailable) {
                    $().customModal({
                        destroyOnClose: true,
                        title: $("#LocAvailable").val(),
                        showCloseButton: true,
                        type: "success",
                        text: $("#LocFiscalizationServiceIsAvailable").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#LocOk").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
                else {
                    showErrorModal($("#LocUnavailable").val(), $("#LocFiscalizationServiceIsUnavailable").val());
                }
                $btn.find("i").addClass("fa-wifi").removeClass("fa-spinner fa-spin");
            },
            error: function () {
                showErrorModal($("#LocError").val(), $("#LocErrorHappenedWhileCheckingFiscalServiceConnectivity").val());
                $btn.find("i").addClass("fa-wifi").removeClass("fa-spinner fa-spin");
            }
        });
    });

    initializeMunicipTypeahead($("#UrlGetMunicipalities").val(), $('#Municip'), $("#MunicipId"));

    sortColumn = "AdDateTime";
    sortOrder = "desc";
    $dataTable = $('#mainGrid');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.WorkPlaceId = $("#Id").val();
            }
        },
        columns: [
            { data: "AdDateTimeDisplay", name: "AdDateTime", orderable: true },
            { data: "AcOperationDisplay", name: "AcOperation", filtertype: "text" },
            { data: "AcSubseqDelivTypeDisplay", name: "AcSubseqDelivType", filtertype: "text" },
            { data: "AnAmount", name: "AnAmount", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right', filtertype: "number" },
            { data: "AcFcdc", name: "AcFcdc", filtertype: "text" }
        ]
    });
}

function SetIsMovableCheckboxState($element) {
    if (!$element || $element.length === 0) return;

    if ($element.val() !== "") {
        $(".t-movable").prop('disabled', false);
        $(".t-immovable").prop('disabled', true);
        $("#IsMobile").val("true");
    }
    else {
        $(".t-movable").prop('disabled', true);
        $(".t-immovable").prop('disabled', false);
        $("#IsMobile").val("false");
    }
}

function initializeCompanyUnitsCreate() {
    initializeCompanyUnitsEdit();
}

//Details
function initializeCompanyUnitsDetails() {
    $("#btnCheckFiscalServiceConnectivity").on("click", function () {
        $.ajax({
            method: "POST",
            url: $("#UrlCheckFiscalServiceConnectivity").val(),
            success: function (isServiceAvailable) {
                if (isServiceAvailable) {
                    $().customModal({
                        destroyOnClose: true,
                        title: $("#LocAvailable").val(),
                        showCloseButton: true,
                        type: "success",
                        text: $("#LocFiscalizationServiceIsAvailable").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#LocOk").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
                else {
                    showErrorModal($("#LocUnavailable").val(), $("#LocFiscalizationServiceIsUnavailable").val());
                }
            },
            error: function () {
                showErrorModal($("#LocError").val(), $("#LocErrorHappenedWhileCheckingFiscalServiceConnectivity").val() + ".");
            }
        });
    });

    $("#btnRegisterCompanyUnit").on("click", function () {
        RaiseCompanyUnitRegistrationPopup();
    });
}

function GenerateErrorMessagesHtml(errorMessages) {
    var errorMessagesHtml = "<ul style=\"text-align:left;\">";
    for (var rowIndex = 0; rowIndex < errorMessages.length; rowIndex++) {
        if (errorMessages[rowIndex] && errorMessages[rowIndex].length > 0) {
            errorMessagesHtml += "<li>" + errorMessages[rowIndex] + "</li>";
        }
    }
    errorMessagesHtml += "</ul>";
    return errorMessagesHtml;
}

function RaiseCompanyUnitRegistrationPopup() {
    $().customModal({
        destroyOnClose: true,
        title: $("#LocCompanyUnitRegistration").val(),
        showCloseButton: true,
        type: "question",
        text: $("#IsRegisteredWithFiscalAuthority").val() === "True" ? $("#LocAreYouSureYouWantToSendCompanyUnitChange").val() : $("#LocAreYouSureYouWantToRegisterCompanyUnit").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#LocNo").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#LocYes").val(),
                action: function () {
                    $.ajax({
                        method: "POST",
                        url: $("#UrlCompanyUnitRegister").val(),
                        data: { companyUnitId: $("#Id").val() },
                        success: function (registrationResponse) {
                            if (registrationResponse !== null) {
                                // bool IsRegistered { get; set; }
                                // string RegistrationError { get; set; }
                                // IEnumerable<string> ValidationErrors { get; set; }

                                // confirmation popup on registration success.
                                if (registrationResponse.IsRegistered) {
                                    $().customModal({
                                        destroyOnClose: true,
                                        title: $("#LocCompanyUnitRegistered").val(),
                                        showCloseButton: true,
                                        type: "success",
                                        text: $("#LocYouHaveRegisteredThisCompanyUnitWithFiscalAuthority").val(),
                                        buttons: [
                                            {
                                                icon: 'fa fa-check',
                                                text: $("#LocOk").val(),
                                                action: function () {
                                                    location.reload();
                                                },
                                                closeOnAction: true,
                                                type: 'primary'
                                            }
                                        ]
                                    });

                                    $("#btnRegisterCompanyUnit").hide();
                                    $("#alertCompanyUnitNotRegistered").hide();
                                    $("#alertCompanyUnitRegistered").show();
                                }
                                else {
                                    var errorMessages = [registrationResponse.RegistrationError];
                                    errorMessages = errorMessages === undefined || errorMessages.length === 0 ? [""] : errorMessages;
                                    let errorMessagesHtml = errorMessages.length > 1 ? GenerateErrorMessagesHtml(errorMessages) : errorMessages[0];

                                    $().customModal({
                                        destroyOnClose: true,
                                        title: $("#LocErrorHappenedWhileRegisteringCompanyUnit").val(),
                                        showCloseButton: true,
                                        type: "error",
                                        text: errorMessagesHtml,
                                        buttons: [
                                            {
                                                icon: 'fa fa-check',
                                                text: $("#LocOk").val(),
                                                closeOnAction: true,
                                                type: 'primary'
                                            }
                                        ]
                                    });
                                }
                                //else if (registrationResponse.ValidationErrors.length > 0) {
                                //    let errorMessagesHtml = GenerateErrorMessagesHtml(registrationResponse.ValidationErrors);
                                //    swal({ title: $("#LocInvalidCompanyUnitData").val(), text: errorMessagesHtml, type: "error", html: true });
                                //}
                            }
                            else {
                                showErrorModal($("#LocError").val(), $("#LocErrorHappenedWhileRegisteringCompanyUnit").val() + ".");
                            }
                            $("#btnRegisterCompanyUnit").find("i").addClass("fa-paper-plane").removeClass("fa-spinner fa-spin");
                        },
                        error: function () {
                            showErrorModal($("#LocError").val(), $("#LocErrorHappenedWhileRegisteringCompanyUnit").val() + ".");
                            $("#btnRegisterCompanyUnit").find("i").addClass("fa-paper-plane").removeClass("fa-spinner fa-spin");
                        }
                    });
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function RaiseCompanyUnitClosePopup() {
    $().customModal({
        destroyOnClose: true,
        title: $("#LocCompanyUnitClose").val(),
        showCloseButton: true,
        type: "alert",
        text: $("#LocAreYouSureYouWantToCloseCompanyUnit").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#LocNo").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#LocYes").val(),
                action: function () {
                    $("#btnCloseCompanyUnit").find("i").removeClass("fa-ban").addClass("fa-spinner fa-spin");
                    $.ajax({
                        method: "POST",
                        url: $("#UrlCompanyUnitClose").val(),
                        data: { companyUnitId: $("#Id").val() },
                        success: function (registrationResponse) {
                            if (registrationResponse !== null) {
                                if (registrationResponse.IsClosed) {
                                    $().customModal({
                                        destroyOnClose: true,
                                        title: $("#LocCompanyUnitClosed").val(),
                                        showCloseButton: true,
                                        type: "success",
                                        text: $("#LocYouHaveRegisteredThisCompanyUnitClosingWithFiscalAuthority").val(),
                                        buttons: [
                                            {
                                                icon: 'fa fa-check',
                                                text: $("#LocOk").val(),
                                                closeOnAction: true,
                                                type: 'primary'
                                            }
                                        ]
                                    });

                                    $("#IsActive").val("False");
                                    $("#CloseDate").val(registrationResponse.DisplayDate);
                                    $("#CloseDate").closest(".form-group").removeClass("hidden");
                                    $("#btnCloseCompanyUnit").hide();
                                    $("#alertCompanyUnitRegistered").hide();
                                }
                                else {
                                    var errorMessages = [registrationResponse.RegistrationError];
                                    let errorMessagesHtml = GenerateErrorMessagesHtml(errorMessages);
                                    showErrorModal($("#LocGeneralError").val(), errorMessagesHtml);
                                }
                            }
                            else {
                                showErrorModal($("#LocError").val(), $("#LocGeneralError").val() + ".");
                            }
                            $("#btnCloseCompanyUnit").find("i").addClass("fa-ban").removeClass("fa-spinner fa-spin");
                        },
                        error: function () {
                            showErrorModal($("#LocError").val(), $("#LocGeneralError").val() + ".");
                            $("#btnCloseCompanyUnit").find("i").addClass("fa-ban").removeClass("fa-spinner fa-spin");
                        }
                    });
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function showErrorModal(title, text) {
    $().customModal({
        destroyOnClose: true,
        title: title,
        showCloseButton: true,
        type: "error",
        text: $("#LocGeneralError").val() + ": " + text,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#LocOk").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function removeCompanyUnit() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#ConfirmDeleteLoc").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#LocNo").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#LocYes").val(),
                action: async function () {
                    var elementId = $("#Id").val();
                    const config = {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: elementId })
                    };

                    const response = await fetch($("#RemoveCompanyUnitUrl").val(), config);
                    if (response.ok) {
                        const json = await response.json();
                        if (json.IsDeleted === true)
                            window.location = $("#IndexCompanyUnitUrl").val();
                        else {
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "alert",
                                text: $("#DeleteWasNotSuccessfulLoc").val() + "<br/><br/>" +  json.Error,
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: $("#ConfirmLoc").val(),
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    }
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}