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

function getTableData() {
    $dataTable = $('#mainGrid');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.TypeOfDocument = $("#SelectedDocType").val();
            }
        },
        columns: [
            { data: "IdView", name: "AcDocType", filtertype: "text", render: $.fn.dataTable.render.link("Id") },
            { data: "Name", name: "AcName", filtertype: "text", render: $.fn.dataTable.render.link("Id") },
            { data: "FiscalWorkplaceId", name: "AcWorkPlace", filtertype: "text", render: $.fn.dataTable.render.link("FiscalWorkplaceId") }
        ]
    });

    $("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 btnCreateNewDocType() {
    window.location = $("#createUrl").val() + "?type=" + $("#SelectedTypeOfDoc").val();
}

function initializeDocumentTypeEdit(fiscalPrintersLocalization, checkFiscalWorkplace) {
    $(document).ready(function () {
        var checkSubmit = false;
        $("#mainForm").on("submit", function (e) {
            $("#saveButton i").removeClass("fa-save").addClass("fa-spinner fa-spin");

            if ($("#CanFiscalize").is(":checked") && !checkSubmit) {
                e.preventDefault();

                if (checkFiscalWorkplace && $("#FiscalWorkplaceId").val().length === 0) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "question",
                        text: $("#WorkPlaceFiscaliteRequiredWorkplaceLoc").val(),
                        width: "25%",
                        onClose: function () {
                            $("#saveButton i").removeClass("fa-spinner fa-spin").addClass("fa-save");
                        },
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });

                    return;
                }

                if (!fiscalPrintersLocalization) {
                    $.ajax({
                        url: $("#checkFiscalWorkplaceUrl").val(),
                        dataType: 'json',
                        data: { docType: $("#Id").val(), fiscalWorkplace: $("#FiscalWorkplaceId").val(), device: $("#FiscalDevice").val() },
                        method: "POST",
                        success: function (data) {
                            if (data) {
                                $("#saveButton i").removeClass("fa-spinner fa-spin").addClass("fa-save");

                                $().customModal({
                                    title: "",
                                    destroyOnClose: true,
                                    showCloseButton: true,
                                    type: "question",
                                    text: $("#FiscalWorkplaceAndDeviceCombinationAlreadyExistsLoc").val(),
                                    width: "25%",
                                    buttons: [
                                        {
                                            icon: 'fa fa-times',
                                            text: $("#NoLoc").val(),
                                            closeOnAction: true,
                                            type: 'ghost'
                                        },
                                        {
                                            icon: 'fa fa-check',
                                            text: $("#YesLoc").val(),
                                            action: async function () {
                                                $("#saveButton i").removeClass("fa-save").addClass("fa-spinner fa-spin");
                                                checkSubmit = true;
                                                $("#mainForm").submit();
                                            },
                                            closeOnAction: true,
                                            type: 'primary'
                                        }
                                    ]
                                });
                            }
                            else {
                                checkSubmit = true;
                                $("#mainForm").submit();
                            }
                        },
                        fail: function () {
                            checkSubmit = true;
                            $("#mainForm").submit();
                        }
                    });
                }
                else {
                    $("#saveButton i").removeClass("fa-save").addClass("fa-spinner fa-spin");
                    checkSubmit = true;
                    $("#mainForm").submit();
                }
            }
        });

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

        $("#CanFiscalize, #FiscalType, #FiscAll").on("change", function (e) {
            if ($("#currentUserLoc").val() === $("#locHR").val()
                && (this.id === "CanFiscalize" || this.id === "FiscAll")
                && ($("#TypeOfDocumentSelect").val() === $("#typeOfDocumentBuyerOrder").val()
                || $("#TypeOfDocumentSelect").val() === $("#typeOfDocumentSupplierOrder").val())
            ) {
                if ($(this).is(":checked")) {
                    $(this).click();

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

                if ($("#CanFiscalize").is(":checked"))
                    $("#fiscalData").removeClass("hidden");
                else
                    $("#fiscalData").addClass("hidden");

                return;
            } else {
                if (isTriggerClickFiscal === true) {
                    isTriggerClickFiscal = false;
                    return;
                }

                checkDocTypeForFiscalDocs($(this)[0].id);
            }
        });

        var isTriggerClick = false;
        $("#Evidence").on("change", function (e) {
            if (isTriggerClick === true) {
                isTriggerClick = false;
                return;
            }

            $.get($("#canChangeIsEvidence").val() + "?docType=" + $("#Id").val(), function (response) {
                if (response === true) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: $("#thereAreAlreadyDocumentsForThisDocumentLoc").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });

                    isTriggerClick = true;
                    $("#Evidence").trigger('click');
                }
            });
        });

        $("#Type").on("change", function (e) {
            if ($(this).val() === $("#documentTypeRetail").val()) {
                $("#printSettings").removeClass("hidden");
                $("#allowZeroTotalContainer").removeClass("hidden");
                $(".pos-settings").removeClass("hidden");
            } else {
                $("#printSettings").addClass("hidden");
                $("#allowZeroTotalContainer").addClass("hidden");
                $(".pos-settings").addClass("hidden");
            }

            if ($(this).val())
                $("#checkPositionPriceQtyContainer").removeClass("hidden");
            else
                $("#checkPositionPriceQtyContainer").addClass("hidden");

            if ($(this).val() === $("#documentTypeWholesale").val()) {
                $("#acEInvoiceExportTypeContainer").removeClass("hidden");
                $('#docTypeCompGdsContainer').removeClass('hidden');
            }
            else {
                $("#acEInvoiceExportTypeContainer").addClass("hidden");
                $('#docTypeCompGdsContainer').addClass('hidden');
            }
        });

        $("#TypeOfDocumentSelect").on("change", function () {
            window.location = $("#createUrl").val() + "?type=" + $("#TypeOfDocumentSelect option:selected").val();
        });

        $("#TypeOfDocument").val($("#TypeOfDocumentSelect option:selected").val());
        $("#Type").val($("#TypeOfDocumentSelect option:selected").attr("data-type"));
        $("#Type").trigger("change");

        if ($("#CanFiscalize").is(":checked"))
            $("#fiscalData").removeClass("hidden");
        else
            $("#fiscalData").addClass("hidden");

        $("#TypeDoc").on("change", function () {
            if ($("#TypeDoc option:selected").val() === $("#typeDocInternal").val() && $("#TypeOfDocumentSelect option:selected").val() === $("#typeOfDocumentReceivedBills").val())
                $("#deferredStorageContainer").removeClass("hidden");
            else
                $("#deferredStorageContainer").addClass("hidden");
        });
        $("#TypeDoc").trigger("change");

        initDocTypeCompGds();
    });
}

function openLPFRServerDataModal($fiscalServer, $fiscalTaxServer, $fiscalCheckConnectionServer, title, tableTitles, rowTitles) {
    let serverLines = "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[0] + "</td><td class='no-padding'><input id='fiscalServer_dataModal' class='form-control' value='" + $fiscalServer.val() + "' /></td></tr>";
    serverLines += "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[1] + "</td><td class='no-padding'><input id='fiscalTaxServer_dataModal' class='form-control' value='" + $fiscalTaxServer.val() + "' /></td></tr>";
    serverLines += "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[2] + "</td><td class='no-padding'><input id='fiscalCheckConnectionServer_dataModal' class='form-control' value='" + $fiscalCheckConnectionServer.val() + "' /></td></tr>";

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "modal",
        title: title,
        content: "<table class='table table-bordered'><thead><tr><th width='20%'>" + tableTitles[0] + "</th><th width='80%'>" + tableTitles[1] + "</th></tr></thead><tbody>" + serverLines + "<tbody></table>",
        buttons: [
            {
                text: $("#OkLoc").val(),
                icon: 'fa fa-check',
                type: 'primary',
                closeOnAction: true,
                action: function () {
                    $fiscalServer.val($("#fiscalServer_dataModal").val());
                    $fiscalTaxServer.val($("#fiscalTaxServer_dataModal").val());
                    $fiscalCheckConnectionServer.val($("#fiscalCheckConnectionServer_dataModal").val());
                }
            }
        ]
    });
}

function initializeDocumentTypeCreate() {
    initializeDocumentTypeEdit();
}

function deleteExpenseType(num) {
    var tableRows = $('table#travelorders-expenses > tbody > tr:nth-child(n+3)');
    var totalRows = tableRows.length;
    var intNum = parseInt(num);
    $('#doctype-expenses-row-' + num).remove();

    for (var i = intNum; i < totalRows; i++) {
        $('#doctype-expenses-row-' + (i + 1) + ' #AnQId-' + (i + 1)).attr("id", "AnQId-" + i).attr("Name", "Expenses[" + i + "].AnQId");
        $('#doctype-expenses-row-' + (i + 1) + ' #DocType-' + (i + 1)).attr("id", "DocType-" + i).attr("Name", "Expenses[" + i + "].DocType");
        $('#doctype-expenses-row-' + (i + 1) + ' #Active-' + (i + 1)).attr("id", "Active-" + i).attr("Name", "Expenses[" + i + "].Active");
        $('#doctype-expenses-row-' + (i + 1) + ' #Type-' + (i + 1)).attr("id", "Type-" + i).attr("Name", "Expenses[" + i + "].Type").val(i);
        $('#doctype-expenses-row-' + (i + 1) + ' #Name-' + (i + 1)).attr("id", "Name-" + i).attr("Name", "Expenses[" + i + "].Name");
        $('#doctype-expenses-row-' + (i + 1) + ' #NotForPay-' + (i + 1)).attr("id", "NotForPay-" + i).attr("Name", "Expenses[" + i + "].NotForPay");
        $('#doctype-expenses-row-' + (i + 1) + ' #EarningType-' + (i + 1)).attr("id", "EarningType-" + i).attr("Name", "Expenses[" + i + "].EarningType");
        $('#doctype-expenses-row-' + (i + 1) + ' #Account-' + (i + 1)).attr("id", "Account-" + i).attr("Name", "Expenses[" + i + "].Account");
        $('#doctype-expenses-row-' + (i + 1) + ' a').attr("onclick", "deleteExpenseType('" + i + "')");

        $("#doctype-expenses-row-" + (i + 1)).attr("id", "doctype-expenses-row-" + i);
    }
}

function addNewExpenseType() {
    var tableRows = $('table#travelorders-expenses > tbody > tr');
    var cloneCount = tableRows.not(':first').length;
    var newAnNo = cloneCount++;
    var expensesRow = '#doctype-expenses-row-' + newAnNo;

    tableRows.find(".select2withAPI").each(function (index) {
        if ($(this).data('select2')) {
            $(this).select2('destroy');
        }
    });

    $('#doctype-expenses-new-row').clone().attr('id', 'doctype-expenses-row-' + newAnNo).appendTo("#travelorders-expenses > tbody");
    $(expensesRow).find('#btn-col').empty().append("<td><a class='a-outline' onclick=deleteExpenseType('" + newAnNo + "')><i class='far fa-trash-alt'></i></a></td>").removeAttr("id").removeClass("add-btn-td");

    $(expensesRow + " #DocType--1").attr("id", "DocType-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].DocType");
    $(expensesRow + " #Active--1").attr("id", "Active-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].Active");
    $(expensesRow + " #Type--1").attr("id", "Type-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].Type");
    $(expensesRow + " #Name--1").attr("id", "Name-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].Name");
    $(expensesRow + " #NotForPay--1").attr("id", "NotForPay-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].NotForPay");
    $(expensesRow + " #EarningType--1").attr("id", "EarningType-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].EarningType");
    $(expensesRow + " #Account--1").attr("id", "Account-" + newAnNo).attr("Name", "Expenses[" + newAnNo + "].Account");

    clearNewExpensesRow();
    select2withAPI();
}

function clearNewExpensesRow() {
    $("#Active--1").attr("checked", false);
    $("#Type--1").val("");
    $("#Name--1").val("");
    $("#NotForPay--1").attr("checked", false);
    $("#EarningType--1").empty();
    $("#Account--1").val("");
}

function setNewCostTypeNumber() {
    var newCostNumberType = $('table#travelorders-expenses > tbody > tr').length - 1;
    $('tr#doctype-expenses-new-row #Type--1').val(newCostNumberType);
}

var isTriggerClickFiscal = false;
function checkDocTypeForFiscalDocs(id) {
    $.get($("#docTypeHasFiscalDocsUrl").val() + "?docType=" + $("#Id").val(), function (response) {
        if (response === true) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#cannotChangeCanFiscalizeSettingLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            isTriggerClickFiscal = true;
            if (id === "FiscalType")
                $("#" + id).val($("#FiscalTypeSaved").val());
            else
                $("#" + id).click();

            return;
        } else
            if (id === "CanFiscalize") {
                if ($("#CanFiscalize").is(":checked"))
                    $("#fiscalData").removeClass("hidden");
                else
                    $("#fiscalData").addClass("hidden");
            }
    });
}

function togglePrintOptionGroup(element, event) {
    event.stopPropagation();
    $(element).closest(".print-option-group").toggleClass("print-group-closed");
}

function selectPrintType($element, type, typeOfDoc) {
    $("div.custom-option-selected").removeClass("custom-option-selected");
    $($element).addClass("custom-option-selected");

    $("#SelectedDocType").val(type);
    $("#SelectedTypeOfDoc").val(typeOfDoc);
    if ($.fn.DataTable.isDataTable('#mainGrid'))
        $.fn.dataTable.reload($('#mainGrid'));
    else
        getTableData();
}

function checkRemoveDocType() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#ConfirmDeleteMessageLoc").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#CancelLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                action: function () {
                    removeDocType();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function removeDocType() {
    $.ajax({
        url: $("#removeUrl").val(),
        dataType: 'json',
        data: { id: $("#Id").val() },
        method: "POST",
        success: function (data) {
            if (!data || data.Error) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: $("#DeleteWasNotSuccessfulLoc").val() + "<br><br>" + data.Error,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else
                location.href = $("#indexUrl").val();
        },
        fail: function (response) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: response.Error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function createNewDocType() {
    location.href = $("#createUrl").val();
}

function copyStatus() {
    if ($("#copyStatusDocTypeSelect option:selected").val()) {
        $.get($("#copyStatusUrl").val() +
            "?docTypeFrom=" + $("#copyStatusDocTypeSelect option:selected").val()
            + "&docTypeTo=" + $("#Id").val()
            + "&overlap=" + ($('input[name="copyStatusRadio"]:checked').val() === "overlapping"),
            function (response) {
                if (!response || response === false) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: $("#ErrorLoc").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "success",
                        text: $("#CopyCompletedLoc").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });
    }
}

function prevNavNeighbour(element) {
    $(element).removeClass("fa-chevron-left").addClass("fa-spinner").addClass("fa-spin");
    window.location = $("#getFirstForTypeOfDocumentUrl").val() + "?type=" + $("#TypeOfDocumentSelect option:selected").prev().val();
}

function nextNavNeighbour(element) {
    $(element).removeClass("fa-chevron-right").addClass("fa-spinner").addClass("fa-spin");
    window.location = $("#getFirstForTypeOfDocumentUrl").val() + "?type=" + $("#TypeOfDocumentSelect option:selected").next().val();
}

function setDocTypeCompGdsVal() {
    var val = $('#DocTypeCompGds').val().substring(0, $('#DocTypeCompGds').val().length - 1);
    $('#docTypeCompGdsSearch.custom-typeahead').val(val).next('.custom-typeahead-display').val(val);
}
function initDocTypeCompGds() {
    $('#DocTypeCompGds').on('change', setDocTypeCompGdsVal);

    setDocTypeCompGdsVal();

    $('#docTypeCompGdsSearch.custom-typeahead').customTypeahead({
        value: "DocType",
        display: "Name",
        minWidth: "330px",
        minSearchLength: 0,
        focusOpen: true,
        paginate: false,
        typeaheadClass: "custom-typeahead-dropdown-invoice",
        columns: [
            { name: "", value: 'DocTypeView', width: "10%" },
            { name: $('#LocName').val(), value: 'Name', width: "90%" }
        ],
        localization: { noResults: $('#LocNoResults').val() },
        url: $('#UrlFindCommodityPackages').val(),
        urlSearchProp: 'search',
        urlPropsFunction: function () {
            return {
                search: $('#docTypeCompGdsSearch.custom-typeahead').val()
            };
        },
        urlRequestMethod: "GET",
        onSelect: function (item) {
            $('#DocTypeCompGds').val(item.DocType);
            setDocTypeCompGdsVal();
            return item;
        }
    });
}