require("../styleImport.js");
require('knockout.validation');
require('./vendors/bootstrap.js');
require('./vendors/knockout.validation.fa-IR.js');
require('./util/validationRules.js');
require("./util/bindingHandlers.js")
require('./util/commonResources.js');
require('./util/dateHelper.js');
require("./components/jqfontselector.js");
require("./components/jqrg.js");
require("./components/jqtabletreeview.js");
require("./components/jqtreeview.js");
require("./components/jsRuler.js");
require("./components/ko-autocomplete.js");
require("./components/ko-consolidate-select.js");
require("./components/ko-datepicker.js");
require("./components/ko-formulamaker.js");
require("./components/ko-inputautocomplete.js");
require("./components/ko-nodeselect.js");
require("./components/ko-radio.js");
require("./components/ko-rg.js");
require("./components/ko-rgborder.js");
require("./components/ko-select.js");
require("./components/ko-filtercolumn.js");

window._h = _h;
window.dateHelper = dateHelper;
import { ClientStorage } from "./util/clientStorage.js";
import { MasterViewModel } from './pages/master/viewModel.js';

var appConfig = function () {
    var defineParams = function () {
        window.clientStorage = new ClientStorage();
        window.locale = 'fa';
        window.anyOpenModal = false;
        window.focusSearchInput = false;
        window.activeSection = '';
        window.resDomain = '';
        window.resSecondDomain = '';
        window.firstload = true;
        window.inCTvm = false;
    }
    var initKnockoutValidation = function (options) {
        ko.validation.locale('fa-IR');
        ko.validation.init({
            grouping: {
                deep: true,
                live: true,
                observable: true
            }
        });
    };
    var initKnockout = function () {
        var item;
        for (let i = 0; i < menus.length; i++) {
            var page = window.location.pathname.toLowerCase().replace("/", "");
            if (page.indexOf(menus[i].enText.toLowerCase()) !== -1) {
                item = menus[i];
            }
        }
        window.resDomain = item.default;
        let model = new MasterViewModel();
        model.pageName(item.enText);
        document.title = "دومینو | " + item.text;
        $("#master-page").attr("data-name", item.enText.toLowerCase());
        ko.applyBindings(model, document.getElementById("ko_wrapper"));
        model.init();
    }
    var initNecessaryModules = function () {
        (function ($) {
            $.fn.dragPageScroll = function (options) {
                options || (options = {});
                var defaults = {
                    topId: 'top_scroll_page',
                    bottomId: 'bottom_scroll_page',
                    delay: 50,
                    height: 80
                };
                options = $.extend(defaults, options);

                var topEl = $('#' + options.topId);
                if (!topEl.length)
                    topEl = $('<div id="top_scroll_page">&nbsp;</div>').appendTo('body');

                var bottomEl = $('#' + options.bottomId);
                if (!bottomEl.length)
                    bottomEl = $('<div id="bottom_scroll_page">&nbsp;</div>').appendTo('body');

                var bothEl = $('#top_scroll_page, #bottom_scroll_page');
                bothEl.hide();
                bothEl.css({
                    position: 'fixed', left: 0, right: 0,
                    height: options.height, zIndex: 999999
                });
                topEl.css({ top: "-80px" });
                bottomEl.css({ bottom: "-80px" });
                var activeDragMode = false;
                var lastTop;
                var lastBottom;
                bothEl.on('dragenter', function (e) {
                    //var direction = ($(this).attr('id') == options.topId) ? 'up' : 'down';
                    activeDragMode = true;
                    return true;
                });
                bothEl.on('dragover', function (e) {
                    //if ($('html,body').is(':animated')) return true;
                    var body = document.body,
                        html = document.documentElement;
                    activeDragMode = true;
                    var scrollTop = html.scrollTop || body.scrollTop;
                    var direction = (this.id === options.topId) ? -1 : 1;
                    var last = (direction === -1) ? lastTop : lastBottom;

                    var height = Math.max(body.scrollHeight, body.offsetHeight,
                        html.clientHeight, html.scrollHeight, html.offsetHeight);
                    var current = (direction === -1) ? scrollTop : height -
                        (scrollTop + window.innerHeight);
                    if (last !== undefined && last === current && current > 0) {
                        var newScrollTop = scrollTop + direction * 40;
                        $('html,body').scrollTop(newScrollTop);
                    }
                    if (direction === -1) lastTop = current; else lastBottom = current;
                    return true;
                });

                var hide = function (e) {
                    topEl.css({ top: "-80px" });
                    bottomEl.css({ bottom: "-80px" });
                    bothEl.hide();
                    // timestamp = undefined;
                    // scrolltop = 0;
                    // scrollbottom = 0;
                    return true;
                };

                $(document).on('dragstart', function (e) {
                    bothEl.show();
                    topEl.css({ top: 0 });
                    bottomEl.css({ bottom: 0 });
                    activeDragMode = true;
                    return true;
                });
                $(document).on('dragend', hide);
                bothEl.on('mouseover', hide);
            };
        })(jQuery);
        $(document).ready(function () {
            $().dragPageScroll();
            $(document).on('click',
                '.searchbox, .searchbox input, .searchbox .selectable, .searchbox label, .searchbox .selectize-control, ' +
                '.searchbox li, .searchbox button, .col-select input, .col-select label, .col-select .selectize-control, .autocom-input, ' +
                '.col-select li, .col-select button,.tbl-menu-row-title , .col-select div, .col-select span, .operator-select li,' +
                '.autocom-li, .autocom-remove, .ncls, .searchbox .selectize-control a, .searchbox .selectize-control .remove, .operator-select div, .operator-select h6',
                function (event) {
                    event.stopPropagation();
                    var visList = $(".drp-menu:visible");
                    var parent = $(event.target).closest(".drp-menu");
                    if (visList &&
                        visList.length > 0 &&
                        parent.length === 0 &&
                        !$(event.target).is('.ncls, .cal-input, .cal-box, .select-textbox, #tree_view ul, #tree_view li,.dmn-ey,.dmn-dirc,.dmn-ttl,.dmn-p,.dmn-dot,.dmn-fld , .autocom-input ,.autocom-ul, .autocom-li, .autocom-span, .autocom-btn')) {
                        var target = ko.contextFor(visList[0]);
                        if (target && target.$data && target.$data["showMenu"]) {
                            target.$data.showMenu(false);
                        }
                        if (target && target.$data && target.$data["showSelectedItems"] && !$(event.target).is("span.mu-spn, .autocom-remove")) {
                            target.$data.showSelectedItems(false);
                        }
                    }
                });

            $(document).on("click",
                function (e) {
                    var parent = $(e.target).closest(".drp-menu");
                    var visList = $(".drp-menu:visible");
                    if (visList &&
                        visList.length > 0 &&
                        !$(e.target).is('.ncls, .cal-input, .cal-box, .select-textbox, #tree_view ul, #tree_view li,.dmn-ey,.dmn-dirc,.dmn-ttl,.dmn-p,.dmn-dot,.dmn-fld , .autocom-input ,.autocom-ul, .autocom-li, .autocom-span, .autocom-btn') &&
                        parent.length === 0 &&
                        !$(e.target).is(".tv-multi")) {
                        var target = ko.contextFor(visList[0]);
                        if (target && target.$data && target.$data["showMenu"])
                            target.$data.showMenu(false);
                    }
                });

            $(document).on('click',
                '.remove',
                function (event) {
                    event.stopPropagation();
                });
            $(document).on('focusout',
                '.search-input',
                function () {
                    window.focusSearchInput = false;
                });

            $(document).on('focusin',
                '.search-input',
                function () {
                    window.focusSearchInput = true;
                });
        });
        $(window).bind("load",
            function () {
                $('.splash').css('display', 'none');
            });

        $(window).bind('storage',
            function (e) {
                if (e.originalEvent.key === "token" && e.originalEvent.newValue === null)
                    _h.backToLogin();

                if (e.originalEvent.key === "ProcessToken" && e.originalEvent.newValue === "")
                    _h.kocnx().checkProcessQueue();

                if (e.originalEvent.key === "ud") {
                    window.location.reload(false);
                }
            });

        $(window).on("beforeunload", function (e) {
            var tab = $(".onClose.active");
            if (tab.length) {
                var changed;
                var tabName = $(tab).attr("id");
                switch (tabName) {
                    case "tree-t":
                        changed = $(".save-tree-act:visible").length;
                        break;
                    case "tablestructure-t":
                        changed = true;
                        break;
                    case "magazine-t":
                        changed = $(".rich-texteditor:visible").length;
                        break;
                }
                if (changed)
                    return 'Are you sure?';
            }
        });

        $.fn.hasAnyClass = function () {
            for (var i = 0; i < arguments.length; i++) {
                if (this.hasClass(arguments[i])) {
                    return true;
                }
            }
            return false;
        }
    };
    var menuUrlHandler = function () {
        var path = window.location.pathname.toLowerCase().split("?");
        if (path[0] !== "") {
            var array = path[0].split("/");
            array = $.grep(array, function (n) { return n !== "" });
            if (array.length > 0) {
                var lis = $(".menu-bar li");
                $.each(lis, function (i, p) {
                    var className = $(p).attr("class").replace("menu-item", "").replace("-menu", "");
                    if (className.indexOf(array[0]) !== -1) {
                        $(p).attr("id", className.trim() + "-menu");
                    }
                });
            }
        }
    }
    var showMvcError = function () {
        switch (window.errorNumber) {
            case 403:
                var text = _h.getApiMessage("Forbidden");
                _h.failToast(text);
                window.errorNumber = 403;
                break;
            case 404:
                var text = _h.getApiMessage("NotFound");
                _h.failToast(text);
                window.errorNumber = 404;
                break;
        }
    }
    return {
        init: function (options) {

            defineParams();
            initKnockoutValidation(options);
            initKnockout(options);
            initNecessaryModules(options);
            menuUrlHandler();
            showMvcError();

        }
    }
}();



appConfig.init();