function initializeSubjects() {
    var userCanAccessSubjectsCud = $('#userCanAccessSubjectsCud').val() === 'True';

    var acKey = decodeURI(url.searchParams.get("acKey"));

    var oibColumn = { data: "VAT", name: "acCode", filtertype: "text" };
    if ($("#CurrentUserLoc").val() === $("#LocCodeHR").val())
        oibColumn = { data: "Pin", name: "acPin", filtertype: "text" };

    $dataTable = $('#grid-data');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.Status = $("#Status").val();
                d.Type = $("#Type").val();
            }
        },
        columns: [
            { data: "IsActive", name: "AcActive", render: $.fn.dataTable.render.toggle("T", true), className: 'dt-body-center' },
            { data: "Id", name: "AcSubject", filtertype: "text", render: $.fn.dataTable.render.link("Id") },
            { data: "Name", name: "AcName2", filtertype: "text", render: $.fn.dataTable.render.ellipsis(50, $('#isGDPR').val(), "VAT") },
            { data: "Address", name: "AcAddress", filtertype: "text" },
            oibColumn,
            {
                data: "WayOfSale",
                name: "AcWayOfSale",
                render: function (data, type, full) {
                    if (full.IsBuyer === "T" && full.IsSupplier === "T")
                        return $("#BuyerAndSupplier").val();
                    else if (full.IsBuyer === "T")
                        return $("#BuyerLoc").val();
                    else if (full.IsSupplier === "T")
                        return $("#SupplierLoc").val();
                    else
                        return "";
                }
            }
        ],
        createdRow: function (row, data, dataIndex) {
            if (data.Id == acKey) {
                $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
            }
        }
    });

    $("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
var switcheries = [];
var subjectBankAccounts = [];
var subjectLumpContracts = [];

function initializeSubjectsEdit(isNotModal) {
    $('#SubjectEditData_Id').focus();
    if ($("#SubjectEditData_GenerSubjNoLen").val() > 0)
        $('#SubjectEditData_Name').focus();

    $("#printButton").prop("disabled", false);
    $("#printButton + button").prop("disabled", false);

    if (isNotModal && $("#Type").val() === $("#SubjectsMenuTypeBasicInfo").val()) {
        $("#subject-buttons #printButton").addClass("hidden");
        $("#subject-buttons #printButton + button").addClass("hidden");
    }

    initializePostTypeahead($('#SubjectEditData_ZipCode').attr('dataUrl'), $('#SubjectEditData_ZipCode'), $("#SubjectEditData_ZipCode"), function (post) {
        if (post.value) {
            var iso = post.value.substring(0, 2);
            $("#SubjectEditData_SelectedCountryId").val(iso);
            $("#SubjectEditData_SelectedCountryId").trigger("change");
        }
    });

    initializeBankTypeahead($('#SearchBanksUrl').val(), $('#subjectAccountBankValue'), $("#subjectAccountBankValue"));

    if ($("#IsEdit").val() === "True") {
        FillSubjectBankAccounts();
        FillSubjectLumpContracts();
    }

    $("#SubjectEditData_SelectedCountryId").on('change', function () {
        $("#SubjectEditData_Country").val($("#SubjectEditData_SelectedCountryId option:selected").attr("data-country"));
        $("#VATPrefix").val($("#SubjectEditData_SelectedCountryId option:selected").val());
    });

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

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

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

    if (!isNotModal) {
        $("#search-dialog").on("hidden.bs.modal", function () {
            $("body").addClass("modal-open");
        });
    }

    displaySubjectTypeData();
    displaySubjectLumpContracts();

    $("#IsBuyer").on('change', function () {
        $("#buyerData").css("display", $(this).is(':checked') ? "block" : "none");

        if (!$(this).is(':checked')) {
            CheckSubjectUsage("Buyer", $(this));
        } else {
            if ($("#VATPrefix option:selected").val())
                $("#SubjectEditData_WayOfSale").val($("#WayOfSaleIsTaxComitted").val());
            else
                $("#SubjectEditData_WayOfSale").val($("#WayOfSaleFinalBuyer").val());

            $("#SubjectEditData_WayOfSale").trigger("change");
        }
    });

    $("#IsSupplier").on('change', function () {
        $("#supplierData").css("display", $(this).is(':checked') ? "block" : "none");

        if (!$(this).is(':checked')) {
            CheckSubjectUsage("Supplier", $(this));
        } else {
            if ($("#VATPrefix option:selected").val())
                $("#WayOfSaleSupplier").val($("#WayOfSaleDomesticTaxpayers").val());
            else
                $("#WayOfSaleSupplier").val($("#WayOfSaleFinalBuyer").val());

            $("#WayOfSaleSupplier").trigger("change");
        }
    });

    $("#SubjectEditData_WayOfSale, #WayOfSaleSupplier").on('change', function () {
        displaySubjectLumpContracts();
        onChangeWayOfSale(this.id);
    });

    $("#IsWarehouse").on('change', function () {
        $("#warehouseData").css("display", $(this).is(':checked') ? "block" : "none");

        if (!$(this).is(':checked')) {
            CheckSubjectUsage("Warehouse", $(this));
        }
    });

    $("#SubjectEditData_BudgedUser").on('change', function () {
        if ($(this).val() > 0) {
            $("#jbkjsContainer").attr("hidden", false);
        } else {
            $("#jbkjsContainer").attr("hidden", true);
        }
    });

    $("#Search").on("keypress", function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $("#ajpesSearch").trigger("click");
        }
    });

    var selectedRow;
    $("#ajpesSearch").on("click", function () {
        if ($("#Search").val() === '')
            return;

        var button = $(this);
        button.addClass("disabled");
        button.find("i").removeClass("fa-search").addClass("fa-spinner fa-spin");

        var search = $("#Search").val();
        var vat = ""; //$('#VAT').val();
        var name = ""; //$('#SubjectEditData_Name').val();
        var address = ""; //$('#Street').val();
        var zipCode = ""; //$('#ZipCode').val();
        var town = ""; //$('#Town').val();
        var maxItems = $("#ajpesMaxItems").val();
        var forCountry = $("#ForCountry").val();

        if (!isNaN(search) || (search.startsWith('SI') && !isNaN(search.split('SI')[1]))) {
            vat = search;
        }
        else {
            name = search;
        }
        vat = vat.match(/\d+/g);

        selectedRow = null;
        $.ajax({
            method: "POST",
            url: $("#AjpesUrl").val(),
            data: {
                vat: vat,
                name: name,
                address: address,
                zipCode: zipCode,
                town: town,
                forCountry: forCountry,
                maxItems: maxItems
            },
            success: function (result) {
                if (result && result.length === 1) {
                    var res1 = result[0];
                    FillResults(res1);
                }
                else if (result && result.length > 1) {
                    $("#search-dialog").appendTo("body");
                    $("#mainGrid").bootgrid("clear").bootgrid("append", result);
                    $("#search-dialog").modal('show');
                }
                else {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: $("#LocAjpesNoResults").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            },
            complete: function () {
                button.find("i").addClass("fa-search").removeClass("fa-spinner fa-spin");
                button.removeClass("disabled");
            }
        });
    });

    $("#mainGrid").bootgrid({
        caseSensitive: false,
        rowCount: -1,
        templates: {
            search: "",
            header: "",
            infos: "",
            footer: ""
        },
        formatters: {
            commands: function (column, row) {
                return "<button class=\"btn btn-xs btn-checkbox command-edit\" data-row-id=\"" + row.Selector + "\"><span class=\"glyphicon glyphicon-ok transparent-icon\"></span></button>";
            },
            text: function (column, row) {
                return "<span title='" + row[column.id] + "'>" + row[column.id] + "</span>";
            }
        }
    }).on("click.rs.jquery.bootgrid", function (e, columns, row) {
        if (row) {
            $(this).find('.selected-row').removeClass('selected-row');
            $(this).find("tr[data-row-id=" + row.Selector + "]").addClass('selected-row');
            $(this).find(".visible-icon").removeClass("visible-icon").addClass("transparent-icon");
            $(this).find("tr[data-row-id=" + row.Selector + "] .command-edit span").addClass("visible-icon").removeClass("transparent-icon");
            selectedRow = row;
        }
    });

    $("#search-selection-finish").on('click', function () {
        if (!selectedRow) return;

        FillResults(selectedRow);
        $("#search-dialog").modal('hide');
    });

    $("#SubjectEditData_VAT").on('change', function () {
        if ($("#CurrentLoc").val() !== $("#MELoc").val()) {
            $.get($("#GetVATValidationUrl").val() + "?taxId=" + $("#SubjectEditData_VAT").val() + "&loc=" + $("#VATPrefix option:selected").val(), function (response) {
                if (response) {
                    var p = checkIfVATExists();
                    p.then(function (result) {
                        if (result) {
                            return;
                        }
                        showIrisModal6971();
                    }).catch(function (err) {
                        // JSON wasn't parsed because of empty response, which is throwing error
                        // no response means no subject with same VAT exists
                        if (p.status === 200) {
                            showIrisModal6971();
                        }
                    });
                }
                else
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: $("#InvalidVATWarning").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            });
        }
    });

    $('#VATPrefix').on('change', function () {
        showIrisModal6971();
    });

    initializeSubjectContactData();
}

function onChangeWayOfSale(id) {
    var vatCodePrefix = "";
    var wayOfSale = $("#SubjectEditData_WayOfSale option:selected").val();
    var wayOfSaleSupplier = $("#WayOfSaleSupplier option:selected").val();

    $.get($("#IsEUISOCodeUrl").val() + "?vatCode=" + $("#SubjectEditData_SelectedCountryId option:selected").val(), function (response) {
        var isEuVatCode = response === true;

        if ((id === "SubjectEditData_WayOfSale" && wayOfSale === 'K') || (id === "WayOfSaleSupplier" && wayOfSaleSupplier === 'K') || isEuVatCode === false) {
            vatCodePrefix = "";
        } else {
            if (isEuVatCode === true)
                vatCodePrefix = $("#SubjectEditData_SelectedCountryId option:selected").val();
            else
                vatCodePrefix = "";
        }

        var showIRIS = true;
        if ($("#CurrentLoc").val() === $("#HRLoc").val()) {
            if (wayOfSale !== $("#CurrentWayOfSale").val()) {
                showIRIS = (wayOfSale === 'I' || $("#CurrentWayOfSale").val() === 'I');
            } else if (wayOfSaleSupplier !== $("#CurrentWayOfSaleSupplier").val()) {
                showIRIS = (wayOfSaleSupplier === 'U' || $("#CurrentWayOfSaleSupplier").val() === 'U');
            }
        }
        $("#Current_" + id).val($("#" + id + " option:selected").val());

        if (showIRIS === true && $("#VATPrefix option:selected").val() !== vatCodePrefix) {
            if ($("#IsEdit").val() === "True") {
                $("#changeSubjectVatPrefix").attr("onclick", "changeSubjectVatPrefix('" + vatCodePrefix + "')");
                $("#subjectWayOfSaleChangedModal").modal("show");
            } else {
                changeSubjectVatPrefix(id, vatCodePrefix);
            }
        }
    });
}

function displaySubjectLumpContracts() {
    if ($("#WayOfSaleSupplier option:selected").val() === $("#WayOfSaleFlatrate").val()) {
        $("#SubjectWayOfSaleSupplierContainer").removeClass("col-md-9").addClass("col-md-4");
        $("#SubjectLumpContractsContainer").attr("hidden", false);
    } else {
        $("#SubjectWayOfSaleSupplierContainer").addClass("col-md-9").removeClass("col-md-4");
        $("#SubjectLumpContractsContainer").attr("hidden", true);
    }
}

function displaySubjectTypeData() {
    $("#buyerData").css("display", $("#IsBuyer").is(':checked') ? "block" : "none");
    $("#supplierData").css("display", $("#IsSupplier").is(':checked') ? "block" : "none");
    $("#warehouseData").css("display", $("#IsWarehouse").is(':checked') ? "block" : "none");
}

function changeSubjectVatPrefix(vatCodePrefix) {
    $("#VATPrefix").val(vatCodePrefix);
    showIrisModal6971();
}

function checkIfVATExists() {
    return $.ajax({
        method: "POST",
        url: $("#getSubjectWithVATUrl").val(),
        data: {
            vat: $("#SubjectEditData_VAT").val(),
            subjectId: $("#IsEdit").val() === "False" ? "" : $("#SubjectEditData_Id").val()
        },
        success: function (result) {
            if (result) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: stringFormat($("#SubjectHasSameRegNumberLoc").val(), result.Id),
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: $("#NoLoc").val(),
                            action: function () {
                                $().customModal({
                                    destroyOnClose: true,
                                    showCloseButton: true,
                                    type: "error",
                                    text: stringFormat($("#SubjectWithRegNoAlreadyExistNoDupplicateAllowedLoc").val(), result.Id),
                                    buttons: [
                                        {
                                            icon: 'fa fa-check',
                                            text: $("#ConfirmLoc").val(),
                                            action: function () { $("#SubjectEditData_VAT").val(""); },
                                            closeOnAction: true,
                                            type: 'primary'
                                        }
                                    ]
                                });
                            },
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: $("#YesLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        }
    });
}

function CheckSubjectUsage(type, $element) {
    $.ajax({
        url: $("#CheckStatusUsageUrl").val(),
        method: "POST",
        data: {
            subjectId: $("#SubjectEditData_Id").val(),
            type: type
        },
        success: function (result) {
            if (result && result.IsUsed === true) {
                $element.trigger('click');

                var errorText = "";
                if (type === "Buyer")
                    errorText = $("#SubjectUsedAsBuyer").val();
                else if (type === "Supplier")
                    errorText = $("#SubjectUsedAsSupplier").val();
                else if (type === "Warehouse")
                    errorText = $("#SubjectUsedAsWarehouse").val();

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

function AddSubjectContactData() {
    if ($("#SubjectContactType").val() && $("#subjectContactValue").val()) {
        switch ($("#SubjectContactType").val()) {
            case $("#subjectContactEmail").val():
                if (!$("#subjectEmail").val()) {
                    AppendSubjectContactData("subjectEmail", $("#subjectContactEmailLoc").val(), $("#subjectContactValue").val());
                    $("#SubjectEditData_Email").val($("#subjectContactValue").val());
                }
                break;
            case $("#subjectContactPhone").val():
                if (!$("#subjectPhone").val()) {
                    AppendSubjectContactData("subjectPhone", $("#subjectContactPhoneLoc").val(), $("#subjectContactValue").val());
                    $("#SubjectEditData_Phone").val($("#subjectContactValue").val());
                }
                break;
            case $("#subjectContactUrl").val():
                if (!$("#subjectUrl").val()) {
                    AppendSubjectContactData("subjectUrl", $("#subjectContactUrlLoc").val(), $("#subjectContactValue").val());
                    $("#SubjectEditData_Url").val($("#subjectContactValue").val());
                }
                break;
            case $("#subjectContactFax").val():
                if (!$("#subjectFax").val()) {
                    AppendSubjectContactData("subjectFax", $("#subjectContactFaxLoc").val(), $("#subjectContactValue").val());
                    $("#SubjectEditData_Fax").val($("#subjectContactValue").val());
                }
                break;
        }

        ClearSubjectContractData();
    }
}

function AppendSubjectContactData(id, type, value) {
    var $row = $('<tr id="contractRow-' + id + '" role="row"></tr>');
    $row.append('<td class="no-padding"><input type="text" id="' + id + '" value="' + type + '" class="form-control" readonly /></td>');
    $row.append('<td class="no-padding"><input type="text" value="' + value + '" class="form-control" readonly /></td>');
    $row.append('<td class="text-center no-padding"><button class="btn-link" type="button" onclick="removeSubjectContractData(' + "'" + id + "'" + ')"><i class="far fa-trash-alt m-t-sm"></i></button></td>');
    $("#subject-contacts").append($row);
}

function removeSubjectContractData(id) {
    switch (id) {
        case "subjectEmail": $("#SubjectEditData_Email").val(""); break;
        case "subjectPhone": $("#SubjectEditData_Phone").val(""); break;
        case "subjectUrl": $("#SubjectEditData_Url").val(""); break;
        case "subjectFax": $("#SubjectEditData_Fax").val(""); break;
    }

    $("#contractRow-" + id).remove();
}

function clearSubjectContractDataTable() {
    removeSubjectContractData("subjectEmail");
    removeSubjectContractData("subjectPhone");
    removeSubjectContractData("subjectUrl");
    removeSubjectContractData("subjectFax");
}

function ClearSubjectContractData() {
    $("#SubjectContactType").val("");
    $("#subjectContactValue").val("");
}

function AppendSubjectBankAccountData(dataModel) {
    if (!dataModel)
        return;

    var $row = $('<tr id="row-' + dataModel.AnNo + '" role="row"></tr>');
    $row.append('<td class="text-center no-padding"><input type="checkbox" id="default-' + dataModel.AnNo + '" value="' + dataModel.Default + '" class="custom-checkbox default-cb" ' + (dataModel.Default ? " checked" : "") + ' onchange="changeBankAccount(' + dataModel.AnNo + ')" /></td>');
    $row.append('<td class="no-padding"><input type="text" id="bnkAcctNo1-' + dataModel.AnNo + '" value="' + dataModel.BnkAcctNo1 + '" class="form-control" onchange="changeBankAccount(' + dataModel.AnNo + ')" autocomplete="off" /></td>');
    $row.append('<td class="no-padding"><input type="text" id="bankName-' + dataModel.AnNo + '" value="' + dataModel.Name + '" class="form-control typeahead_3" onchange="changeBankAccount(' + dataModel.AnNo + ')" autocomplete="off" /></td>');
    $row.append('<td class="no-padding"><input type="text" id="bankNote-' + dataModel.AnNo + '" value="' + dataModel.Note + '" class="form-control" onchange="changeBankAccount(' + dataModel.AnNo + ')" autocomplete="off" /></td>');
    $row.append('<td class="text-center no-padding"><input type="checkbox" id="blocked-' + dataModel.AnNo + '" value="' + dataModel.Blocked + '" class="custom-checkbox" ' + (dataModel.Blocked ? " checked" : "") + ' onchange="changeBankAccount(' + dataModel.AnNo + ')" /></td>');
    $row.append('<td class="text-center no-padding"><button class="btn-link" onclick="deleteBankAccount(' + dataModel.AnNo + ')"><i class="far fa-trash-alt m-t-sm"></i></button></td>');
    $("#subject-trr-accounts").append($row);
    $(".custom-checkbox").customCheckbox();
    initializeBankTypeahead($('#SearchBanksUrl').val(), $('#bankName-' + dataModel.AnNo), $('#bankName-' + dataModel.AnNo));

    $("#subjectAccountNumberValue").val("");
    $("#subjectAccountBankValue").val("");
    $("#subjectAccountNoteValue").val("");
    $("#subjectAccountDefaultValue").attr("checked", false);
    $("#subjectAccountClosedValue").attr("checked", false);
    if (dataModel.Default)
        onAccountDefault(dataModel.AnNo);
    refreshSubjectBankAccountsDisplay();
}

function AddSubjectBankAccount() {
    var model = {
        AnNo: subjectBankAccounts.length > 0 ? subjectBankAccounts[subjectBankAccounts.length - 1].AnNo + 1 : 1,
        BnkAcctNo1: $("#subjectAccountNumberValue").val(),
        Name: $("#subjectAccountBankValue").val(),
        Note: $("#subjectAccountNoteValue").val(),
        Default: $("#subjectAccountDefaultValue").is(':checked'),
        Blocked: $("#subjectAccountClosedValue").is(':checked')
    };

    subjectBankAccounts.push(model);
    AppendSubjectBankAccountData(model);
}

function AddBankAccountDataAjpes(trrs) {
    deleteAllBankAccounts();
    trrs = trrs.split(",");

    for (var i = 0; i < trrs.length; i++) {
        var trr = trrs[i];
        $.get($("#GetBankByCodeUrl").val() + "?code=" + trr, function (response) {
            var model = {
                AnNo: subjectBankAccounts.length > 0 ? subjectBankAccounts[subjectBankAccounts.length - 1].AnNo + 1 : 1,
                BnkAcctNo1: trr,
                Name: response,
                Note: "",
                Default: false,
                Blocked: false
            };

            subjectBankAccounts.push(model);
            AppendSubjectBankAccountData(model);
        });
    }
}

function deleteBankAccount(anNo) {
    subjectBankAccounts.splice(subjectBankAccounts.findIndex(i => i.AnNo === anNo), 1);
    $("#row-" + anNo).remove();
    refreshSubjectBankAccountsDisplay();
}

function deleteAllBankAccounts() {
    for (var i = 0; i < subjectBankAccounts.length; i++) {
        $("#row-" + subjectBankAccounts[i].AnNo).remove();
    }

    subjectBankAccounts = [];
    refreshSubjectBankAccountsDisplay();
}

function refreshSubjectBankAccountsDisplay() {
    var displayAccountNumbers = [];

    if (subjectBankAccounts && subjectBankAccounts.length > 0) {
        for (var i = 0; i < subjectBankAccounts.length; i++) {
            if (subjectBankAccounts[i].Default)
                displayAccountNumbers.unshift(subjectBankAccounts[i].BnkAcctNo1);
            else
                displayAccountNumbers.push(subjectBankAccounts[i].BnkAcctNo1);
        }

        $("#SubjectEditData_BankAccountNumbers").val(displayAccountNumbers.join(", "));
    }
}

function onAccountDefault(anNo) {
    $(".default-cb").prop("checked", false);
    $("#default-" + anNo).prop("checked", true);

    for (var i = 0; i < subjectBankAccounts.length; i++) {
        if (subjectBankAccounts[i].AnNo !== anNo)
            subjectBankAccounts[i].Default = false;
        else
            subjectBankAccounts[i].Default = true;
    }
}

function changeBankAccount(anNo) {
    var bankAccount = subjectBankAccounts[subjectBankAccounts.findIndex(i => i.AnNo === anNo)];

    bankAccount.BnkAcctNo1 = $("#bnkAcctNo1-" + anNo).val();
    bankAccount.Name = $("#bankName-" + anNo).val();
    bankAccount.Note = $("#bankNote-" + anNo).val();
    bankAccount.Blocked = $("#blocked-" + anNo).is(':checked');
    bankAccount.Default = $("#default-" + anNo).is(':checked');

    if (bankAccount.Default)
        onAccountDefault(bankAccount.AnNo);
}

function FillSubjectBankAccounts() {
    $.get($("#GetSubjectBankAccountsUrl").val() + "?subjectId=" + $("#SubjectEditData_Id").val(), function (response) {
        subjectBankAccounts = response;

        if (subjectBankAccounts && subjectBankAccounts.length > 0)
        for (var i = 0; i < subjectBankAccounts.length; i++) {
            AppendSubjectBankAccountData(subjectBankAccounts[i]);
        }
    });
}

function FillSubjectLumpContracts() {
    $.get($("#GetSubjectLumpContractsUrl").val() + "?subjectId=" + $("#SubjectEditData_Id").val(), function (response) {
        subjectLumpContracts = response;

        if (subjectLumpContracts && subjectLumpContracts.length > 0)
            for (var i = 0; i < subjectLumpContracts.length; i++) {
                AppendSubjectLumpContractsData(subjectLumpContracts[i]);
            }
    });
}

function AppendSubjectLumpContractsData(dataModel) {
    if (!dataModel)
        return;

    var $row = $('<tr id="lc-row-' + dataModel.AnNo + '" role="row"></tr>');
    $row.append('<td class="text-center no-padding"><input type="text" id="lc-anNo-' + dataModel.AnNo + '" value="' + dataModel.AnNo + '" class="form-control" onchange="changeLumpContract(' + dataModel.AnNo + ')" readonly /></td>');
    $row.append('<td class="no-padding"><input type="text" id="lc-contract-' + dataModel.AnNo + '" value="' + dataModel.Contract + '" class="form-control" onchange="changeLumpContract(' + dataModel.AnNo + ')" autocomplete="off" /></td>');
    $row.append('<td class="no-padding"><input type="text" id="lc-dateFrom-' + dataModel.AnNo + '"  value="' + dataModel.DateFrom + '" class="form-control datepicker" onchange="changeLumpContract(' + dataModel.AnNo + ')" autocomplete="off" /></td>');
    $row.append('<td class="no-padding"><input type="text" id="lc-dateTo-' + dataModel.AnNo + '"  value="' + dataModel.DateTo + '" class="form-control datepicker" onchange="changeLumpContract(' + dataModel.AnNo + ')" autocomplete="off" /></td>');
    $row.append('<td class="text-center no-padding"><button class="btn-link" onclick="deleteLumpContract(' + dataModel.AnNo + ')"><i class="far fa-trash-alt m-t-sm"></i></button></td>');

    $("#subject-lump-contracts").append($row);
    $('.datepicker').datepicker()
        .on('click', function (e) {
            $(this).select();
        }).on('changeDate', function () {
            $(this).datepicker('hide');
        });

    $("#subjectLumpContractSerialNum").val("");
    $("#subjectLumpContractNumber").val("");
    $("#subjectLumpContractDateFrom").datepicker("setDate", "");
    $("#subjectLumpContractDateTo").datepicker("setDate", "");

    $("#SubjectEditData_PermitLumpCompen").val(dataModel.Contract);
}

function AddSubjectLumpContract() {
    if (subjectLumpContracts && subjectLumpContracts.length > 0) {
        for (var i = 0; i < subjectLumpContracts.length; i++) {
            if (($("#subjectLumpContractDateFrom").val() >= subjectLumpContracts[i].DateFrom && $("#subjectLumpContractDateFrom").val() <= subjectLumpContracts[i].DateTo)
                || ($("#subjectLumpContractDateTo").val() >= subjectLumpContracts[i].DateFrom && $("#subjectLumpContractDateFrom").val() <= subjectLumpContracts[i].DateTo)) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: $("#ContractAlreadyExistsForSelectedPeriodLoc").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            action: function () { $("#subjectLumpContractDateFrom").focus(); },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                return;
            }
        }
    }

    var model = {
        AnNo: subjectLumpContracts.length > 0 ? subjectLumpContracts[subjectLumpContracts.length - 1].AnNo + 1 : 1,
        Contract: $("#subjectLumpContractNumber").val(),
        DateFrom: $("#subjectLumpContractDateFrom").val(),
        DateTo: $("#subjectLumpContractDateTo").val()
    };

    subjectLumpContracts.push(model);
    AppendSubjectLumpContractsData(model);
}

function changeLumpContract(anNo) {
    var subjectLumpContract = subjectLumpContracts[subjectLumpContracts.findIndex(i => i.AnNo === anNo)];

    subjectLumpContract.Contract = $("#lc-contract-" + anNo).val();
    subjectLumpContract.DateFrom = $("#lc-dateFrom-" + anNo).datepicker("getDate");
    subjectLumpContract.DateTo = $("#lc-dateTo-" + anNo).datepicker("getDate");
}

function deleteLumpContract(anNo) {
    subjectLumpContract.splice(subjectLumpContract.findIndex(i => i.AnNo === anNo), 1);
    $("#lc-row-" + anNo).remove();

    if (subjectLumpContracts && subjectLumpContracts.length > 0)
        $("#SubjectEditData_PermitLumpCompen").val(subjectLumpContracts[subjectLumpContracts.length - 1].Contract);
}

function FillResults(res1) {
    if (res1) {
        if ($('#SubjectEditData_Id').val() !== "") {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                id: "rewriteSubjectModal",
                type: "alert",
                text: $("#SubjectRewriteDataLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: $("#NoLoc").val(),
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: $("#YesLoc").val(),
                        action: function () { FillSubjectData(res1); },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            FillSubjectData(res1);
        }
    }
}

function FillSubjectData(res1) {
    clearSubjectContractDataTable();

    $('#SubjectEditData_Name').val(res1.Name);
    if (res1.Address)
        $('#SubjectEditData_Address').val(res1.Address);
    else
        $('#SubjectEditData_Address').val(res1.Street + " " + res1.StreetNumber);
    $('#SubjectEditData_Town').val(res1.ZipCode + " - " + res1.Town);
    $('#SubjectEditData_ZipCode').val(res1.ZipCode);
    if (res1.ZipCode && res1.ZipCode.length >= 2) {
        var iso = res1.ZipCode.substring(0, 2);
        $("#SubjectEditData_SelectedCountryId").val(iso);
    } else {
        $('#SubjectEditData_SelectedCountryId').val($("#ForCountry").val());
    }
    $("#SubjectEditData_SelectedCountryId").trigger("change");
    $('#Region').val(res1.Region);
    $('#SubjectEditData_Country').val(res1.CountryId);
    $('#SubjectEditData_WayOfSale').val(res1.WayOfSale);
    if ($("#IsEdit").val() !== "True") {
        $('#SubjectEditData_Id').val(res1.ShortName !== "" ? res1.ShortName.substring(0, 30).trim() : res1.Name.substring(0, 30).trim());
    }

    if ($("#ForCountry").val() === $("#HRLoc").val()) {
        $('#SubjectEditData_VAT').val(res1.RegNo);
        $('#SubjectEditData_Pin').val(res1.VAT);
        $('#SubjectEditData_PinPrefix').val(res1.VATPrefix);
        $("#SubjectEditData_Pin").trigger("change");
    } else {
        $('#SubjectEditData_RegNo').val(res1.RegNo);
        $('#SubjectEditData_VAT').val(res1.VAT);
        $('#VATPrefix').val(res1.VATPrefix);
        $("#SubjectEditData_VAT").trigger("change");
    }

    $('#SubjectEditData_BankAccountNumbers').val(res1.BankAccountNumbers);
    $("#SubjectEditData_Email").val(res1.Email);
    $("#SubjectEditData_Phone").val(res1.Phone && res1.Phone.length > 20 ? res1.Phone.substr(0, (res1.Phone.indexOf(",") !== -1 ? res1.Phone.indexOf(",") : 20)) : res1.Phone);
    $("#SubjectEditData_Url").val(res1.Url);
    $("#SubjectEditData_Fax").val(res1.Fax && res1.Fax.length > 20 ? res1.Fax.substr(0, (res1.Fax.indexOf(",") !== -1 ? res1.Fax.indexOf(",") : 20)) : res1.Fax);

    initializeSubjectContactData();
    if (res1.BankAccountNumbers)
        AddBankAccountDataAjpes(res1.BankAccountNumbers);
}

function initializeSubjectContactData() {
    if ($("#SubjectEditData_Email").val())
        AppendSubjectContactData("subjectEmail", $("#subjectContactEmailLoc").val(), $("#SubjectEditData_Email").val());
    if ($("#SubjectEditData_Phone").val())
        AppendSubjectContactData("subjectPhone", $("#subjectContactPhoneLoc").val(), $("#SubjectEditData_Phone").val());
    if ($("#SubjectEditData_Url").val())
        AppendSubjectContactData("subjectUrl", $("#subjectContactUrlLoc").val(), $("#SubjectEditData_Url").val());
    if ($("#SubjectEditData_Fax").val())
        AppendSubjectContactData("subjectFax", $("#subjectContactFaxLoc").val(), $("#SubjectEditData_Fax").val());
}

function toggleSwitch(switch_elem, on) {
    if (on && !$(switch_elem)[0].checked) { // turn it on
        $(switch_elem).trigger('click').prop("checked", "checked"); // it was off, turn it on
    } else if (!on && $(switch_elem)[0].checked) { // turn it off
        $(switch_elem).trigger('click').removeProp("checked"); // turn it off
    }
}

function changeAjpesMaxResults() {
    $.ajax({
        url: $("#saveSettingsUrl").val(),
        type: "post",
        data: {
            dropDownName: $("#ajpesMaxResult").val(),
            selectedValue: $("#ajpesMaxItems option:selected").val()
        }
    });
}

function openSubjectTrrModal() {
    $("#subjectTrrModal").modal('show');
}

function openSubjectLumpContractsModal() {
    $("#subjectLumpContractsModal").modal('show');
}

//Create
function initializeSubjectsCreate(isNotModal) {
    initializeSubjectsEdit(isNotModal);
}

function importSubjectsClick() {
    window.location = $("#importSubjectsUrl").val();
}

//Import subjects
var subjects = [];
var validationErrors = [];
var subjectsWithErrors = [];

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

    var drEvent = $('.dropify').dropify({
        messages: {
            'default': $("#DragAndDropOrClick").val(),
            'replace': $("#DragAndDropOrClick").val(),
            'remove': $("#Remove").val(),
            'error': $("#WrongFormat").val()
        },
        error: {
            'fileExtension': ''
        }
    });

    $("#importFileForm").on('change', function (e) {
        if ($(".dropify-wrapper").hasClass("has-preview"))
            uploadFile();
    });

    $("#showOnlyErrors").on('change', function (e) {
        if ($('input#showOnlyErrors').is(':checked')) {
            subjectsImportExcel(subjectsWithErrors);
        } else {
            subjectsImportExcel(subjects);
        }
    });
}

function uploadFile() {
    var formData = new FormData();
    formData.append("file", $('#ImportFile').get(0).files[0]);

    $.ajax({
        url: $("#importFileForm").attr("data-url"),
        type: 'POST',
        dataType: 'json',
        mimeType: 'multipart/form-data',
        contentType: false,
        cache: false,
        processData: false,
        data: formData,
        beforeSend: function (xhr) {
            $("<i class='fas fa-spinner fa-spin fa-2x upload-loader-icon' id='upload-loader'></i>").appendTo(".dropify-preview");
            $("<i class='fas fa-spinner fa-spin fa-2x upload-loader-icon' id='table-loader'></i>").appendTo(".import-table");
        },
        success: function (result) {
            $('#upload-loader').remove();
            $('#table-loader').remove();
            subjects = [];
            validationErrors = [];
            subjectsWithErrors = [];

            if (result.Errors && result.Errors.length > 0) {
                subjects = AddSubjectsToTableList(subjects, result.InvalidSubjects, true);
                subjectsWithErrors = AddSubjectsToTableList(subjectsWithErrors, result.InvalidSubjects);
                $("#errorsCount").text(result.Errors.length);
                validationErrors = result.Errors;
            }

            if (result.SubjectsToInsert && result.SubjectsToInsert.length > 0) {
                subjects = AddSubjectsToTableList(subjects, result.SubjectsToInsert);
                $("#subjectToInsertCount").text(result.SubjectsToInsert.length);
            }

            if (result.SubjectsToUpdate && result.SubjectsToUpdate.length > 0) {
                subjects = AddSubjectsToTableList(subjects, result.SubjectsToUpdate);
                $("#subjectToUpdateCount").text(result.SubjectsToUpdate.length);
            }

            if ($('input#showOnlyErrors').is(':checked')) {
                subjectsImportExcel(subjectsWithErrors);
            } else {
                subjectsImportExcel(subjects);
            }
        }
    });
}

function AddSubjectsToTableList(tableList, subjectList, addToStart = false) {
    if (tableList && tableList.length > 0) {
        if (addToStart === true)
            tableList = [...subjectList, ...tableList];
        else
            tableList = [...tableList, ...subjectList];
    } else {
        tableList = [...subjectList];
    }

    return tableList;
}

function onClickCreateNewSubject() {
    openSubjectModal($("#subjectTypeCreate").val());
}

function setSearchSubjectData(id) {
    $('#SubjectEditData_Id').val(id);
    $('#SubjectEditData_Name').val(id);
    $('#Search').val(id);
    clearSubjectContractDataTable();

    $('#subjectModal').on('shown.bs.modal', function () {
        $("#Search").focus();
    });
}

function subjectsImportExcel(items) {
    $("#uploadContainer").addClass("hidden");
    $("#subjectTableContainer").removeClass("hidden");

    $dataTable = $('#mainGrid');
    if ($.fn.dataTable.isDataTable('#mainGrid')) {
        $("#mainGrid").DataTable().clear();
        $("#mainGrid").DataTable().rows.add(items).draw();
    } else
        $dataTable.DataTable({
            data: items,
            serverSide: false,
            ajax: undefined,
            scroller: false,
            responsive: false,
            paging: false,
            info: false,
            sScrollX: "100%",
            scrollX: true,
            fixedColumns: {
                leftColumns: 3
            },
            columns: [
                { data: "Id", render: $.fn.dataTable.render.input(null, true, "row-", "Id"), visible: false },
                { data: "HasErrors", render: $.fn.dataTable.render.errorStatus("status-", "Id"), className: 'dt-body-center dt-head-center statusIcon' },
                { data: "AcSubject", render: $.fn.dataTable.render.input(null, true, "AcSubject-", "Id", "fixedCol") },
                { data: "AcName2", render: $.fn.dataTable.render.input(null, false, "AcName2-", "Id") },
                { data: "AcName3", render: $.fn.dataTable.render.input(null, false, "AcName3-", "Id") },
                { data: "AcAddress", render: $.fn.dataTable.render.input(null, false, "AcAddress-", "Id") },
                { data: "AcCountry", render: $.fn.dataTable.render.dropdownOptions($("#countryOptions"), "AcCountry-", "Id", "dt-dropdown") },
                { data: "AcPost", render: $.fn.dataTable.render.select2($("#postOptions"), "AcPost-", "Id", "") },
                { data: "AcSKIS", render: $.fn.dataTable.render.dropdownOptions($("#subjectCisOptions"), "AcSkis-", "Id", "dt-dropdown small") },
                { data: "AcActivityCode", render: $.fn.dataTable.render.dropdownOptions($("#subjectACOptions"), "AcActivityCode-", "Id", "dt-dropdown small") },
                { data: $("#CurrentLoc").val() !== $("#HRLoc").val() ? "AcVatCodePrefix" : "AcPincodePrefix", render: $.fn.dataTable.render.dropdownOptions($("#prefixOptions"), "AcVatCodePrefix-", "Id", "dt-dropdown small") },
                { data: $("#CurrentLoc").val() !== $("#HRLoc").val() ? "AcCode" : "AcPin", render: $.fn.dataTable.render.input(null, false, "AcCode-", "Id", "medium") },
                { data: "AcRegNo", render: $.fn.dataTable.render.input(null, false, "AcRegNo-", "Id", "medium") },
                { data: "AcIbanprefix", render: $.fn.dataTable.render.input(null, false, "AcIbanPrefix-", "Id", "small") },
                { data: "AcSwiftcode", render: $.fn.dataTable.render.input(null, false, "AcSwiftCode-", "Id", "medium") },
                { data: "AcBuyer", render: $.fn.dataTable.render.checkbox(null, "AcBuyer-", "Id"), className: 'dt-body-center dt-head-center' },
                { data: "AcSupplier", render: $.fn.dataTable.render.checkbox(null, "AcSupplier-", "Id"), className: 'dt-body-center dt-head-center' },
                { data: "AcBank", render: $.fn.dataTable.render.checkbox(null, "AcBank-", "Id"), className: 'dt-body-center dt-head-center' },
                { data: "AcMunicipality", render: $.fn.dataTable.render.checkbox(null, "AcMunicip-", "Id"), className: 'dt-body-center dt-head-center' },
                { data: "AcWarehouse", render: $.fn.dataTable.render.checkbox(null, "AcWarehouse-", "Id"), className: 'dt-body-center dt-head-center' },
                { data: "AcDept", render: $.fn.dataTable.render.checkbox(null, "AcDept-", "Id"), className: 'dt-body-center dt-head-center' },
                { data: "AcPhone", render: $.fn.dataTable.render.input(null, false, "AcPhone-", "Id") },
                { data: "AcFax", render: $.fn.dataTable.render.input(null, false, "AcFax-", "Id") },
                {
                    data: "AcXmldocType", render: $.fn.dataTable.render.dropdown([
                        { value: "", name: "" },
                        { value: "P", name: $("#paperLoc").val() },
                        { value: "K", name: $("#paperAndElectronicLoc").val() },
                        { value: "E", name: $("#emailEStyleSimpleInvoiceLoc").val() }
                    ], "AcXmlDocType-", "Id", "dt-dropdown")
                },
                {
                    data: "AcWayOfSale", render: $.fn.dataTable.render.dropdown(
                        ($("#CurrentLoc").val() !== "BA" ? [
                            { value: "", name: "" },
                            { value: "Z", name: $("#wayOfSaleIsTaxCommited").val() },
                            { value: "K", name: $("#wayOfSaleFinalBuyer").val() }
                        ] : $("#CurrentLoc").val() === "BA" ? [
                            { value: "", name: "" },
                            { value: "Z", name: $("#wayOfSaleIsTaxCommited").val() },
                            { value: "K", name: $("#wayOfSaleBiH").val() },
                            { value: "S", name: $("#wayOfSaleRS").val() },
                            { value: "B", name: $("#wayOfSaleBiH").val() }
                        ] : []), "AcWayOfSale-", "Id", "dt-dropdown")
                },
                {
                    data: "AcSuppSaleMet", render: $.fn.dataTable.render.dropdown(
                        ($("#CurrentLoc").val() === "SI" ? [
                            { value: "", name: "" },
                            { value: "D", name: $("#wayOfSaleDomesticTaxpayers").val() },
                            { value: "F", name: $("#wayOfSaleFlatrate").val() },
                            { value: "K", name: $("#wayOfSaleOtherNotTaxCommited").val() },
                            { value: "U", name: $("#wayOfSaleImport").val() },
                            { value: "E", name: $("#wayOfSaleExportSaleEU").val() },
                            { value: "N", name: $("#wayOfSaleNonresident").val() }
                        ] : $("#CurrentLoc").val() === "HR" ? [
                            { value: "", name: "" },
                            { value: "1", name: $("#wayOfSaleR1").val() },
                            { value: "2", name: $("#wayOfSaleR2").val() },
                            { value: "K", name: $("#wayOfSaleOtherNotTaxCommited").val() }
                        ] : $("#CurrentLoc").val() === "BA" ? [
                            { value: "", name: "" },
                            { value: "D", name: $("#wayOfSaleDomesticTaxpayers").val() },
                            { value: "U", name: $("#wayOfSaleImport").val() },
                            { value: "K", name: $("#wayOfSaleOtherNotTaxCommited").val() },
                            { value: "N", name: $("#wayOfSaleNonresident").val() }
                        ] : $("#CurrentLoc").val() === "RS" ? [
                            { value: "", name: "" },
                            { value: "D", name: $("#wayOfSaleDomesticTaxpayers").val() },
                            { value: "F", name: $("#wayOfSaleFlatrate").val() },
                            { value: "K", name: $("#wayOfSaleOtherNotTaxCommited").val() }
                        ] : $("#CurrentLoc").val() === "MK" ? [
                            { value: "", name: "" },
                            { value: "D", name: $("#wayOfSaleDomesticTaxpayers").val() },
                            { value: "K", name: $("#wayOfSaleOtherNotTaxCommited").val() },
                            { value: "N", name: $("#wayOfSaleNonresident").val() }
                        ] : []), "AcSuppSaleMet-", "Id", "dt-dropdown lastCol")
                }
            ],
            drawCallback: function () {
                var $selects = $('.dt-select2');

                $('.dt-select2').select2({
                    ajax: {
                        url: $("#postTypeaheadUrl").val(),
                        data: function (params) {
                            return query = {
                                search: params.term
                            };
                        },
                        processResults: function (data) {
                            return {
                                results: data
                            };
                        }
                    },
                    placeholder: $("#selectLoc").val(),
                    allowClear: false
                });

                for (var i = 0; i < $selects.length; i++) {
                    if ($selects[i] && $selects[i].value === "")
                        $("#" + $selects[i].id).next().addClass("table-input-error");
                }
            }
        });

    $(".dt-dropdown").off("change");
    $("input, .dt-dropdown").on("change", function () {
        onChangeTableData($(this));
    });

    $(".dt-select2").on("change", function () {
        onChangeTableData($(this));
    });

    $('#mainGrid').DataTable().columns.adjust();
    DisplayErrors();
    $('.fixedCol').parent('td').addClass('fixedColBorder');
    $('#saveButton').removeClass('disabled');

    $('.fixedCol').on('keydown', function (e) {
        if (e.which === 9) {
            e.preventDefault();
            var id = e.target.id.split('-')[1];
            $("#AcName2-" + id).focus();
        }
    });

    $('.lastCol').on('keydown', function (e) {
        if (e.which === 9) {
            e.preventDefault();
            var id = e.target.id.split('-')[1];
            $("#AcSubject-" + id + ".fixedCol").closest("tr").next().find(".fixedCol").focus();
        }
    });
}

function onChangeTableData($element) {
    var row = $dataTable.DataTable().row($element.closest('tr'));

    if ($element.hasClass("fixedCol")) {
        $("#" + $element[0].id).val($element.val());
        $(".fixedCol#" + $element[0].id).removeClass("table-input-error");
    }

    var subject = getRowData(row.data());
    if (!subject)
        return;
    var inputsWithErrors = $element.closest('tr').find(".table-input-error");

    $.ajax({
        url: $("#ValidateSubjectUrl").val(),
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(subject)
    }).done(function (response) {
        subjects.map(subj => {
            if (subj.Id === subject.Id) {
                subj = subject;
                if (response.Success)
                    subj.HasErrors = false;
            }
        });

        inputsWithErrors.removeClass("table-input-error");

        validationErrors = validationErrors.filter(function (obj) {
            return obj.Id !== subject.Id;
        });

        if (!response.Success) {
            validationErrors = validationErrors.concat(response.Errors);
            $("#status-" + subject.Id).html("<i class='fa fa-times fa-lg text-danger'></i>");
        } else {
            subjectsWithErrors = subjectsWithErrors.filter(function (obj) {
                return obj.Id !== subject.Id;
            });

            $("#status-" + subject.Id).empty();
        }

        DisplayErrors();
    });
}

function getItemsForDropdown(list) {
    var dropdownReadyList = [];
    list.forEach(function (item, index) {
        dropdownReadyList.push({ value: item.Id, name: item.Name });
    });

    return dropdownReadyList;
}

function getRowData(data) {
    if (!data)
        return;
    var subject = data;
    var rowId = data.Id;

    subject.AcSubject = $("#AcSubject-" + rowId).val();
    subject.AcName2 = $("#AcName2-" + rowId).val();
    subject.AcName3 = $("#AcName3-" + rowId).val();
    subject.AcAddress = $("#AcAddress-" + rowId).val();
    subject.AcCountry = $("#AcCountry-" + rowId).val();
    subject.AcPost = $("#AcPost-" + rowId + " option:selected").val();
    subject.AcSKIS = $("#AcSkis-" + rowId).val();
    subject.AcActivityCode = $("#AcActivityCode-" + rowId).val();
    if ($("#CurrentLoc").val() === "HR") {
        subject.AcPincodePrefix = $("#AcVatCodePrefix-" + rowId).val();
        subject.AcPin = $("#AcCode-" + rowId).val();
    } else {
        subject.AcVatCodePrefix = $("#AcVatCodePrefix-" + rowId).val();
        subject.AcCode = $("#AcCode-" + rowId).val();
    }
    subject.AcRegNo = $("#AcRegNo-" + rowId).val();
    subject.AcIbanprefix = $("#AcIbanPrefix-" + rowId).val();
    subject.AcSwiftcode = $("#AcSwiftCode-" + rowId).val();
    subject.AcBuyer = $("#AcBuyer-" + rowId).prop("checked") ? "T" : "F";
    subject.AcSupplier = $("#AcSupplier-" + rowId).prop("checked") ? "T" : "F";
    subject.AcBank = $("#AcBank-" + rowId).prop("checked") ? "T" : "F";
    subject.AcMunicipality = $("#AcMunicip-" + rowId).prop("checked") ? "T" : "F";
    subject.AcWarehouse = $("#AcWarehouse-" + rowId).prop("checked") ? "T" : "F";
    subject.AcDept = $("#AcDept-" + rowId).prop("checked") ? "T" : "F";
    subject.AcPhone = $("#AcPhone-" + rowId).val();
    subject.AcFax = $("#AcFax-" + rowId).val();
    subject.AcXmldocType = $("#AcXmlDocType-" + rowId).val();
    subject.AcWayOfSale = $("#AcWayOfSale-" + rowId).val();
    subject.AcSuppSaleMet = $("#AcSuppSaleMet-" + rowId).val();

    return subject;
}

function DisplayErrors() {
    if (validationErrors && validationErrors.length > 0) {
        validationErrors.forEach(err => {
            $("#" + err.ColumnName + "-" + err.Id).addClass("table-input-error");
            if (err.ColumnName === "AcPost") {
                $("#" + err.ColumnName + "-" + err.Id).next().addClass("table-input-error");
                $("#" + err.ColumnName + "-" + err.Id).removeClass("table-input-error");
            } else if (err.ColumnName === "AcSubject") {
                $(".fixedCol#" + err.ColumnName + "-" + err.Id).addClass("table-input-error");
            }
        });
    }

    var errors = $(".table-input-error");
    if (errors)
        $("#errorsCount").text(errors.length);
}

function SaveProcessedSubjects() {
    var hasErrors = $(".table-input-error");
    if (hasErrors.length > 0)
        return;

    $.ajax({
        method: "POST",
        url: $("#processSubjectsInsertAndUpdateUrl").val(),
        data: { subjects: subjects },
        success: function (response) {
            if (response.Success === true)
                window.location = $("#subjectsIndex").val();
            else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: response.Errors,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        }
    });
}

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

                    const response = await fetch($("#DeleteSubjectUrl").val(), config);
                    if (response.ok) {
                        const json = await response.json();
                        if (json.IsDeleted === true)
                            window.location = $("#subjectsIndex").val();
                        else {
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                id: "subjectAlreadyInUseErrorModal",
                                type: "alert",
                                text: $("#SubjectAlreadyInUseLoc").val(),
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: $("#ConfirmLoc").val(),
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    }
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

async function saveEPayment() {
    var reload = false;
    if ($("#input-ep-type").val() && $("#input-ep-mailbox").val()) {
        await saveEparam(0, false);
        reload = true;
    }

    if ($("#input-ws-mailbox").val()) {
        await saveWebshop(0, false);
        reload = true;
    }

    return reload;
}

async function submitSaveSubject(onSuccess) {
    if ($("#ePayment").length != 0) {
        let reload = await saveEPayment();
        if (reload) {
            location.reload();
        }
    }

    $("#saveButton i").addClass("fa-spin fa-spinner").removeClass("fa-save");

    var formData = $("#subjectForm").serializeArray();
    formData.push({ name: 'SubjectEditData.BankAccountsJsonString', value: JSON.stringify(subjectBankAccounts) });
    formData.push({ name: 'SubjectEditData.LumpContractsJsonString', value: JSON.stringify(subjectLumpContracts) });
    formData.push({ name: 'SubjectEditData.Consignee', value: $("#Consignee").val() ? $("#Consignee").val().join(";") : undefined });
    formData.push({ name: 'SubjectEditData.IdentList', value: $("#IdentList").val() ? $("#IdentList").val().join(";") : undefined });
    formData.push({ name: 'SubjectEditData.Payer', value: $("#Payer").val() ? $("#Payer").val() : "" });

    var url = $("#createSubjectUrl").val();
    if ($("#IsEdit").val() === "True")
        url = $("#editSubjectUrl").val();

    $.post(url, formData)
        .done(function (response) {
            $("#saveButton i").removeClass("fa-spin fa-spinner").addClass("fa-save");

            if (response.Success) {
                if (response.ShowError) {
                    showErrorSaving(response.ErrorType);
                }
                else {
                    var p = paw.utils.value.isFunction(onSuccess) ? onSuccess() : null;
                    paw.utils.async.when(p).then(function () {
                        if ($("#IsEdit").val() === "True")
                            window.location = $("#subjectsIndex").val();
                        else
                            window.location = $("#subjectsIndex").val() + "?search=" + response.id;
                    });
                    
                }
            } else if (!response.Success && response.ErrorGeneratingId) {
                var errMsg = stringFormat($("#FieldRequiredForCreatingKeyLoc").val(), response.subject.ErrorGeneratingId);
                if (response.subject.ErrorGeneratingValue)
                    errMsg = stringFormat($("#FieldRequiredForCreatingKeyLoc").val(), $("#SubjectEditData_GenerSubjNoField").val());
                if (response.subject.ErrorGeneratingProperty)
                    errMsg = stringFormat($("#FieldDoesNotExistLoc").val(), $("#SubjectEditData_GenerSubjNoField").val());

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: errMsg,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {
                $("#saveButton i").removeClass("fa-spin fa-spinner").addClass("fa-save");
                clearValidationErrors();

                if (response.ShowError)
                    showErrorSaving(response.ErrorType);

                if (response.errors)
                    displayResponseValidationErrors(response);
            }
        });
}

function showErrorSaving(errType) {
    var err = "";
    if (errType === $("#SubjectSavingPartBankAcc").val())
        err = $("#BankAccountAlreadyInUseLoc").val();
    else
        err = $("#ErrorSavingLoc").val();

    subjectErrorModal(err);
}

function prepareSubjectTypeSwitchery(type) {
    $("#IsSupplier").trigger('change');
    $("#IsBuyer").trigger('change');

    if (type === $("#BuyerEnum").val())
        $("#IsBuyer").click();
    else if (type === $("#SupplierEnum").val())
        $("#IsSupplier").click();
}

var printWindow;
function print(type) {
    var url = $("#printSubjectUrl").val()
        + "?Subject=" + $("#SubjectId").val()
        + "&ReportType=" + type;

    printWindow = createPrintWindow(printWindow);
    printPAAS(null, false, false, url, false);
}

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

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

//Subject Institution Region
const educationsTableId = "subjectInstitutionEducations";
const safetyAtWorkTableId = "subjectInstitutionSafetyAtWork";
const VZDTabId = "VZDTabId";
const VZDEducationsTabId = "VZD-educations-tab";
const VZDExaminationsTabId = "VZD-examinations-tab";

function saveSubjectInstitutionType() {
    $.ajax({
        method: "POST",
        url: $("#SaveSubjectInstitutionType").val(),
        data: {
            Performer: $("#SubjectId").val(),
            Type: $('input[name="Type"]:checked').val()
        },
        success: function (response) {
            if (!response || !response.Status) {
                subjectErrorModal($("#GeneralErrorLoc").val());
            }
        }
    });
}

function addInstitutionEducation(id) {
    const data = getEducationData(id, educationsTableId);

    $.ajax({
        type: "POST",
        url: $("#AddInstitutionEducationUrl").val(),
        data: data,
        success: function (response) {
            if (!response) {
                subjectErrorModal($("#GeneralErrorLoc").val());
            } else {
                window.location.reload();
            }
        },
        error: function () {
            subjectErrorModal($("#GeneralErrorLoc").val());
        }
    });
}

function editInstitutionEducation(id) {
    const data = getEducationData(id, educationsTableId);
     
    $.ajax({
        type: "POST",
        url: $("#EditInstitutionEducationUrl").val(),
        data: data,
        success: function (response) {
            if (!response) {
                subjectErrorModal($("#GeneralErrorLoc").val());
            }

            if (data.Performer != $("#SubjectId").val()) {
                // Delete row because subject has changed
                $(`#${educationsTableId} #QId-${data.QId}`).closest("tr").remove();

                return;
            }

            if (data.QId != response.QId) {
                // New QId is created, refresh all data
                window.location.reload();
            }
        },
        error: function () {
            subjectErrorModal($("#GeneralErrorLoc").val());
        }
    });
}

function deleteInstitutionEducation(id) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteInstitutionEducationUrl").val(),
        data: { qId: id },
        success: function (response) {
            if (response) {
                if (!response.IsDeleted && response.EducationInProgress) {
                    subjectErrorModal($("#EducationInProgressLoc").val(), false);
                } else if (!response.IsDeleted) {
                    subjectErrorModal($("#GeneralErrorLoc").val(), false);
                } else {
                    $(`#${educationsTableId} #QId-${id}`).closest("tr").remove();
                }
            }
        },
        error: function () {
            subjectErrorModal($("#GeneralErrorLoc").val(), true);
        }
    });
}

function getEducationData(id, tableId) {
    return {
        Type: $(`#${tableId} #EducationType-${id}`).val(),
        FuncKnow: $(`#${tableId} #FuncKnow-${id}`).val(),
        Performer: $(`#${tableId} #Performer-${id}`).val(),
        Occup: $(`#${tableId} #Profession-${id}`).val(),
        Department: $(`#${tableId} #Department-${id}`).val(),
        Note: $(`#${tableId} #Note-${id}`).val(),
        Periodical: $(`#${tableId} #Periodical-${id}`).val(),
        QId: $(`#${tableId} #QId-${id}`).val(),
        Code: $(`#${tableId} #Code-${id}`).val(),
        Duration: formatDurationString(id)
    }
}

function formatSelectedString(select) {
    let value = $('#select2-' + select.id + '-container').text();

    if (value.indexOf(",") > -1) {
        value = value.split(", ")[0];
        $('#select2-' + select.id + '-container').text(value);
    }
}

function setEducationNumber(professionElement, id) {
    const value = $(professionElement).val();
    const firstNumber = value.substring(0, 1);
    $('#Education-' + id).text(firstNumber);
}

function subjectErrorModal(text, reload = true) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        id: "subjectErrorModal",
        type: "alert",
        text: text,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                closeOnAction: true,
                type: 'primary',
                action: function () {
                    if (reload) {
                        window.location.reload();
                    }
                }
            }
        ]
    });
}

function formatDurationString(id) {
    let days = formatTwoDigitString($("#Days-" + id).val()) || "00";
    let hours = formatTwoDigitString($("#Hours-" + id).val()) || "00";
    let minutes = formatTwoDigitString($("#Minutes-" + id).val()) || "00";

    let duration = `${days} ${$("#DurationDays").val()} ${hours} ${$("#DurationHours").val()} ${minutes} ${$("#DurationMinutes").val()}`;

    if (duration.length > 19) {
        duration = duration.substring(0, 19);
    }

    return duration;
}

function formatTwoDigitString(n) {
    if (n) {
        return (n < 10 && n.length < 2 ? "0" : "") + n;
    }
}

function openNoteModal(id, field) {
    const tableId = $(field).closest("table").attr("id");

    $("#institution-note-modal").val($(`#${tableId} #Note-${id}`).val());
    $("#note-modal").data('noteId', id);
    $("#note-modal").data('tableId', tableId);

    $('#note-modal').modal('show');
}

function saveNote() {
    const noteValue = $("#institution-note-modal").val();
    const noteId = $("#note-modal").data('noteId');
    const tableId = $("#note-modal").data('tableId');

    if (noteValue) {
        $(`#${tableId} .note-icon-${noteId}`).addClass("theme-color");
        $(`#${tableId} .note-icon-${noteId}`).removeClass("transparent-color");
    }
    else {
        $(`#${tableId} .note-icon-${noteId}`).removeClass("theme-color");
        $(`#${tableId} .note-icon-${noteId}`).addClass("transparent-color");
    }

    $(`#${tableId} #Note-${noteId}`).val(noteValue);

    if (noteId !== 0 && tableId == educationsTableId) editInstitutionEducation(noteId, educationsTableId); 
    if (noteId !== 0 && tableId == safetyAtWorkTableId) editInstitutionSafetyAtWork(noteId, safetyAtWorkTableId); 
}

function hoverNote() {
    $('.institution-note-wrapper').hover(
        function () {
            $(this).find('.note-hidden-icon').addClass('default-icon-color');
        },
        function () {
            $(this).find('.note-hidden-icon').removeClass('default-icon-color');
        }
    );
}

//Subject Institution Safety at Work Region
function addInstitutionSafetyAtWork(id) {
    const data = getSafetyAtWorkData(id, safetyAtWorkTableId);

    $.ajax({
        type: "POST",
        data: data,
        url: $("#AddInstitutionSafetyAtWorkUrl").val(),
        success: function (response) {
            if (!response) {
                subjectErrorModal($("#GeneralErrorLoc").val());
            } else {
                window.location.reload();
            }
        },
        error: function () {
            subjectErrorModal($("#GeneralErrorLoc").val());
        }
    });
}

function editInstitutionSafetyAtWork(id) {
    const data = getSafetyAtWorkData(id, safetyAtWorkTableId);

    $.ajax({
        type: "POST",
        url: $("#EditInstitutionSafetyAtWorkUrl").val(),
        data: data,
        success: function (response) {
            if (!response) {
                subjectErrorModal($("#GeneralErrorLoc").val());
            }

            if (data.Performer != $("#SubjectId").val()) {
                // Delete row because subject has changed
                $(`#${safetyAtWorkTableId} #QId-${data.QId}`).closest("tr").remove();

                return;
            }

            if (data.QId != response.QId) {
                // New QId is created, refresh all data
                window.location.reload();
            }
        },
        error: function () {
            subjectErrorModal($("#GeneralErrorLoc").val());
        }
    });
}

function deleteInstitutionSafetyAtWork(id) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteInstitutionSafetyAtWorkUrl").val(),
        data: { qId: id },
        success: function (response) {
            if (!response.IsDeleted) {
                subjectErrorModal($("#GeneralErrorLoc").val(), false);
            } else {
                $(`#${safetyAtWorkTableId} #QId-${id}`).closest("tr").remove();
            }
        },
        error: function () {
            subjectErrorModal($("#GeneralErrorLoc").val(), true);
        }
    });
}

function getSafetyAtWorkData(id, tableId) {
    return {
        QId: $(`#${tableId} #QId-${id}`).val(),
        FuncKnow: $(`#${tableId} #FuncKnow-${id}`).val(),
        Type: $(`#${tableId} #Type-${id}`).val(),
        SetOf: $(`#${tableId} #SetOf-${id}`).val(),
        Periodical: $(`#${tableId} #Periodical-${id}`).val(),
        Performer: $(`#${tableId} #Performer-${id}`).val(),
        Note: $(`#${tableId} #Note-${id}`).val(),
        Department: $(`#${tableId} #Department-${id}`).val(),
    }
}

function setActiveVZDTab(button) {
    if (button.id === VZDEducationsTabId) {
        $(button).removeClass('btn-default').addClass('bcg-theme-color');
        $("#" + VZDExaminationsTabId).addClass('btn-default').removeClass('bcg-theme-color');
        localStorage.setItem(VZDTabId, VZDEducationsTabId);

    } else {
        $(button).removeClass('btn-default').addClass('bcg-theme-color');
        $("#" + VZDEducationsTabId).addClass('btn-default').removeClass('bcg-theme-color');
        localStorage.setItem(VZDTabId, VZDExaminationsTabId);
    }

    handleVZDTables();
}

function showHideExaminationsTable(institutionType) {
    if ($(institutionType).val() == $("#VZD").val()) {
        $(".VZD-tabs-wrapper").removeClass("hidden");
        handleVZDTables();
    } else {
        $(".VZD-tabs-wrapper").addClass("hidden");
        handleVZDTables();
    }
}

function displaySubjectInstitutionTable() {
    $("#" + safetyAtWorkTableId).addClass("hidden");
    $("#" + educationsTableId).removeClass("hidden");
}

function displaySubjectInstitutionSafetyAtWorkTable() {
    $("#" + safetyAtWorkTableId).removeClass("hidden");
    $("#" + educationsTableId).addClass("hidden");
}

function handleVZDTables() {
    if ($("#" + VZDEducationsTabId).hasClass("bcg-theme-color")) {
        displaySubjectInstitutionTable();
    } else {
        displaySubjectInstitutionSafetyAtWorkTable();
    }
}

function setInstitutionTypeOrVZDActiveTab() {
    const urlString = window.location.href;
    const url = new URL(urlString);
    const institutionType = decodeURI(url.searchParams.get("institutionType")); 

    if (institutionType == $("#EducationalInstitutionType").val()) {
        $("#educationalInstitution").trigger("click");

        return;
    } 

    const activeVZDTab = localStorage.getItem(VZDTabId);

    if (activeVZDTab) {
        $("#" + activeVZDTab).trigger('click');
    }
}

function showIrisModal6971() {
    if ($("#IsEdit").val() === "True") {
        $("#iris6971Modal").modal("show");
    }
}

function saveAndContactSupport() {
    submitSaveSubject(function () {
        return paw.mod.Aion.fetchEncParameter().then(function (enc) {
            var href = $('#SupportUrl').val();
            href += '?ENC = ' + enc;
            window.open(href, '_blank');
        });
    });
}