;
(function($, window, undefined) {
    //初始化用户信息
    window.User = new function() {
        var logourl = "custom/logo.png?m=" + Math.random();
        var loginlogourl = "custom/loginlogo.png?m=" + Math.random();
        //存在定制logo
        if (URL_Request("isp2p") == "p6s" || URL_Request("isp2p") == "p2p") {
            console.log("vms上的协议不用定制验证图片");
        } else {
            if (validateImage(logourl)) {
                var maxWidth = 320; // 图片最大宽度
                var maxHeight = $(".jy-style-1 #header").height(); // 图片最大高度
                if (maxHeight == 0) {
                    maxHeight = 60;
                }
                setLogoImg(logourl, maxWidth, maxHeight, "#logo-group #comLogoImgId");
            } else {
                var divd = document.getElementById("logo-group");
                if (divd) {
                    divd.style.display = 'none';
                }
            }
            if (validateImage(loginlogourl)) {
                setLogoImg(loginlogourl, 1072, $(".containertop").height() || 72, "#loginimgId");
            }
        }


        //判断图片是否存在
        function validateImage(url) {
            var xmlHttp;
            if (window.ActiveXObject) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } else if (window.XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            }
            xmlHttp.open("Get", url, false);
            xmlHttp.send();
            // console.log(xmlHttp,"xmlHttp");
            if (xmlHttp.status == 404) {
                return false;
            } else {
                return true;
            }
        }

        /**
         * 根据获取的客户定制logo裁剪符合我们框架的图片并拼接到对应的logo占位上去
         * @param logoUrl
         */
        function setLogoImg(logoUrl, maxWidth, maxHeight, id) {
            if (logoUrl) {
                var image = new Image();
                image.onload = function() {
                    $(id).attr("src", logoUrl);
                    var width = image.width; // 图片实际宽度
                    var height = image.height; // 图片实际高度
                    // 检查图片是否超宽
                    if (width > maxWidth || width == 0) {
                        width = maxWidth;
                    } else {
                        width = image.width;
                    }
                    // 检查图片是否超高
                    if (height > maxHeight || height == 0) {
                        height = maxHeight;
                    } else {
                        height = image.height;
                    }
                    id == "#bgimg" ? $(id).css("width", "100%") : $(id).css("width", width) // 设定实际显示宽度
                    $(id).css("height", height);
                };
                image.src = logoUrl;
            }
        }
    };

    /*
     * 通用导航栏、侧边栏插件
     */
    $.fn.extend({
        //顶部导航栏
        topnavmenu: function(options) {
            var defaults = {
                clickCallback: function($a) {}
            };
            var opts = $.extend(defaults, options);
            var $this = $(this);
            $this.find("li").click(function() {
                var $li = $(this);
                $this.find("li.active").each(function() {
                    var icon = $(this)[0].id + "icon";
                    var picts = document.getElementById(icon);
                    if ($(this)[0].id == "log") {
                        picts.setAttribute("src", "img/icon/log.png");
                    } else if ($(this)[0].id == "preview") {
                        picts.setAttribute("src", "img/icon/yl.png");
                    } else if ($(this)[0].id == "remoteplayback") {
                        picts.setAttribute("src", "img/icon/hf.png");
                    } else if ($(this)[0].id == "configuration") {
                        picts.setAttribute("src", "img/icon/pz.png");
                    }
                    $(this).removeClass("active");

                });
                $li.addClass("active");
                if (typeof opts.clickCallback == "function") {
                    opts.clickCallback($li);
                }
            });
        },
        //侧边栏
        sidebarfresh: function(options) {
            var defaults = {
                accordion: "true", //可折叠的
                speed: 250, //折叠展开速度
                closedSign: "", //图标
                openedSign: ""
            };

            var opts = $.extend(defaults, options);
            var $this = $(this);

            $this.find("li.open").each(function() {
                if (!$(this).hasClass("active")) {
                    $(this).find("ul:first").slideUp(opts.speed);
                    $(this).removeClass("open");
                    $(this).find("b:first").delay(opts.speed).html(opts.closedSign);
                }
            });

            //open active level
            $this.find("li.active").each(function() {
                $(this).parents("ul").slideDown(opts.speed);
                $(this).parents("ul").parent("li").find("b:first").html(opts.openedSign);
                $(this).parents("ul").parent("li").addClass("open");
            });

        },
        sidebarmenu: function(options) {

                var defaults = {
                    accordion: "true", //可折叠的
                    speed: 200, //折叠展开速度
                    closedSign: "", //图标
                    openedSign: "",
                    renderBefore: function() {},
                    renderAfter: function() {}
                };

                // Extend our default options with those provided.
                var opts = $.extend(defaults, options);
                //Assign current element to variable, in this case is UL element
                var $this = $(this);

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

                //add a mark [+] to a multilevel menu
                $this.find("li").each(function() {
                    if ($(this).find("ul").length != 0) {
                        //add the multilevel sign next to the link
                        $(this).find("a:first").append("<b class='collapse-sign'>" + opts.closedSign + "</b>");

                        //avoid jumping to the top of the page when the href is an #
                        if ($(this).find("a:first").attr("href") == "#") {
                            $(this).find("a:first").click(function() {
                                return false;
                            });
                        }
                    }
                });

                //open active level
                $this.find("li.active").each(function() {
                    $(this).parents("ul").slideDown(opts.speed);
                    $(this).parents("ul").parent("li").find("b:first").html(opts.openedSign);
                    $(this).parents("ul").parent("li").addClass("open");
                });

                $this.find("li a").click(function() {

                    if ($(this).parent().find("ul").length != 0) {

                        if (opts.accordion) {
                            //Do nothing when the list is open
                            if (!$(this).parent().find("ul").is(":visible")) {
                                parents = $(this).parent().parents("ul");
                                visible = $this.find("ul:visible");
                                visible.each(function(visibleIndex) {
                                    var close = true;
                                    parents.each(function(parentIndex) {
                                        if (parents[parentIndex] == visible[visibleIndex]) {
                                            close = false;
                                            return false;
                                        }
                                    });
                                    if (close) {
                                        if ($(this).parent().find("ul") != visible[visibleIndex]) {
                                            $(visible[visibleIndex]).slideUp(opts.speed, function() {
                                                $(this).parent("li").find("b:first").html(opts.closedSign);
                                                $(this).parent("li").removeClass("open");
                                            });

                                        }
                                    }
                                });
                            }
                        } // end if
                        if ($(this).parent().find("ul:first").is(":visible") && !$(this).parent().find("ul:first").hasClass("active")) {
                            $(this).parent().find("ul:first").slideUp(opts.speed, function() {
                                $(this).parent("li").removeClass("open");
                                $(this).parent("li").find("b:first").delay(opts.speed).html(opts.closedSign);
                            });

                        } else {
                            $(this).parent().find("ul:first").slideDown(opts.speed, function() {
                                /*$(this).effect("highlight", {color : '#616161'}, 500); - disabled due to CPU clocking on phones*/
                                $(this).parent("li").addClass("open");
                                $(this).parent("li").find("b:first").delay(opts.speed).html(opts.openedSign);
                            });
                        } // end else
                    } // end if
                });


                if (typeof opts.renderAfter == "function") {
                    opts.renderAfter();
                }
            } // end function
    });

    /* ~ END: CUSTOM MENU PLUGIN */

    $.fn.serializeJson = function() {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(function() {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };

    /*
     * ELEMENT EXIST OR NOT
     * Description: returns true or false
     * Usage: $('#myDiv').doesExist();
     */

    $.fn.doesExist = function() {
        return jQuery(this).length > 0;
    };

    //去字符串两端空格
    if (!String.prototype.trim) {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, "");
        };
    }
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function(str) {
            return (this.match("^" + str) == str);
        };
    }

    if (!String.prototype.endsWith) {
        String.prototype.endsWith = function(str) {
            return (this.match(str + "$") == str);
        };
    }

    if (!Date.prototype.Format) {
        Date.prototype.Format = function(fmt) {
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "h+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        };
    }
    $.dateFormat = function(date, fmt) {
        var date = date == undefined ? new Date() : date;
        date = typeof date == 'number' ? new Date(date) : date;
        fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
        var obj = {
            'y': date.getFullYear(), // 年份，注意必须用getFullYear
            'M': date.getMonth() + 1, // 月份，注意是从0-11
            'd': date.getDate(), // 日期
            'q': Math.floor((date.getMonth() + 3) / 3), // 季度
            'w': date.getDay(), // 星期，注意是0-6
            'H': date.getHours(), // 24小时制
            'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
            'm': date.getMinutes(), // 分钟
            's': date.getSeconds(), // 秒
            'S': date.getMilliseconds() // 毫秒
        };
        var week = ['天', '一', '二', '三', '四', '五', '六'];
        for (var i in obj) {
            fmt = fmt.replace(new RegExp(i + '+', 'g'), function(m) {
                var val = obj[i] + '';
                if (i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
                for (var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
                return m.length == 1 ? val : val.substring(val.length - m.length);
            });
        }
        return fmt;
    };
    if (!String.prototype.dateFormat) {
        String.prototype.dateFormat = function(fmt) {
            var dateStr = this.valueOf();
            if (!dateStr || typeof dateStr != "string") {
                return "";
            }
            var o = {
                "year": dateStr.length >= 4 ? dateStr.substring(0, 4) : "",
                "month": dateStr.length >= 6 ? dateStr.substring(4, 6) : "",
                "day": dateStr.length >= 8 ? dateStr.substring(6, 8) : "",
                "hour": dateStr.length >= 10 ? dateStr.substring(8, 10) : "",
                "minu": dateStr.length >= 12 ? dateStr.substring(10, 12) : "",
                "seconds": dateStr.length >= 14 ? dateStr.substring(12, 14) : ""
            };
            var date = new Date(o.year, parseInt(o.month) - 1, o.day, o.hour, o.minu, o.seconds).Format(fmt);
            return date;
        };
    }
    //轻提示
    $.optionBootoast = function(message, type) {
        bootoast({
            message: message,
            type: type,
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    };
    //格式年月日时分秒20170302T020000,拆分年月日时分秒
    $.formatDate = function(val) {
        var ymd = val.split("T")[0];
        var hms = val.split("T")[1];
        return {
            y: ymd.substring(0, 4),
            m: ymd.substring(4, 6),
            d: ymd.substring(6, 8),
            h: hms.substring(0, 2),
            ms: hms.substring(2, 4),
            s: hms.substring(4, 6),
        }
    };
    //格式年月日时分秒2023-03-23 10:20:09,拆分年月日时分秒
    $.dateString = function(val) {
            var ymd = val.split(" ")[0];
            var hms = val.split(" ")[1];
            return {
                y: ymd.substring(0, 4),
                m: ymd.substring(5, 7),
                d: ymd.substring(8, 10),
                h: hms.substring(0, 2),
                ms: hms.substring(3, 5),
                s: hms.substring(6, 8),
            }
        }
        //正在加载中的遮罩层
    $.MaskUtil = (function() {
        var $mask;
        function init(message) {
            if ($mask) {
                // 如果已经存在遮罩层，先移除它
                try {
                    $('#myWaitingModal').modal('hide');
                    $mask.remove();
                    $('.modal-backdrop').remove();
                } catch(e) {
                    console.log('移除旧遮罩层时出错:', e);
                }
                $mask = null;
            }
                if(message==""){
                     $mask = $('<div id="myWaitingModal" style="display:block;">' +
                            '<div class="modal-backdrop fade show" style="z-index:1040;"></div>' +
                            '<div id="loading" class="loading">' +
                            '</div>' +
                            '</div>').appendTo("body");
                }else{
                     $mask = $('<div id="myWaitingModal" style="display:block;">' +
                            '<div class="modal-backdrop fade show" style="z-index:1040;"></div>' +
                            '<div id="loading" class="loading">' +
                            '<div style="text-align:center">' + message + '</div>' +
                            '</div>' +
                            '</div>').appendTo("body");
                }


        }
        return {
            mask: function(message) {
                init(message);
                // $('#myWaitingModal').modal('show');
            },
            unmask: function () {
                 // 先隐藏模态框
                // $('#myWaitingModal').modal('hide');

                // 监听隐藏完成事件
                if ($mask) {
                    $mask.remove();
                    $mask = null;
                }
            }
        }
    }());
    $.RestartModel = (function() {
        var $mask;

        function init(callback, isUpplementary, callbackDatas) {
            var tips;
            switch (isUpplementary) {
                case '0':
                    tips = $.i18n.prop('i18n-enevt-tip');
                    break;
                case '1':
                    if (config.deviceCap[0].FaceSnapshot == 'true' && config.deviceCap[0].IsFaceReco == "true" && config.deviceAiCap[0].Firedetectsupport == "true") {
                        tips = $.i18n.prop('i18n-enevt-newtip2');
                    } else if (config.deviceCap[0].FaceSnapshot == 'true' && config.deviceCap[0].IsFaceReco == "true") {
                        tips = $.i18n.prop('i18n-enevt-newtip');
                    } else if (config.deviceAiCap[0].Firedetectsupport == "true") {
                        tips = $.i18n.prop('i18n-enevt-newtip1');
                    }
                    break;
                case '2':
                    tips = $.i18n.prop('i18n-enevt-newtip3');
                    break;
                case '3':
                    tips = $.i18n.prop('i18n-enevt-newtip4');
                case '4':
                    tips = $.i18n.prop('i18n-lang-msg');
                    break;
            }
            if (!$mask) {
                $mask = $('<div class="modal fade" id="restStartModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\
                <div class="modal-dialog" style="width: 480px;">\
                    <div class="modal-content" style="border-radius: 6px;left:85%;transform:translateX(-50%)">\
                        <div class="modal-header">\
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x&nbsp;</button>\
                            <h5 class="modal-title" id="myModalLabel">' + $.i18n.prop('i18n-tip') + '</h5>\
                        </div>\
                        <div class="modal-body">\
                            <img src="img/login/tishi@2x.png" style="width: 32px;height: 32px;">\
                            <span class="tip-text">' + tips + '</span>\
                        </div>\
                        <div class="modal-footer">\
                            <button type="button" class="btn btn-default" data-dismiss="modal" style="background: #F1F2F5;" id="modelCancel">' + $.i18n.prop('i18n-cancel') + '</button>\
                            <button type="button" class="btn btn-primary" style="background: #3A77FE" id="modelSave">' + $.i18n.prop('i18n-confirm') + '</button>\
                        </div>\
                    </div>\
                </div>\
            </div>').appendTo("body");
            }
            $("#modelSave").click(function() {
                if (typeof callback === "function") {
                    callback(); // 执行传入的逻辑
                }
                $('#restStartModel').modal('hide');
                $mask = null;
                $('#restStartModel').remove();
                $('.modal-backdrop').hide();
            })
            $("#modelCancel").click(function() {
                $('#restStartModel').modal('hide');
                $mask = null;
                if (typeof callbackDatas === "function") {
                    callbackDatas(); // 告诉我取消弹框了执行恢复逻辑
                }
                $('#restStartModel').remove();
                $('.modal-backdrop').hide();
            })

        }
        return {
            mask: function(callback, isUpplementary, callbackDatas) {
                init(callback, isUpplementary, callbackDatas);
                $('#restStartModel').modal('show');
            },
        }
    }());
})(jQuery, this);



$.root_ = $("body");
$.left_panel = $("#left-panel");
$.sidebarUl = $("#sidebarUl");

// desktop or mobile
$.device = null;
$.enableJarvisWidgets = true;
$.enableMobileWidgets = false;

var ismobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));

if (!ismobile) {
    $.root_.addClass("desktop-detected");
    $.device = "desktop";
} else {
    $.root_.addClass("mobile-detected");
    $.device = "mobile";
}


/*
 * RESIZER WITH THROTTLE
 * Source: http://benalman.com/code/projects/jquery-resize/examples/resize/
 */

(function($, window, undefined) {

    var elems = $([]),
        jq_resize = $.resize = $.extend($.resize, {}),
        timeout_id, str_setTimeout = "setTimeout",
        str_resize = "resize",
        str_data = str_resize + "-special-event",
        str_delay = "delay",
        str_throttle = "throttleWindow";

    jq_resize[str_delay] = $.throttle_delay;

    jq_resize[str_throttle] = true;

    $.event.special[str_resize] = {

        setup: function() {
            if (!jq_resize[str_throttle] && this[str_setTimeout]) {
                return false;
            }

            var elem = $(this);
            elems = elems.add(elem);
            $.data(this, str_data, {
                w: elem.width(),
                h: elem.height()
            });
            if (elems.length === 1) {
                loopy();
            }
        },
        teardown: function() {
            if (!jq_resize[str_throttle] && this[str_setTimeout]) {
                return false;
            }

            var elem = $(this);
            elems = elems.not(elem);
            elem.removeData(str_data);
            if (!elems.length) {
                clearTimeout(timeout_id);
            }
        },

        add: function(handleObj) {
            if (!jq_resize[str_throttle] && this[str_setTimeout]) {
                return false;
            }
            var old_handler;

            function new_handler(e, w, h) {
                var elem = $(this),
                    data = $.data(this, str_data);
                data.w = w !== undefined ? w : elem.width();
                data.h = h !== undefined ? h : elem.height();

                old_handler.apply(this, arguments);
            }

            if ($.isFunction(handleObj)) {
                old_handler = handleObj;
                return new_handler;
            } else {
                old_handler = handleObj.handler;
                handleObj.handler = new_handler;
            }
        }
    };

    function loopy() {
        timeout_id = window[str_setTimeout](function() {
            elems.each(function() {
                var elem = $(this),
                    width = elem.width(),
                    height = elem.height(),
                    data = $.data(this, str_data);
                if (width !== data.w || height !== data.h) {
                    elem.trigger(str_resize, [data.w = width, data.h = height]);
                }

            });
            loopy();

        }, jq_resize[str_delay]);

    }

})(jQuery, this);


function openSidebar() {
    $("body").removeClass("fullscreen");
}

function closeSidebar() {
    $("body").addClass("fullscreen");
}

//弹出框关闭提示
function initModalConfig() {
    //设置modal中tabindex=-1时，下来框可搜索
    $.fn.modal.Constructor.prototype.enforceFocus = function() {};
    //设置modal中confirm=“true”时，支持modal关闭提示。
    $("body").on("shown.bs.modal", ".modal[role='dialog'][confirm='true']", function(e) {
        var modal = e.target;
        var closeBtn = $(modal).find("[data-dismiss='modal']").not($(modal).find(".modal [data-dismiss='modal']"));
        closeBtn.unbind("click").click(function(e) {
            if ($(modal).attr("confirm") == "true") {
                bootbox.confirm({
                    size: "small",
                    message: $.i18n.prop('i18n-closemodeltitle'),
                    className: "box-top-150",
                    buttons: {
                        confirm: {
                            label: $.i18n.prop('i18n-yes'),
                            className: "btn-primary"
                        },
                        cancel: {
                            label: $.i18n.prop('i18n-no'),
                            className: "btn-default"
                        }

                    },
                    callback: function(result) {
                        if (result) {
                            $(modal).modal("hide");
                        }
                    }
                });
                return false;
            } else {
                return true;
            }

        });
    });
}
// 获取页面缩放比例
function getRatio() {
    var ratio = 0;
    var screen = window.screen;
    var ua = navigator.userAgent.toLowerCase();

    if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }

    if (ratio) {
        ratio = Math.round(ratio * 100);
    }

    return ratio;
}


/*
 * initPage
 * Description: fire certain scripts that run through the page
 * to check for form elements, tooltip activation, popovers, etc...
 */
function initPage() {

    if ($.device === "desktop") {
        // is desktop

        // activate tooltips
        $("[rel=tooltip]").tooltip();

        // activate popovers
        $("[rel=popover]").popover();

        // activate popovers with hover states
        $("[rel=popover-hover]").popover({
            trigger: "hover"
        });


        //setup nav height (dynamic)
        nav_page_height();

        // run form elements
        runAllForms();

        //模态框关闭提示：设置模态框根节点属性 confirm="true"
        initModalConfig();

    } else {

        // is mobile

        // activate popovers
        $("[rel=popover]").popover();

        // activate popovers with hover states
        $("[rel=popover-hover]").popover({
            trigger: "hover"
        });


        //setup nav height (dynamic)
        nav_page_height();

        // run form elements
        runAllForms();

        //模态框关闭提示：设置模态框根节点属性 confirm="true"
        initModalConfig();


    }

}

/*
 * VARIABLES
 * Description: All Global Vars
 */
// Impacts the responce rate of some of the responsive elements (lower value affects CPU but improves speed)
$.throttle_delay = 350;

// The rate at which the menu expands revealing child elements on click
$.menu_speed = 235;

// Note: You will also need to change this variable in the "variable.less" file.
$.navbar_height = 60;

$.shortcut_dropdown = $("#shortcut");

/* ~ END: INITIALIZE JARVIS WIDGETS */

// Fix page and nav height
function nav_page_height() {
    var setHeight = $("#main").height();
    //menuHeight = $.left_panel.height();

    var windowHeight = $(window).height() - $.navbar_height;
    //set height

    if (setHeight > windowHeight) { // if content height exceedes actual window height and menuHeight
        $.left_panel.css("min-height", setHeight + "px");
        $.root_.css("min-height", setHeight + $.navbar_height + "px");
        $.sidebarUl.css("max-height", windowHeight + "px")
    } else {
        $.left_panel.css("min-height", windowHeight + "px");
        $.root_.css("min-height", windowHeight + "px");
        $.sidebarUl.css("max-height", windowHeight + "px")
    }
}


$("#main").resize(function() {
    nav_page_height();
    check_if_mobile_width();
});

$("nav").resize(function() {
    nav_page_height();
});

function check_if_mobile_width() {
    if ($(window).width() < 979) {
        $.root_.addClass("mobile-view-activated");
    } else if ($.root_.hasClass("mobile-view-activated")) {
        $.root_.removeClass("mobile-view-activated");
    }
}


/*
 * INITIALIZE FORMS
 * Description: Datepicker, Autocomplete
 */

function runAllForms() {


    /*
     * Autocomplete
     * Dependency: js/jqui
     */
    if ($.fn.autocomplete) {
        $("[data-autocomplete]").each(function() {

            var $this = $(this);
            var availableTags = $this.data("autocomplete") || ["The", "Quick", "Brown", "Fox", "Jumps", "Over", "Three", "Lazy", "Dogs"];

            $this.autocomplete({
                source: availableTags
            });
        });
    }


    /*
     * AJAX BUTTON LOADING TEXT
     * Usage: <button type="button" data-loading-text="Loading..." class="btn btn-xs btn-default ajax-refresh"> .. </button>
     */
    $("button[data-loading-text]").on("click", function() {
        var btn = $(this);
        btn.button("loading");
        setTimeout(function() {
            btn.button("reset");
        }, 3000);
    });

}

/* ~ END: INITIALIZE FORMS */


/*
 *高性能JS动态脚本加载封装
 * Usage:
 * Define function = myPrettyCode ()...
 * loadScript("js/my_lovely_script.js", myPrettyCode);
 */

var jsArray = {};

function loadScript(scriptName, callback) {
    if (!jsArray[scriptName]) {
        jsArray[scriptName] = true;

        // var body = document.getElementsByTagName("body")[0];
        var content = document.getElementById("content");

        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = scriptName;
        script.onload = callback;

        // body.appendChild(script);
        content.appendChild(script);
    } else if (callback) { // changed else to else if(callback)
        callback();
    }
}

/**
 * 查找路径是，path + name + '_' +language + '.properties',所以这三个参数很重要。也是通过，language参数的变化，进行多语言切换的
 * @param type
 */
function loadProperties(type) {
    var pathUrl = ''
    if (window.deviceType == 'IPC') {
        pathUrl = 'ipc/language';
    } else if (window.deviceType == 'NVR') {
        pathUrl = 'nvr/language';
    } else {
        pathUrl = 'hvr/language';
    }
    jQuery.i18n.properties({
        name: 'strings', // 资源文件名称
        path: pathUrl, // 资源文件所在目录路径
        mode: 'map', // 模式：变量或 Map
        language: type, // 对应的语言
        cache: false,
        encoding: 'UTF-8',
        callback: function() { // 回调方法
            $('[data-i18n-text]').each(function() {
                if (type === "en") {
                    $(this).text(capitalizeFirstLetter($.i18n.prop($(this).data('i18n-text'))));
                } else {
                    $(this).text($.i18n.prop($(this).data('i18n-text')));
                }
            });
            $('[data-i18n-placeholder]').each(function() {
                if (type === "en") {
                    $(this).attr("placeholder", capitalizeFirstLetter($.i18n.prop($(this).data('i18n-placeholder'))));
                } else {
                    $(this).attr("placeholder", $.i18n.prop($(this).data('i18n-placeholder')));
                }

            });
            $('[data-i18n-value]').each(function() {
                if (type === "en") {
                    $(this).val(capitalizeFirstLetter($.i18n.prop($(this).data('i18n-value'))));
                } else {
                    $(this).val($.i18n.prop($(this).data('i18n-value')));
                }

            });
            $('[data-i18n-title]').each(function() {
                if (type === "en") {
                    $(this).attr("title", capitalizeFirstLetter($.i18n.prop($(this).data('i18n-title'))));
                } else {
                    $(this).attr("title", $.i18n.prop($(this).data('i18n-title')));
                }

            });
        },
    });
}

/**
 * 首字母大写转换
 * @param str
 * @returns {string}
 */
function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * 配置保存提示
 * @param xhr
 * @constructor
 */

function SaveState(xhr, tiptype, url) {
    var xmlDoc;
    if (sessionStorage.getItem("xystyle") == "p2p") {
        if(xhr.responseJSON[0].attach.response){
            xmlDoc = xmlStr2XmlObj(Base64.decode(xhr.responseJSON[0].attach.response));
        }else{
            xmlDoc='404'//这个目前是因为vms上有不支持的接口去请求了会没有响应所以认为请求失败
        }
    } else {
        xmlDoc = xhr.responseXML;
    }
    var typeTip;
    if (url == 'TimedCaptureCfg') {
        typeTip = $.i18n.prop('i18n-short-time')
    } else if (url == 'Config') {
        typeTip = $.i18n.prop('i18n-snapshort')
    } else if(url == 'Onvif'){
        typeTip = $.i18n.prop('i18n-onvife-xie')
    }else if(url == 'Protocol'){
        typeTip = $.i18n.prop('i18n-HK-Protocol')
    }else{
        typeTip = ""
    }
    if(xmlDoc=='404'){
        var state = "404"
    }else{
        var state = $(xmlDoc).find('statusCode').eq(0).text();
    }
    if ("0" == state) {
        bootoast({
            message: tiptype == 1 ? $.i18n.prop('i18n-tipssu-voice') : typeTip + $.i18n.prop('i18n-savesuccess'),
            type: 'success',
            position: 'bottom-center',
            icon: undefined,
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        })
    } else {
        if (url) {
            bootoast({
                message: tiptype == 1 ? $.i18n.prop('i18n-tipsfa-voice') : typeTip + $.i18n.prop('i18n-savefail') + '(/' + url + ')',
                type: 'danger',
                position: 'bottom-center',
                icon: undefined,
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            })
        } else {
            bootoast({
                message: tiptype == 1 ? $.i18n.prop('i18n-tipsfa-voice') : typeTip + $.i18n.prop('i18n-savefail'),
                type: 'danger',
                position: 'bottom-center',
                icon: undefined,
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            })
        }

    }
    return state
}
/**
 * 配置特殊保存提示
 * @param {xhr1 xhr2}
 * @constructor
 */

function SaveStateTwo(xhr1, xhr2) {
    var xmlDoc1, xmlDoc2;
    if (sessionStorage.getItem("xystyle") == "p2p") {
        xmlDoc1 = xmlStr2XmlObj(Base64.decode(xhr1.responseJSON[0].attach.response));
        xmlDoc2 = xmlStr2XmlObj(Base64.decode(xhr2.responseJSON[0].attach.response));
    } else {
        xmlDoc1 = xhr1.responseXML;
        xmlDoc2 = xhr2.responseXML;
    }
    var state1 = $(xmlDoc1).find('statusCode').eq(0).text();
    var state2 = $(xmlDoc2).find('statusCode').eq(0).text();
    if ("0" == state1 && "0" == state2) {
        bootoast({
            message: $.i18n.prop('i18n-savesuccess'),
            type: 'success',
            position: 'bottom-center',
            icon: undefined,
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        })
    } else {
        bootoast({
            message: $.i18n.prop('i18n-savefail'),
            type: 'danger',
            position: 'bottom-center',
            icon: undefined,
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        })

    }
}

/**
 * @function 两个接口同时保存
 * @param {url1,url2}
 *
 */
function multipleSaveState(url1, url2, callback) {
    $.when(url1, url2).done(function(res1, res2) {
        if (sessionStorage.getItem("xystyle") == "p2p") {
            var xmlDoc1 = xmlStr2XmlObj(Base64.decode(res1[2].responseJSON[0].attach.response));
            var xmlDoc2 = xmlStr2XmlObj(Base64.decode(res2[2].responseJSON[0].attach.response));
        } else {
            var xmlDoc1 = new DOMParser().parseFromString(res1[2].responseText, "text/xml")
            var xmlDoc2 = new DOMParser().parseFromString(res2[2].responseText, "text/xml")
        }
        var statusCode1 = $(xmlDoc1).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
        var statusCode2 = $(xmlDoc2).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
        if (statusCode1 == 0 && statusCode2 == 0) {
            $.optionBootoast($.i18n.prop('i18n-savesuccess'), "success");
            if (callback) callback();
        } else {
            $.optionBootoast($.i18n.prop('i18n-savefail'), "danger");
        }
    }).fail(function() {
        $.optionBootoast($.i18n.prop('i18n-savefail'), "danger");
    })
}

/**
 * 根据当前语言决定返回当前lable宽度
 * @param id
 *@param col
 */
function luangetolabewidth() {
    var ppi = window.innerWidth;
    var labels = document.getElementsByTagName("label");
    var url = window.location.href;
    var hash = url.split('#')[1];
    var isOsd = hash.indexOf('osd.html') != -1;
    var isLicen = hash.indexOf('licenseplate.html') != -1;
    var isLight = hash.indexOf('lighting.html') != -1;
    var isPage = hash.indexOf('ispPage.html') != -1;
    if ((sessionStorage.getItem("language") !== "zh" && sessionStorage.getItem("language") !== "tw")) {
        //非中文与繁体
        if (window.devicePixelRatio > 1.25) {
            if (isPage) {
                $('.left-layout').css('margin-right', '72px');
            }
            var classMap = {
                "col-md-1": "col-md-2",
                "col-md-2": "col-md-3",
                "col-md-3": "col-md-4"
            };
        } else { //小于等于1.25
            if (isOsd) {
                var classMap = {
                    "col-md-2": "col-md-4",
                };
            } else if (isLicen) {
                var classMap = {
                    "col-md-1": "col-md-2",
                    "col-md-3": "col-md-4"
                };
            } else {
                var classMap = {
                    "col-md-1": "col-md-2",
                    "col-md-2": "col-md-3",
                    "col-md-3": "col-md-4"
                };
            }
        }
    } else { //中文或者繁体
        if (isLicen) {
            $(".right-layout").width(500);

        }
        if (ppi < 1920) {
            if (window.devicePixelRatio > 1 && window.devicePixelRatio <= 1.25) {
                var bls = getRatio();
                var newWs = (560 * 100 / bls) * 0.75;
                $('.left-layout').css('width', newWs);
                if (isOsd) {
                    var classMap = {
                        "col-md-2": "col-md-3",
                    };
                    $(".left-layout").width(420);
                }
                if (isPage) {
                    var classMap = {
                        "col-md-1": "col-md-2",
                        "col-md-2": "col-md-3",
                        "col-md-3": "col-md-4"
                    };
                    $(".left-layout").width(420);
                }
            }
            if (window.devicePixelRatio > 1.25) {
                if (isOsd) {
                    $(".left-layout").width(680);
                }
                if (isLight) {
                    $('.right-layout').width(400);
                }
                if (isPage) {
                    $('.left-layout').width(570);
                }
                $('.box-layout').width(650);
                var classMap = {
                    "col-md-1": "col-md-2",
                    "col-md-2": "col-md-3",
                    "col-md-3": "col-md-4"
                };

            }
        }
    }
    if (classMap) {
        for (var i = 0; i < labels.length; i++) {
            if (labels[i].className.indexOf("checkbox-inline") == -1) {
                for (var oldClass in classMap) {
                    if (labels[i].className.indexOf(oldClass) != -1) {
                        labels[i].classList.remove(oldClass);
                        labels[i].classList.add(classMap[oldClass]);
                        break;
                    }
                }
            }
        }
    }


}
/* ~ END: LOAD SCRIPTS */


// LOGOUT BUTTON
$("#logout a").click(function(e) {
    logout();
    e.preventDefault();
});


/**
 * easyvideo下载插件
 */

$("#downloadeasyplay").click(function() {
    downloweasyvideo()
});


/*
 * LOGOUT ACTION
 */

function logout() {
    if (sessionStorage.getItem("playstyle") == "EasyVideo") { //销毁设备
        if (self.playervideo) {
            self.playervideo.destroy();
        } else {
            self.playervideo = new Playervideo();
            self.playervideo.destroy();
        }
        sessionStorage.setItem('isWakeupeasyvideo', "");
        localStorage.removeItem("uniqueId");
    } else if (sessionStorage.getItem("playstyle") == "ActiveX") { //销毁设备
        var ncx = document.getElementById("previewocx");
        if (ncx == null) {}
        try {
            ncx.StopVoiceStream(0);
        } catch (e) {}
    }
    sessionStorage.setItem('connectionfail', "");
    sessionStorage.setItem('file', null);
    sessionStorage.setItem('stream', null);
    localStorage.removeItem("reawaken");
    localStorage.removeItem("UID");
    localStorage.removeItem("taskId");
    window.localStorage.setItem('Token', "default"); //登出界面，清空token，将token设置为默认值
    clearTimeout(config.gs_interval);
    clearTimeout(config.enventInterval);
    sessionStorage.setItem('playstyle', "");
    // localStorage.removeItem("playstyle");
    $.root_.addClass("animated fadeOutUp");
    setTimeout(function() {
        window.location.href = "/";
    }, 1000);
}
var playmodelst = getplayMode();

// 查询版本列表
function queryListWasm(param) {
    $.ajax({ //测试服
        // url: "http://139.9.6.140:8090/UtilERP/device/web/download-wasm?boardId=FFFE&deviceType=FFFF&customer=C009&versionId=V001",
        // 正式服
        url: "http://utilerp.p6sai.com:8090/UtilERP/device/web/download-wasm?boardId=FFFE&deviceType=FFFF&customer=C009&versionId=V001",
        type: "GET",
        dataType: 'jsonp',
        jsonp: "callbackName",
        timeout: 1000 * 30, // 设置超时时间为30秒
        jsonpCallback: "showDatawasm",
        success: function(xmlDoc, textStatus, xhr) {},
        error: function(xhr, textStatus) {
            if (param === "login") {
                sessionStorage.setItem('dnowe',undefined);
                if (textStatus === 'timeout' || xhr.status === 404) {
                    // 处理超时的情况
                    if (JSON.stringify(playmodelst) === JSON.stringify(["WebPlayer"])) {
                        $.optionBootoast($.i18n.prop("i18n-Connectiontimeoutfw"), "danger");
                    } else {
                        if (playmodelst.indexOf("EasyVideo") !== -1) {
                            $.getScript("js/EasyVideo/playervideo.js", function() { //请求成功后的回调函数
                                self.playervideo = new Playervideo(); //尝试通话及创建设备连接，创建成功则是代表应用被注册，否则没有
                                self.playervideo.createdev();
                            });
                        } else {
                            window.location.href = "index.html";
                        }
                    }
                } else {
                    // 处理其他错误
                    $.optionBootoast($.i18n.prop("i18n-p2p-msgcehad6"), "danger"); //查询失败
                }

            }
        }
    });
}

function downloadwasm(param) {
    // dbName = 'wasmIndexDB';
    let openRequest = window.indexedDB.open(config.dbName);
    openRequest.onerror = function(event) {
        if (event.target.error.name == 'NotFoundError') {
            console.log('数据库不存在');
            // 数据库就创建并且下载文件传进去
        }
    };
    openRequest.onsuccess = function(event) {
        config.db = event.target.result; // 数据库对象
        console.log(config.dbName, '数据库存在呀');
        config.srateTy = false;
        // 数据库存在则判断是否存在wasm文件
        const transaction = config.db.transaction('wasmIndexDB');
        const store = transaction.objectStore('wasmIndexDB');
        // 获取游标
        const cursorRequest = store.openCursor(null, 'prev');
        cursorRequest.onsuccess = function(event) {
            const cursor = event.target.result;
            if (cursor) {
                // 这是最后一条数据,存在就直接用
                config.oldValue = cursor.value;
                sessionStorage.setItem('file', config.oldValue.id); //不能判断文件
                sessionStorage.setItem('dnowe',undefined);
                if (window.location.pathname == "/") {
                    if (playmodelst.indexOf("EasyVideo") !== -1) {
                        $.getScript("js/EasyVideo/playervideo.js", function() { //请求成功后的回调函数
                            self.playervideo = new Playervideo(); //尝试通话及创建设备连接，创建成功则是代表应用被注册，否则没有
                            self.playervideo.createdev();
                        });
                    } else {
                        window.location.href = "index.html";
                    }
                }
                // config.srateTy = true;
            } else {
                // 不存在就去查询然后下载
                queryListWasm(param);

            }
        };
        // if (config.srateTy) { //存在就比较版本号更新文件
        //     console.log(config.oldValue, "老的值");
        //     queryListWasm("login");
        // } else {
        // }
        // event.target.result.close();

    };
    openRequest.onupgradeneeded = function(event) {
        console.log('数据库存在，但需要升级');
        // 数据库存在，但需要升级的处理逻辑
        config.db = event.target.result; // 获取数据库对象
        // debugger;
        let objectStore;
        if (!config.db.objectStoreNames.contains(config.dbName)) {
            objectStore = config.db.createObjectStore(config.dbName, {
                keyPath: 'id'
            }); // 创建表
            objectStore.createIndex('id', 'id', {
                unique: true
            }); // 创建索引
        }
        // 注意：此时数据库已经打开，需要关闭它
        // event.target.result.close();
    };
}

function showDatawasm(data) {
    if (data.code == '200') {
        sessionStorage.setItem('dnowe',undefined);
        // if (config.srateTy) {
        if (config.oldValue != null && config.oldValue.id == data.data.version) {
            // 没有新版本直接进去了
            var AA = atob(data.data.file);
            var n = AA.length;
            var u8arr = new Uint8Array(n); //创建初始化为0的，包含length个元素的无符号整型数组
            while (n--) {
                u8arr[n] = AA.charCodeAt(n); //返回字符串第一个字符的 Unicode 编码
            }
            var file = stringToFileStream(u8arr, 'aa.wasm', 'application/wasm');
            sessionStorage.setItem('file', data.data.version); //不能判断文件
            // window.location.href = "index.html";
            if (window.location.pathname == "/") {
                if (playmodelst.indexOf("EasyVideo") !== -1) {
                    $.getScript("js/EasyVideo/playervideo.js", function() { //请求成功后的回调函数
                        self.playervideo = new Playervideo(); //尝试通话及创建设备连接，创建成功则是代表应用被注册，否则没有
                        self.playervideo.createdev();
                    });
                } else {
                    window.location.href = "index.html";
                }
            }
            return;
        } else { //有新版本就用新版本的
            var AA = atob(data.data.file);
            var n = AA.length;
            var u8arr = new Uint8Array(n); //创建初始化为0的，包含length个元素的无符号整型数组
            while (n--) {
                u8arr[n] = AA.charCodeAt(n); //返回字符串第一个字符的 Unicode 编码
            }
            var file = stringToFileStream(u8arr, 'aa.wasm', 'application/wasm');
            sessionStorage.setItem('file', data.data.version);
            // 这里是下载文件流到数据库中去
            var dataS = {}
            dataS.id = data.data.version;
            dataS.filefaer = file
            addData(config.db, 'wasmIndexDB', dataS);
        }
    }
    // else {
    //     debugger;
    //     var AA = atob(data.data.file);
    //     var n = AA.length;
    //     var u8arr = new Uint8Array(n); //创建初始化为0的，包含length个元素的无符号整型数组
    //     while (n--) {
    //         u8arr[n] = AA.charCodeAt(n); //返回字符串第一个字符的 Unicode 编码
    //     }
    //     var file = stringToFileStream(u8arr, 'aa.wasm', 'application/wasm');
    //     // 这里是下载文件流到数据库中去
    //     var dataS = {}
    //     dataS.id = data.data.version;
    //     dataS.filefaer = file;
    //     addData(config.db, 'wasmIndexDB', dataS);
    // }
    // }
    else {
        sessionStorage.setItem('dnowe',undefined);
        $.optionBootoast($.i18n.prop("i18n-query-failed"), "danger"); //查询失败
    }
}
//添加数据文件
function addData(db, storeName, data) {
    let request = db.transaction([storeName], 'readwrite') // 事务对象 指定表格名称和操作模式（"只读"或"读写"）
        .objectStore(storeName) // 仓库对象
        .add(data);

    request.onsuccess = function(event) {
        console.log('数据写入成功');
        // 数据写入成功之后就把文件加载进去开始使用
        // sessionStorage.setItem("playstyle", "WebPlayer");
        // window.location.href = "index.html";
        if (window.location.pathname == "/") {
            if (playmodelst.indexOf("EasyVideo") !== -1) {
                $.getScript("js/EasyVideo/playervideo.js", function() { //请求成功后的回调函数
                    self.playervideo = new Playervideo(); //尝试通话及创建设备连接，创建成功则是代表应用被注册，否则没有
                    self.playervideo.createdev();
                });
            } else {
                window.location.href = "index.html";
            }
        }
    };

    request.onerror = function(event) {
        console.log('数据写入失败');
        throw new Error(event.target.error)
    }
};
// 根据版本获取文件
// function getDataByKey(db, storeName, key) {
//     debugger;
//     let transaction = db.transaction([storeName]); // 事务
//     let objectStore = transaction.objectStore(storeName); // 仓库对象
//     let request = objectStore.get(key);

//     request.onerror = function(event) {
//         console.log('事务失败')
//     }

//     request.onsuccess = function(event) {
//         console.log('查询结果: ', request.result)
//     }
// };
// 字符串转blob
function stringToFile(str, mimeType) {
    return new Blob([str], { type: mimeType });
}

function stringToFileStream(str, fileName, mimeType) {
    const file = stringToFile(str, mimeType);
    // const fileStream = URL.createObjectURL(file);
    // sessionStorage.setItem('file', fileStream);
    return file;
}
// buffer转blob
function arrayBufferToBlob(buffer) {
    return new Blob([buffer], { type: 'application/wasm' });
}
// 数值转二进制
function decimalToBinary(num) {
    var binaryString = num.toString(2);
    return parseInt(binaryString);
}
// 数值转数组
function getDigits(num) {
    let strNum = num.toString();
    let digits = [];
    for (let i = 0; i < strNum.length; i++) {
        digits.push(parseInt(strNum[i]));
    }
    return digits;
}
// 设置二进制数的bit位
function setBit(value, bit) {
    var num = value;
    var bitPosition = bit;
    // 创建一个掩码，其中只有我们想要设置的位是1，其他位都是0
    let mask = 1 << bitPosition; // 左移操作符将数字1移动到我们想要设置的位上
    // 使用按位或操作符设置该位为1
    num = num | mask;
    return num;
}
// 获取当前时间并转换为YYYY-MM-DDThh:mm:ss
function getCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
}
// 新增XML对象转字符串函数
function xmlObj2XmlStr(xmlObj) {
    var xmlStr = '';
    if (document.all) {
        // IE浏览器使用xmlDom.xml属性
        xmlStr = xmlObj.xml;
    } else {
        // 标准浏览器使用XMLSerializer
        var serializer = new XMLSerializer();
        xmlStr = serializer.serializeToString(xmlObj);
    }
    return xmlStr;
}

function notifyVms(data) {
    var url;
    if(sessionStorage.getItem("xystyle") == "p6s"){
        url = config.p6sURL + '/client/notify';
    }else if(sessionStorage.getItem("xystyle") == "p2p"){
        url = config.baseUrl + '/client/notify';
    }
    $.ajax({
        type: "POST",
        url: url,
        data:data,
        dataType: 'json',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        },
        success: function(data) {
        },
        error: function(data) {}
    });

}
