function initializeProductsProductList() {
    $("#Keywords").attr('placeholder', $('#searchPlaceholder').val());

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

    var userCanAccessProductImport = $('#userCanAccessProductImport').val() === "True";
    var userCanAccessProductCud = $('#userCanAccessProductCud').val() === "True";

    $dataTable = $('#grid-data');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.SelectedTaxGroupId = $("#SelectedTaxGroupId").val();
                d.Type = $("#Type").val();
                d.Category = $("#Category").val();
                d.MeasurementUnit = $("#MeasurementUnit").val();
                d.SupplierId = $("#SupplierId").val();
                d.Status = $("#Status").val();
            }
        },
        columns: [
            { data: "Active", name: "AcActive", render: $.fn.dataTable.render.toggle("T", true), className: 'dt-body-center' },
            { data: "Ident", name: "AcIdent", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
            { data: "Name", name: "AcName", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
            { data: "RetailPrice", name: "AnSalePrice", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()), className: 'dt-body-right' },
            { data: "SellingPrice", name: "AnRtprice", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()), className: 'dt-body-right' },
            { data: "Classif", name: "AcClassif", filtertype: "text" },
            { data: "Classif2", name: "AcClassif2", filtertype: "text" },
            { data: "Type", name: "TypeNavigation.AcName", filtertype: "text" },
            { data: "Barcode", name: "AcCode", filtertype: "text" },
            { data: "Supplier", name: "AcSupplier", filtertype: "text" }
        ],
        createdRow: function (row, data) {
            if (data.Active !== "T") {
                $(row).addClass('danger');
            }
            if (data.Ident == acKey) {
                $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
            }
        }
    }).on('xhr.dt', function (e, settings, json, xhr) {
        if (json && json.recordsTotal)
            $('.grid-data-total-items').html(json.recordsTotal);
    });

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

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

    initializePartnerTypeahead($('#SupplierId').attr('dataUrl'), $('#SupplierId'), $("#SupplierId"), function (item) {
        $.fn.dataTable.reload($dataTable);
    });

    $("#SupplierId").on('change', function () {
        if ($("#SupplierId").val() === "")
            $.fn.dataTable.reload($dataTable);
    });
}

function initializeProductSerialNumbersList() {
    var id = decodeURI(url.searchParams.get("id"));

    $dataTable = $('#grid-data');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Ident = id;
            }
        },
        columns: [
            { data: "Warehouse", name: "AcWarehouse", filtertype: "text" },
            { data: "SerialNo", name: "AcSerialNo", filtertype: "text" },
            { data: "IsFree", name: "AcFree", render: $.fn.dataTable.render.toggle(true, true), className: 'dt-body-center', filtertype: "text" },
            { data: "Stock", name: "AnStock", render: $.fn.dataTable.render.number('.', ',', 3), className: 'dt-body-right', filtertype: "number" },
            { data: "Reserved", name: "AnReserved", render: $.fn.dataTable.render.number('.', ',', 3), className: 'dt-body-right', filtertype: "number" },
            { data: "Free", name: "AnFree", render: $.fn.dataTable.render.number('.', ',', 3), className: 'dt-body-right', filtertype: "number" },
            { data: "DateDue", name: "AdDateDue", className: 'dt-body-center', filtertype: "dateTime" }
        ]
    });

    $dataTable.on('xhr.dt', function (e, settings, json, xhr) {
        checkDateDueColumnDisplay();
        initializeSerialNoTableHeight();
    });

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

    $("#Column, #SerialNo, #DateDue").on("change", function () {
        var element = this;
        checkDateDueColumnDisplay();

        $.get($("#SetItemHasStockUrl").val() + "?ident=" + $("#Ident").val(), function (response) {
            if (response === true) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: $("#CannotChangeSerialNumbersManagmentLoc").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                if ($(element).hasClass("js-switch"))
                    $(element).attr("checked", $("#Selected" + element.id).val() === "True");
                else
                    $(element).val($("#Selected" + element.id).val());
            } else {
                $("#Selected" + element.id).val($(element).val());

                if ($("#SerialNo option:selected").val() !== "N") {
                    $(".otherDataContainer").removeClass("hidden");

                    if ($("#SerialNo option:selected").val() !== "S")
                        $("#columnContainer").removeClass("hidden");
                    else
                        $("#columnContainer").addClass("hidden");
                } else {
                    $(".otherDataContainer").addClass("hidden");
                    $("#columnContainer").addClass("hidden");
                }
            }
        });
    });
}

function checkDateDueColumnDisplay() {
    if ($("#DateDue").is(':checked'))
        $('td:nth-child(7),th:nth-child(7)').show();
    else
        $('td:nth-child(7),th:nth-child(7)').hide();
}

function saveProductSerialNumbersData() {
    $("#saveButton").find("i").addClass("fa-spinner fa-spin");
    $("#saveButton").prop("disabled", true);

    $.ajax({
        method: "POST",
        url: $("#SaveSerialNumbersDataUrl").val(),
        data: {
            Id: $("#Ident").val(),
            Column: $("#Column option:selected").val(),
            SerialNo: $("#SerialNo option:selected").val(),
            SerialnoDueType: $("#SerialnoDueType option:selected").val(),
            MonthDue: $("#MonthDue").val(),
            DateDue: $("#DateDue").is(':checked')
        },
        success: function (response) {
            $("#saveButton").find("i").removeClass("fa-spinner fa-spin");
            $("#saveButton").prop("disabled", false);
        }
    });
}

function restoreSerialNumbersStatus() {
    $("#restoreSerialNumberStatusBtn").find("i").addClass("fa-spinner fa-spin");
    $("#restoreSerialNumberStatusBtn").prop("disabled", true);

    $.get($("#SerialNoStatusRecalcUrl").val() + "?ident=" + $("#Ident").val(), function (response) {
        $("#restoreSerialNumberStatusBtn").find("i").removeClass("fa-spinner fa-spin");
        $("#restoreSerialNumberStatusBtn").prop("disabled", false);

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

function initializeProductsEdit() {
    $(document).ready(function () {
        initializeNumberInputs();
        $('#ProductEditData_Id').focus();

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

        $(".side-menu-item").on("click", function (e) {
            e.preventDefault();
            if ($("#IsEdit").val() === "False")
                submitSaveProduct($(this).attr("data-url"));
        });

        if ($('#ProductEditData_IsArso').prop("checked") === true) {
            $('#packagingWrapper').removeClass('hidden');
        }

        $('#ProductEditData_IsArso').on('change', function () {
            if ($(this).prop("checked")) {
                $('#packagingWrapper').removeClass('hidden');
            }
            else if (!$(this).prop("checked")) {
                $('#packagingWrapper').addClass('hidden');
            }
        });

        $('#ProductEditData_CustTariff').on('change', function () {
            if ($("#ProductEditData_SellingPrice").val())
                calculateRetailPrice();
            else
                calculateSellingPrice();
        });

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

        $('#ProductEditData_SelectedTaxGroupId').on('change', function () {
            $("#ProductEditData_TaxRateNumber").val($(this).find("option:selected").attr("data-vat"));

            if (toNumber($('#ProductEditData_RetailPrice').val()) > 0)
                calculateSellingPrice();
            else {
                calculateRetailPrice();
            }

            if ($("#IsEdit").val() === "False") {
                $("#ProductEditData_SelectedTaxGroupIdReceive").val($("#ProductEditData_SelectedTaxGroupId").val());
                $("#ProductEditData_SelectedTaxGroupIdReceive").trigger("change");
            }
        });

        $('#ProductEditData_SelectedTaxGroupIdReceive').on('change', function () {
            $("#ProductEditData_TaxRateNumberReceive").val($(this).find("option:selected").attr("data-vat"));
        });

        $('#ProductEditData_SellingPrice').on('change', function () {
            $("#ProductEditData_SellingPrice").attr("data-val", $('#ProductEditData_SellingPrice').val());
            calculateRetailPrice();
        });

        $('#ProductEditData_RetailPrice').on('change', function () {
            calculateSellingPrice();
        });

        initializePartnerTypeahead($('#ProductEditData_SupplierId').attr('dataUrl'), $('#ProductEditData_SupplierId'), $("#ProductEditData_SupplierId"));
        initializePartnerTypeahead($('#ProductEditData_ForSubject').attr('dataUrl'), $('#ProductEditData_ForSubject'), $("#ProductEditData_ForSubject"));
        $("#ProductEditData_TaxRateNumber").val($("#ProductEditData_SelectedTaxGroupId").find("option:selected").attr("data-vat"));
        $("#ProductEditData_TaxRateNumberReceive").val($("#ProductEditData_SelectedTaxGroupIdReceive").find("option:selected").attr("data-vat"));
    });
}

function calculateRetailPrice() {
    if ($('#ProductEditData_SelectedTaxGroupId').val() && $('#ProductEditData_SellingPrice').val()) {
        getPrice("SP", formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_SellingPrice").val(), true), $('#ProductEditData_RetailPrice'));
    }
}

function calculateSellingPrice() {
    if ($('#ProductEditData_SelectedTaxGroupId').val() && $('#ProductEditData_RetailPrice').val()) {
        getPrice("BP", formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_RetailPrice").val(), true), $('#ProductEditData_SellingPrice'));
    }
}

function getPrice(type, price, $element) {
    if ($('#ProductEditData_SelectedTaxGroupId').val() && $('#ProductEditData_SellingPrice').val()) {
        $.ajax({
            method: "POST",
            url: $("#GetItemPriceUrl").val(),
            data: {
                Ident: $("#ProductEditData_Id").val(),
                CustTarif: $("#ProductEditData_CustTariff option:selected").val(),
                VAT: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_SelectedTaxGroupId option:selected").attr("data-vat"), true),
                Type: type,
                SalePrice: price,
                RetailPrice: price
            },
            success: function (response) {
                if (type === "BP")
                    $("#ProductEditData_SellingPrice").attr("data-val", response);
                $element.val(response);
                initializeNumberInputs();
            }
        });
    }
}

function initializeProductsCreate() {
    initializeProductsEdit();
}

function importProductsClick() {
    window.location = $("#importProductsUrl").val();
}

//Import products
var products = [];
var validationErrors = [];
var productsWithErrors = [];

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

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

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

    $("#showOnlyErrors").on('change', function (e) {
        if ($('input#showOnlyErrors').is(':checked')) {
            productsImportExcel(productsWithErrors);
        } else {
            productsImportExcel(products);
        }
    });
}

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

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

            if (result.Errors && result.Errors.length > 0) {
                products = AddProductsToTableList(products, result.InvalidProducts, true);
                productsWithErrors = AddProductsToTableList(productsWithErrors, result.InvalidProducts);
                $("#errorsCount").text(result.Errors.length);
                validationErrors = result.Errors;
            }

            if (result.ProductsToInsert && result.ProductsToInsert.length > 0) {
                products = AddProductsToTableList(products, result.ProductsToInsert);
                $("#productsToInsertCount").text(result.ProductsToInsert.length);
            }

            if (result.ProductsToUpdate && result.ProductsToUpdate.length > 0) {
                products = AddProductsToTableList(products, result.ProductsToUpdate);
                $("#productsToUpdateCount").text(result.ProductsToUpdate.length);
            }

            if ($('input#showOnlyErrors').is(':checked')) {
                productsImportExcel(productsWithErrors);
            } else {
                productsImportExcel(products);
            }
        }
    });
}

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

    return tableList;
}

function productsImportExcel(items) {
    $("#uploadContainer").addClass("hidden");
    $("#productTableContainer").removeClass("hidden");

    $dataTable = $('#products-grid');
    if ($.fn.dataTable.isDataTable('#products-grid')) {
        $("#products-grid").DataTable().clear();
        $("#products-grid").DataTable().rows.add(items).draw();
    } else
        $('#products-grid').DataTable({
            data: items,
            serverSide: false,
            ajax: undefined,
            scroller: false,
            responsive: false,
            paging: false,
            info: false,
            sScrollX: "100%",
            scrollX: true,
            fixedColumns: {
                leftColumns: 3
            },
            columns: [
                { data: "Id", render: $.fn.dataTable.render.input(null, true, "row-", "Id"), visible: false },
                { data: "HasErrors", render: $.fn.dataTable.render.errorStatus("status-", "Id"), className: 'dt-body-center dt-head-center statusIcon' },
                { data: "AcIdent", render: $.fn.dataTable.render.input(null, true, "AcIdent-", "Id", "fixedCol") },
                { data: "AcName", render: $.fn.dataTable.render.input(null, false, "AcName-", "Id") },
                { data: "AcSupplier", render: $.fn.dataTable.render.input(null, false, "AcSupplier-", "Id") },
                { data: "AcCode", render: $.fn.dataTable.render.input(null, false, "AcCode-", "Id", "medium") },
                { data: "AcUm", render: $.fn.dataTable.render.dropdownOptions($("#unitsOptions"), "AcUm-", "Id", "dt-dropdown") },
                { data: "AcSetOfItem", render: $.fn.dataTable.render.dropdownOptions($("#typesOptions"), "AcSetOfItem-", "Id", "dt-dropdown") },
                { data: "AcVatcode", render: $.fn.dataTable.render.dropdownOptions($("#taxOptions"), "AcVatcode-", "Id", "dt-dropdown") },
                { data: "AnRtprice", render: $.fn.dataTable.render.input(null, false, "AnRtprice-", "Id", "medium numberInput") },
                { data: "AnWsprice", render: $.fn.dataTable.render.input(null, false, "AnWsprice-", "Id", "medium numberInput") },
                { data: "AnWsprice2", render: $.fn.dataTable.render.input(null, false, "AnWsprice2-", "Id", "medium numberInput") },
                { data: "AnPrStPrice", render: $.fn.dataTable.render.input(null, false, "AnPrStPrice-", "Id", "medium numberInput") },
                { data: "AcCurrency", render: $.fn.dataTable.render.input(null, false, "AcCurrency-", "Id", "small") },
                { data: "AcClassif", render: $.fn.dataTable.render.dropdownOptions($("#primaryClassifOptions"), "AcClassif-", "Id", "dt-dropdown") },
                { data: "AcClassif2", render: $.fn.dataTable.render.dropdownOptions($("#secondaryClassifOptions"), "AcClassif2-", "Id", "dt-dropdown") },
                { data: "AcCustTariff", render: $.fn.dataTable.render.dropdownOptions($("#typesOptions"), "AcSetOfItem-", "Id", "dt-dropdown medium") },
                { data: "AnPriceSupp", render: $.fn.dataTable.render.input(null, false, "AnPriceSupp-", "Id", "medium numberInput") },
                { data: "AcVatcodeReceive", render: $.fn.dataTable.render.dropdownOptions($("#taxOptions"), "AcVatcodeReceive-", "Id", "dt-dropdown") }
            ]
        });

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

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

    $('#products-grid').DataTable().columns.adjust();
    initializeNumberInputs();
    DisplayProductErrors(validationErrors);
    $('.fixedCol').parent('td').addClass('fixedColBorder');
}

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

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

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

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

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

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

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

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

        DisplayProductErrors(validationErrors);
    });
}

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

    return dropdownReadyList;
}

function getProductRowData(data) {
    if (!data)
        return;
    var product = data;
    var rowId = data.Id;

    product.AcIdent = $("#AcIdent-" + rowId).val();
    product.AcName = $("#AcName-" + rowId).val();
    product.AcSupplier = $("#AcSupplier-" + rowId).val();
    product.AcCode = $("#AcCode-" + rowId).val();
    product.AcUm = $("#AcUm-" + rowId).val();
    product.AcSetOfItem = $("#AcSetOfItem-" + rowId).val();
    product.AcVatcode = $("#AcVatcode-" + rowId).val();
    product.AnRtprice = toNumber($("#AnRtprice-" + rowId).val());
    product.AnWsprice = toNumber($("#AnWsprice-" + rowId).val());
    product.AnWsprice2 = toNumber($("#AnWsprice2-" + rowId).val());
    product.AnPrStPrice = toNumber($("#AnPrStPrice-" + rowId).val());
    product.AcCurrency = $("#AcCurrency-" + rowId).val();
    product.AcClassif = $("#AcClassif-" + rowId).val();
    product.AcClassif2 = $("#AcClassif2-" + rowId).val();
    product.AcCustTariff = $("#AcCustTariff-" + rowId).val();
    product.AnPriceSupp = toNumber($("#AnPriceSupp-" + rowId).val());
    product.AcVatcodeReceive = $("#AcVatcodeReceive-" + rowId).val();

    return product;
}

function DisplayProductErrors(errorList) {
    if (errorList && errorList.length > 0) {
        errorList.forEach(err => {
            $("#" + err.ColumnName + "-" + err.Id).addClass("table-input-error");
            if (err.ColumnName === "AcIdent") {
                $(".fixedCol#" + err.ColumnName + "-" + err.Id).addClass("table-input-error");
            }
        });
    }

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

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

    products.forEach(function (item, index) {
        item.AnRtprice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.AnRtprice, true);
        item.AnWsprice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.AnWsprice, true);
        item.AnWsprice2 = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.AnWsprice2, true);
        item.AnPrStPrice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.AnPrStPrice, true);
        item.AnPriceSupp = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.AnPriceSupp, true);
    });

    swapLoadingIcon(true, "saveButton", "fa fa-save");
    $.ajax({
        method: "POST",
        url: $("#processProductsInsertAndUpdateUrl").val(),
        data: { products: products },
        success: function (response) {
            swapLoadingIcon(false, "saveButton", "fa fa-save");
            if (response.Success === true)
                window.location = $("#identsIndexUrl").val();
            else {
                $("#errorModalMessage").text(response.Errors);
                $("#errorModal").modal('show');
            }
        }
    });
}

// Import products contract prices
var productsContractPrices = [];
var validationErrorsContractPrices = [];
var productsWithErrorsContractPrices = [];

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

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

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

    $("#showOnlyErrors").on('change', function (e) {
        if ($('input#showOnlyErrors').is(':checked')) {
            productsContractPricesImportExcel(productsWithErrorsContractPrices);
        } else {
            productsContractPricesImportExcel(productsContractPrices);
        }
    });
}

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

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

            if (result.Errors && result.Errors.length > 0) {
                productsContractPrices = AddProductsToTableList(productsContractPrices, result.InvalidProducts, true);
                productsWithErrorsContractPrices = AddProductsToTableList(productsWithErrorsContractPrices, result.InvalidProducts);
                $("#errorsCount").text(result.Errors.length);
                validationErrorsContractPrices = result.Errors;
            }

            if (result.ProductsToInsert && result.ProductsToInsert.length > 0) {
                productsContractPrices = AddProductsToTableList(productsContractPrices, result.ProductsToInsert);
                $("#productPricesToInsertCount").text(result.ProductsToInsert.length);
            }

            if (result.ProductsToUpdate && result.ProductsToUpdate.length > 0) {
                productsContractPrices = AddProductsToTableList(productsContractPrices, result.ProductsToUpdate);
                $("#productPricesToUpdateCount").text(result.ProductsToUpdate.length);
            }

            if ($('input#showOnlyErrors').is(':checked')) {
                productsContractPricesImportExcel(productsWithErrorsContractPrices);
            } else {
                productsContractPricesImportExcel(productsContractPrices);
            }
        }
    });
}

function productsContractPricesImportExcel(items) {
    $("#uploadContainer").addClass("hidden");
    $("#productContractPricesTableContainer").removeClass("hidden");

    $dataTable = $('#products-grid');
    if ($.fn.dataTable.isDataTable('#products-grid'))
        $dataTable.DataTable().destroy();

    $dataTable.DataTable({
        data: items,
        serverSide: false,
        ajax: undefined,
        scroller: false,
        responsive: false,
        paging: false,
        info: false,
        sScrollX: "100%",
        scrollX: true,
        fixedColumns: {
            leftColumns: 3
        },
        columns: [
            { data: "Id", render: $.fn.dataTable.render.input(null, true, "row-", "Id"), visible: false },
            { data: "HasErrors", render: $.fn.dataTable.render.errorStatus("status-", "Id"), className: 'dt-body-center dt-head-center statusIcon' },
            { data: "AcIdent", render: $.fn.dataTable.render.input(null, true, "AcIdent-", "Id", "fixedCol") },
            { data: "AcSubject", render: $.fn.dataTable.render.input(null, false, "AcSubject-", "Id") },
            { data: "AcInvoInOut", render: $.fn.dataTable.render.dropdownOptions($("#typesOptions"), "AcInvoInOut-", "Id", "small dt-dropdown") },
            { data: "AnContractPrice", render: $.fn.dataTable.render.input(null, false, "AnContractPrice-", "Id", "medium numberInput") },
            { data: "AnRebate", render: $.fn.dataTable.render.input(null, false, "AnRebate-", "Id", "medium numberInput") },
            { data: "AnRebate2", render: $.fn.dataTable.render.input(null, false, "AnRebate2-", "Id", "medium numberInput") },
            { data: "AnRebate3", render: $.fn.dataTable.render.input(null, false, "AnRebate3-", "Id", "medium numberInput") },
            { data: "AcFormula", render: $.fn.dataTable.render.input(null, false, "AcFormula-", "Id", "medium") },
            { data: "AdValidityDateFrom", render: $.fn.dataTable.render.input(null, false, "AdValidityDateFrom-", "Id", "small datepicker") },
            { data: "AdValidityDateTo", render: $.fn.dataTable.render.input(null, false, "AdValidityDateTo-", "Id", "small datepicker") },
            { data: "AnPaymentPeriod", render: $.fn.dataTable.render.input(null, false, "AnPaymentPeriod-", "Id", "small") },
            { data: "AnDeliveryDate", render: $.fn.dataTable.render.input(null, false, "AnDeliveryDate-", "Id", "small") },
            { data: "AcCurrency", render: $.fn.dataTable.render.input(null, false, "AcCurrency-", "Id", "small") }
        ]
    });

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

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

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

    $('#products-grid').DataTable().columns.adjust();
    initializeNumberInputs();
    DisplayProductErrors(validationErrorsContractPrices);
    $('.fixedCol').parent('td').addClass('fixedColBorder');
}

function importProductContractPricesClick() {
    window.location = $("#importProductsContractPricesUrl").val();
}

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

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

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

    $.ajax({
        url: $("#ValidateProductUrl").val(),
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(product)
    }).done(function (response) {
        inputsWithErrors.removeClass("table-input-error");
        if (!response.Success) {
            validationErrors = response.Errors;
            $("#status-" + product.Id).html("<i class='fa fa-times fa-lg text-danger'></i>");
        } else {
            validationErrorsContractPrices = [];
            $("#status-" + product.Id).empty();
            product.HasErrors = false;
        }

        productsContractPrices.map(prod => {
            if (prod.Id === product.Id) {
                prod = product;
            }
        });

        DisplayProductErrors(validationErrorsContractPrices);
    });
}

function getProductContractPricesRowData(data) {
    if (!data)
        return;
    var product = data;
    var rowId = data.Id;

    product.AcIdent = $("#AcIdent-" + rowId).val();
    product.AcSubject = $("#AcSubject-" + rowId).val();
    product.AcInvoInOut = $("#AcInvoInOut-" + rowId).val();
    product.AnContractPrice = toNumber($("#AnContractPrice-" + rowId).val());
    product.AnRebate = toNumber($("#AnRebate-" + rowId).val());
    product.AnRebate2 = toNumber($("#AnRebate2-" + rowId).val());
    product.AnRebate3 = toNumber($("#AnRebate3-" + rowId).val());
    product.AcFormula = $("#AcFormula-" + rowId).val();
    product.AdValidityDateFrom = $("#AdValidityDateFrom-" + rowId).val();
    product.AdValidityDateTo = $("#AdValidityDateTo-" + rowId).val();
    product.AnPaymentPeriod = $("#AnPaymentPeriod-" + rowId).val();
    product.AnDeliveryDate = $("#AnDeliveryDate-" + rowId).val();
    product.AcCurrency = $("#AcCurrency-" + rowId).val();

    return product;
}

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

    $.ajax({
        method: "POST",
        url: $("#processProductsInsertAndUpdateUrl").val(),
        contentType: 'application/json',
        data: JSON.stringify(productsContractPrices),
        success: function (response) {
            if (response.Success === true)
                window.location = $("#identsIndexUrl").val();
            else {
                $("#errorModalMessage").text(response.ErrorMessage + "\n" + response.Errors);
                $("#errorModal").modal('show');
            }
        }
    });
}

function submitSaveProduct(openTab = null) {
    var formData = $("#productForm").serializeArray();
    formData = changeFormDataValue(formData, 'ProductEditData.SuppliersPrice', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_SuppliersPrice").val(), true));
    formData = changeFormDataValue(formData, 'ProductEditData.SellingPrice', formatDisplay(null, $("#ProductEditData_SellingPrice").attr("data-val"), true));
    formData = changeFormDataValue(formData, 'ProductEditData.RetailPrice', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_RetailPrice").val(), true));
    formData = changeFormDataValue(formData, 'ProductEditData.Stock', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_Stock").val(), true));
    formData = changeFormDataValue(formData, 'ProductEditData.WSPrice', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_WSPrice").val(), true));
    formData = changeFormDataValue(formData, 'ProductEditData.WSPrice2', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_WSPrice2").val(), true));

    var url = $("#createProductUrl").val();
    if ($("#IsEdit").val() === "True")
        url = $("#editProductUrl").val();

    swapLoadingIcon(true, "saveButton", "fa fa-save");
    $.post(url, formData)
        .done(function (response) {
            swapLoadingIcon(false, "saveButton", "fa fa-save");
            if (response.Success) {
                if (openTab) {
                    $("#ProductEditData_Id").val(response.id);
                    $("#deleteProductBtn").removeClass("hidden");
                    window.history.pushState({}, null, $("#editProductUrl").val() + "?id=" + response.id);
                    window.location = $("#editProductUrl").val() + openTab + response.id;
                } else if ($("#IsEdit").val() === "True")
                    window.location = $("#productsIndex").val();
                else
                    window.location = $("#productsIndex").val() + "?search=" + response.id;
            } else if (!response.Success && response.ErrorGeneratingId) {
                var errMsg = stringFormat($("#FieldRequiredForCreatingKeyLoc").val(), response.product.GenerItemNoField);
                if (response.product.ErrorGeneratingValue)
                    errMsg = stringFormat($("#FieldRequiredForCreatingKeyLoc").val(), $("#ProductEditData_GenerItemNoField").val());
                if (response.product.ErrorGeneratingProperty)
                    errMsg = stringFormat($("#FieldDoesNotExistLoc").val(), $("#ProductEditData_GenerItemNoField").val());

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

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

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

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

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

function saveSetItemCpa(anQid) {
    let sufix = anQid != 0 ? "-" + anQid : "";

    var errorTxt = "";
    if ($("#IsEdit").val() !== "True")
        errorTxt = $("#TxtGeneralError").val();
    else if (!$("#input-cpa-clasif" + sufix).val() || !$("#input-cpa-docType" + sufix).val())
        errorTxt = $("#TxtEnterData").val();

    if (errorTxt !== "") {
        $().customModal({
            destroyOnClose: true,
            title: '',
            showCloseButton: true,
            type: "alert",
            text: errorTxt,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#TxtConfirm").val(),
                    closeOnAction: true,
                    type: 'primary'
                }]
        });

        return;
    }

    let data = {
        AnQid: anQid ? anQid : 0,
        ItemQid: $("#AnQid").val(),
        ClassProdByAct: $("#input-cpa-clasif" + sufix).val(),
        DocType: $("#input-cpa-docType" + sufix).val(),
    };

    postSetItemCpa(data);
}

function postSetItemCpa(data) {
    $.ajax({
        url: $("#SaveCpaUrl").val(),
        type: 'POST',
        data: data,
        success: function (result) {
            if (!result.Status) {
                return;
            }
            location.reload();
        }
    });
}

function deleteSetItemCpa(anQid) {
    var deleteText = $("#TxtDeleteQuestion").val();
    var deleteTitle = $("#TxtConfirmation").val();
    var confirmText = $("#TxtConfirm").val();
    var cancelText = $("#TxtCancel").val();

    $().customModal({
        destroyOnClose: true,
        title: deleteTitle,
        showCloseButton: true,
        type: "question",
        text: deleteText,
        buttons: [{
            icon: 'fa fa-times',
            text: cancelText,
            closeOnAction: true,
            type: 'ghost'
        },
        {
            icon: 'fa fa-check',
            text: confirmText,
            closeOnAction: true,
            action: async function () {
                await new Promise((resolve, reject) => setTimeout(function () {
                    removeSetItemCpa(anQid);
                    resolve();
                }, 1500));
            },
            closeOnAction: true,
            type: 'primary'
        }]
    });
}

function removeSetItemCpa(anQid) {
    $.ajax({
        url: $("#DeleteCpaUrl").val() + '?anQId=' + anQid,
        type: 'GET',
        success: function (data) {
            if (data && data.Status) {
                $("#tr-cpa-" + anQid).remove();
            }
            else {
                $(document).ready(function () {
                    $().customModal({
                        destroyOnClose: true,
                        title: '',
                        showCloseButton: true,
                        type: "alert",
                        text: $("#TxtGeneralError").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#TxtConfirm").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }]
                    });
                });
            }
        }
    });
}

var heightInitialized = false;
function initializeSerialNoTableHeight() {

    if (heightInitialized) {
        return;
    }
    heightInitialized = true;

    var rectTop = document.getElementById("grid-data").getBoundingClientRect().top;
    var rectBottom = document.body.scrollHeight;

    let offset = 3;
    let dtHeight = (rectBottom - rectTop - offset) + "px";

    $(".dataTables_scrollBody").css("height", dtHeight);
    $(".dataTables_scrollBody").css("min-height", dtHeight);
}