;
(function($, window, undefined) {
    // Your left nav in your app will no longer fire ajax calls
    $.navAsAjax = config.navAsAjax;
    $topnavmenu = config.$topnavmenu;
    $sidebarUl = config.$sidebarUl;

    // $.bread_crumb = $('#ribbon ol.breadcrumb');

    var Router = function() {
        /*
         * AJAX routes
         *
         */
        var that = this;

        this.initRouter = function(options) {
            var defaults = {
                beforeInit: function() {}, //路由初始化前回调
                afterInit: function() {}, //路由初始化后回调
                menus: null
            };

            var opts = $.extend(defaults, options);
            //初始化路由表
            var renderRoutes = function(menus, routes) {
                menus = menus || [];
                menus.forEach(function(menu) {
                    if (menu.url) {
                        routes[menu.url] = menu;
                    }
                    if (menu.children) {
                        renderRoutes(menu.children, routes);
                    }
                })
            };
            var menus = opts.menus || [];
            var routes = {};
            renderRoutes(menus, routes);
            that.routes = routes;



            if (typeof opts.beforeInit == "function") {
                opts.beforeInit();
            }

            if ($.navAsAjax) {
                if ($('nav').length) {
                    that.checkURL();
                }

                //侧边栏导航
                $(document).on('click', 'nav a[href!="#"]', function(e) {
                    e.preventDefault();
                    var $this = $(e.currentTarget);
                    if (!$this.parent().hasClass("active") && !$this.attr('target')) {

                        if ($.root_.hasClass('mobile-view-activated')) {
                            $.root_.removeClass('hidden-menu');
                            window.setTimeout(function() {
                                if (window.location.search) {
                                    window.location.href =
                                        window.location.href.replace(window.location.search, '')
                                        .replace(window.location.hash, '') + '#' + $this.attr('href');
                                } else {
                                    window.location.hash = $this.attr('href')
                                }
                            }, 150);
                        } else {
                            if (window.location.search) {
                                window.location.href =
                                    window.location.href.replace(window.location.search, '')
                                    .replace(window.location.hash, '') + '#' + $this.attr('href');
                            } else {
                                window.location.hash = $this.attr('href');
                            }
                        }
                    }

                });

                // fire links with targets on different window
                $(document).on('click', 'nav a[target="_blank"]', function(e) {
                    e.preventDefault();
                    var $this = $(e.currentTarget);
                    window.open($this.attr('href'));
                });

                // fire links with targets on same window
                $(document).on('click', 'nav a[target="_top"]', function(e) {
                    e.preventDefault();
                    var $this = $(e.currentTarget);

                    window.location = ($this.attr('href'));
                });

                // all links with hash tags are ignored
                $(document).on('click', 'nav a[href="#"]', function(e) {
                    e.preventDefault();
                });

                //顶部导航
                $(document).on('click', '#top-nav-menu a[href!="#"]', function(e) {
                    e.preventDefault();

                });

                // DO on hash change
                $(window).on('hashchange', function(e) {
                    that.checkURL();
                    var backdrop = $("body div.modal-backdrop"); //改变hash值,清出遮罩
                    if (backdrop.length > 0) {
                        backdrop.remove();
                    }
                });

                if (typeof opts.afterInit == "function") {
                    opts.afterInit();
                }
            }
        };

        this.checkURL = function() {
            var hashUrl = location.hash.replace(/^#/, '');
            var url = hashUrl.replace(/\?.*/, '');
            if (url == "preview.html" || url == "remoteplayback.html") {
                $("#main").removeClass("left12").addClass("left24");
                // $("#main").addClass("showchancel");
            } else {
                $("#main").removeClass("left24").addClass("left12");
            }
            $("#main").removeClass("nopadding");
            $("#main").removeClass("showyt");
            $("#content").removeClass("showbj");
            container = $('#content');
            if (url) {
                //定位侧边栏
                $('nav li.active,.nav li.active').removeClass("active");
                $('nav li:has(a[href="' + url + '"])').addClass("active");
                //根据侧边栏定位顶部导航，并显示对应的侧边栏
                var navNode = $("nav ul:has(li.active):first").parent();
                if (navNode && navNode.length > 0) {
                    //显示侧边栏
                    $sidebarUl.children("nav.show").removeClass("show").addClass("hide");
                    navNode.removeClass("hide").addClass("show");
                    var topIndex = navNode.attr('id');
                    $topnavmenu.find("li.active").removeClass("active");
                    $topnavmenu.find("li#" + topIndex).addClass("active");
                }
                if (openTopMenu()) {

                }
                that.loadURL(hashUrl + location.search, container);
            } else {
                if (openTopMenu()) {
                    var topUrl = $('#top-nav-menu li:first a').attr("href");
                    if (topUrl && topUrl != "#") {
                        window.location.hash = topUrl;
                        return;
                    } else {
                        var $this = $('nav > ul > li:first-child  a[href!="#"]:first');
                        if ($this.attr('href')) {
                            $('nav li.active').removeClass("active");
                            $this.parent().addClass("active");
                            window.location.hash = $this.attr('href');
                        }
                    }
                }
                var $this = $('nav > ul > li:first-child  a[href!="#"]:first');
                if ($this.attr('href')) {
                    $('nav li.active').removeClass("active");
                    $this.parent().addClass("active");
                    window.location.hash = $this.attr('href');
                }
            }
            if (config.deviceInfo.DeviceName == 'NVR') {
                if ($("#channelManagement").hasClass('active')) {
                    document.getElementById("channelManagementicon").setAttribute("src", "nvr/img/icon/vdselect.png");
                } else {
                    document.getElementById("channelManagementicon").setAttribute("src", "nvr/img/icon/vd.png");
                }
            }
            if (config.deviceInfo.DeviceName == 'HVR') {
                if ($("#channelManagement").hasClass('active')) {
                    document.getElementById("channelManagementicon").setAttribute("src", "hvr/img/icon/vdselect.png");
                } else {
                    document.getElementById("channelManagementicon").setAttribute("src", "hvr/img/icon/vd.png");
                }
            }
            if ($("#audioAndvideo").hasClass('active')) {
                document.getElementById("audioAndvideoicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/videoselect.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/videoselect.png" : "hvr/img/icon/videoselect.png");
            } else {
                document.getElementById("audioAndvideoicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/video.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/video.png" : "hvr/img/icon/video.png");
            }

            if ($("#image").hasClass('active')) {
                document.getElementById("imageicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/imageselect.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/imageselect.png" : "hvr/img/icon/imageselect.png");
            } else {
                document.getElementById("imageicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/image.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/image.png" : "hvr/img/icon/image.png");
            }


            if ($("#OrdinaryEvent").hasClass('active')) {
                document.getElementById("OrdinaryEventicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/ptsjselect.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/ptsjselect.png" : "hvr/img/icon/ptsjselect.png");
            } else {
                document.getElementById("OrdinaryEventicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/ptsj.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/ptsj.png" : "hvr/img/icon/ptsj.png");
            }

            if ($("#IntelligentEvent").hasClass('active')) {
                document.getElementById("IntelligentEventicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/smartselect.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/smartselect.png" : "hvr/img/icon/smartselect.png");
            } else {
                document.getElementById("IntelligentEventicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/smart.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/smart.png" : "hvr/img/icon/smart.png");
            }

            if ($("#netWork").hasClass('active')) {
                document.getElementById("netWorkicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/networkselect.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/networkselect.png" : "hvr/img/icon/networkselect.png");
            } else {
                document.getElementById("netWorkicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/network.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/network.png" : "hvr/img/icon/network.png");
            }
            if (config.deviceInfo.DeviceName == 'NVR') {
                if ($("#storagesyssin").hasClass('active')) {
                    document.getElementById("storagesyssinicon").setAttribute("src", "nvr/img/icon/ccselect.png");
                } else {
                    document.getElementById("storagesyssinicon").setAttribute("src", "nvr/img/icon/cc.png");
                }
            }
            if (config.deviceInfo.DeviceName == 'HVR') {
                if ($("#storagesyssin").hasClass('active')) {
                    document.getElementById("storagesyssinicon").setAttribute("src", "hvr/img/icon/ccselect.png");
                } else {
                    document.getElementById("storagesyssinicon").setAttribute("src", "hvr/img/icon/cc.png");
                }
            }
            if (config.deviceInfo.DeviceName == 'IPC') {
                if ($("#storage").hasClass('active')) {
                    document.getElementById("storageicon").setAttribute("src", "ipc/img/icon/ccselect.png");
                } else {
                    document.getElementById("storageicon").setAttribute("src", "ipc/img/icon/cc.png");
                }
            }
            if ($("#system").hasClass('active')) {
                document.getElementById("systemicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/szselect.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/szselect.png" : "hvr/img/icon/szselect.png");
            } else {
                document.getElementById("systemicon").setAttribute("src", config.deviceInfo.DeviceName == 'IPC' ? "ipc/img/icon/sz.png" : config.deviceInfo.DeviceName == 'NVR' ? "nvr/img/icon/sz.png" : "hvr/img/icon/sz.png");
            }
        };

        this.open = function(url) { //重定向到指定url
            if (url) {
                // $("#main").removeClass("hide");
                container = $('#content');
                that.loadURL(url + location.search, container);
            }
        };

        this.redirect = function(url) {
            if (url) {
                // $("#main").removeClass("hide");
                window.location.hash = url;
            }
        };

        this.openNavMenu = function() {
            var hash = location.hash.replace(/^#/, '');
            // $('nav li.active').removeClass("active");
            if (openTopMenu()) {
                var topUrl = $('#top-nav-menu li.active a').attr("href");
                if (topUrl) {
                    window.location.hash = topUrl;
                }
                return;
            }

            if (!config.openSideFirst) {
                return;
            }
            var $this = $('nav.show > ul > li:first-child  a[href!="#"]:first');
            var url = $this.attr('href');
            if (url && url != hash) {
                $('nav li.active').removeClass("active");
                $this.parent().addClass("active");
                // window.location.hash = url;
            }

        };

        this.loadURL = function(url, container) {
            if (url.trim() == '/') {
                return;
            }
            $.ajax({
                type: "GET",
                url: url,
                dataType: 'html',
                cache: config.pageCache,
                beforeSend: function() {
                    // cog placed
                    container.html('<h1><img src="../../img/loading-bg.gif"> Loading...</h1>');

                    if (container[0] == $("#content")[0]) {
                        $("html").animate({
                            scrollTop: 0
                        }, "fast");
                    }
                },
                success: function(data) {
                    container.css({
                        opacity: '0.0'
                    }).html(data).delay(50).animate({
                        opacity: '1.0'
                    }, 100);
                    loadProperties(sessionStorage.getItem("language"));
                    config.dataId = url.split("=")[1];
                    if (config.refreshplayvideo) {
                        if (config.deviceInfo.DeviceName == 'IPC') {
                            if (url != "preview.html" && url != "remoteplayback.html" && url != "ipc/pages/log.html") {
                                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                                    preHiddenDisplaywindow(4);
                                }
                            }
                        } else if (config.deviceInfo.DeviceName == 'NVR') {
                            if (url != "preview.html" && url != "remoteplayback.html" && url != "nvr/pages/log.html") {
                                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                                    preHiddenDisplaywindow(4);
                                }
                            }
                        } else {
                            if (url != "preview.html" && url != "remoteplayback.html" && url != "hvr/pages/log.html") {
                                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                                    preHiddenDisplaywindow(4);
                                }
                            }
                        }

                    } else {
                        if (URL_Request("isp2p") != "p6s" && URL_Request("isp2p") != "p2p") {
                            if (config.deviceInfo.DeviceName == 'NVR') {
                                if (url != "preview.html" && url != "remoteplayback.html" && url != "nvr/pages/log.html") {
                                    if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                                        preHiddenDisplaywindow(4);
                                    }
                                }
                            }

                        }
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    container.html('<h4 style="margin-top:10px; display:block; text-align:center"> Error 404! Page not found.</h4>');
                },
                async: false
            });

            //console.log("ajax request sent");
        };
        this.refresh = function() {
            var url = location.hash.replace(/^#/, ''); //hash值 去掉#后
            container = $('#content');
            Router.loadURL(url + location.search, container);
        };


    };


    //没有侧边栏时，隐藏侧边栏，当且当顶部导航有链接时，默认打开
    function openTopMenu() {
        var topActive = $('#top-nav-menu li.active');
        var menuId = topActive.attr("id");
        var sidebar = $("#sidebarUl #" + menuId + " a");
        if (sidebar.length == 0) {
            closeSidebar();
            return true;
        } else {
            openSidebar();
            return false;
        }
    }

    var Router = new Router();
    window.Router = Router;

})(jQuery, this);