$(document).ready(function () {
    applySwitchery();
    dateTimePicker();
    applyJsSwitch();
});

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

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

function dateTimePicker() {
    $('.datetimepicker').each(function (index, element) {
        $('#' + element.id).datetimepicker({
            format: 'DD.MM.YYYY HH:mm',
            locale: 'sl-SI'
        });
    });

    $('.datepicker').each(function (index, element) {
        $('#' + element.id).datetimepicker({
            format: 'DD.MM.YYYY',
            locale: 'sl-SI'
        });
    });
}

function initializeDataTables(tableId, keywordsId, columns,
    acKey = '', fixedColumnsLeft = '', fixedColumnsRight = '',
    onCreateRowSetPreviewDropdown = false, date = '', dataLoadCallback = null) {
    var typingTimer;
    var doneTypingInterval = 600;

    if (keywordsId.length > 0) {
        $('#' + keywordsId).off('keyup');
        $('#' + keywordsId).on('keyup', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(function () { $dataTable.DataTable().ajax.reload(); }, doneTypingInterval);
        });
    }

    //$("select").off("change");
    $(".select2withAPI, .select2").on("change", function () {
        //$('#' + tableId).DataTable().ajax.reload();
    });

    $(".selectpicker-dropdown").on("hide.bs.dropdown", function () {
        $dataTable.DataTable().ajax.reload();

        var allValue = $("#All").val();
        var dropdowns = $(".filter-option-inner-inner");
        var dropdownsFilterValues = [];

        for (let i = 0; i < dropdowns.length; i++) {
            if (dropdowns[i].innerText !== allValue) {
                dropdownsFilterValues.push(dropdowns[i]);
            }
        }

        if (dropdownsFilterValues.length > 0) {
            $(".filter-search-icon").addClass("theme-color");
        } else {
            $(".filter-search-icon").removeClass("theme-color");
        }
    });

    $(".filter-datepicker").datepicker({
        format: 'dd.mm.yyyy'
    }).on('changeDate', function () {
        $(this).datepicker('hide');
        $.fn.dataTable.reload($dataTable);
        //$(".filter-search-icon").addClass("theme-color");
    });

    $(".filter-search-icon").on("click", function () {
        $dataTable.DataTable().ajax.reload();
    });

    if (date) {
        $("#TravelDateFrom").val(date);
        $('#DateFrom').val(date);
        $("#TravelDateFrom").datepicker('setDate', date);
    }

    if ($('#' + tableId).length !== 0) {
        $dataTable = $('#' + tableId);
        $dataTable.DataTable({
            ajax: {
                url: $dataTable.attr('data-url'),
                data: function (d) {
                    d.Keywords = $('#' + keywordsId).val(),
                        d.Status = $('#status').val(),
                        d.AcKey = $('#AcKey').val(),
                        d.Worker = $('#Worker').val(),
                        d.DateFrom = $('#DateFrom').val(),
                        d.DateTo = $('#DateTo').val(),
                        d.Buyer = $('#Buyer').val(),
                        d.Currency = $('#Currency').val(),
                        d.SubjectId = $('#SubjectId').val(),
                        d.PeriodFilter = $('#PeriodFilter').val(),
                        d.PaymentMethod = $('#PaymentMethod').val(),
                        d.DetailedByBill = $('#DetailedByBill').val(),
                        d.OpenItem = $('#OpenItem').val(),
                        d.Type = $('#Type').val(),
                        d.DocumentType = $('#DocType').val(),
                        d.docType = $('#DocTypes').val(),
                        d.DDW = $('#DDW').val(),
                        d.Accounts = $("#Accounts").val(),
                        d.Workers = $("#Workers").val(),
                        d.Department = $("#Department").val(),
                        d.Departments = $("#Departments").val(),
                        d.CostDrv = $("#CostDrv").val(),
                        d.Vehicles = $("#Vehicles").val(),
                        d.Statuses = $("#Statuses").val(),
                        d.DocTypes = $("#DocumentTypes").val();
                        d.TravelDateFrom = $("#TravelDateFrom").val();
                        d.TravelDateTo = $("#TravelDateTo").val();
                        d.CaseNumber = $("#CaseNumber").val();
                        d.Client = $("#Client").val();
                }
            },
            columns: columns,
            colReorder: {
                fixedColumnsLeft: fixedColumnsLeft,
                fixedColumnsRight: fixedColumnsRight
            },
            drawCallback: function () {
                select2withAPI();
                if (tableId === "payorders") {
                    focusOnOrderFromMove();
                }

                datatablesBaseDrawCallback($(this));
                docTypePermissionCtrl.evalPermissions(undefined, $(this));
            },
            createdRow: function (row, data, dataIndex) {
                if (onCreateRowSetPreviewDropdown) {
                    $(row).find(".custom-dropdown").customDropdown();
                    setPreviewDropdownToggle($(row).find(".custom-dropdown"));
                }

                if (data.AcKey == acKey) {
                    $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
                }
            },
        }).on('xhr.dt', function (e, settings, json, xhr) {
            if (tableId = "travelorders" && json && json.prop) {
                $('#grid-data-total-sum').html($.fn.dataTable.render.number('.', ',', 2).display(json.prop.Sum));
                $('.grid-data-start-items').html(json.recordsTotal === 0 ? '0' : '1');
                $('.grid-data-total-items').html(json.recordsTotal);
            }

            if (dataLoadCallback) {
                dataLoadCallback();
            }
        });
    }
}

var selectedAcKeys = [];

function gridPrint() {

}

function gridDelete(deleteUrl, backUrl) {
    $.ajax({
        cache: false,
        type: "post",
        url: deleteUrl,
        data: {
            keys: selectedAcKeys
        },
        success: function (result) {
            selectedAcKeys = [];
            $.fn.dataTable.reload($dataTable);
            $("#deleteButton").addClass('btn-outline disabled').removeClass('btn-danger');
        },
        error: function (error) {
            swal($("#GeneralErrorMessage").val() + error);
        }
    });

}

function checkBoxSelectionChanged(checkboxValue) {

    var index = selectedAcKeys.indexOf(checkboxValue);

    if (index !== -1) {
        selectedAcKeys.splice(index, 1);
    }
    else {
        selectedAcKeys.push(checkboxValue);
    }
}

function ToLocalDate(value) {
    var pattern = /Date\(([^)]+)\)/;
    var results = pattern.exec(value);
    var dt = new Date(parseFloat(results[1]));
    var dateFinal = dt.getDate() + "." + (dt.getMonth() + 1) + "." + dt.getFullYear();
    return dateFinal;
}

function toggleTable(obj, tableId) {

    $("#" + obj).toggleClass('fa-angle-double-down');
    $("#" + obj).toggleClass('fa-angle-double-up');

    $('#' + tableId).find("tbody").toggle();
}

$(function () {
    if (!$.validator || $.validator.methods) {
        return;
    }
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    };
});

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [day, month, year].join('.');
}

function submitForm(redirectToCreate, submitButtonId) {
    $("#redirectToCreate").val(redirectToCreate);
    $("#" + submitButtonId).click();
    return false;
}

function SubmitFormByFormId(formId) {
    document.getElementById(formId).submit();
}

$(function () {
    $(document).on('click', '.open-modal', function () {
        $.fn.modal.Constructor.prototype.enforceFocus = function () { };
        var $buttonClicked = $(this);
        var id = $buttonClicked.attr('data-modal-id');
        $('#' + id).modal('show');
        var url = $buttonClicked.attr('data-url');
        var title = $buttonClicked.attr('data-modal-title');

        var options = { "backdrop": "true", keyboard: true };
        $.ajax({
            type: "GET",
            url: url,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (data) {
                $('#ModalContent').html(data);
                $('#ModalTitle').html(title);
                $('#' + id).modal(options);
            },
            error: function (error) {
                swal($("#GeneralErrorMessage").val() + error);
            }
        });
    });
});

function ajaxUploadDocument() {
    window.addEventListener("submit", function (e) {
        var form = e.target;
        if (form.getAttribute("enctype") === "multipart/form-data") {
            if (form.dataset.ajax) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var xhr = new XMLHttpRequest();
                xhr.open(form.method, form.action);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (form.dataset.ajaxUpdate) {
                            var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                            if (updateTarget) {
                                updateTarget.innerHTML = xhr.responseText;
                            }
                        }
                    }
                };
                xhr.send(new FormData(form));
            }
        }
    }, true);
}

function reloadDataTable(tableId) {
    $.fn.dataTable.reload($("#" + tableId));
}

function forEveryHTMLElement(querySelector, fn) {
    var elements = Array.prototype.slice.call(document.querySelectorAll(querySelector));
    elements.forEach(function (element) {
        fn(element);
    });
}
