function initializeTaxes() {
    $dataTable = $('#mainGridTaxRates');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.Taxes = $("#Taxes").val() ? $("#Taxes").val().toString() : null;
                d.Status = $("#Status").val();
            }
        },
        columns: [
            { data: "VATCode", name: "AcVatcode", filtertype: "text", render: $.fn.dataTable.render.link("VATCode") },
            { data: "Name", name: "AcName", filtertype: "text", render: $.fn.dataTable.render.link("VATCode") },
            { data: "FiscalCode", name: "AcFiscalCode", filtertype: "text" },
            { data: "NameFisk", name: "AcNameFisk", filtertype: "text" },
            { data: "VAT", name: "AnVat", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()) },
            {
                data: "EDocument", name: "acEDocument", filtertype: "text", render: function (data, type) {
                    switch (data) {
                        case "S":
                            return data + " - " + $("#StandardTaxRateLoc").val();
                        case "E":
                            return data + " - " + $("#ExemptFromVATLoc").val();
                        case "O":
                            return data + " - " + $("#TheSubjectIsNotInTheVATSystemLoc").val();
                        case "Z":
                            return data + " - " + $("#ZeroVATRateLoc").val();
                        case "G":
                            return data + " - " + $("#ExemptFromVATDueToExportLoc").val();
                        case "AE":
                            return data + " - " + $("#TransferOfTaxLiabilityLoc").val();
                        case "B":
                            return data + " - " + $("#ExemptFromVATLoc").val();
                        case "R":
                            return data + " - " + $("#ExemptionFromVATLoc").val();
                    }

                    return data;
                }
            },
            { data: "Statement", name: "AcStatement", filtertype: "text" }
        ]
    });

    $("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);
    });
}

function printTax(reportCode) {
    swapLoadingIcon(true, "printButton", "far fa-print");

    var url = $("#TaxPrintUrl").val() + "?ReportType=" + reportCode + "&Status=" + $("#Status").val();
    var taxes = $("#Taxes").val() ? $("#Taxes").val().toString() : null;
    if (taxes)
        url = url + "&Taxes=" + taxes;

    printWindow = window.open();
    printWindow.document.write(generatePrintingPage());
    printPAAS("", false, false, url, false);
    swapLoadingIcon(false, "printButton", "far fa-print");
}

function updateTaxRates(context) {
    $(context).find("i").removeClass("fa-paper-plane").addClass("fa-spin fa-spinner");
    $.ajax({
        url: $("#UpdateTaxRatesUrl").val(), type: 'POST', cache: false
    }).done(function (data) {
        if (data.Success) {
            $().customModal({
                destroyOnClose: true,
                type: "success",
                text: $("#TaxRatesUpdateSuccessfulLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#OkLoc").val(),
                        type: 'primary',
                        closeOnAction: true,
                        action: function () {
                            location.reload();
                        }
                    }
                ]
            });
        }
        else if (data.Error && data.Error.length > 0) {
            $().customModal({
                destroyOnClose: true,
                type: "error",
                text: data.Error,
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: $("#OkLoc").val(),
                        type: 'primary',
                        closeOnAction: true
                    }
                ]
            });
        }
        else {
            $().customModal({
                destroyOnClose: true,
                type: "error",
                text: $("#GeneralErrorMessage").val(),
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: $("#OkLoc").val(),
                        type: 'primary',
                        closeOnAction: true
                    }
                ]
            });
        }
    }).fail(function () {
        $().customModal({
            destroyOnClose: true,
            type: "error",
            text: $("#GeneralErrorMessage").val(),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#OkLoc").val(),
                    type: 'primary',
                    closeOnAction: true
                }
            ]
        });
    }).always(function () {
        $(context).find("i").removeClass("fa-spin fa-spinner").addClass("fa-paper-plane");
    });
}

function initializeTaxesEdit() {
    $('#VATCode').focus();

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

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

    $("#VAT").on("change", function () {
        if ($("#IsEdit").val() === "True")
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#ConfirmChangeTaxPercentLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: $("#CancelLoc").val(),
                        action: function () {
                            $("#VAT").val($("#savedVAT").val());
                        },
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        action: function () {
                            confirmChangeIdentPrices();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
    });
}

async function confirmChangeIdentPrices() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        id: "confirmChangeIdentPricesModal",
        type: "alert",
        text: $("#InItemPricingRetailPriceWillBeChangedLoc").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#CancelLoc").val(),
                action: function () {
                    $("#VAT").val($("#savedVAT").val());
                },
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                class: 'btnConfirmChangeIdentPrices',
                text: $("#ConfirmLoc").val(),
                action: async function () {
                    $("#savedVAT").val($("#VAT").val());
                    await changeTaxPercent();
                },
                type: 'primary'
            }
        ]
    });
}

async function changeTaxPercent() {
    await fetch($("#ChangeTaxPercentUrl").val(), {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ VATCode: $("#VATCode").val(), VAT: $("#VAT").val() })
    }).then((response) => response.json()
    ).then(async (data) => {
        $("#confirmChangeIdentPricesModal").customModal('close');
    }).catch((error) => {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $("#GeneralErrorMessage").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    });
}

function removeTax() {
    $().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 elementId = $("#VATCode").val();
                    const config = {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: elementId })
                    };

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