var ContentType = Object.freeze({ "invoice": 1, "login": 2 });
var invoiceItems = [];
var selectedIdent = { data: null };
var cashRegisterOpen = false;
var isGDPR = false;
var isTaxPayer = true;
var printSettings = undefined;
var isFiscalPrinter;
var useFiscalPrinterRounding;
var globalCashRegisterLocalization;
var parallelCurrencyFxRate;

var toPayValue = 0;
var paidValue = 0;
var avansValue = 0;
var noteModal = null;

function focusIdentSearch() {
    $('#IdentSearch').next().focus();
}

function enableDate(enable) {
    if (enable) {
        $("#InvoiceDate").prop("disabled", false);
    }
    else {
        $("#InvoiceDate").datepicker("update", new Date($("#defaultInvoiceDate").val()));
        $("#InvoiceDate").prop("disabled", true);
    }
}

function getIdentByAnNo(anNo) {
    return findObjectByKey(invoiceItems, "anNo", toNumber(anNo));
}

function getIdentRowElement(anNo) {
    return $("#invoice tbody").find("#ident_" + anNo);
}

function resetCashier(id) {
    $("#CashRegisterCashiersSelect").val(id);
}

// Initialize when document ready
async function initializeCashRegisterCashRegister(isCashRegisterFiscalPrinter, cashRegisterLocalization, demandPin, localization) {
    if (!$("#DocType").val())
        $("#DocType").val($("#loginDevice").val());
    avansValue = toNumber($("#MoveAdvancePaymentSum").val());
    globalCashRegisterLocalization = cashRegisterLocalization;
    isFiscalPrinter = isCashRegisterFiscalPrinter;

    //Initialize subject edit for modal
    initializeSubjectsEdit();
    hasUnfiscalizedInvoices();
    checkForTaxSetting("I", $("#PartnerWayOfSale").val());

    var addSubjectMousedown = false;
    $("#PartnerName").blur(function () {
        if (addSubjectMousedown) {
            openSubjectModal(this.id);
            addSubjectMousedown = false;
        }
        else {
            createNewSubjectModal($("#PartnerId"), $("#PartnerName"), this.id, $("#SelectedPartnerName"));
        }
    });

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

    $("#NewPartner").mousedown(function () {
        addSubjectMousedown = true;
    });

    if ($("#DocumentTabActive").val() === "True")
        $('[href="#documents"]').tab('show');

    isLPFR = demandPin;
    saveInvoiceJsonUrl = $('#SaveInvoiceJson').data('url');
    LPFRUpdateInvoiceUrl = $('#LPFRUpdateInvoice').data('url');
    lpfrFiscalizationDataUrl = $('#lpfrFiscalizationDataUrl').data('url');
    printPreview = $('#PrintPreview').data('url');
    invoiceIdentsUrl = $('#InvoiceIdents').data('url');
    cashRegisterLoginUrl = $('#CashRegisterLogin').data('url');
    cashRegisterLogOutUrl = $('#CashRegisterLogOut').data('url');
    CashRegisterIndexUrl = $('#CashRegisterIndex').data('url');
    CashRegisterCancelInvoiceUrl = $('#CashRegisterCancelInvoice').data('url');
    CashRegisterRemoveInvoiceUrl = $('#CashRegisterRemoveInvoice').data('url');
    cashRegisterLoginLoc = $('#CashRegisterLoginLoc').data('text');
    cashRegisterLogoutLoc = $('#CashRegisterLogoutLoc').data('text');
    invoiceDisplayErrorLoc = $('#InvoiceDisplayErrorLoc').data('text');
    GeneralErrorLoc = $('#GeneralErrorLoc').data('text');
    loginLoc = $('#LoginLoc').data('text');
    loggingInLoc = $('#LoggingInLoc').data('text');
    invalidLoginLoc = $('#InvalidLoginLoc').data('text');
    requestErrorLoc = $('#RequestErrorLoc').data('text');
    isGDPR = toBoolean($("#IsGDPR").val());
    isTaxPayer = toBoolean($("#IsTaxPayer").val());
    printSettings = $("#PrintSettings").val() && $("#PrintSettings").val().length > 0 ? $("#PrintSettings").val().split(",") : null;
    setStatements($("#Statements"), $("#Statement").val());
    useFiscalPrinterRounding = toBoolean($('#UseFiscalPrinterRounding').val());
    parallelCurrencyFxRate = toNumber($("#ParallelCurrencyFxRate").val());

    if (isTaxPayer)
        $(".tax-payer-visible").show();
    else
        $(".tax-payer-visible").hide();

    changeSubjectRabate(toNumber($("#defaultPartnerRebate").val()));

    $("#IdentSearch").on("focus-custom-typeahead", function () {
        if ($("#IsInitialized").val() === "False") {
            openDepositModal("I", $("#FiscalWorkplaceId").val(), cashRegisterLocalization.currency, cashRegisterLocalization.depositInput,
                cashRegisterLocalization.value, $("#UrlRegisterDeposit").val(), $("#LocError").val(), undefined, undefined, () => { $("#IsInitialized").val("True"); });
        }
    });

    //Initialize dropdowns (item search focus must be after typeahed initialization or else typeahed item hover won't work)
    initializeInvoiceIdentInputs($('#IdentSearch'), PriceType.Pos, DiscountType.SellerDiscount, $("#DefaultDecimalPlacesPrice").val(), $("#Warehouse"), $("#PartnerId"), $("#PartnerWayOfSale"),
        {
            noResults: globalCashRegisterLocalization.noResults, name: globalCashRegisterLocalization.name, ident: globalCashRegisterLocalization.ident, price: globalCashRegisterLocalization.price, stock: globalCashRegisterLocalization.stock, advancedIdentSearch: cashRegisterLocalization.advancedIdentSearch, advancedSearch: cashRegisterLocalization.advancedSearch },
        null, $("#SpecPayment"));
    initializePartnerTypeahead($('#PartnerName').attr('dataUrl'), $('#PartnerName'), $("#PartnerId"), function (item) {
        $("#PartnerWayOfSale").val(item.wayOfSale);
        checkForTaxSetting("I", $("#PartnerWayOfSale").val());
        $("#PartnerAddress").html(item.completeAddress);
        $("#PartnerName").prop("title", $('#PartnerName').val());
        $("#SelectedPartnerName").val(item.value);
        $("#SelectedPartnerPriceRate").val(item.priceRate);
        $("#SelectedPartnerRebate").val(item.rebate);
        changeSubjectRabate(item.rebate);

        var statement = $("#Statement").val();
        if (statement)
            statement += "," + item.statement;
        else
            statement = item.statement;

        $("#Statement").val(statement);
        setStatements($("#Statements"), $("#Statement").val());

        if ($("#UserLoc").val() === $("#LocRS").val() && item.wayOfSale === $("#WayOfSaleTaxCommitted").val()) {
            $("#BuyerID").val(item.vat);
            $("#BuyerIdDef").val("10");
        }

        // Set items prices for subject
        if (invoiceItems.length > 0) {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: $("#BuyerChangedGetIdentPricesLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: $("#NoLoc").val(),
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: $("#YesLoc").val(),
                        action: function () {
                            checkClosedVATPeriod();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        setTimeout(function () {
            $('#IdentSearch').typeahead('close');
            focusIdentSearch();
        }, 100);
    });

    //Initialize datepickers
    $('.datepicker').datepicker().on('click', function (e) {
        $(this).select();
    });

    $('.cashregister-dt-picker').datetimepicker({
        format: 'DD.MM.YYYY HH:mm:ss',
        locale: 'rs-RS'
    }).on('dp.change', function (event) {
        $(this).trigger('change');
    });

    $("#invoice, #invoice-for-payment, #identSearchTable").on("numberinput-error", ".numberInput", function () {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $('#RabateValidationError').data('text'),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    });

    $("#IsFiscalSalesBookSelected").on('change', function () {
        if ($(this).is(":checked")) {
            $("#IsFiscalSalesBookSelected").val(true);
            $("#fiscalSalesBookData").removeClass("hidden");
            enableDate(true);
        }
        else {
            $("#IsFiscalSalesBookSelected").val(false);
            $("#fiscalSalesBookData").addClass("hidden");
            enableDate(false);
        }
    });

    $("#Status").on('change', function () {
        $("#Status").prop("title", $("#Status option:selected").text());
    });

    //Display cash register
    toggleCashRegister(toBoolean($("#IsCashRegisterOpened").val()));
    $("#invoice-loader").addClass("hidden");

    //F8 shortcut for print
    $(document).on('keydown', function (e) {
        if (e.keyCode === 119 && !$(".printDropdown").is(':disabled')) {
            e.preventDefault();
            $('#printButton').trigger('click');
        }
    });

    displayIdents();

    if ($("#CanFiscalize").val() === "False") {
        $("#IdentSearch").closest("tr").find("input").prop('disabled', true);
    }

    if (isFiscalPrinter) setPrinterMethods($("#LocalApiUrl").val(), $("#CentralApiUrl").val(), $("#loginDevice").val());

    $().customModal({
        onCreated: function () {
            $("#paymentMethodsModalContent").remove();
            updatePaymentModalValues(toPayValue, sumPaidValue($("#paymentModal").find(".payment-method-table")), $("#paymentModal"));
            $("#paymentModal").find(".payment-method-table input").on("click", paymentMethodClicked);
            setPrintDropdownToggle($("#paymentModal"));
        },
        onOpen: function () {
            if ($("#SpecPayment option:selected").val() === "N") {
                $('#paymentModal .payment-method-table input[data-fiscalize="0"]').first().trigger("click");
                $('#paymentModal .payment-method-table .paymentTypeInput').prop("disabled", true);
            } else {
                $('#paymentModal .payment-method-table .paymentTypeInput').prop("disabled", false);
                $element = $("#paymentModal .payment-method-table input[data-id='" + $("#PaymentMethodId").val() + "']");
                if ($element && $element.length > 0) {
                    $element.trigger("click");
                    $("#paymentModal .payment-methods-modal-list").animate({
                        scrollTop: $element.offset().top - $("#paymentModal .payment-methods-modal-list").offset().top - 10
                    }, 800);
                }
                else {
                    updatePaymentModalValues(toPayValue, sumPaidValue($("#paymentModal").find(".payment-method-table")), $("#paymentModal"));
                }
            }

            checkForSlipTypePayMethod();
        },
        destroyOnClose: false,
        title: cashRegisterLocalization.invoicePayment,
        showCloseButton: true,
        openOnCreate: false,
        help: $("#PaymentMethodsModalHelpUrl").val(),
        id: "paymentModal",
        class: "custom-modal-mobile-full-size",
        draggable: true,
        type: "modal",
        maxWidth: "680px",
        content: $("#paymentMethodsModalContent").html(),
        buttons: [
            //TODO: uncomment when preview implemented
            /*{
                icon: 'fa fa-eye',
                text: 'Predogled',
                action: function () { console.log("Open preview"); },
                closeOnAction: false,
                type: 'ghost'
            },*/
            {
                icon: 'far fa-calendar-alt',
                text: localization.installmentsLocalization.installments,
                action: async function () {
                    let checkPayments = $("#paymentModal .payment-method-table input[data-sliptype='" + "1" + "']")
                        .toArray()
                        .filter(function (x) { return toNumber($(x).val()) > 0; })
                        .map(x => { return { id: $(x).attr("data-id"), amount: toNumber($(x).val()), name: $(x).attr("data-name") }; });

                    await openInstallmentsModal($("#AcKey").val(), checkPayments, localization.installmentsLocalization, $("#MoveInstallmentsUrl").val() + "?acKey=" + $("#AcKey").val(),
                        $("#CreateMoveInstallmentsUrl").val(), $("#UpdateInstallmentUrl").val(), $("#ClearInstallmentUrl").val(), $("#InstallmentsContractPrintUrl").val(),
                        $("#SearchBanksUrl").val(), $("#InstallmentsHelpUrl").val(),
                        async function () { await invoiceSubmit('', false, false, false); });
                },
                closeOnAction: false,
                type: 'ghost',
                class: 'paymentInstallmentsButton'
            },
            {
                content: $("#POSFinancialOnly").val() === "True" && $("#UserLoc").val() === $("#LocBA").val() ? $("#saveButton")[0].outerHTML : $($("#printersDropdown").html()).removeClass("dropdown").addClass("dropup")[0].outerHTML
            }
        ]
    });

    if (isNewDocumentType($("#loginDevice").val())) {
        if (demandPin) {
            openLpfrPinModal($('#PinUrlLPFR').val(), $("#EnterPinLoc").val(), $("#OkLoc").val(), $("#CancelLoc").val(),
                async function () {
                    focusIdentSearch();

                    let lpfrConnectionSuccess = await checkLpfrConnectionWithToast(
                        $('#AttentionUrlPFR').val(),
                        cashRegisterLocalization.lpfrConnectionSuccessful + ' (' + $("#loginDevice option:selected").text()?.trim() + ')',
                        cashRegisterLocalization.lpfrConnectionFailed + ' (' + $("#loginDevice option:selected").text() + ')'
                    );
                    if (lpfrConnectionSuccess) saveLastDocumentType($("#loginDevice").val());
                },
                function (error) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: false,
                        type: "alert",
                        text: error,
                        closeOtherModals: false,
                        buttons: [
                            {
                                text: $("#OkLoc").val(),
                                icon: 'fa fa-check',
                                closeOnAction: true,
                                action: function () {
                                    $("#lpfrPinModal input").focus();
                                },
                                type: 'primary'
                            },
                        ]
                    });
                },
                undefined,
                localization.lpfrLocalization
            );
        }
        else {
            if ($("#IsCanceled").val() === "False") {
                focusIdentSearch();
            }

            let lpfrConnectionSuccess = true;
            if ($("#UserLoc").val() === $("#LocRS").val() && !isFiscalPrinter) {
                lpfrConnectionSuccess = await checkLpfrConnectionWithToast(
                    $('#AttentionUrlPFR').val(),
                    cashRegisterLocalization.pfrConnectionSuccessful + ' (' + $("#loginDevice option:selected").text()?.trim() + ')',
                    cashRegisterLocalization.lpfrConnectionFailed + ' (' + $("#loginDevice option:selected").text() + ')'
                );
            }

            if (lpfrConnectionSuccess) saveLastDocumentType($("#loginDevice").val());
        }
    }
    if (isFiscalPrinter) {
        if ($("#POSFinancialOnly").val() !== "True" || $("#UserLoc").val() !== $("#LocBA").val()) {
            let machineName = await getLocalMachineName($("#LocalApiUrl").val(), true);
            $.ajax({
                url: $("#ValidPaymentMethods").val(), type: 'GET', cache: false, data: { machineName: machineName, docType: $("#loginDevice").val() }
            }).done(function (data) {
                $("#paymentModal .payment-method-table tr").addClass("invalidPaymentMethod");

                if (data) {
                    data.forEach(payMet => {
                        $("#paymentModal .payment-method-table tr input[data-id='" + payMet.PaymentMethod + "']").closest("tr").removeClass("invalidPaymentMethod");
                    });
                }

                $('#paymentModal .payment-method-table tr.invalidPaymentMethod').remove();

            }).fail(function () {
                $("#paymentModal .payment-method-table tr").remove();
            });
        }
    }

    //Initialize number inputs
    initializeNumberInputs();
    $("#loginDevice").prop("title", $("#loginDevice option:selected").text());
    $("#CashRegisterCashiersSelect").prop("title", $("#CashRegisterCashiersSelect option:selected").text());

    noteModal = new paw.com.noteEditor.NoteEditorPopup({}, {
        popupTitle: cashRegisterLocalization.note,
        save: cashRegisterLocalization.save,
        cancel: cashRegisterLocalization.cancel
    });

    $('.dropify').on('change', function () {
        uploadAttachmentFile(function () {
            $("#cashRegForm").submit();
        }, function () {
            $('.dropify-clear').click();
        });
    });

    var cc = paw.com.CameraCaptureComponent.create($('#camera-capture'), function (captured) {
        uploadAttachmentFile(function () {
            paw.com.CameraCaptureComponent.uploadAsForm($('#cashRegForm')[0], 'uploadFiles', captured, cc).then(function () {
                window.location.reload();
            });
        }, function () {

        });
    });

    dropifyUploadAttachments();
    $(".connectionsTabContainer .linkedDocumentContainer:last").addClass("container-selected");

    var isWorkPlaceClosed = isFiscalWorkplaceClosed();
    if (isWorkPlaceClosed)
        return;
}
async function cashRegisterPayment(element) {
    if ($("#UserLoc").val() === $("#LocME").val()) {
        var $errField;
        var errMsg = "";
        var identMeasUnitEmpty = invoiceItems.find(ident => ident.measurementUnit === "" || ident.measurementUnit === null);
        var identPriceZero = invoiceItems.find(ident => toNumber(ident.price) === 0);

        if (identMeasUnitEmpty !== undefined) {
            errMsg = $("#FiscalizationFailedIdentWithoutMeasUnitLoc").val();
            $errField = $("#measurementUnit-" + identMeasUnitEmpty.AnNo);
        } else if (identPriceZero !== undefined) {
            errMsg = $("#IdentWithPrice0FiscalizationNotPossible").val();
            $errField = $("#price-" + identPriceZero.AnNo);
        }

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

            disableInvoiceGUI(false);
            return;
        }
    }

    $(element).find("i").addClass("fa-spinner fa-spin");
    await invoiceSubmit('', false, false, false);
    if ($("#AcKey").val() && $("#IsCanceled").val() === "False" && $(".advPayConn").length === 0 && $("#DocTypeAdvancePymnt").val() && $("#DocTypeAdvancePymnt").val() !== "")
        moveAdvancePaymentLinks(true, element);
    else {
        $('#paymentModal').customModal('open');
        $(element).find("i").removeClass("fa-spinner fa-spin");
    }
}

function paymentMethodRowClicked(e) {
    if ($(e.target).hasClass("parallelPaymentTypeInput") || $(e.target).hasClass("paymentTypeInput")) return;
    $(e.currentTarget).find("input").first().trigger("click");
}

function paymentMethodModalPaymentReset() {
    $("#paymentModal").find(".payment-method-table input").val("");
    updatePaymentModalValues(toPayValue, sumPaidValue($("#paymentModal").find(".payment-method-table")), $("#paymentModal"));
}

function updatePaymentModalValues(toPay, paid, $modal) {
    toPayValue = toPay;
    paidValue = paid;

    $("#PaymentMethodsModalToPay").text(formatDisplay(2, Math.abs(toPay) + avansValue));
    if (parallelCurrencyFxRate != 1) $("#ParallelPaymentMethodsModalToPay").text(formatDisplay(2, convertToParallelCurency(Math.abs(toPay) + avansValue, parallelCurrencyFxRate)));

    $("#paymentModalPaidValue").text(formatDisplay(2, paid));
    if (parallelCurrencyFxRate != 1) $("#parallelPaymentModalPaidValue").text(formatDisplay(2, convertToParallelCurency(paid, parallelCurrencyFxRate)));

    let overpaid = parseFloat((round(Math.abs(toPay), 2) + round(avansValue, 2) - round(paid, 2)).toFixed(2));

    //Overpaid
    if (overpaid < 0) {
        $("#toPayLabel").hide();
        $("#toReturnLabel").show();
        $(".printDropdown").prop('disabled', false);
        $(".printDropdown + .dropdown-toggle").prop('disabled', false);
        $("#paymentModalOverpaidValue").closest(".payment-methods-modal-totals-container").addClass("highlighted-input");
    }
    //Paid exactly the same
    else if (overpaid === 0) {
        $("#toPayLabel").show();
        $("#toReturnLabel").hide();
        $(".printDropdown").prop('disabled', false);
        $(".printDropdown + .dropdown-toggle").prop('disabled', false);
        $("#paymentModalOverpaidValue").closest(".payment-methods-modal-totals-container").removeClass("highlighted-input");
    }
    //Underpaid
    else {
        $("#toPayLabel").show();
        $("#toReturnLabel").hide();
        if ($("#CanFiscalize").val() === "True") {
            $(".printDropdown").prop('disabled', true);
            $(".printDropdown + .dropdown-toggle").prop('disabled', true);
        }
        $("#paymentModalOverpaidValue").closest(".payment-methods-modal-totals-container").addClass("highlighted-input");
    }

    $("#cashRegisterPaymentBtn").prop('disabled', !invoiceItems || invoiceItems.length === 0);

    $("#paymentModalOverpaidValue").text(formatDisplay(2, Math.abs(overpaid)));
    if (parallelCurrencyFxRate != 1) $("#parallelPaymentModalOverpaidValue").text(formatDisplay(2, convertToParallelCurency(Math.abs(overpaid), parallelCurrencyFxRate)));

    if ($modal) {
        var $inputs = $modal.find(".payment-method-table input");
        $inputs.each((index, input) => {
            if ($(input).val() && toNumber($(input).val()) !== 0) {
                $(input).closest("tr").addClass("row-highlight");
            }
            else {
                $(input).closest("tr").removeClass("row-highlight");
            }
        });
    }
}

function paymentMethodOnKeyUp(e) {

    // up arrow
    if (e.keyCode === 38) {
        $(e.target).closest("tr").prev().find("input").focus();
    }
    // down arrow
    else if (e.keyCode === 40) {
        $(e.target).closest("tr").next().find("input").focus();
    }
}

function paymentMethodOnBlur(e) {
    let $element = $(e.target);
    if (($element.hasClass("parallelPaymentTypeInput") || $element.closest("td").find(".parallelPaymentTypeInput").length > 0) && toNumber($element.val()) !== 0) {
        if($element.hasClass("parallelPaymentTypeInput")){
            $element.closest("td").find(".paymentTypeInput").val(formatDisplay(2, convertFromParallelCurency(toNumber($element.val()), parallelCurrencyFxRate)));
        }
        else {
            $element.closest("td").find(".parallelPaymentTypeInput").val(formatDisplay(2, convertToParallelCurency(toNumber($element.val()), parallelCurrencyFxRate)));
        }
    }
    updatePaymentModalValues(toPayValue, sumPaidValue($element.closest("table")), $element.closest(".custom-modal"));
}

function paymentMethodClicked() {
    if ($(this).val()) return;

    let paymentDifference = Math.abs(toPayValue) + avansValue - paidValue;
    if (paymentDifference <= 0) return;

    if ($(this).hasClass("parallelPaymentTypeInput")) {
        paymentDifference = convertToParallelCurency(paymentDifference, parallelCurrencyFxRate);
    }

    $(this).val(formatDisplay(2, paymentDifference));
    updatePaymentModalValues(toPayValue, sumPaidValue($(this).closest("table")), $(this).closest(".custom-modal"));
    checkForSlipTypePayMethod();
}

function sumPaidValue($table) {
    let inputsPaid = 0;
    var $inputs = $table.find("input:not(.parallelPaymentTypeInput)");
    $inputs.each((index, input) => {
        inputsPaid += toNumber($(input).val());
    });

    return inputsPaid;
}

function checkForSlipTypePayMethod() {
    let checkPaymentMethods = $("#paymentModal .payment-method-table input[data-sliptype='" + "1" + "']").toArray()
        .filter(function (x) { return toNumber($(x).val()) > 0; })
        .map(x => { return { id: $(x).attr("data-id"), amount: toNumber($(x).val()), name: $(x).attr("data-name") }; });

    if (!checkPaymentMethods || checkPaymentMethods.length === 0) {
        $(".paymentInstallmentsButton").prop('disabled', true);
        $(".paymentInstallmentsButton").addClass("hidden");
    } else {
        $(".paymentInstallmentsButton").prop('disabled', false);
        $(".paymentInstallmentsButton").removeClass("hidden");
    }
}

function convertToParallelCurency(value, fxRate) {
    return (value * fxRate).toFixed(2);
}

function convertFromParallelCurency(value, fxRate) {
    return (value / fxRate).toFixed(2);
}

async function addPosition(selectedInvoiceItemData, isLoadingData = false) {
    if ($("#UserLoc").val() === $("#LocRS").val() && checkIdentQuantity(invoiceItems, $("#SelectedItemQuantity"), true) === false)
        return;

    var isWorkPlaceClosed = isFiscalWorkplaceClosed();
    if (isWorkPlaceClosed && isLoadingData == false)
        return;

    let currentIdent = {
        productId: selectedInvoiceItemData.id,
        name: selectedInvoiceItemData.name_only,
        code: selectedInvoiceItemData.id,
        note: selectedInvoiceItemData.note ? selectedInvoiceItemData.note : "",
        quantity: selectedInvoiceItemData.quantity,
        price: selectedInvoiceItemData.price,
        discount: selectedInvoiceItemData.rabate,
        vat: selectedInvoiceItemData.vat,
        vatFiscalCode: selectedInvoiceItemData.vatFiscalCode,
        vatCode: selectedInvoiceItemData.vatCode,
        measurementUnit: selectedInvoiceItemData.measurementUnit,
        incBase: selectedInvoiceItemData.incBase,
        notIncBase: selectedInvoiceItemData.notIncBase,
        incBaseP: selectedInvoiceItemData.incBaseP,
        notIncBaseP: selectedInvoiceItemData.notIncBaseP,
        anNo: selectedInvoiceItemData.anNo ? selectedInvoiceItemData.anNo : generateAnNo(),
        setItemRTPrice: selectedInvoiceItemData.setItemRTPrice,
        setItemWSPrice: selectedInvoiceItemData.setItemWSPrice,
        setItemWSPrice2: selectedInvoiceItemData.setItemWSPrice2,
        setItemPrStPrice: selectedInvoiceItemData.setItemPrStPrice,
        setItemContractPrice: selectedInvoiceItemData.setItemContractPrice,
        setItemContractPriceRabate: selectedInvoiceItemData.setItemContractPriceRabate,
        currency: selectedInvoiceItemData.currency,
        serialNo: selectedInvoiceItemData.serialNo,
        dateDue: selectedInvoiceItemData.dateDue,
        setItemType: selectedInvoiceItemData.setItemType,
        qid: selectedInvoiceItemData.qid,
        vatCalcReceiver: selectedInvoiceItemData.vatCalcReceiver
    };

    invoiceItems.push(currentIdent);
    if (currentIdent.setItemType === $("#SetItemTypePackagedGoods").val())
        onlySave($("#saveButton"), $("#SaveAndLoadPackedGoodsType").val());
    else {
        let newRow = generateIdentRow(currentIdent);
        $("#invoice tbody").append(newRow);
        setDropdownSelectedValue("measurementUnit-" + currentIdent.anNo, currentIdent.measurementUnit);
        reorderColumns(true, newRow);
        $("#invoice")[0].scrollIntoView(false);

        if (!currentIdent.PricesForSelect && $("#CustomerRabatAllowed").val() === "True") {
            if (selectedInvoiceItemData && selectedInvoiceItemData.pricesForSelect && selectedInvoiceItemData.pricesForSelect.length > 0)
                addSelectOptions(selectedInvoiceItemData.pricesForSelect, "selectedItemPriceSelect-" + currentIdent.anNo);
            else {
                var pricesForItem = [];
                pricesForItem.push({ Id: currentIdent.setItemRTPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), currentIdent.setItemRTPrice) + " - " + $("#SellingPriceLoc").val() });
                pricesForItem.push({ Id: currentIdent.setItemWSPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), currentIdent.setItemWSPrice) + " - " + $("#WSPriceLoc").val() });
                pricesForItem.push({ Id: currentIdent.setItemWSPrice2, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), currentIdent.setItemWSPrice2) + " - " + $("#WS2PriceLoc").val() });
                pricesForItem.push({ Id: currentIdent.setItemPrStPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), currentIdent.setItemPrStPrice) + " - " + $("#PrStPriceLoc").val() });
                pricesForItem.push({ Id: currentIdent.setItemContractPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), currentIdent.setItemContractPrice) + " - " + $("#ContractPriceLoc").val(), Rabate: currentIdent.setItemContractPriceRabate });

                addSelectOptions(pricesForItem, "selectedItemPriceSelect-" + currentIdent.anNo);
            }
        }

        $(".custom-select").customSelect();
        $('#invoice tbody tr input.numberInput').trigger("change");
        recalculateItem(currentIdent.anNo);
        updatePrintDisplay();

        if ($("#CheckPositionPriceQty").val() === "True" && (currentIdent.quantity === 0 || currentIdent.price === 0)) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: stringFormat($("#InoicePositionQuantityOrPrice0WarningLoc").val(), currentIdent.anNo),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        if (isLoadingData === false)
            onlySave($("#saveButton"), $("#SaveAndCheckForSerialsType").val());
    }

    $("#loginDevice").prop("disabled", true);
    $("#cashRegisterLoginContainer").addClass("document-head-disabled-input");
}

function displayIdents(onlyNew = false) {
    if ($("#AcKey").val() !== '') {
        disableInvoiceGUI(true);
        $("#identTableLoader").removeClass("hidden");
        var jqxhr = $.ajax({
            url: invoiceIdentsUrl,
            dataType: 'json',
            data: {
                acKey: $("#AcKey").val(),
                subject: $("#PartnerId").val(),
                subjectType: $("#PartnerWayOfSale").val(),
                saleType: "P"
            },
            method: "GET",
            success: function (data) {
                if (data === null) {
                    alert(invoiceDisplayErrorLoc);
                }
                else {
                    data.forEach(function (item) {
                        if (onlyNew === false || (onlyNew === true && $("#ident_" + item.AnNo).length === 0)) {
                            addPosition({
                                id: item.Code,
                                name: item.Name,
                                name_only: item.Name,
                                code: item.Code,
                                note: item.Note,
                                quantity: item.Quantity,
                                price: item.PriceWithVAT,
                                totalPrice: item.TotalPriceWithVAT,
                                rabate: item.Rabate,
                                vat: item.VAT,
                                vatFiscalCode: item.VATFiscalCode,
                                vatCode: item.VATCode,
                                measurementUnit: item.MeasurementUnit,
                                anNo: item.AnNo,
                                incBase: item.IncBase,
                                notIncBase: item.NotIncBase,
                                incBaseP: item.IncBaseP,
                                notIncBaseP: item.NotIncBaseP,
                                setItemRTPrice: item.SetItemRTPrice,
                                setItemWSPrice: item.SetItemWSPrice,
                                setItemWSPrice2: item.SetItemWSPrice2,
                                setItemPrStPrice: item.SetItemPrStPrice,
                                setItemContractPrice: item.SetItemContractPrice,
                                setItemContractPriceRabate: item.SetItemContractPriceRabate,
                                serialNo: item.SerialNo,
                                dateDue: item.DateDue,
                                setItemType: item.SetItemType,
                                qid: item.Qid,
                                vatCalcReceiver: item.VatcalcReceiver
                            }, true);
                        }
                    });
                    disableInvoiceGUI(false);
                    $("#identTableLoader").addClass("hidden");
                }

                updatePaymentModalValues(toPayValue, paidValue, $("#paymentModal"));
            },
            fail: function () {
                alert(invoiceDisplayErrorLoc);
            }
        });
        docTypePermissionCtrl.queue(jqxhr);
    }
}

function openSubjectModal() {
    clearValidationErrors();
    $('#subjectModal form')[0].reset();
    $("#subjectModal").appendTo("body");
    setSearchSubjectData($("#PartnerName").val());
    $("#subjectModal").modal('show');
}

function saveSubject() {
    var formData = $("#subjectForm").serializeArray();

    $.post($("#CreateSubjectUrl").val(), formData)
        .done(function (response) {

            if (response.Success) {
                $("#PartnerId").val(response.subject.Id);
                $("#PartnerName").val(response.subject.Id);
                var partnerAddress = response.subject.Address + (!response.subject.ZipCode ? "" : ", " + response.subject.ZipCode) + (!response.subject.VAT ? "" : ", " + response.subject.VAT);
                $("#PartnerAddress").text(partnerAddress);

                clearValidationErrors();
                $("#subjectModal").modal('hide');
            }
            else {
                clearValidationErrors();

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

function clearValidationErrors() {
    $(".field-validation-valid").text(' ');
}

function displayResponseValidationErrors(response) {
    for (var i = 0; i < response.errors.length; i++) {
        var span = document.getElementById(response.errors[i].Key + "-validation");
        errorText = document.createTextNode(response.errors[i].Value);
        if (span)
            span.appendChild(errorText);
    }
}

function generateAnNo() {
    return invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].anNo + 1 : 1;
}

//Login
var newCashierLogin = false;
function toggleLogin() {
    if (cashRegisterOpen) {
        cashRegisterLogout();
    }
    else {
        newCashierLogin = false;
        openCashierLoginModal();
    }
}

function cashierChanged(element) {
    newCashierLogin = true;
    let selectedCashierId = $(element).val();
    openCashierLoginModal(selectedCashierId);
}

function toggleCashRegister(open, onlyDisable) {
    cashRegisterOpen = open;
    if (toBoolean($("#CanFiscalize").val())) {
        $("#add-position").prop('disabled', !open);
        $(".note-button").prop('disabled', !open);
        $("#InvoiceNote").prop('disabled', !open);
        $("#PartnerName").prop('disabled', !open);
        $("#InvoiceDate").prop('disabled', !open);
        $("#Note").prop('disabled', !open);
        $("#Statement").prop('disabled', !open);
        $("#DiscountPercentage").prop('disabled', !open);
        $("#DiscountAmount").prop('disabled', !open);
        $("#CashRegisterCashiersSelect").prop('disabled', !open);
        $("#loginDevice").prop('disabled', !$("#AcKey").val() ? false : !open);
        $(".operations").prop('disabled', !open);
        $("#FiscSalesBookSetNo").prop('disabled', !open);
        $("#FiscSalesBookSerNo").prop('disabled', !open);
        $("#FiscSalesBookDocNo").prop('disabled', !open);
        $("#IdentSearch").closest("tr").find("input").prop('disabled', !open);
        $("#invoice .ident-editable-field").prop('disabled', !open);
    } else
        disableCreateNewButtons();

    if (!onlyDisable) {
        if (open) {
            displayContent(ContentType.invoice);
        }
        else {
            displayContent(ContentType.login);
        }
    }

    enableDate($("#IsFiscalSalesBookSelected").is(":checked"));
}

function displayContent(contentType) {
    $("#invoice-data").hide().removeClass("hidden");
    $("#invoice-login-alert").hide().removeClass("hidden");
    updatePrintDisplay();

    if (contentType === ContentType.invoice) {
        $("#invoice-data").show();
        $("#invoice-note-Wrapper").show();
        $(".create-subject").show();
        $(".invoice-form").removeClass("hidden");
    }
    else if (contentType === ContentType.login) {
        $("#invoice-login-alert").show();
        $(".create-subject").hide();

        $("#CashRegisterCashiersSelect")
            .focus().addClass("selected-input-item")
            .on("blur", function () { $(this).removeClass("selected-input-item"); });
    }
}

function updatePrintDisplay() {
    if (!isFiscalPrinter) return;

    if (!cashRegisterOpen || !invoiceItems || invoiceItems.length < 1) {
        $(".printDropdown").prop('disabled', true);
        $(".printDropdown + .dropdown-toggle").prop('disabled', true);
    }
    else {
        $(".printDropdown").prop('disabled', false);
        $(".printDropdown + .dropdown-toggle").prop('disabled', false);
    }

    if (printSettings && printSettings.length > 1) {
        $(".printDropdown").closest(".dropdown").addClass("btn-group");
        $(".printDropdown + .dropdown-toggle").show();

        $.each($(".print-option"), function (key, item) {
            if (printSettings.indexOf($(item).attr("data-print")) > -1)
                $(item).show();
            else
                $(item).hide();
        });
    }
    else {
        $(".printDropdown + .dropdown-toggle").hide();
    }
}

function openCashierLoginModal(userId) {
    let $modal = $("#cashierLoginModal");
    if (!$modal.length) return;

    if (userId) {
        $modal.find("#loginPassword").closest(".form-group").show();
        $modal.find("#userId").val(userId);
        $modal.find("#loginPassword").val();
        setTimeout(function () { $modal.find("#loginPassword").focus(); }, 500);
    }
    else {
        $modal.find("#loginPassword").closest(".form-group").hide();
    }

    $modal.find("button[type='submit'] span").text(loginLoc);
    $modal.find("button[type='submit'] i").attr("class", "");

    $modal.modal({
        show: true,
        keyboard: false,
        backdrop: 'static'
    });
}

function cashierRegisterLogin(e) {
    if (newCashierLogin) {
        let $modal = $("#cashierLoginModal");
        if (!$modal.length) return;

        $modal.find(".close").prop('disabled', true);
        $modal.find("button[type='submit'] span").text(loggingInLoc);
        $modal.find("button[type='submit'] i").attr("class", "fa fa-spinner fa-spin");
        $modal.find("#login-modal-validation").text("");

        return;
    }

    if (!$("#loginDevice").val()) {
        cashRegisterLogout();
        return;
    }

    $("#invoice-error").addClass("hidden");
    $("#invoice-loader").removeClass("hidden");
    toggleCashRegister(false, true);

    $.post(cashRegisterLoginUrl, { Id: $("#loginDevice").val() })
        .done(function (data) {
            if (data.success) {
                $("#CashRegisterCashiersSelect").prop("title", $("#CashRegisterCashiersSelect option:selected").text());

                //Refresh until refactor
                window.location.href = CashRegisterIndexUrl;
                return;

                //TODO: uncomment after refactor
                //if (data.moveExists) {
                //    window.location.href = CashRegisterIndexUrl;
                //    return;
                //}
                //else if ($("#AcKey").val()) {
                //    clearInvoice();
                //}

                //getDocTexts($("#DocTextsUrl").val(), $("#Statement"), $("#Statements"), $("#loginDevice").val());

                //$("#invoice-loader").addClass("hidden");
                //setCashierLoginSuccess(data);
                //if (isFiscalPrinter) setPrinterMethods($("#LocalApiUrl").val(), $("#CentralApiUrl").val(), $("#loginDevice").val());
                //$("#DocType").val($("#loginDevice").val());
                //useFiscalPrinterRounding = data.useFiscalPrinterRounding;
                //$("#UseFiscalPrinterRouding").val(useFiscalPrinterRounding);
            } else {
                $("#invoice-loader").addClass("hidden");
                $("#invoice-error").removeClass("hidden");
            }
        })
        .fail(function (err) {
            $("#invoice-loader").addClass("hidden");
            $("#invoice-error").removeClass("hidden");
        });
}

function setCashierLoginSuccess(data) {
    printSettings = data.printerSettings;
    $("#PartnerId").val(data.partnerId);
    $("#defaultPartnerId").val(data.partnerId);
    $("#Note").val(data.defaultNote);

    $("#PartnerName").val(data.partnerId);
    $("#defaultPartnerName").val(data.partnerId);

    $("#PartnerAddress").html(data.partnerAddress);
    $("#defaultPartnerAddress").val(data.partnerAddress);

    $("#PartnerWayOfSale").val(data.partnerWayOfSaleBuyer);
    $("#defaultPartnerWayOfSale").val(data.partnerWayOfSaleBuyer);
    checkForTaxSetting("I", $("#PartnerWayOfSale").val());

    if (data.payMethod)
        $("#PaymentMethodId").val(data.payMethod);

    changeSubjectRabate(data.partnerRebate);

    toggleCashRegister(true);
    focusIdentSearch();
}

function cashRegisterLogout() {
    toggleCashRegister(false);
    $("#invoice-error").addClass("hidden");
    $("#invoice-loader").removeClass("hidden");

    $.post(cashRegisterLogOutUrl)
        .done(function (data) {
            if (data) {
                printSettings = null;

                clearInvoice();
                $("#PartnerName").val("");
                $("#loginDevice").val("");
                $("#invoice-loader").addClass("hidden");
            } else {
                $("#invoice-loader").addClass("hidden");
                $("#invoice-error").removeClass("hidden");
            }
        })
        .fail(function () {
            $("#invoice-loader").addClass("hidden");
            $("#invoice-error").removeClass("hidden");
        });
}

function generateIdentRow(ident) {
    let canFiscalize = toBoolean($("#CanFiscalize").val());
    let identTransformedId = ident.anNo;

    var decimalPlacesPrice = $("#DefaultDecimalPlacesPrice").val();
    var decimalPlacesQuantity = $("#DefaultDecimalPlacesQuantity").val();
    var decimalPlacesValue = $("#DefaultDecimalPlacesValue").val();
    let identRow = '<td><input type="text" class="form-control" disabled value="' + ident.anNo + '" /></td>';
    identRow += '<td onclick="redirectToIdent(&quot;' + ident.code + '&quot;)"><input type="text" id="id-' + ident.anNo + '" class="form-control" value="' + ident.code + '"  title="' + ident.code + '" disabled data-dtp="Write" data-dtp-state="disabled" /></td>';
    identRow += '<td><input type="text" id="name-' + ident.anNo + '" class="identName form-control ident-editable-field" onBlur="recalculateItem(\'' + identTransformedId + '\')" ' + (canFiscalize ? "" : "disabled") + ' value="' + ident.name.replace(/"/g, '&quot;') + '" title="' + ident.name.replace(/"/g, '&quot;') + '" data-dtp="Write" data-dtp-state="disabled" /></td>';
    identRow += '<td><input type="text" id="quantity-' + ident.anNo + '" step="' + decimalPlacesQuantity + '" data-round="' + (decimalPlacesQuantity ? decimalPlacesQuantity : "") + '" min="0" class="identQuantity form-control ident-editable-field numberInput invoice-input text-right required" ' + (canFiscalize ? "" : "disabled") + ' value="' + ident.quantity + '" onKeyPress="identEnterKeyPress(event)" onBlur="changeIdentQuantity(\'' + identTransformedId + '\')" autocomplete="off" data-dtp="Write" data-dtp-state="disabled" /></td>';
    identRow += '<td><select id="measurementUnit-' + ident.anNo + '" class="identMeasurementUnit form-control ident-editable-field custom-select" ' + (canFiscalize ? "" : "disabled") + ' value="' + ident.measurementUnit + '" onchange="recalculateItem(' + identTransformedId + ')" data-dtp="Write" data-dtp-state="disabled">' + $("#measUnitOptions").html() + '</select></td >';

    if ($("#CustomerRabatAllowed").val() !== "True")
        identRow += '<td><input type="text" step="' + decimalPlacesPrice + '" min="0" class="identPrice form-control numberInput invoice-input text-right ident-editable-field required" ' + (canFiscalize ? "" : "disabled") + ' value="' + ident.price + '" onKeyPress="identEnterKeyPress(event)" onBlur="recalculateItem(\'' + identTransformedId + '\')" autocomplete="off" data-dtp="Write" data-dtp-state="disabled" /></td>';
    else
        identRow += '<td><div class="inputSelectContainer"><select id="selectedItemPriceSelect-' + ident.anNo + '" input-id="price-' + ident.anNo + '" value="' + ident.price + '"' +
            ' onchange="document.getElementById(' + "'price-" + ident.anNo + "'" + ').value=this.options[this.selectedIndex].value;recalculateItem(\'' + identTransformedId + '\');formatNumberInput($(document.getElementById(' + "'price-" + ident.anNo + "'" + ')));"' +
            ' class="form-control custom-select ident-editable-field inputSelect"' +
            ' input-onblur="recalculateItem(\'' + identTransformedId + '\')" input-step="' + decimalPlacesPrice + '" min="0" input-val="' + ident.price + '"' +
            ' input-disabled="' + (canFiscalize ? "" : true) + '"' +
            ' input-class="identPrice form-control numberInput invoice-input ident-editable-field text-right inputOnSelect required" autocomplete="off" ' + (canFiscalize ? "" : "disabled") + ' data-dtp="Write" data-dtp-state="disabled" /></div></td>';

    identRow += '<td><input type="text" step="' + decimalPlacesPrice + '" data-min="0" data-max="100" class="identDiscount form-control numberInput invoice-input text-right ident-editable-field required" ' + (canFiscalize ? "" : "disabled") + ' value="' + ident.discount + '" onKeyPress="identEnterKeyPress(event)" onBlur="recalculateItem(\'' + identTransformedId + '\')" autocomplete="off" data-dtp="Write" data-dtp-state="disabled" /></td>';
    identRow += '<td class="' + (!isTaxPayer ? "hidden" : "") + '"><input id="vatPercent-' + ident.anNo + '" value="' + ident.vat + '" class="hidden" /><select class="identVat form-control custom-select ident-editable-field" ' + (canFiscalize ? "" : "disabled") + ' value="' + ident.vatCode + '" onchange="onChangeIdentTax(' + identTransformedId + ')" data-dtp="Write" data-dtp-state="disabled">' + $("#taxOptions").html() + '</select></td>';
    identRow += '<td><input type="text" step="' + decimalPlacesPrice + '" class="identTotalAmount form-control numberInput invoice-input text-right" value="' + calculateItemTotalAmount(ident) + '" disabled /></td>';

    var dropdownActions = '';
    // Part list
    if (ident.setItemType && (ident.setItemType === "P" || ident.setItemType === "U" || ident.setItemType === "G" || ident.setItemType === "H")) {
        dropdownActions =
            '<li class="dropdown-item">' +
            '<button type="button" class="btn btn-link" onclick="checkPartListModal(' + ident.anNo + ')">' +
            '<i class="fa fa-solid fa-cube"></i>' +
            '<span class="m-l-xs">' + $("#SpecificationLoc").val() + '</span>' +
            '</button>' +
            '</li>';
    }

    // Serial numbers
    if (ident.serialNo && ident.serialNo !== "N") {
        dropdownActions +=
            '<li class="dropdown-item">' +
            '<button type="button" class="btn btn-link" onclick="' + (ident.quantity >= 0 ? "checkIdentSerialNoIssue" : "checkIdentSerialNo") + '(' + ident.anNo + ', \`M\`, null, null, \`true\`)">' +
            '<i class="serialNo-icon"></i>' +
            '<span class="m-l-xs">' + $("#SerialNumbersLoc").val() + '</span>' +
            '</button>' +
            '</li>';
    }

    identRow += (
        '<td class="actions-cell">' +
        '<div class="table-expand-button m-r-sm"><span data-toggle="dropdown" aria-expanded="true">' +
        '<i class="fas fa-ellipsis-h clickable-icon"></i>' +
        '</span>' +
        '<ul class="dropdown-menu">' +
        (dropdownActions && dropdownActions != '' ? dropdownActions : '') +
        '<li class="dropdown-item">' +
        '<button id="noteModal-' + ident.anNo + '" onclick="openCashRegisterIdentNoteModal(' + identTransformedId + ')" type="button" class="identNote paw-width-fit paw-text-left btn btn-link ' + (ident.note && ident.note.trim() !== "" ? "btn-active" : "") + '" data-dtp="Write" data-dtp-state="disabled">' +
        (canFiscalize ?
            ('<input id="note-' + ident.anNo + '" value="' + ident.note + '" class="hidden" data-dtp="Write" data-dtp-state="disabled" />' +
            '<input id="acKey-' + ident.anNo + '" value="' + ident.acKey + '" class="hidden" data-dtp="Write" data-dtp-state="disabled" />')
            : '') +
        '<input id="serialNo-' + ident.anNo + '" value="' + ident.serialNo + '" class="hidden" data-dtp="Write" data-dtp-state="disabled" />' +
        '<input id="dateDue-' + ident.anNo + '" value="' + ident.dateDue + '" class="hidden" data-dtp="Write" data-dtp-state="disabled" />' +
        '<input id="qtyOld-' + ident.anNo + '" value="0" class="hidden" data-dtp="Write" data-dtp-state="disabled" />' +
        '<input id="qid-' + ident.anNo + '" value="' + ident.qid + '" class="hidden" data-dtp="Write" data-dtp-state="disabled" />' +
        '<input id="vatCalcReceiver-' + ident.anNo + '" value="' + ident.vatCalcReceiver + '" class="hidden" data-dtp="Write" data-dtp-state="disabled" />' +
        '<i class="fa fa-comment"></i>' +
        '<span class="m-l-xs">' + $("#NoteLoc").val() + '</span>' +
        '</button>' +
        '</li>' +
        '<li role="separator" class="divider"></li>' +
        (canFiscalize ?
            '<li class="dropdown-item">' +
                '<button type="button" id="identRemove-' + ident.anNo + '" onclick="canDeleteItem(' + ident.anNo + ')" class="paw-width-fit paw-text-left btn btn-outline editableInput" data-dtp="Delete" data-dtp-state="disabled"><span class="far fa-trash-alt"></span></button></td>' +
                    '<i class="far fa-trash-alt"></i>' +
                    '<span class="m-l-xs">' + $("#DeleteLoc").val() + '</span>' +
                    '</button>' +
            '</li>' : '') +
        '</ul></div></td>'
    );

    $identRow = $('<tr role="row" id="ident_' + identTransformedId + '">' + identRow + '</tr>');
    $identRow.find('.identVat').val(ident.vatCode);
    $identRow.find('.identMeasurementUnit').val(ident.measurementUnit);
    setNoteButton(ident, $identRow);

    return $identRow;
}

function redirectToIdent(ident) {
    window.location = $("#IdentEditUrl").val() + "?id=" + ident;
}

function canDeleteItem(anNo) {
    $.get($("#canDeleteUrl").val() + "?acKey=" + $("#AcKey").val() + "&anNo=" + anNo, function (response) {
        canDeleteResponse = response;
        if (response.HasConnectedTrafficDocument === true) {
            docHasConnectedTraffic(response.ConnectedTrafficAcKey, response.ConnectedTrafficAnNo, anNo);
        } else {
            removeItem(anNo);
        }
    });
}

function removeItem(anNo) {
    let item = getIdentByAnNo(anNo);
    if (!item) return;

    invoiceItems.splice(invoiceItems.indexOf(item), 1);
    getIdentRowElement(item.anNo).remove();
    recalculateInvoice();
    focusIdentSearch();
    updatePrintDisplay();
    onlySave($("#saveButton"));

    if (toBoolean($("#CanFiscalize").val()) && invoiceItems.length === 0) {
        $("#loginDevice").prop("disabled", false);
        $("#cashRegisterLoginContainer").removeClass("document-head-disabled-input");
    }
}

function identEnterKeyPress(e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        focusIdentSearch();
    }
    return true;
}

function calculateItemTotalAmount(item) {
    if (useFiscalPrinterRounding) {
        let discountedPrice = round(toNumber(item.price) * (1 - toNumber(item.discount) / 100), toNumber($("#RoundPosItem").val()));
        return round(discountedPrice * toNumber(item.quantity), toNumber($("#RoundPosItem").val()));
    }
    else {
        let price = round(toNumber(item.quantity) * toNumber(item.price), toNumber($("#RoundPosItem").val()));
        let discountedPrice = round(toNumber(price) * (1 - toNumber(item.discount) / 100), toNumber($("#RoundPosItem").val()));
        return discountedPrice;
    }
}

function calculateItemTotalExciseAmount(item) {
    var totalPrice = toNumber(item.quantity) * toNumber(item.basisForTax);
    //var discountedPrice = totalPrice * (1 - toNumber(item.discount) / 100);
    return totalPrice;
}

function changeIdentTax(anNo) {
    let $item = getIdentRowElement(anNo);
    var vatPercent = toNumber($item.find(".identVat option:selected").attr("data-vat"));
    $("#vatPercent-" + anNo).val(vatPercent);
    recalculateItem(anNo);
}

function onChangeIdentTax(anNo) {
    let $item = getIdentRowElement(anNo);
    var vatCalcReceiver = $item.find(".identVat option:selected").attr("data-vatcalcreceiver");

    if (vatCalcReceiver === "T") {
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: stringFormat($("#VatCodeWithReversePaymentPosLoc").val(), $item.find(".identVat option:selected").val()),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#NoLoc").val(),
                    action: async function () {
                        canDeleteItem(anNo);
                    },
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#YesLoc").val(),
                    action: async function () {
                        changeIdentTax(anNo);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
}

function changeIdentQuantity(anNo) {
    if (canChangeIdentQuantity(anNo) === false)
        return;

    recalculateItem(anNo);
    if (toNumber($("#quantity-" + anNo).val()) < 0)
        checkIdentSerialNo(anNo, "M");
    else
        checkIdentSerialNoIssue(anNo, "M");
}

function canChangeIdentQuantity(anNo, showModal = true) {
    let ident = getIdentByAnNo(anNo);
    if (($('#identSerialNoGridIssue tbody tr').length > 0 || $('#identSerialNoGrid > tbody > tr').length > 0) &&
        ((ident.quantity > 0 && toNumber($("#quantity-" + anNo).val()) < 0) || (ident.quantity < 0 && toNumber($("#quantity-" + anNo).val()) > 0))) {

        if (showModal) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: $("#CannotChangeSignReleaseSerialsFirstLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        action: function () {
                            $("#quantity-" + anNo).focus();
                        },
                        type: 'primary'
                    }
                ]
            });
        }
        return false;
    }
    return true;
}

function recalculateItem(anNo, invoiceRecalculateInvoice = true) {
    if (canChangeIdentQuantity(anNo, false) === false)
        return;

    let ident = getIdentByAnNo(anNo);
    let $item = getIdentRowElement(anNo);
    if (!ident || !$item.length) return;

    if ($("#UserLoc").val() === $("#LocRS").val())
        checkIdentQuantity(invoiceItems, $item.find(".identQuantity"));

    if ($("#IsCanceled").val() === "False"
        && toNumber($item.find(".identQuantity").val()) < 0
        && $("#UserLoc").val() === $("#LocME").val()) {

        $item.find(".identQuantity").val(0);
        formatNumberInput($item.find(".identQuantity"));

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

    ident.name = $item.find(".identName").val();
    ident.quantity = toNumber($item.find(".identQuantity").val());
    ident.vatCode = $item.find(".identVat").val();
    ident.vat = toNumber($("#vatPercent-" + anNo).val());
    ident.vatFiscalCode = $item.find(".identVat option:selected").attr("data-fiscalCode");
    ident.price = (toNumber($item.find(".identPrice").val()) / (1 + (ident.vat / 100))) * (1 + toNumber($("#vatPercent-" + anNo).val()) / 100);
    ident.discount = toNumber($item.find(".identDiscount").val());
    ident.measurementUnit = $item.find(".identMeasurementUnit").val();
    ident.basisForTax = ((ident.price - ident.notIncBase) / (1 + ident.vat / 100 + ident.notIncBaseP) - ident.incBase) / (1 + ident.incBaseP);

    $item.find(".identPrice").val(ident.price);
    formatNumberInput($item.find(".identPrice"));
    $item.find(".identTotalAmount").val(calculateItemTotalAmount(ident));
    formatNumberInput($item.find(".identTotalAmount"));

    if (invoiceRecalculateInvoice)
        recalculateInvoice();
}

var noteIdent;
function openCashRegisterIdentNoteModal(anNo) {
    var ident = getIdentByAnNo(anNo);
    noteIdent = ident;
    noteModal.show(ident.note, {
        onSave: function (content) {
            ident.note = content;
            setNoteButton(ident);
        }
    });

}

function identNoteSubmit(e) {
    e.preventDefault();
    e.stopPropagation();

    let $modal = $("#noteModal");
    if (!$modal.length) return;
    $modal.modal('hide');

    noteIdent.note = $modal.find("#item-note").val();
    setNoteButton(noteIdent);
    return false;
}

function setNoteButton(ident, $identRow) {
    if (!$identRow)
        $identRow = getIdentRowElement(ident.anNo);

    $identRow.find(".identNote")
        .removeClass("btn-link btn-active")
        .addClass(ident.note.length > 0 ? "btn-link btn-active" : "btn-link");
}

//Invoice Functionalities
function recalculateInvoice() {
    var total = 0;
    var discount = 0;
    var tax = 0;
    var discountedTotal = 0;
    var discountPercentageSum = 0;
    var toPay = 0;

    invoiceItems.forEach(function (item) {
        var calculatedItemTotalExciseAmount = calculateItemTotalExciseAmount(item);
        total += calculatedItemTotalExciseAmount;
        discount += item.price * item.quantity * item.discount / 100;
        var calculatedItemTotalAmount = calculateItemTotalAmount(item);
        let itemTax = (calculatedItemTotalAmount - item.notIncBase) / (100 + item.vat + item.notIncBaseP * 100) * item.vat;
        discountedTotal += calculatedItemTotalAmount;
        tax += itemTax;
        discountPercentageSum += item.discount;
        toPay += item.vatCalcReceiver === "T" ? calculatedItemTotalExciseAmount : calculatedItemTotalAmount;
    });

    $("#TotalAmount").val(round(discountedTotal + discount, toNumber($("#RoundPos").val())));
    formatNumberInput($("#TotalAmount"));
    $("#DiscountAmount").val(discount);
    formatNumberInput($("#DiscountAmount"));
    $("#TaxAmount").val(round(tax, toNumber($("#RoundPos").val())));
    formatNumberInput($("#TaxAmount"));
    $("#TotalValue").val(round(total, toNumber($("#RoundPos").val())));
    formatNumberInput($("#TotalValue"));
    toPayValue = round(toPay, toNumber($("#RoundPos").val()));
    $("#ToPayAmount").val(round(discountedTotal, toNumber($("#RoundPos").val())));
    formatNumberInput($("#ToPayAmount"));
    $("#ToPayAmountDisplay").text($("#ToPayAmount").val());
    updatePaymentModalValues(toPayValue, paidValue, $("#paymentModal"));
    $("#DiscountPercentage").val(invoiceItems.length > 0 ? discountPercentageSum / invoiceItems.length : 0);
    formatNumberInput($("#DiscountPercentage"));
}

function PaymentMethodChanges(element) {
    if ($("#PaymentMethodId").val() === "85") { //TODO: get correct number
        $("#NumberOfDays").prop('disabled', false);
    }
    else {
        $("#NumberOfDays").prop('disabled', true);
    }
}

function clearInvoice() {
    invoiceItems = [];
    $("#invoice tbody").html("");

    $("#NumberOfDays").val("");
    $("#InvoiceNote").val("");
    $("#CurrentClerk").val("True");
    confirmOtherClerk = false;

    $("#InvoiceDate").datepicker("update", new Date());

    $("#FiscSalesBookSetNo").val("");
    $("#FiscSalesBookSerNo").val("");
    $("#FiscSalesBookDocNo").val("");

    if ($("#IsFiscalSalesBookSelected").is(":checked"))
        $("#IsFiscalSalesBookSelected").trigger("click");

    $("#PartnerId").val($("#defaultPartnerId").val());
    $("#PartnerName").val($("#defaultPartnerName").val());
    $("#PartnerAddress").html($("#defaultPartnerAddress").val());
    $("#PartnerWayOfSale").val($("#defaultPartnerWayOfSale").val());
    checkForTaxSetting("I", $("#PartnerWayOfSale").val());

    $("#InvoiceNumber").val("");
    $("#InvoiceNumber").closest("form-group").addClass("hidden");

    $("#AcKey").val("");
    $("#AcKeyDisplayContainer").html("");
    $("#CanFiscalize").val("True");

    $("#Note").val("");
    $("#Statement").val("");
    $("#Department").val($("#defaultDepartment").val());

    $("#invoiceHeadDataDisplay").addClass("hidden");
    $("#invoiceNumberDisplay").html("");

    $("#Statements").val("");
    setStatements($("#Statements"), $("#Statement").val());

    $("#defaultInvoiceDate").val(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).toISOString());
    $("#InvoiceDate").datepicker("update", new Date($("#defaultInvoiceDate").val()));

    $("#newDocumentButton").addClass("hidden");

    $("#cancelationLink").addClass("hidden");

    $("#loginDevice").prop("disabled", false);
    $("#loginDevice").closest(".document-head-disabled-input").removeClass("document-head-disabled-input");

    $("#paymentModal").find(".payment-method-table input").val("");
    paidValue = 0;

    recalculateInvoice();
}

async function onlySave(context, saveType = null) {
    $(context).find('i').removeClass('fa-save').addClass('fa-spin fa-spinner');
    await invoiceSubmit('', false, false, true, saveType);
    $(context).find('i').addClass('fa-save').removeClass('fa-spin fa-spinner');
}

var confirmOtherClerk = false;
var printWindow;
async function invoiceSubmit(printType, isPreview = false, fiscalize = true, closePaymentModal = true, saveType = null, checkHRPaymentLimit = true) {
    var isWorkPlaceClosed = isFiscalWorkplaceClosed();
    if (isWorkPlaceClosed)
        return;

    if (fiscalize === true && !confirmOtherClerk && $("#CurrentClerk").val() === "False") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: $("#DifferentOperatersLoc").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#YesLoc").val(),
                    closeOnAction: true,
                    action: function () {
                        confirmOtherClerk = true;
                        invoiceSubmit(printType, isPreview, fiscalize, closePaymentModal);
                    },
                    type: 'primary'
                },
                {
                    icon: 'fa fa-times',
                    text: $("#NoLoc").val(),
                    closeOnAction: true,
                    action: function () {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: $("#DifferentOperatersTaxingfailedLoc").val(),
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: $("#ConfirmLoc").val(),
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    },
                    type: 'primary'
                }
            ]
        });

        $("#cashRegisterPaymentBtn").removeAttr("disabled");
        return;
    }
    let checkPaymentMethodsCash = $("#paymentModal .payment-method-table input[data-fiscalize='" + "G" + "']").toArray().filter(function (x) { return toNumber($(x).val()) > 700; });
    if ($("#UserLoc").val() === $("#LocHR").val()
        && $("#PartnerWayOfSale").val() === "Z"
        && checkPaymentMethodsCash.length > 0
        && checkHRPaymentLimit === true) {

        disableInvoiceGUI(false);
        let payMetId = checkPaymentMethodsCash[0].id;
        $("#changePaymentTypeIrisModal").attr('onclick', 'focusElement("#' + payMetId + '")');
        $("#ignoreIrisModal").attr('onclick', 'invoiceSubmit("' + printType + '", "' + isPreview + '", "' + fiscalize + '", "' + closePaymentModal + '", "' + saveType + '", "' + false + '")');
        $("#iris1006038Modal").modal("show");
        return;
    }

    if ((toNumber($("#ToPayAmount").val()) > toNumber($("#MaxCashPayment").val())) && (toNumber($("#MaxCashPayment").val()) > 0)) {
        var paymentMethodCash = $("#paymentModal .payment-method-table input[data-fiscalize='" + "G" + "']").toArray();
        if (paymentMethodCash.length > 0) {
            let cashPaymentSum = paymentMethodCash.map(i => toNumber($(i).val())).reduce((a, b) => a + b);
            if (toNumber(cashPaymentSum) > toNumber($("#MaxCashPayment").val())
                && $("#PartnerWayOfSale").val() === "K"
                && fiscalize == true) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: stringFormat($("#MaxCashPaymentErrorLoc").val(), formatDisplay(2, toNumber($("#MaxCashPayment").val()))),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#custom-modal-confirm").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }]
                });
                return;
            }
        }
    }

    $("#cashRegisterPaymentBtn").prop("disabled", true);
    if (fiscalize) {
        let checkPaymentMethods = $("#paymentModal .payment-method-table input[data-sliptype='" + "1" + "']").toArray()
            .filter(function (x) { return toNumber($(x).val()) > 0; })
            .map(x => { return { id: $(x).attr("data-id"), amount: toNumber($(x).val()), name: $(x).attr("data-name") }; });
        let installmentsPaymentsResponse = await checkInstallmentsPayment($("#MoveInstallmentsUrl").val() + "?acKey=" + $("#AcKey").val(),
            checkPaymentMethods, globalCashRegisterLocalization.installmentValueNotCorrectError, globalCashRegisterLocalization.currency);

        if (!installmentsPaymentsResponse.success) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                closeOtherModals: false,
                type: "error",
                text: installmentsPaymentsResponse.errorMessage,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#OkLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            $("#cashRegisterPaymentBtn").removeAttr("disabled");
            return;
        }
    }

    if (!toBoolean($("#CanFiscalize").val()) && (($("#FiscalizationCode").val() && $("#FiscalizationCode").val().length > 0) || isFiscalPrinter)) {
        //TODO: uncomment for PAAS
        //if (!isFiscalPrinter) {
        //    printWindow = window.open();
        //    printWindow.document.write(generatePrintingPage());
        //    printPAAS(printType, !isPreview, isPreview);
        //} else {
        //    printType = printSettings && printSettings.length > 0 ? printSettings[0] : 'printer_80';
        //    window.open(printPreview + "?id=" + $("#AcKey").val() + "&paperSize=" + printType);
        //}

        if (printType === "PDV") {
            printWindow = window.open();
            printWindow.document.write(generatePrintingPage());
            printPAAS("btnPrintTaxRateReport", false, false);
            return;
        }

        if ($("#UserLoc").val() === $("#LocRS").val() && $("#FiscTraining").val() === "True") {
            if (printWindow) {
                printWindow.close();
            }

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

            $("#cashRegisterPaymentBtn").removeAttr("disabled");
            return;
        }

        printType = printType && printType.length > 0 ? printType : (printSettings && printSettings.length > 0 ? printSettings[0] : 'printer_80');
        if (isLPFR) {
            printWindow = window.open();
            printWindow.document.write(generatePrintingPage());
            var lpfrData = await getLpfrData(lpfrFiscalizationDataUrl + "?acKey=" + $("#AcKey").val());
            if (lpfrData) {
                await lpfrFiscalization(lpfrData.LPFRCheckServer, lpfrData.LPFRServer, LPFRUpdateInvoiceUrl, lpfrData.LPFRJson, $("#AcKey").val(), function () {
                    printWindow.location = printPreview + "?id=" + $("#AcKey").val() + "&paperSize=" + printType + "&ignoreCopy=false";
                    printWindow.focus();
                }, function (error) {
                    printWindow.close();
                    displayError(error);
                });
            }
        }
        else {
            window.open(printPreview + "?id=" + $("#AcKey").val() + "&paperSize=" + printType);
        }

        $("#cashRegisterPaymentBtn").removeAttr("disabled");
        return;
    }

    var error = false;
    if (!$("#PartnerId").val() || $("#PartnerId").val().length < 0) {
        showInputError($("#PartnerName"), true);
        $("#PartnerId").closest(".form-group").find("span[class^='field-validation']").text($("#RequiredInputLoc").val());
        error = true;


        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: "<b>" + $("#PartnerId").closest(".form-group").find("label.control-label").text() + "</b>: " + $("#RequiredInputLoc").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: "Ok",
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
    else {
        showInputError($("#PartnerName"), false);
    }

    if ($("#IsFiscalSalesBookSelected").is(":checked") && isLocale(siteLocale.SI)) {
        let vkrError = false;
        if ($("#FiscSalesBookSetNo").val().length !== 2) {
            showInputError($("#FiscSalesBookSetNo"), true);
            error = true;
            vkrError = true;
        }
        else {
            showInputError($("#FiscSalesBookSetNo"), false);
        }

        if ($("#FiscSalesBookSerNo").val().length !== 12) {
            showInputError($("#FiscSalesBookSerNo"), true);
            error = true;
            vkrError = true;
        }
        else {
            showInputError($("#FiscSalesBookSerNo"), false);
        }

        if ($("#FiscSalesBookDocNo").val().length > 20 || $("#FiscSalesBookDocNo").val().length < 1) {
            showInputError($("#FiscSalesBookDocNo"), true);
            error = true;
            vkrError = true;
        }
        else {
            showInputError($("#FiscSalesBookDocNo"), false);
        }

        if (vkrError) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: globalCashRegisterLocalization.fiscalSalesBookError,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "Ok",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    }

    if (error === true) {
        $("#cashRegisterPaymentBtn").removeAttr("disabled");
        return;
    }

    let invoice = {};
    invoice.partnerId = $("#PartnerId").val();
    invoice.numberOfDays = $("#NumberOfDays").val();
    invoice.note = encodeURIComponent($("#Note").val());
    invoice.invoiceDate = $("#InvoiceDate").datepicker("getDate").toISOString();
    invoice.acKey = $("#AcKey").val();
    invoice.statement = $("#Statement").val();
    invoice.canFiscalize = toBoolean($("#CanFiscalize").val());
    invoice.statement = $("#Statements").val() ? $("#Statements").val().toString() : "";
    invoice.department = $("#Department").val();
    invoice.corrType = $("#CorrType").val();
    invoice.BuyerCostCenterId = $("#BuyerCostCenterId").val();
    invoice.BuyerCostCenterIdDef = $("#BuyerCostCenterIdDef option:selected").val();
    invoice.BuyerIdDef = $("#BuyerIdDef option:selected").val();
    invoice.BuyerID = $("#BuyerID").val();
    invoice.RefundRelatedDoc = $("#RefundRelatedDoc").val();
    invoice.FiscalStatus = $("#FiscalStatus").val();
    invoice.RefundRelatedDocDate = $("#RefundRelatedDocDate").data() && $("#RefundRelatedDocDate").data().date ? $("#RefundRelatedDocDate").data().date : null;
    invoice.Status = $("#Status").val();
    invoice.SpecPayment = $("#SpecPayment").val();
    invoice.POSFinancialOnly = $("#POSFinancialOnly").val();
    invoice.UpdateNoteClerk = confirmOtherClerk;

    if ($("#IsFiscalSalesBookSelected").is(":checked")) {
        invoice.FiscSalesBookSetNo = $("#FiscSalesBookSetNo").val();
        invoice.FiscSalesBookSerNo = $("#FiscSalesBookSerNo").val();
        invoice.FiscSalesBookDocNo = $("#FiscSalesBookDocNo").val();
        invoice.IsFiscalSalesBookSelected = $("#IsFiscalSalesBookSelected").val();
    }

    invoice.paymentMethods = jQuery.map($("#paymentModal").find(".payment-method-table input"), function (input) {
        if (toNumber($(input).val()) === 0) return null;

        return {
            name: $(input).attr("data-name"),
            amount: (toNumber($(input).val()) * (toPayValue < 0 ? -1 : 1)),
            acPayMethod: $(input).attr("data-id"),
            currency: $(input).attr("data-currency")
        };
    });

    invoice.items = [];
    invoiceItems.forEach(function (item) {
        var copyObject = { ...item };
        copyObject.price = formatDisplay($($(".identPrice")[0]).attr("step"), copyObject.price, true);
        copyObject.quantity = formatDisplay($($(".identQuantity")[0]).attr("step"), copyObject.quantity, true);
        copyObject.discount = formatDisplay($($(".identDiscount")[0]).attr("step"), copyObject.discount, true);
        copyObject.vat = formatDisplay($($(".identDiscount")[0]).attr("step"), copyObject.vat, true);
        copyObject.incBase = 0;
        copyObject.incBaseP = 0;
        copyObject.notIncBaseP = 0;
        copyObject.notIncBase = 0;
        copyObject.basisForTax = formatDisplay($($(".identPrice")[0]).attr("step"), copyObject.basisForTax, true);
        invoice.items.push(copyObject);
    });

    await saveInvoice(invoice, printType, isPreview, fiscalize, closePaymentModal, saveType);
    $("#cashRegisterPaymentBtn").removeAttr("disabled");
}

async function saveInvoice(invoice, printType, isPreview, fiscalize, closePaymentModal = true, saveType = null) {
    disableInvoiceGUI(true);

    if ($("#UserLoc").val() === $("#LocRS").val() && invoiceItems.some(s => s.vatFiscalCode === "" || !s.vatFiscalCode)) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $("#AllTaxesNeedFiscalCodeLoc").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        return;
    }

    if (isFiscalPrinter) invoice.machineName = await getLocalMachineName($("#LocalApiUrl").val());

    if (fiscalize) {
        printWindow = window.open();
        printWindow.document.write(generatePrintingPage());
    }

    await fetch(saveInvoiceJsonUrl + "?fiscalize=" + fiscalize, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(invoice)
    }).then((response) => response.json()
    ).then(async (data) => {
        if (data.HasIdentCreateErrors !== true) {
            $("#IdentCreateErrMsg").val("");
            $("#identSearchTable :input").prop("disabled", false);
            $("#add-position").prop("disabled", false);
            focusIdentSearch();
            enableUploadFiles();
        }

        if (!data.Success && data.Errors && data.Errors.length > 0) {
            let $errorModalContent = $("<div></div>");
            data.Errors.forEach(function (errorItem) {
                $errorModalContent.append("<div>" + errorItem + "</div>");
            });

            if (!data.IgnoreError && fiscalize)
                printWindow.close();
            else if (data.IgnoreError && fiscalize) {
                printWindow.close();

                $().customModal({
                    destroyOnClose: true,
                    title: $("#ErrorLoc").val(),
                    type: "error",
                    content: $errorModalContent.html(),
                    buttons: [{
                        text: $("#ConfirmLoc").val(),
                        icon: 'fa fa-check',
                        action: async function () {
                            printWindow = window.open();
                            printWindow.document.write(generatePrintingPage());
                            handleFiscalPrint(data, fiscalize, printType);
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }]
                });
                return;
            }

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

        handleFiscalPrint(data, fiscalize, printType, saveType);
    }).catch((error) => {
        disableInvoiceGUI(false);
        $().customModal({
            destroyOnClose: true,
            title: $("#ErrorLoc").val(),
            type: "error",
            text: GeneralErrorLoc + " " + error,
            buttons: [{
                text: $("#ConfirmLoc").val(),
                icon: 'fa fa-check',
                closeOnAction: true,
                type: 'primary'
            }]
        });

        if (printWindow)
            printWindow.close();
    });

    if (closePaymentModal) $('#paymentModal').customModal('close');
}

async function handleFiscalPrint(data, fiscalize, printType, saveType) {
    if (data.AcKey) {
        $("#AcKey").val(data.AcKey);
        $("#formButtonsBtnGroupContainer").removeClass("hidden");
        refreshArrows(data.AcKey, data.AcKeyDisplay);

        if (data.Reference) {
            $("#invoiceNumberDisplay").html(data.Reference);
            $("#invoiceNumberDisplay").removeClass("hidden");
        }

        if (data.Qid)
            $("#Qid").val(data.Qid);

        if (data.Protocol)
            $("#Protocol").val(data.Protocol);
    }

    if (printType === "PDV") {
        printPAAS("btnPrintTaxRateReport", false, false);
        return;
    }

    if (fiscalize && (data.Success || data.IgnoreError) && ((data.FiscalPrinter && data.AcKey) || !data.FiscalPrinter)) {
        if (data.FiscalPrinter) {
            let result = await printWithFiscalPrinter(data, $("#LocalApiUrl").val(), $("#CentralApiUrl").val(), $("#loginDevice").val());

            printWindow.close();
            window.history.pushState({}, null, CashRegisterIndexUrl);
            clearInvoice();
            disableInvoiceGUI(false);
            $().customModal({
                destroyOnClose: true,
                title: $("#ErrorLoc").val(),
                type: "success",
                text: $("#InvoicePrintSuccessLoc").val(),
                buttons: [{
                    text: $("#ConfirmLoc").val(),
                    icon: 'fa fa-check',
                    closeOnAction: true,
                    type: 'primary'
                }]
            });
        }
        else if (data.LPFR) {
            await lpfrFiscalization(data.LPFRCheckServer, data.LPFRServer, LPFRUpdateInvoiceUrl, data.LPFRJson, $("#AcKey").val(), function () {
                printWindow.location = printPreview + "?id=" + $("#AcKey").val() + "&paperSize=" + printType + "&ignoreCopy=true";
                printWindow.focus();

                disableInvoiceGUI(false);
                if ($("#CurrentUserIsDemo").val() === "True" || $("#AcKey").val().length > 0) {
                    window.location.href = CashRegisterIndexUrl;
                }
                else {
                    clearInvoice();
                }
            }, function (error) {
                printWindow.close();
                displayError(error);
            });
        }
        else {
            //TODO: uncomment for PAAS
            //printPAAS(printType, toBoolean($("#CanFiscalize").val()), isPreview);
            printWindow.location = printPreview + "?id=" + data.AcKey + "&paperSize=" + printType + "&ignoreCopy=" + toBoolean($("#CanFiscalize").val());
            printWindow.focus();
            //--

            disableInvoiceGUI(false);

            if ($("#CurrentUserIsDemo").val() === "True" || $("#AcKey").val().length > 0)
                window.location.href = CashRegisterIndexUrl;
            else
                clearInvoice();
        }
    }
    else {
        disableInvoiceGUI(false);
        if (saveType && saveType === $("#SaveAndCheckForSerialsType").val() && invoiceItems && invoiceItems.length > 0)
            checkIdentSerialNoIssue(invoiceItems[invoiceItems.length - 1].anNo, "M", invoiceItems[invoiceItems.length - 1].serialNo, invoiceItems[invoiceItems.length - 1].quantity);
        else if (saveType && saveType === $("#SaveAndLoadPackedGoodsType").val()) {
            invoiceItems.splice(invoiceItems.length - 1, 1);
            displayIdents(true);
        }
    }
}

function showInputError($element, show) {
    if (show)
        $element.addClass("error-input-item");
    else
        $element.removeClass("error-input-item");
}

function disableInvoiceGUI(disable) {
    $(".print-loader-icon").removeClass(disable ? "fa-print" : "fa-spinner fa-spin").addClass(disable ? "fa-spinner fa-spin" : "fa-print");
    $(".print-loader-icon").closest("button").prop('disabled', disable);
    $(".print-loader-icon").closest("button").next(".dropdown-toggle").prop('disabled', disable);
}

function invokeCancelInvoice(button, isCurrentClerk, createCopy) {
    if (!isCurrentClerk) {
        $().customModal({
            title: $("#CancelationOfInvoiceLoc").data('text') + '?',
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: $("#CancelInvoiceWillBecreatedByCurrentUserLoc").data('text'),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#CancelLoc").val(),
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#CancelInvoiceLoc").val(),
                    action: async function () {
                        cancelInvoice(button, createCopy);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
    else {
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: $("#CancelInvoiceConfirmLoc").data('text'),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#CancelLoc").val(),
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#CancelInvoiceLoc").val(),
                    action: async function () {
                        cancelInvoice(button, createCopy);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
}

function cancelInvoice(button, createCopy) {
    $(button).find('i').removeClass('fa-ban').addClass('fa-spinner fa-spin fa-fw');

    if (createCopy === true) {
        printWindow = createPrintWindow(printWindow);
        printWindow.blur();
        window.focus();
    }

    $.get(CashRegisterCancelInvoiceUrl + "?acKey=" + $("#AcKey").val() + "&createCopy=" + createCopy, function (data) {
        if (data.Success) {
            if (createCopy === true) {
                window.location.href = CashRegisterIndexUrl + '?acKey=' + data.AcKeyCopy;
                printWindow.location = printPreview + "?id=" + data.AcKey;
                printWindow.focus();
            } else
                window.location.href = CashRegisterIndexUrl + '?acKey=' + data.AcKey;
        }
        else {
            if (createCopy === true)
                printWindow.close();

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: data.Error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
            $(button).find('i').removeClass('fa-spinner fa-spin fa-fw').addClass('fa-times');
        }
    }).fail(function () {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: GeneralErrorLoc,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        $(button).find('i').removeClass('fa-spinner fa-spin fa-fw').addClass('fa-times');
    });
}

function docHasConnectedTraffic(acKey, text, anNo) {
    $().customModal({
        title: "",
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: stringFormat($("#ConnectedTrafficDocDeleteLoc").val(), acKey, text),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#YesLoc").val(),
                action: async function () {
                    if (anNo)
                        removeItem(anNo);
                    else
                        invokeRemoveInvoice("#deleteButton");
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function canDeleteInvoice(button) {
    $.get($("#canDeleteUrl").val() + "?acKey=" + $("#AcKey").val(), function (response) {
        canDeleteResponse = response;
        if (response.HasConnectedTrafficDocument === true) {
            docHasConnectedTraffic(response.ConnectedTrafficAcKey, response.ConnectedTrafficAnNo);
        } else {
            invokeRemoveInvoice(button);
        }
    });
}

function invokeRemoveInvoice(button) {
    if (!$("#AcKey").val()) {
        window.location.href = CashRegisterIndexUrl;
        return;
    }

    $(button).find('i').removeClass('fa-trash-alt').addClass('fa-spinner fa-spin fa-fw');

    $.get(CashRegisterRemoveInvoiceUrl + "?acKey=" + $("#AcKey").val(), function (data) {
        if (data.Success) {
            window.location.href = CashRegisterIndexUrl;
        }
        else {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: data.Error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#custom-modal-confirm").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            $(button).find('i').removeClass('fa-spinner fa-spin fa-fw').addClass('fa-trash-alt');
        }
    }).fail(function () {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: GeneralErrorLoc,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#custom-modal-confirm").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });

        $(button).find('i').removeClass('fa-spinner fa-spin fa-fw').addClass('fa-times');
    });
}

function invoiceDiscountChange() {
    invoiceItems.forEach(function (item) {
        item.discount = toNumber($("#DiscountPercentage").val());
        getIdentRowElement(item.anNo).find(".identDiscount").val(item.discount);
        formatNumberInput(getIdentRowElement(item.anNo).find(".identDiscount"));
        recalculateItem(item.anNo, false);
    });

    recalculateInvoice();
}

function invoiceDiscountValueChange() {
    var discountAmount = toNumber($("#DiscountAmount").val());
    var totalPrice = toNumber($("#TotalAmount").val());

    var percent = 0;
    if (discountAmount && totalPrice > 0)
        percent = discountAmount / totalPrice * 100;

    $("#DiscountPercentage").val(percent);
    invoiceDiscountChange();
}

function toBoolean(value) {
    if (!value)
        return false;

    if (typeof value === "boolean")
        return value;

    if (typeof value === 'string' || value instanceof String)
        return JSON.parse(value.toLowerCase());

    return false;
}

function openInvoiceNoteModal() {
    noteModal.show($("#Note").val(), {
        onSave: function (content) {
            $("#Note").val(content)
            $("#noteIcon")
                .removeClass("btn-active")
                .addClass(content !== "" ? "btn-active" : "");
        }
    });
}

function saveInvoiceNote() {
    $("#invoiceNoteModal").modal("hide");
    $("#Note").val($("#invoiceNoteModal textarea").val());

    $("#noteIcon")
        .removeClass("btn-active")
        .addClass($("#Note").val() !== "" ? "btn-active" : "");
}

function canceledLink(ackey) {
    location.href = $("#CashRegisterIndex").val() + '?ackey=' + ackey;
}

function initDepositModal(mode) {
    let modalTitle = mode === "I" ? globalCashRegisterLocalization.depositInput : globalCashRegisterLocalization.depositOutput;
    openDepositModal(mode, $("#FiscalWorkplaceId").val(), globalCashRegisterLocalization.currency, modalTitle,
        globalCashRegisterLocalization.value, $("#UrlRegisterDeposit").val(), $("#LocError").val(), undefined, undefined, () => { $("#IsInitialized").val("True"); });
}

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

function checkClosedVATPeriod() {
    $.ajax({
        type: "POST",
        data: JSON.stringify({ Date: new Date($("#InvoiceDate").datepicker("getDate")).toISOString() }),
        url: $("#TestClosedVATPeriodUrl").val(),
        contentType: "application/json"
    }).done(function (response) {
        if (response && response.Result === "F") {
            setIdentPrices();
        } else {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: false,
                type: "alert",
                text: $("#TaxPeriodIsClosedLoc").val(),
                closeOtherModals: false,
                buttons: [
                    {
                        text: $("#OkLoc").val(),
                        icon: 'fa fa-check',
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function setIdentPrices() {
    var model = {
        AcKey: $("#AcKey").val(),
        Type: "M",
        Subject: $("#PartnerId").val(),
        PriceRate: $("#SelectedPartnerPriceRate").val(),
        Currency: $("#Currency").val(),
        Date: new Date($("#InvoiceDate").datepicker("getDate")).toISOString(),
        DateInv: new Date($("#InvoiceDate").datepicker("getDate")).toISOString(),
    };

    $.ajax({
        method: "POST",
        url: $("#MoveChaPriceClassUrl").val(),
        data: JSON.stringify(model),
        contentType: "application/json",
        success: function (data) {
            if (data.IsPriceUpdated === true) {
                if (data.Idents !== null && data.Idents.length > 0) {
                    data.Idents.forEach(function (ident) {
                        if (ident.PriceOld !== ident.PriceNew) {
                            let newPrice = ident.PriceNew + (ident.PriceNew / 100 * toNumber($("#vatPercent-" + ident.AnNo).val()));
                            getIdentRowElement(ident.AnNo).find(".identPrice").val(newPrice);
                            formatNumberInput(getIdentRowElement(ident.AnNo).find(".identPrice"));
                        }
                    });
                }
            }

            for (var i = 0; i < invoiceItems.length; i++) {
                getIdentRowElement(invoiceItems[i].anNo).find(".identDiscount").val($("#SelectedPartnerRebate").val());
                formatNumberInput(getIdentRowElement(invoiceItems[i].anNo).find(".identDiscount"));
                recalculateItem(invoiceItems[i].anNo, false);
            }

            recalculateInvoice();
            onlySave($("#saveButton"));

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

function moveAdvancePaymentLinks(showModal, element) {
    var model = {
        Subject: $("#PartnerId").val(),
        DocType: $("#loginDevice").val(),
        AcKey: $("#AcKey").val(),
        Date: new Date($("#InvoiceDate").datepicker("getDate")).toISOString(),
        VAT: "",
        Type: "O",
        InvoiceType: $("#AdvancePaymentMoveLinksTypeWholesale").val()
    };

    $.ajax({
        type: "POST",
        data: JSON.stringify(model),
        url: $("#MoveAdvancePaymentLinksUrl").val(),
        contentType: "application/json"
    }).done(function (response) {
        if (response && response.length > 0 && response.some(x => x.Marked === "F")) {
            $("#MoveAdvancePaymentLinksIsPos").val("True");
            $("#MoveAdvancePaymentLinksType").val($("#AdvancePaymentMoveLinksTypeWholesale").val());
            $("#MoveAdvancePaymentLinksSubject").val($("#PartnerId").val());
            $("#MoveAdvancePaymentLinksInvoiceDate").val($("#InvoiceDate").val());
            $("#subjectHasOpenAdvancePaymentsMsg").text($("#BuyerHasOpenAdvancePaymentsIRISLoc").val());
            $("#subjectOnOpenMsg").text($("#BuyerOnDocumentHasOpenAdvancePaymentsLoc").val());
            refreshMoveAdvancePaymentLinksTable(response);

            $('#advancePaymentCreatedContinueOpenOrPrint').removeAttr('onclick');
            $('#advancePaymentCreatedContinueOpenOrPrint').on('click', function () {
                $('#paymentModal').customModal('open');
            });

            if (showModal) {
                $('#advancePaymentContinueOpenOrPrint').on('click', function () {
                    $('#paymentModal').customModal('open');
                });
                $("#moveAdvancePaymentLinksOpenWarningModal").modal('show');
            } else
                $("#moveAdvancePaymentLinksModal").modal('show');
        } else {
            $('#paymentModal').customModal('open');
        }

        $(element).find("i").removeClass("fa-spinner fa-spin");
    });
}

function moveAdvancePaymentLinksHelp() {
    window.open($("#MoveAdvancePaymentLinksPOSUrl").val(), '_blank');
}

function redirectToAdvancePayment(acKey) {
    window.location = $("#EditReceivingAdvancePaymentUrl").val() + "?id=" + acKey;
}

function openDocMoveConnection(ackey, moveType = null) {
    if (moveType && moveType === "POS")
        location.href = $("#CashRegisterIndex").val() + '?ackey=' + ackey;
    else
        location.href = $("#editWholesaleUrl").val() + "?id=" + ackey;
}

function redirectToOrderDocument(acKey, orderType) {
    if (acKey && orderType === $("#OrderTypeBuyer").val())
        window.location = $("#EditBuyerOrderUrl").val() + "?id=" + acKey;
    else if (acKey && orderType === $("#OrderTypeSupplier").val())
        window.location = $("#EditSupplierOrderUrl").val() + "?id=" + acKey;
    else if (acKey && orderType === $("#AdvancePaymentTypeOfDoc").val())
        window.location = $("#EditReceivingAdvancePaymentUrl").val() + "?id=" + acKey;
}

function openUnconfirmedBills() {
    window.location.href = $("#IssuedBillsBillingUrl").val() + "?showUnconfirmedBills=" + true + "&docType=" + $("#loginDevice").val() + "&acKey=" + $("#AcKey").val();
}

function hasUnfiscalizedInvoices() {
    var data = {
        DateFrom: $("#DateNowMinusTwoDays").val(),
        DateTo: $("#DateNow").val(),
        DocType: $("#loginDevice").val(),
    };

    $.post($("#IssuedBillsUnconfirmedGetAllIdsUrl").val(), { filter: data })
        .done(function (response) {
            if (response !== null && response.length > 0) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: stringFormat($("#FiscErrorsForLast48HoursLoc").val(), response.length),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        });
}

function openAdvancePaymentForSubjectHelp() {
    window.open($("#moveAdvancePaymentLinksExistOnBuyerHelp").val(), '_blank');
}

function swapLoadingIcon(loading, buttonId, icon) {
    var $button = $("#" + buttonId);
    var $buttonIcon = $button.find("i");
    var $buttonGroupButtons = $button.parent().find("button");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
        $buttonGroupButtons.attr("disabled", true);
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
        $buttonGroupButtons.removeAttr("disabled");
    }
}

function dropifyUploadAttachments() {
    var error = $("#GeneralErrorMessage").val();
    var remove = $("#Remove").val();
    var dragOrClick = $("#AddAttachment").val();
    var dragOrClickToReplace = $("#AddAttachment").val();
    var fileSizeMessage = $("#FileSizeMessage").val();
    var fileNotAllowedMessage = $("#FileNotAllowedMessage").val();

    var dr = $('.dropify').dropify({
        messages: {
            'default': dragOrClick,
            'replace': dragOrClickToReplace,
            'remove': remove,
            'error': error
        },
        error: {
            'fileSize': fileSizeMessage,
            'fileExtension': fileNotAllowedMessage
        }
    });
}

function uploadAttachmentFile(onUpload, onCancel) {
    if ($("#DocTypeDms").val() !== "" && $("#DocTypeClassification").val() !== "") {
        swapLoadingIcon(true, "saveButton");
        swapLoadingIcon(true, "printButton", "fa-print");
        onUpload();
    } else {
        $("#createDocumentIrisMessage").text(stringFormat($("#IncorrectDocTypeSettingsLoc").val(), $("#DocType").val()));
        $("#openDocTypeSettings").attr("onclick", "window.open('" + $("#EditDocumentTypeUrl").val() + "?id=" + $("#DocType").val() + "', '_self')");
        $("#openClassificationSettings").attr("onclick", "window.open('" + $("#SettingsClassificationsUrl").val() + "?type=" + 'Classifications' + "', '_self')");
        $("#createDocumentErrorModal").modal("show");
        onCancel();
    }
}

function openDmsDoc(ackey) {
    if (!ackey)
        ackey = $("#DocumentKey").val();

    location.href = $("#EditDocumentTypeUrl").val() + '?qid=' + ackey;
}

function isFiscalWorkplaceClosed() {
    if ($("#IsFiscalWorkplaceClosed").val() === "True") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $("#FiscalWorkplaceClosedCannotCreateNewDocLoc").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    action: async function () {
                        $("#DocTypeSelect").focus();
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        return true;
    }
    return false;
}