function anonymizeText(isGDPR, vat, text, emptyText) {
    emptyText = emptyText || '';
    let hasVAT = vat !== null && vat !== undefined && vat.trim() !== "";
    return isGDPR || hasVAT ? (text ? text : emptyText) : (text ? text.replace(/./g, '*') : emptyText);
}

function forceDropdown() {
    $('.dropdown-toggle').click(function () {
        if ($(this).parent().hasClass('dropup'))
            $(this).parent().removeClass('dropup');
    });
}

function findObjectByKey(array, key, value, transformOriginalFunction) {
    for (var i = 0; i < array.length; i++) {
        if (transformOriginalFunction ? transformOriginalFunction(array[i][key]) === value : array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

function setGlobalHelpUrl(helpUrl) {
    $("#globalHelpUrl").attr("href", helpUrl);
}

function setGlobalExampleHelpUrl(helpUrl) {
    $("#globalExampleHelpUrl").attr("href", helpUrl);
}


function removeSpacesFromId(value) {
    return value.replace(/\s+/g, '_');
}

function reformatDate(dateString) {
    var dateElements = dateString.split('.');
    return dateElements[2] + '-' + dateElements[1] + '-' + dateElements[0];
}

$(document).ready(function () {
    $(".tabs-container .horizontal-menu .active").on("click", function (e) {
        if ($("body").hasClass("body-small")) {
            e.preventDefault();
            if ($(this).closest("ul").hasClass("horizontal-menu-open"))
                $(this).closest("ul").removeClass("horizontal-menu-open");
            else
                $(this).closest("ul").addClass("horizontal-menu-open");
        }
    });

    $("textarea").on("click", function (e) {
        $(this).focus();
    });
});

function createNewSubjectModal($elementId, $displayElement, type, $elementName) {
    setTimeout(function () {
        if ($displayElement[0].id !== $(document.activeElement)[0].id)
            if ($displayElement.val() &&
                (!$("#OurCompIsName2").val() || $("#OurCompIsName2").val() === "False" && ($elementId.val() !== $displayElement.val()) ||
                ($("#OurCompIsName2").val() && $("#OurCompIsName2").val() === "True" && $displayElement.val() !== $elementName.val()) && $elementId.val() !== $displayElement.val())) {

                $("#subjectTypeCreate").val(type);
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: $("#EnteredSubjectDoesNotExistCreateNewLoc").val(),
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: $("#NoLoc").val(),
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: $("#YesLoc").val(),
                            action: function () {
                                onClickCreateNewSubject();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
    }, 1);
}

function closeModal(id) {
    $('#' + id).modal('hide');
}

function changeFormDataValue(formData, name, value) {
    for (var x = 0; x < formData.length; x++) {
        if (formData[x].name === name) {
            formData[x].value = value;
        }
    }

    return formData;
}

function displayValidationErrors(response) {
    for (var i = 0; i < response.errors.length; i++) {
        var $span = $("#" + response.errors[i].Key + " + span");
        $span.text(response.errors[i].Value);
    }
}

function stringFormat(text, param, param2, param3) {
    if (param) {
        var reg = new RegExp("\\{" + 0 + "\\}", "gm");
        text = text.replace(reg, param);
    }

    if (param2) {
        var reg2 = new RegExp("\\{" + 1 + "\\}", "gm");
        text = text.replace(reg2, param2);
    }

    if (param3) {
        var reg3 = new RegExp("\\{" + 2 + "\\}", "gm");
        text = text.replace(reg3, param3);
    }

    return text;
}
function createSubjectSetValues(subjectType, value) {
    $("#" + subjectType + "Id").val(value);
    $("#" + subjectType).val(value);
}

function showForPay76a(show) {
    if (show === true) {
        $("#statementsContainer").removeClass("col-md-3");
        $("#statementsContainer").addClass("col-md-2");
        $("#forPay76aContainer").prop("hidden", false);
    } else {
        $("#statementsContainer").addClass("col-md-3");
        $("#statementsContainer").removeClass("col-md-2");
        $("#forPay76aContainer").prop("hidden", true);
    }
}

function addSelectOptions(items, elementId) {
    var inputSelect = document.getElementById(elementId);
    if (!inputSelect)
        return;

    inputSelect.innerText = null;
    if (items)
        for (var i = 0; i < items.length; i++) {
            var rabate = items[i].Rabate ? items[i].Rabate : 0;
            if (items[i].Id > 0)
                inputSelect.innerHTML +=
                    '<option value="' + items[i].Id + '" data-discount="' + rabate + '" ' + (items[i].Selected && items[i].Selected === true ? 'selected' : '') + '>'
                    + items[i].Text
                    + '</option>';
        }
}

function setDropdownSelectedValue(id, value, isValue = false) {
    var dropDownOptions = document.getElementById(id);
    for (var i = 0; i < dropDownOptions.options.length; i++) {
        if (isValue) {
            if (dropDownOptions.options[i].value?.toUpperCase() === value?.toUpperCase()) {
                dropDownOptions.options[i].selected = true;
                return;
            }
        }
        if (dropDownOptions.options[i].text?.toUpperCase() === value?.toUpperCase()) {
            dropDownOptions.options[i].selected = true;
            return;
        }
    }
}

function generatePrintingPage() {
    let bodyClasses = $("body").attr("class").split(/\s+/);
    let bodyThemeIndex = bodyClasses?.findIndex((className) => className.startsWith("theme-"));
    let bodyTheme = bodyThemeIndex > -1 ? bodyClasses[bodyThemeIndex] : undefined;
    let bodyBackgrounColor = "white";

    let animation = $("#RepeatAnimationPath").val();
    if (bodyTheme) {
        bodyTheme = bodyTheme.replace("theme-", "");
        bodyTheme = bodyTheme.charAt(0).toUpperCase() + bodyTheme.slice(1);
        if (bodyTheme == "Dark") bodyBackgrounColor = "#3f444e";
        animation = animation.replace("Trademark", bodyTheme);
    }

    return '<div style="width:100%;height:100%;position:relative;margin:0;padding:0;background-color:' + bodyBackgrounColor + '"><div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);"><div style="position: relative;"><img style="min-width: 300px;" src="' + window.location.origin + animation + '"><span style="position: absolute; bottom: 0; left: 50%; transform: translate(-50%, 0%); display:inline-block; width:100%; text-align: center; font-family: sans-serif; color:#636363;">' + $("#LoadingDocumentLoc").val() + '...</span></div></div></div>';
}

async function printPAAS(type, fiscalize = false, preview = false, url, reload = true, checksum = null, dialogResponse = null, signature = null, LPFRUpdateInvoiceUrl = null, lpfrCopyUrl = null, acKey = null, addToPrints = null) {
    if (!url)
        url = $("#PAASPrintByAcKeyAndTypeUrl").val() + "?acKey=" + $("#AcKey").val() +
            "&type=" + type + "&fiscalize=" + fiscalize + "&preview=" + preview;

    if (checksum)
        url += "&checksum=" + checksum;
    if (dialogResponse)
        url += "&dialogResponse=" + dialogResponse;

    if (checksum)
        printWindow = createPrintWindow(printWindow);

    if (signature) signature = signature.replace("data:image/png;base64,", "");

    if (lpfrCopyUrl) {
        var lpfrData = await getLpfrData(lpfrCopyUrl);
        await lpfrFiscalization(lpfrData.LPFRCheckServer, lpfrData.LPFRServer, LPFRUpdateInvoiceUrl, lpfrData.LPFRJson, acKey ? acKey : $("#AcKey").val());
    }

    await fetch(url, {
        method: "POST",
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ signature: signature })
    }).then((response) => response.json()
    ).then(async (response) => {
        if (response && response.Error) {
            if (printWindow) printWindow.close();

            if (response.PrintingError)
                parsePAASError(response.PrintingError, type, fiscalize, preview);
            else if (response.ExtendedError)
                parsePAASError(response.ExtendedError, type, fiscalize, preview);
            else
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: response.Error + (response.Extended ? "</br></br>" + response.Extended : ""),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

            swapLoadingIcon(false, "saveButton", "fa fa-save");
            swapLoadingIcon(false, "printButton", "far fa-print");
        } else if (response.LPFR) {
            await lpfrFiscalization(response.LPFRCheckServer, response.LPFRServer, LPFRUpdateInvoiceUrl, response.LPFRJson, acKey ? acKey : $("#AcKey").val(), async function () {
                await printPAAS(type, false, preview, url, reload, checksum, dialogResponse, signature);
            }, function (error) {
                if (printWindow) printWindow.close();

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

            if (addToPrints) {
                prints.push(response);
                return;
            }

            var byte = base64ToArrayBuffer(response);
            var blob = new Blob([byte], { type: 'application/pdf' });
            printWindow.location.href = URL.createObjectURL(blob);
        }
    });
}

function base64ToArrayBuffer(_base64Str) {
    var binaryString = window.atob(_base64Str);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}

function parsePAASError(errModel, type, fiscalize, preview) {
    var errButtons = [];

    if (errModel && errModel.Buttons) {
        let buttonIndex = 0;
        errModel.Buttons.forEach(function (errBtn) {
            let buttonType = errModel.Results && errModel.Results.length > buttonIndex ? errModel.Results[buttonIndex] : 0;
            errButtons.push({
                icon: '',
                text: errBtn,
                closeOnAction: true,
                type: 'primary',
                action: function () {
                    if (errModel.Checksum && buttonType !== 2 && buttonType !== 5 && buttonType !== 8 && buttonType !== 9)
                        printPAAS(type, fiscalize, preview, null, true, errModel.Checksum, errBtn);
                }
            });
            buttonIndex++;
        });
    }

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "error",
        text: errModel.Error,
        title: errModel.Title,
        buttons: errButtons
    });
}

function disableCreateNewButtons() {
    $(".createNewButton").attr("disabled", true);
}

function setPrintDropdownToggle($area) {
    $area.find('.dropdown-submenu a').on("click", function (e) {
        $(this).children(".dropdown-menu[style*='display: block']").toggle();
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
    });

    $area.find('.dropdown-menu a').on("click", function (e) {
        if ($(this).closest("li").hasClass("dropdown-submenu")) {
            $(this).closest(".dropdown-menu").find(".dropdown-submenu").not($(this).closest("li")).children(".dropdown-menu").hide();
        }
    });
}

function showDeleteNotLastDocModal() {
    $().customModal({
        title: "",
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#deleteWholeDocumentIsNotLastOneLoc").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#cancelLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#deleteLoc").val(),
                action: function () {
                    deleteNotLastDoc();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

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

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

function updateInvoiceItemsDiscount(percent) {
    for (var i = 0; i < invoiceItems.length; i++) {
        invoiceItems[i].Rabate = percent;
        $("#rabate-" + invoiceItems[i].AnNo).val(percent);
        $("#rabate1-" + invoiceItems[i].AnNo).val(percent);
        formatNumberInput($("#rabate-" + invoiceItems[i].AnNo));
        formatNumberInput($("#rabate1-" + invoiceItems[i].AnNo));
        changeIdentData(invoiceItems[i].AnNo);
    }

    updatePriceTable();
}

function updateInvoiceItemsVat(vat, vatCode) {
    for (var i = 0; i < invoiceItems.length; i++) {
        invoiceItems[i].VAT = vat;
        invoiceItems[i].VATCode = vatCode;
        $("#vat-" + invoiceItems[i].AnNo).val(vatCode);
        changeIdentData(invoiceItems[i].AnNo);
    }
}

function updateInvoiceItemsDepartment(department) {
    for (var i = 0; i < invoiceItems.length; i++) {
        invoiceItems[i].Department = department;
        $("#department-" + invoiceItems[i].AnNo).val(department);
    }
}

function createPrintWindow(printWindow) {
    printWindow = window.open();
    printWindow.document.write(generatePrintingPage());
    return printWindow;
}

async function getFxRateCalcOperation(dateId) {
    var date = $("#" + dateId).datepicker("getDate");

    return new Promise((resolve, reject) => {
        $.get($("#GetFxRateCalcOperationUrl").val(), { Date: new Date(date).toISOString() })
            .done(function (response) {
                $("#FxRateCalcOperation").val(response);
                resolve(true);
            });
    });
}

function calculateWithOperation(value, fxRate, reverse = false) {
    if (($("#FxRateCalcOperation").val() === "D" && !reverse) || ($("#FxRateCalcOperation").val() === "M" && reverse))
        return value / fxRate;
    else
        return value * fxRate;
}

function fromISOToStandardDateFormatString(date) {
    var dateFormat = $("#DateFormat").val().toUpperCase();
    return moment(date).format(dateFormat);
}

function jsRenderDataTable(dataTableId, dataTableModalBodyClass, reduceHeightSize = 150, setMaxHeight = false) {
    if ($.fn.dataTable.isDataTable('#' + dataTableId)) {
        var height = jsGetDataTableHeightPx(dataTableId, dataTableModalBodyClass, reduceHeightSize) + "px";
        $('.dataTables_scrollBody:has(#' + dataTableId + ')').css('min-height', height);

        if (setMaxHeight)
            $('.dataTables_scrollBody:has(#' + dataTableId + ')').css('max-height', height);
    }
}

function jsGetDataTableHeightPx(dataTableId, dataTableModalBodyClass, reduceHeightSize) {
    var retHeightPx = 350;

    var dataTable = document.getElementById(dataTableId);
    if (!dataTable) {
        return retHeightPx;
    }

    var dataTableHeight = $("." + dataTableModalBodyClass).height();
    if (dataTableHeight !== null) {
        dataTableHeight = dataTableHeight - (reduceHeightSize ? reduceHeightSize : 150);
        retHeightPx = Math.max(100, dataTableHeight);
    }
    return retHeightPx;
}

function AddInvoiceDocumentConnections(connectionResponse, orderType = null) {
    let currency = $("#Currency").val();
    var onclick = "canceledLink";

    if (orderType && orderType === "0")
        onclick = "redirectToOrderDocument";

    for (var x = 0; x < connectionResponse.length; x++) {
        $("#connections").append(
            '<div class="form-group">' +
            '<input id="connection-' + connectionResponse[x].AcKey + '" value="' + connectionResponse[x].AcKey + '" hidden/>' +
            '<h4 class="form-control clickable-icon connectionContainer ' + (orderType === 'A' ? 'advPayConn' : '') + '" value="' + connectionResponse[x].AcKey + '" disabled>' +
            (orderType ? '<a onclick="redirectToOrderDocument(\'' + connectionResponse[x].AcKey + '\', \'' + orderType + '\')">'
                : '<a onclick="canceledLink(\'' + connectionResponse[x].AcKey + '\')">') + connectionResponse[x].AcKeyDisplay + '</a>' +
            '<span class="pull-right">' + formatDisplay(2, connectionResponse[x].Price) + " " + currency + '</span>' +
            '</h4>' +
            '</div>'
        );
    }

    $("#connectionsCount").text(toNumber($("#connectionsCount").text().trim()) + connectionResponse.length);
}

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

function checkForIdentNegativeQuantity() {
    if (invoiceItems !== null && invoiceItems.length > 0 && invoiceItems.some(s => s.Quantity < 0 || s.quantity < 0) && $(".connectionContainer").length === 0)
        $("#referenceDocCancellationContainer").removeClass("hidden");
    else
        $("#referenceDocCancellationContainer").addClass("hidden");
}

function checkIdentQuantity(itemsList, $quantity, isInsert = false) {
    if (itemsList !== null && itemsList.length > (isInsert ? 0 : 1)) {
        var quantity = toNumber($quantity.val());
        var showError = false;

        if (itemsList.find(x => x.Quantity < 0 || x.quantity < 0) && quantity > 0) {
            $quantity.val(-Math.abs(quantity));
            showError = true;
        } else if (itemsList.find(x => x.Quantity > 0 || x.quantity > 0) && quantity < 0) {
            $quantity.val(Math.abs(quantity));
            showError = true;
        }

        formatNumberInput($quantity);

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

    return true;
}

function updateReportTreeDisplay($reportTree, canFiscalize) {
    $reportTree.find("li.print-option").removeClass("hidden");

    if (canFiscalize !== "True") {
        $reportTree.find(
            "li.print-option[data-print='705'],li.print-option[data-print='706'],li.print-option[data-print='2S6']," +
            "li.print-option[data-print='707'],li.print-option[data-print='708'],li.print-option[data-print='2S7']," +
            "li.print-option[data-print='709'],li.print-option[data-print='710'],li.print-option[data-print='2S8']"
        ).addClass("hidden");
    }

    $reportTree.find(".printMD:has(li.hidden)").closest(".print-menu-dropdown-submenu").addClass("hidden");
    $reportTree.find(".printMD:has(li:not(.hidden))").closest(".print-menu-dropdown-submenu").removeClass("hidden");
}

function CheckLastInvoice(url, docType) {
    return new Promise(function (resolve, reject) {
        fetch(url + "?docType=" + docType, {
            method: "GET",
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Basic QUQ6YTIxODQwNzZDRTczNzlEOUZERkVEYXRhTGFiMTIz'
            }
        }).then((response) => response.json()
        ).then((data) => {
            resolve(data);
        }).catch((error) => {
            resolve(undefined);
        });
    });
}

async function setDocTypeStatusOptions(docType, $status) {
    swapLoadingIcon(true, "saveButton", "fa fa-save");
    swapLoadingIcon(true, "printButton", "far fa-print");

    await fetch($("#GetDocTypeStatusesUrl").val() + "?docType=" + docType, {
        method: "GET",
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((response) => response.json()
    ).then(async (response) => {
        var isFirstOption = true;
        var options = "<option value>" + $("#SelectOptionLoc").val() + "</option>";

        for (var option of response) {
            options += "<option value=" + option.Status + " " + (isFirstOption === true ? 'selected' : '') + ">" + option.Name + "</option>";
            isFirstOption = false;
        }
        $status[0].innerHTML = null;
        $status[0].innerHTML = options;
    });

    swapLoadingIcon(false, "saveButton", "fa fa-save");
    swapLoadingIcon(false, "printButton", "far fa-print");
}

function createNewInvoice(url, docType, type = null) {
    const docTypeValue = $("#" + docType).val();
    const separator = url.includes($("#CreateThemisDocumentUrl").val()) ? "&" : "?";
    let createUrl = `${url}${separator}selectedDocType=${docTypeValue}`;

    if (type !== null)
        createUrl = createUrl + "&type=" + type;

    location.href = createUrl;
}

function RunDocumentTaskAction(action, taskId, subjectElementId, runTaskUrl, redirectUrl, commentEltId) {
    let taskModel = {
        ActionName: action,
        Id: taskId,
        SubjectId: subjectElementId && subjectElementId.length > 0 ? $("#" + subjectElementId).val() : undefined,
        Comment: commentEltId && commentEltId.length > 0 ? $('#' + commentEltId).val() : undefined
    };

    var taskRunLandingUrl = $("#TaskRunLandingUrl").val();
    var overrideRedirect = taskRunLandingUrl && taskRunLandingUrl.length > 0;

    $.ajax({
        url: runTaskUrl,
        contentType: "application/json",
        data: JSON.stringify(taskModel),
        method: "POST",
        success: function (data) {
            if (data) {
                let localStorageRunTasksData = localStorage.getItem("runSelectedTasks");
                if (localStorageRunTasksData) {
                    localStorageRunTasksData = JSON.parse(localStorageRunTasksData);

                    if (localStorageRunTasksData && localStorageRunTasksData.length > 0 && localStorageRunTasksData[0] === taskId) {
                        localStorageRunTasksData.splice(0, 1);

                        localStorage.setItem("runSelectedTasks", JSON.stringify(localStorageRunTasksData));
                        if (localStorageRunTasksData && localStorageRunTasksData.length > 0) {
                            window.location = overrideRedirect ? taskRunLandingUrl : $("#EditTaskUrl").val() + "?id=" + localStorageRunTasksData[0];
                            return;
                        }
                    }
                }

                window.location = overrideRedirect ? taskRunLandingUrl : redirectUrl;
            }
            else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: $("#general-error").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#custom-modal-confirm").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }]
                });
            }
        },
        fail: function (error) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#general-error").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#custom-modal-confirm").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }]
            });
        }
    });
}

function setDocTypeRounding(docTypeSelectId) {
    $("#RoundTSetting").val($(docTypeSelectId + " option:selected").attr("data-roundValueOc"));
    $("#RoundValueSetting").val($(docTypeSelectId + " option:selected").attr("data-roundValueOc"));

    $("#RoundT").val(GetNumberOfDecimals($(docTypeSelectId + " option:selected").attr("data-roundT")));
    $("#RoundValue").val(GetNumberOfDecimals($(docTypeSelectId + " option:selected").attr("data-roundValue")));
    $("#RoundPrice").val(GetNumberOfDecimals($(docTypeSelectId + " option:selected").attr("data-roundPrice")));
    $("#RoundTfc").val(GetNumberOfDecimals($(docTypeSelectId + " option:selected").attr("data-roundTfc")));
    $("#RoundValueOc").val(GetNumberOfDecimals($(docTypeSelectId + " option:selected").attr("data-roundValueOc")));

    $(".roundT").attr("data-round", $("#RoundT").val());
    $(".roundValue").attr("data-round", $("#RoundValue").val());
}

function GetNumberOfDecimals(round) {
    if (!round)
        return 0;

    var parts;
    if (round.includes('.'))
        parts = round.split('.');
    else
        parts = round.split(',');

    if (parts.Length < 2)
        return 0;

    return parts[1].replace(/0+$/g, '').length;
}

function pad(str, max) {
    str = str.toString();
    return str.length < max ? pad("0" + str, max) : str;
}

function setTabScrollArrows() {
    var hidWidth;
    var scrollBarWidths = 40;

    var widthOfList = function () {
        var itemsWidth = 0;
        $('.tabs-list li').each(function () {
            var itemWidth = $(this).outerWidth();
            itemsWidth += itemWidth;
        });
        return itemsWidth;
    };

    var widthOfHidden = function () {
        return (($('.tabs-wrapper').outerWidth()) - widthOfList() - getLeftPosi()) - scrollBarWidths;
    };

    var getLeftPosi = function () {
        return $('.tabs-list').position().left;
    };

    var reAdjust = function () {
        if (($('.tabs-wrapper').outerWidth()) < widthOfList()) {
            $('.scroller-right').show();
        }
        else {
            $('.scroller-right').hide();
        }

        if (getLeftPosi() < 0) {
            $('.scroller-left').show();
        }
        else {
            $('.item').animate({ left: "-=" + getLeftPosi() + "px" }, 'slow');
            $('.scroller-left').hide();
        }
    };

    reAdjust();

    $(window).on('resize', function (e) {
        reAdjust();
    });

    $('.scroller-right').click(function () {

        $('.scroller-left').fadeIn('slow');
        $('.scroller-right').fadeOut('slow');

        $('.tabs-list').animate({ left: "+=" + (widthOfHidden() + 80) + "px" }, 'slow', function () {

        });
    });

    $('.scroller-left').click(function () {
        $('.scroller-right').fadeIn('slow');
        $('.scroller-left').fadeOut('slow');

        $('.tabs-list').animate({ left: "-=" + getLeftPosi() + "px" }, 'slow', function () {

        });
    });    
}

function qparams(params) {
    var qparams = "";
    for (var k in params) {
        var val = params[k];
        if (val === null || val === undefined) {
            continue;
        }
        qparams += k + '=' + val + '&';
    }
    return '?' + qparams.substring(0, qparams.length - 1);
}

function debouncer(func, wait) {
    let timeout;
    return function () {
        const context = this;
        const args = arguments;
        const later = function () {
            timeout = null;
            func.apply(context, args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function selectDocumentForFiles(element, id) {
    $(".connectionContainer").removeClass("container-selected");
    $(element).addClass("container-selected");
    $("#DocumentKey").val(id);
}

function setInputValueAndDataVal($element, value) {
    $element.val(value);
    $element.attr("data-val", value);
}

function navigateToURL(url) {
    window.location.href = url;
}

var identTaxSettings = null;
async function checkForTaxSetting(invoiceType, wayOfSale) {
    $.get($("#CheckForTaxSettingUrl").val() + "?type=" + invoiceType + "&wayOfSale=" + wayOfSale, function (response) {
        if (response)
            identTaxSettings = response;
    });
}