var icimagestr = [];
var str_ic_imagestr = [];
var icbwstr = ["close", "weak", "normal", "strong"];
var icbwstrd = ["automatic", "weak", "normal", "strong", "close"];
var str_ic_bwd = $.i18n.prop("i18n-Wide-dynamicValue").split(",");
var str_ic_bw = $.i18n.prop("i18n-ic-bw").split(",");
var str_ic_codestream = $.i18n.prop("i18n-ic-codestream").split(",");
var recordlistData; //脸库数组
var bit = [64, 128, 256, 512, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 8192, 10240, 12288];
var get_xml_doc, getBasic_xml_doc, gs_stream_cap_xml, gs_main_stream_xml, gs_first_stream_xml, gs_second_stream_xml, get_osdxml_doc, get_timexml_doc, xmlDocelec, xmlDoccross, xmlDocoffDuty, xmlflow, xmlface, xmlFaceReco, gs_ptz_cfg;
var carStatus = false;
var faceStatus = false;
var numberOfScreens = 0;
var streamType = 2;
var fontsizce=0;
var dot=false;
var isosdType = '';
var thoroughfareArray = [];
// var MultiArray = [];
var thoroughfare = config.thoroughfare;
var inember = 0;
var keepdoit = {
    width: '',
    base64: '',
    height: '',
    length: ''
}
var keepdoit2 = {
    width: '',
    base64: '',
    height: '',
    length: ''
};
var gs_stream_type_map_table = [{
        strResolutionID: "resolution",
        strXMLStreamName: "MainStreamCapability"
    },
    {
        strResolutionID: "resolution",
        strXMLStreamName: "SubStreamCapability"
    },
    {
        strResolutionID: "resolution",
        strXMLStreamName: "SecondStreamCapability"
    },
    {
        strResolutionID: "resolution",
        strXMLStreamName: "SecondStreamCapability"
    }
];
var eable3d=false;//3D开关是否打开
var canvasRecorder=null;
var osdline1, osdline2, osdchar1, osdchar2, quckparam, osd2, isFaceSnapEnable, isCarPlateSnapEnable, isCarctronSnapenable,osd1;
$(document).ready(function() {
    config.lastnav = "preview";
    // $("#ptzPresetPointbody").height(document.documentElement.clientHeight - 200);
    if ((/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null)) {
        if (config.playMode.includes("WebPlayer") && (sessionStorage.getItem('file') == null || sessionStorage.getItem('file') == "null")) {
            downloadwasm();
        }

    }
    InitPreview();
    // getfacetime(); // 进入预览页面获取人脸抓拍使能，来显示隐藏人脸事件按钮
    // getCarPlateSnap(); // 进入预览页面获取车牌抓拍使能，来显示隐藏车牌抓拍按钮
    //默认码流
    if (sessionStorage.getItem("playstyle") == "ActiveX" || sessionStorage.getItem("playstyle") == "EasyVideo") {
        if (sessionStorage.getItem('stream') === null||sessionStorage.getItem('stream')=="null") {
            // 若不存在，则设置 'stream' 的值
            sessionStorage.setItem('stream', "miancodestream");
        }
        // sessionStorage.setItem('stream', "miancodestream");
    } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
        if (sessionStorage.getItem('stream') === null||sessionStorage.getItem('stream')=="null") {
            // 若不存在，则设置 'stream' 的值
            sessionStorage.setItem('stream', "codestream1");
        }
        // sessionStorage.setItem('stream', "codestream1");
    }
    if (config.deviceInfo.DeviceName == "IPC") {
        getOSD();
        $(".nvr").hide();
        $("#originalScale").show();
        if (config.isSupportMultiChannel == true) {
            // $("#main").addClass("showchancel");//这里不能显示出来
            var liveHtml = "";
            for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                liveHtml += '<div class="channel-list" id="Multichacel' + i + '" data-id=' + i + '>'
                if (i < 3) {
                    if (i == 1) {
                        liveHtml += '<span class="preview-left-name">' + $.i18n.prop('i18n-tracking') + '</span>' +
                            '<div class="previewLeftImg">' +
                            '<img src="img/preview/nvrplay.png"   id="Multichacel' + i + 'img">' +
                            '</div>' +
                            '<div class="previewMiddleImg" id="previewMiddle' + i + 'Img"></div>' +
                            '</div>';
                    }
                    if (i == 2) {
                        liveHtml += '<span class="preview-left-name">' + $.i18n.prop('i18n-panoramic') + '</span>' +
                            '<div class="previewLeftImg">' +
                            '<img src="img/preview/nvrchcel.png"   id="Multichacel' + i + 'img">' +
                            '</div>' +
                            '<div class="previewMiddleImg" id="previewMiddle' + i + 'Img"></div>' +
                            '</div>';
                    }
                }
                if (i >= 3) { //这里超过2目的设备需要固件提供能力或者其他的东西让网页判断枪机和球机，已沟通暂时不处理3目以上
                    liveHtml += '<span class="preview-left-name" title="CAM' + i + '">通道' + i + '</span>' +
                        '<div class="previewLeftImg">' +
                        '<img src="img/preview/nvrchcel.png"  id="Multichacel' + i + 'img">' +
                        '</div>' +
                        '<div class="previewMiddleImg" id="previewMiddle' + i + 'Img"></div>' +
                        '</div>';
                }
                // MultiArray.push(false);
            }
            $(".previewLeftd").html(liveHtml);

        } else {
            $(".rightdiv").hide();
            $("#main").removeClass("showchancel");
        }
    } else {
        if (!(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null)) {
            streamType = 4;
        }
        config.liveStatus = true;
        $(".nvr").show();
        $("#4proportion3").hide();
        $("#16proportion9").hide();
        $("#playType").hide();
        // $("#intercom").hide()
        $("#main").addClass("showchancel");
        $(".previewLeft").show();
        var liveHtml = "";
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            liveHtml += '<div class="channel-list" id="nvrchacel' + i + '" data-id=' + i + '>'
            if (i < 10) {
                liveHtml += '<span class="preview-left-name" title="CAM0' + i + '">通道0' + i + '</span>' +
                    '<div class="previewLeftImg">' +
                    '<img src="img/preview/nvrchcel.png"   id="nvrchacel' + i + 'img">' +
                    '</div>' +
                    '<div class="previewMiddleImg" id="previewMiddle' + i + 'Img"></div>' +
                    '</div>';
            }
            if (i >= 10) {
                liveHtml += '<span class="preview-left-name" title="CAM' + i + '">通道' + i + '</span>' +
                    '<div class="previewLeftImg">' +
                    '<img src="img/preview/nvrchcel.png"  id="nvrchacel' + i + 'img">' +
                    '</div>' +
                    '<div class="previewMiddleImg" id="previewMiddle' + i + 'Img"></div>' +
                    '</div>';
            }
            thoroughfareArray.push(false);
        }
        $(".previewLeft").html(liveHtml);
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            CHOSDGetSel(i);
        }
    }
    if (config.deviceInfo.DeviceName == 'IPC') {
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", 0);
    } else {
        $("#isNvrimg").hide() //根据项目经理需求，nvr时隐藏通用中的图像模块
            //$("#isNvrnoptz").hide() //根据项目经理需求，nvr时隐藏通用中的步长
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", 0, false);
        // 这里默认展示分屏的数量4-4,8-9-9,9以上16
        if (config.deviceInfo.VideoInputChannels == 4) {
            document.getElementById("defaultscreen").src = document.getElementById("screen4").src;
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                ChangeLayout(2)
            }
        } else if (config.deviceInfo.VideoInputChannels == 8 || config.deviceInfo.VideoInputChannels == 9) {
            document.getElementById("defaultscreen").src = document.getElementById("screen9").src;
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                ChangeLayout(3)
            }
        } else if (config.deviceInfo.VideoInputChannels > 9) {
            document.getElementById("defaultscreen").src = document.getElementById("screen16").src;
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                ChangeLayout(4)
            }
        }
    }
    $(".select2").select2({
        minimumResultsForSearch: -1,
    });
    getfacetime(); // 进入预览页面获取人脸抓拍使能，来显示隐藏人脸事件按钮
    getCarPlateSnap(); // 进入预览页面获取车牌抓拍使能，来显示隐藏车牌抓拍按钮
    $(".previewLeft .channel-list").on("click", function(evt) {
        var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
        var channel = evt.currentTarget.getAttribute('data-id');
        var classname = 'nvrchacel' + channel;
        if (thoroughfareArray[channel - 1]) {
            document.getElementById("" + classname).querySelector("img").src = "img/preview/nvrchcel.png";
            if (g_bIsIE) {
                StopVideo(channel - 1);
            } else {
                playbackChannel('', false, "", "", 1, channel - 1, streamType);
            }
            config.play_push_list.splice(config.play_push_list.indexOf(channel - 1), 1); //关闭的通道就清除掉
            thoroughfareArray[channel - 1] = false;
        } else {
            document.getElementById("" + classname).querySelector("img").src = "img/preview/nvrplay.png";
            if (g_bIsIE) {
                PlayVideo(channel - 1, streamType);
                ChannelShowText(channel - 1, "CAM" + channel);
            } else {
                playbackChannel('', true, "", "", 1, channel - 1, streamType);
            }
            config.play_push_list.push(channel - 1);
            thoroughfareArray[channel - 1] = true;

        }
    });
    // 多目设备点击播放
    $(".previewLeftd .channel-list").on("click", function(evt) {
        var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
        var channel = evt.currentTarget.getAttribute('data-id');
        inember = channel - 1;
        var classname = 'Multichacel' + channel;
        document.getElementById("" + classname).querySelector("img").src = "img/preview/nvrplay.png";
        if (channel == 1) {
            document.getElementById("Multichacel2").querySelector("img").src = "img/preview/nvrchcel.png";
        } else {
            document.getElementById("Multichacel1").querySelector("img").src = "img/preview/nvrchcel.png";
        }
        if (g_bIsIE) {
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", channel - 1);
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                easyldspecialvideos(false);
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", channel - 1);
            } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                $("#axdiv").empty();
                clearInterval(config.gs_interval);
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", channel);
            }
        }
        $("#miancodestream").click();
    });
    // if (config.deviceCap.FaceSnapshot == "true" || config.deviceCap.IsFaceReco == "true") {
    //     $("#electron").show();
    // } else {
    //     $("#electron").hide();
    // }
    // 车牌抓拍能力
    // if (config.deviceCap.carSupport == "true") {
    //     $("#carctron").show();
    // } else {
    //     $("#carctron").hide();
    // }
    if (config.enventInterval == '') {
        self.enventwesoket = new enventwesoket("main");
    }
    config.enventInterval = setInterval(function() {
        var nowTimeds = Math.round(Date.parse(new Date()) / 1000).toString();
        if (config.enventList.length > 0) {
            for (var i = 0; i < config.enventList.length; i++) {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    if (nowTimeds - config.enventList[i].time > 5) {
                        if (config.enventList[i].type == "videoShade") {
                            $("#spzd").remove();
                        } else if (config.enventList[i].type == "leavePost") {
                            $("#ligang").remove();
                        } else if (config.enventList[i].type == "outOfBound") {
                            $("#yuejie").remove();
                        } else if (config.enventList[i].type == "fenceDetectAlarm"||config.enventList[i].type == "fenceDetectAlarmV2") {
                            $("#quyu").remove();
                        } else if (config.enventList[i].type == "motionDetection") {
                            $("#yidon").remove();
                        }
                    }
                } else { //nvr事件超时处理
                    if (nowTimeds - config.enventList[i].time > 5) {
                        if (config.enventList[i].type == "motionDetection") {
                            $("#previewMiddle" + config.enventList[i].EVtype + "Img #yidon").remove();
                        } else if (config.enventList[i].type == "humanDetection") {
                            $("#previewMiddle" + config.enventList[i].EVtype + "Img #renxin").remove();
                        }
                    }

                }
            }
        }
    }, 1000);


    if (config.deviceInfo.DeviceName == "IPC") {
        switch (config.deviceCap[inember].StreamCount) {
            case 2:
                if (sessionStorage.getItem("stream") == "miancodestream") {
                    $("<label class='btn btn-groupbtn active' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck'>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("miancodestream").innerText);
                } else if (sessionStorage.getItem("stream") == "codestream1") {
                    $("<label class='btn btn-groupbtn' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck'>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn active' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("codestream1").innerText);
                }
                break;
            case 3:
                if (sessionStorage.getItem("stream") == "miancodestream") {
                    $("<label class='btn btn-groupbtn active' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck' checked>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn' id='codestream2'><input type='radio' name='options' id='codestream2check'>" + $.i18n.prop('i18n-codestream2') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("miancodestream").innerText);
                } else if (sessionStorage.getItem("stream") == "codestream1") {
                    $("<label class='btn btn-groupbtn' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck' checked>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn active' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn' id='codestream2'><input type='radio' name='options' id='codestream2check'>" + $.i18n.prop('i18n-codestream2') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("codestream1").innerText);
                } else if (sessionStorage.getItem("stream") == "codestream2") {
                    $("<label class='btn btn-groupbtn' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck' checked>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn active' id='codestream2'><input type='radio' name='options' id='codestream2check'>" + $.i18n.prop('i18n-codestream2') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("codestream2").innerText);
                }
                break;
            default:
                if (sessionStorage.getItem("stream") == "miancodestream") {
                    $("<label class='btn btn-groupbtn active' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck'>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("miancodestream").innerText);
                } else if (sessionStorage.getItem("stream") == "codestream1") {
                    $("<label class='btn btn-groupbtn' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck'>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
                    $("<label class='btn btn-groupbtn active' id='codestream1'><input type='radio' name='options' id='codestream1check'>" + $.i18n.prop('i18n-codestream1') + "</label>").appendTo("#codestreamlableoption");
                    $('#codestream span').text(document.getElementById("codestream1").innerText);
                }
                break;
        }

    } else {
        $("<label class='btn btn-groupbtn' id='miancodestream'><input type='radio' name='options' id='miancodestreamcheck'>" + $.i18n.prop('i18n-miancodestream') + "</label>").appendTo("#codestreamlableoption");
        $("<label class='btn btn-groupbtn active' id='codestream1'><input type='radio' name='options' id='codestream1check'> " + $.i18n.prop('i18n-yl-codesum1') + " </label>").appendTo("#codestreamlableoption");
        $('#codestream span').text(document.getElementById("codestream1").innerText);
    }

    if (config.devicelose) {
        addEventListener("resize", function(event) {});
    }

    $(window).resize(function() {
        // $("#ptzPresetPointbody").height(document.documentElement.clientHeight - 200);
        if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#preview.html" && $("#axdiv")[0]) {
            preWindowfollowing(false)
        }
    });

    $("#slideleftId").click(function() {
        $("#slideleftId").toggle();
        $("#sliderightId").toggle();
        $(".singlePanel").toggleClass("showyt");
        $(".actionBar").toggleClass("showyt");
        $(".actionBarandface").toggleClass("showyt");
        $(".faceenvent").toggleClass("showyt");
        $("#content").toggleClass("showbj");
        $("#main").toggleClass("nopadding");
        $(".leftdiv").toggleClass("right");
        $(".previewRight").toggle();
        if(canvasRecorder && (sessionStorage.getItem("playstyle") == "WebPlayer"||sessionStorage.getItem("playstyle") == "MJPEG")){
            canvasRecorder.resizeCanvas();
        }
    });
    $("#sliderightId").click(function() {
        $("#slideleftId").toggle();
        $("#sliderightId").toggle();
        $(".singlePanel").toggleClass("showyt");
        $(".actionBar").toggleClass("showyt");
        $(".actionBarandface").toggleClass("showyt");
        $(".faceenvent").toggleClass("showyt");
        $("#content").toggleClass("showbj");
        $("#main").toggleClass("nopadding");
        $(".leftdiv").toggleClass("right");
        $(".previewRight").toggle();
        if(canvasRecorder && (sessionStorage.getItem("playstyle") == "WebPlayer"||sessionStorage.getItem("playstyle") == "MJPEG")){
            canvasRecorder.resizeCanvas();
        }
    });
    $("#slideleftIdmor").click(function() {
        $("#slideleftIdmor").toggle();
        $("#sliderightIdmor").toggle();
        $(".singlePanel").toggleClass("showlt");
        $(".actionBar").toggleClass("showlt");
        $(".actionBarandface").toggleClass("showlt");
        $(".faceenvent").toggleClass("showlt");
        $("#content").toggleClass("showbj");
        $("#main").toggleClass("nopadding");
        $(".rightdiv").toggleClass("left");
        $(".previewLeftd").toggle();
    });
    $("#sliderightIdmor").click(function() {
        $("#slideleftIdmor").toggle();
        $("#sliderightIdmor").toggle();
        $(".singlePanel").toggleClass("showlt");
        $(".actionBar").toggleClass("showlt");
        $(".actionBarandface").toggleClass("showlt");
        $(".faceenvent").toggleClass("showlt");
        $("#content").toggleClass("showbj");
        $("#main").toggleClass("nopadding");
        $(".rightdiv").toggleClass("left");
        $(".previewLeftd").toggle();
    });

    // document.addEventListener('click', function (e) { console.log('click!') })


    $("#chancelright").click(function() {
        $("#chancelright").hide();
        $("#chancelleft").show();
        $("#main").addClass("showchancel");
        $(".previewLeft").show();
    });

    $("#chancelleft").click(function() {
        $("#chancelright").show();
        $("#chancelleft").hide();
        $("#main").removeClass("showchancel");
        $(".previewLeft").hide();
    });
    // 车牌事件
    $("#carctron").click(function() {
        if (faceStatus == true) {
            $.optionBootoast($.i18n.prop('i18n-TIPS-refise'), "danger");
            return
        }
        carStatus = true;
        //抓拍事件
        $("#carctron").toggleClass("activeimg");
        document.getElementById("tipsa").src = "img/enventicon/cpshibie_icon02.png";
        if (config.deviceCap[inember].carSupport == "true" && isCarPlateSnapEnable == "true") {
            if (!$(".faceenvent").hasClass('showyt')) {
                $(".play").addClass("faceheight");
                $("#czbar").toggleClass("actionBar");
                $("#czbar").toggleClass("actionBarandface");
                $(".faceenvent").toggle();
                $(".customize").hide();
                $("#carctron").hide();
                $("#fullscreen").hide();
                $("#facegobck").show();
                $("#facejs").hide();
                $("#mySwitchText").hide();
            }
        }
        //布控事件
        if (config.deviceCap[inember].lincenPlate == "true" && isCarctronSnapenable == "true") {
            if (!$(".singlePanel").hasClass('showyt')) {
                $(".previewRight").toggle();
                $(".singlePanel").toggleClass("showyt");
                $(".actionBar").toggleClass("showyt");
                $(".actionBarandface").toggleClass("showyt");
                $(".faceenvent").toggleClass("showyt");
                $("#content").toggleClass("showbj");
                $("#main").toggleClass("nopadding");
                $(".leftdiv").toggleClass("right");
            }
            $("#slideleftId").hide();
            $("#sliderightId").hide();
            $("#previewTab").hide();
            if ($("#previewyt").hasClass('active')) {
                $("#previewyt").toggleClass("active");
                $("#previewyt").toggleClass("fade");
            }
            if ($("#previewcommon").hasClass('active')) {
                $("#previewcommon").toggleClass("active");
                $("#previewcommon").toggleClass("fade");
            }
            if ($("#previewzn").hasClass('active')) {
                $("#previewzn").toggleClass("active");
                $("#previewzn").toggleClass("fade");
            }
            $(".concterFaceReco").show();
            $(".titleCarReco").show();
        }
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preWindowfollowing(false, 1);
            preWindowfollowing(false);
        }

    });
    //人脸事件
    $("#electron").click(function() {
        if (carStatus == true) {
            $.optionBootoast($.i18n.prop('i18n-TIPS-refise'), "danger");
            return
        }
        faceStatus = true;
        faceGroupsQueryAll();
        $("#electron").toggleClass("activeimg");
        config.enableelectron = false;
        document.getElementById("tipsa").src = "img/face/facecapture.png"
        if (config.deviceCap[inember].FaceSnapshot == "true") { //抓拍
            $(".play").addClass("faceheight");
            $("#czbar").toggleClass("actionBar");
            $("#czbar").toggleClass("actionBarandface");
            $(".faceenvent").toggle();
            $(".customize").hide();
            $("#electron").hide();
            $("#fullscreen").hide();
            $("#facegobck").show();
            $("#facejs").show();
            $("#mySwitchText").show();
        }
        if (config.deviceCap[inember].IsFaceReco == "true") { //识别
            if (!$(".singlePanel").hasClass('showyt')) {
                $(".previewRight").toggle();
                $(".singlePanel").toggleClass("showyt");
                $(".actionBar").toggleClass("showyt");
                $(".actionBarandface").toggleClass("showyt");
                $(".faceenvent").toggleClass("showyt");
                $("#content").toggleClass("showbj");
                $("#main").toggleClass("nopadding");
                $(".leftdiv").toggleClass("right");
            }
            $("#slideleftId").hide();
            $("#sliderightId").hide();
            $("#previewTab").hide();
            if ($("#previewyt").hasClass('active')) {
                $("#previewyt").toggleClass("active");
                $("#previewyt").toggleClass("fade");
            }
            if ($("#previewcommon").hasClass('active')) {
                $("#previewcommon").toggleClass("active");
                $("#previewcommon").toggleClass("fade");
            }
            if ($("#previewzn").hasClass('active')) {
                $("#previewzn").toggleClass("active");
                $("#previewzn").toggleClass("fade");
            }
            if (config.isShowFaces) {
                $(".concterFaceReco").show();
            } else {
                $(".concterFaceReco").hide();
            }
            $(".titleFaceReco").show();
            // $(".concterFaceReco").show();
        }
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preWindowfollowing(false, 1);
            preWindowfollowing(false);
        }
    });



    // 封装点击事件处理函数
    function handleClick(elementClass) {
        return function() {
            if (carStatus) {
                return;
            }
            var playStyle = sessionStorage.getItem("playstyle");
            // 使用严格相等比较避免意外类型强制
            if (playStyle === "EasyVideo") {
                preHiddenDisplaywindow(4);
            } else if (playStyle === "ActiveX") {
                $("#axdiv").hide();
            }
            var faceFeature = document.getElementById('face_Feature');
            var elements = faceFeature.getElementsByClassName(elementClass);
            var leftnum = -1;
            for (var i = 0; i < elements.length; i++) {
                if (elements[i] === this) {
                    leftnum = i;
                    break;
                }
            }
            var lefttotal = elements.length;
            var chancelName = config.osdname + config.peopleface_detect_list[lefttotal - leftnum - 1].chancel;
            $("#caputImagemodalbody").empty();
            $("#caputImagemodalbody").prepend(
                "<div class='bigcaptuerimg'><img src='" + config.peopleface_detect_list[lefttotal - leftnum - 1].caputImagePath + "'></div>" +
                "<div class='modefooterfacecapte'><span class='viewbigimgtitle'>" + $.i18n.prop('i18n-Channelname') + ":" + chancelName + "</span>" +
                "<span class='zhuapitime'>" + $.i18n.prop('i18n-Capturetime') + ":" + config.peopleface_detect_list[lefttotal - leftnum - 1].time + "</span>" +
                "<span>" +
                "</span>" +
                "</div>");

            $("#caputImageModal").modal("show");
        };
    }

    if (config.IsPushFaceFeatures === "true") {
        $("#face_Feature").on("click", ".oneCaput", handleClick("oneCaput"));
    } else {
        $("#face_Feature").on("click", ".zppeople", handleClick("zppeople"));
    }

    $('#caputImageModal').on('hide.bs.modal', function() {
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(3);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            $("#axdiv").show();
        }
    });

    $("#face_Analysis").on("click", ".peopleparent", function() {
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            $("#axdiv").hide();
        }
        var rightnum = $("#face_Analysis .peopleparent").index(this);
        var righttotal = $("#face_Analysis").children(".onepeopleFaceReco").length;
        quckparam = config.face_detect_list[righttotal - rightnum - 1];
        var chancelName = config.osdname + config.face_detect_list[righttotal - rightnum - 1].chancel;
        $("#snapImagemodalbody").empty();
        if (config.face_detect_list[righttotal - rightnum - 1].match != 0) { //比对通过
            $("#snapImagemodalbody").prepend(
                "<div class='bigcaptuerimg'><img src='" + config.face_detect_list[righttotal - rightnum - 1].caputImagePath + "'></div>" +
                "<div class='modefooterfacecapte'><span class='viewbigimgtitle'>" + $.i18n.prop('i18n-Channelname') + ":" + chancelName + "</span>" +
                "<span class='zhuapitime'>" + $.i18n.prop('i18n-name') + ":" + config.face_detect_list[righttotal - rightnum - 1].faceName + "</span>" +
                "<span class='viewbigimgtitle'>" + $.i18n.prop('i18n-facegroupname') + ":" + config.face_detect_list[righttotal - rightnum - 1].faceLibName + "</span>" +
                "</div>" +
                "<div class='viewbigimgtitle'>" + $.i18n.prop('i18n-Capturetime') + ":" + config.face_detect_list[righttotal - rightnum - 1].time + "</div>"
            );
        } else { //比对不通过
            $("#snapImagemodalbody").prepend(
                "<div class='bigcaptuerimg'><img src='" + config.face_detect_list[righttotal - rightnum - 1].caputImagePath + "'></div>" +
                "<div class='modefooterfacecapte'><span class='viewbigimgtitle'>" + $.i18n.prop('i18n-Channelname') + ":" + chancelName + "</span>" +
                "<span class='zhuapitime'>" + $.i18n.prop('i18n-Capturetime') + ":" + config.face_detect_list[righttotal - rightnum - 1].time + "</span>" +
                "<span class='viewbigimgresult'>" + $.i18n.prop('i18n-Comparisonresult') + "</span>" +
                "</div>"
            );

            for (var i = 0; i < recordlistData.length; i++) {
                if (recordlistData[i].GroupName == "unBindGroup") {
                    recordlistData[i].GroupName = '未绑定脸库';
                } else if (recordlistData[i].GroupName == "whiteListGroup") {
                    recordlistData[i].GroupName = '白名单脸库';
                } else if (recordlistData[i].GroupName == "blackListGroup") {
                    recordlistData[i].GroupName = '黑名单脸库';
                } else {
                    recordlistData[i].GroupName = recordlistData[i].GroupName;
                }
                $("<option value='" + recordlistData[i].GroupID + "'>" + recordlistData[i].GroupName + "</option>").appendTo("#facezhupairule");
            }

            $("#facezhupairule").select2({
                width: 150,
                minimumResultsForSearch: -1,
            });

            if (config.deviceCap[inember].IsFaceLibConfig == "true") {
                $(".qucikfacerk").hide();
            } else {
                $(".qucikfacerk").show();
            }
        }
        $("#snapImageModal").modal("show");
    });



    $('#snapImageModal').on('hide.bs.modal', function() {
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(3);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            $("#axdiv").show();
        }
    });

    //人脸事件返回
    $("#facegobck").click(function() {
        if (carStatus) {
            carStatus = false;
            $("#carctron").toggleClass("activeimg");
            //抓拍
            if (config.deviceCap[inember].carSupport == "true" && isCarPlateSnapEnable == "true") {
                $(".play").removeClass("faceheight");
                $("#czbar").toggleClass("actionBar");
                $("#czbar").toggleClass("actionBarandface");
                $(".faceenvent").toggle();
                $(".customize").show();
                $("#carctron").show();
                $("#fullscreen").show();
                $("#facegobck").hide();
                $("#facejs").hide();
                $("#mySwitchText").hide();
            }
            //布控事件
            if (config.deviceCap[inember].lincenPlate == "true" && isCarctronSnapenable == "true") {
                $("#slideleftId").show();
                $("#sliderightId").hide();
                $("#previewTab").show();
                if ($("#previewyt").hasClass('fade')) {
                    $("#previewyt").toggleClass("active");
                    $("#previewyt").toggleClass("fade");
                }
                if ($("#previewcommon").hasClass('fade')) {
                    $("#previewcommon").toggleClass("active");
                    $("#previewcommon").toggleClass("fade");
                }
                if ($("#previewzn").hasClass('fade')) {
                    $("#previewzn").toggleClass("active");
                    $("#previewzn").toggleClass("fade");
                }
                $(".concterFaceReco").hide();
                $(".titleCarReco").hide();
                $("#slideleftId").click();
            }
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preWindowfollowing(false, 2);
                preWindowfollowing(false);
            }
        } else {
            faceStatus = false;
            config.enableelectron = true;
            $("#electron").toggleClass("activeimg");
            if (config.deviceCap[inember].FaceSnapshot == "true") { //抓拍
                $(".play").removeClass("faceheight");
                $("#czbar").toggleClass("actionBar");
                $("#czbar").toggleClass("actionBarandface");
                $(".faceenvent").toggle();
                $(".customize").show();
                $("#electron").show();
                $("#fullscreen").show();
                $("#facegobck").hide();
                $("#facejs").hide();
                $("#mySwitchText").hide();
            }
            if (config.deviceCap[inember].IsFaceReco == "true") { //识别
                $("#slideleftId").show();
                $("#sliderightId").hide();
                $("#previewTab").show();
                if ($("#previewyt").hasClass('fade')) {
                    $("#previewyt").toggleClass("active");
                    $("#previewyt").toggleClass("fade");
                }
                if ($("#previewcommon").hasClass('fade')) {
                    $("#previewcommon").toggleClass("active");
                    $("#previewcommon").toggleClass("fade");
                }
                if ($("#previewzn").hasClass('fade')) {
                    $("#previewzn").toggleClass("active");
                    $("#previewzn").toggleClass("fade");
                }
                $(".titleFaceReco").hide();
                $(".concterFaceReco").hide();
                $("#slideleftId").click();
            }
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preWindowfollowing(false, 2);
                preWindowfollowing(false);
            }

        }

    });

    //人脸接收事件
    $("#facejs").click(function() {
        config.stopjs = !!$(this).hasClass('cw-switch-checked');
        $(this).toggleClass('cw-switch-checked');
    });

    $("#soundopen").click(function() {
        var pictsdj = document.getElementById("intercom");
        if (pictsdj.getAttribute("src", 2) == "img/preview/intercomselect.png") {
          return   $.optionBootoast($.i18n.prop('i18n-language_closeDj'), 'danger')
        }
        var picts = document.getElementById("soundopen");
        if (picts.getAttribute("src", 2) == "img/preview/soundopen.png") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    $("#soundopen").attr("title", $.i18n.prop('i18n-soundopen'));
                    picts.setAttribute("src", "img/preview/soundclose.png");
                    StopAudio(1); // 停止音频
                } else {
                    if (config.play_push_list.indexOf(config.chnelNum) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        $("#soundopen").attr("title", $.i18n.prop('i18n-soundopen'));
                        picts.setAttribute("src", "img/preview/soundclose.png");
                        AudioContrl(-1, 0);
                        config.nums_push_list.splice(config.nums_push_list.indexOf(config.chnelNum), 1); //关闭的通道就清除掉
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // 停止音频
                if (config.deviceInfo.DeviceName == 'IPC') {
                    $("#soundopen").attr("title", $.i18n.prop('i18n-soundopen'));
                    picts.setAttribute("src", "img/preview/soundclose.png");
                    stopPreaudio();
                } else {
                    if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        $("#soundopen").attr("title", $.i18n.prop('i18n-soundopen'));
                        picts.setAttribute("src", "img/preview/soundclose.png");
                        stopPreaudio(config.thoroughfare); //nvr关闭音频
                        config.nums_push_list.splice(config.nums_push_list.indexOf(config.thoroughfare), 1); //关闭的通道就清除掉
                    }
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    $("#soundopen").attr("title", $.i18n.prop('i18n-soundclose'));
                    picts.setAttribute("src", "img/preview/soundopen.png");
                    PlayAudio(1); // 打开音频
                } else {
                    if (config.play_push_list.indexOf(config.chnelNum) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        $("#soundopen").attr("title", $.i18n.prop('i18n-soundclose'));
                        picts.setAttribute("src", "img/preview/soundopen.png");
                        AudioContrl(-1, 1);
                        config.nums_push_list.push(config.chnelNum); //记录那个通道的声音被打开了
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // 打开音频
                if (config.deviceInfo.DeviceName == 'IPC') {
                    $("#soundopen").attr("title", $.i18n.prop('i18n-soundclose'));
                    picts.setAttribute("src", "img/preview/soundopen.png");
                    openaudio();
                } else {
                    if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        $("#soundopen").attr("title", $.i18n.prop('i18n-soundclose'));
                        picts.setAttribute("src", "img/preview/soundopen.png");
                        openaudio(config.thoroughfare); //nvr打开音频
                        config.nums_push_list.push(config.thoroughfare) //记录那个通道的声音被打开了
                    }
                }
            }

        }
        // $("#soundopen").toggleClass("activeimg");
    });
    $("#intercom").click(function() {
        var pictssy = document.getElementById("soundopen");
        if (pictssy.getAttribute("src", 2) == "img/preview/soundopen.png") {
            return   $.optionBootoast($.i18n.prop('i18n-language_closeVoice'), 'danger')
        }
        var picts = document.getElementById("intercom");
        if (picts.getAttribute("src", 2) == "img/preview/intercomselect.png") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/intercom.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
                    Stoptalkback();
                } else {
                    // 这里表示支持和ipc对讲，但实际仅仅支持本地对讲不需要通道号所以先注释（保留代码）
                    // if (config.play_push_list.indexOf(config.chnelNum) == -1) { //表示没有开预览
                    //     $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    // } else {
                    picts.setAttribute("src", "img/preview/intercom.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
                    StopVoiceStream()
                        // }

                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/intercom.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
                    Closeintercom();
                } else {
                    // 这里表示支持和ipc对讲，但实际仅仅支持本地对讲不需要通道号所以先注释（保留代码）
                    // if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                    //     $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    // } else {
                    picts.setAttribute("src", "img/preview/intercom.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
                    Closeintercom(); //nvr的关闭对讲，如果需要传通道号，这个通道号是从插件的回调拿
                    // }
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/intercomselect.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-closeintercom'));
                    Playtalkback();
                } else {
                    // 这里表示支持和ipc对讲，但实际仅仅支持本地对讲不需要通道号所以先注释（保留代码）
                    // if (config.play_push_list.indexOf(config.chnelNum) == -1) { //表示没有开预览
                    //     $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    // } else {
                    picts.setAttribute("src", "img/preview/intercomselect.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-closeintercom'));
                    StartVoiceStream()
                        // }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/intercomselect.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-closeintercom'));
                    OpenIntercom();
                } else {
                    // 这里表示支持和ipc对讲，但实际仅仅支持本地对讲不需要通道号所以先注释（保留代码）
                    // if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                    //     $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    // } else {
                    picts.setAttribute("src", "img/preview/intercomselect.png");
                    $("#intercom").attr("title", $.i18n.prop('i18n-closeintercom'));
                    OpenIntercom(); //nvr的打开对讲
                    // }
                }
            }

        }
    });
    $("#capture").click(function() {
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            if (config.deviceInfo.DeviceName == 'IPC') {
                CaptureImage(); // 截图
            } else {
                if (config.play_push_list.indexOf(config.chnelNum) == -1) { //表示没有开预览
                    $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                } else {
                    CaptureImager(config.chnelNum)
                }
            }
        } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            if (config.deviceInfo.DeviceName == 'IPC') {
                easyCaptureImage(true);
            } else {
                if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                    $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                } else {
                    easyCaptureImage(true, config.thoroughfare); //nvr的抓图，需要传通道号，这个通道号是从插件的回调拿
                }
            }
        }

    });
    $("#videoimg").click(function() {
        var picts = document.getElementById("videoimg"); //这里可以抽出来写的，后面需优化20231227
        if (picts.getAttribute("src", 2) == "img/preview/videoselect.png") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/video.png");
                    $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
                    StopRecord(); // 停止录像
                } else {
                    if (config.play_push_list.indexOf(config.chnelNum) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        picts.setAttribute("src", "img/preview/video.png");
                        $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
                        nvrStopRecord(config.chnelNum); // 停止录像
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // 停止录像
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/video.png");
                    $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
                    easyStopRecord();
                } else {
                    if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        picts.setAttribute("src", "img/preview/video.png");
                        $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
                        easyStopRecord(config.thoroughfare); //nvr的录像，需要传通道号，这个通道号是从插件的回调拿
                    }
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/videoselect.png");
                    $("#videoimg").attr("title", $.i18n.prop('i18n-stoprecording'));
                    StartRecord(); // 开始录像
                } else {
                    if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        picts.setAttribute("src", "img/preview/videoselect.png");
                        $("#videoimg").attr("title", $.i18n.prop('i18n-stoprecording'));
                        nvrStartRecord(config.chnelNum)
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // 开始录像
                if (config.deviceInfo.DeviceName == 'IPC') {
                    picts.setAttribute("src", "img/preview/videoselect.png");
                    $("#videoimg").attr("title", $.i18n.prop('i18n-stoprecording'));
                    easyStartRecord();
                } else {
                    if (config.play_push_list.indexOf(config.thoroughfare) == -1) { //表示没有开预览
                        $.optionBootoast($.i18n.prop("i18n-yl-tipsshow"), 'danger')
                    } else {
                        picts.setAttribute("src", "img/preview/videoselect.png");
                        $("#videoimg").attr("title", $.i18n.prop('i18n-stoprecording'));
                        easyStartRecord(config.thoroughfare);
                    }
                }

            }

        }
    });
    $("#fullscreen").click(function() {
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            if (config.deviceInfo.DeviceName == 'IPC') {
                FullScreen(); // 全屏
            } else {
                FullScreenr()
            }
        } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            easyFullScreen();
        }
    });
    $("#play").click(function() {
        $("#play").toggleClass("activeimg");
    });
    $("#playchancel").click(function() {
        $("#playchancel").addClass("activeimg");
        $("#stopchancel").removeClass("activeimg");
        for (var a = 1; a <= config.deviceInfo.VideoInputChannels; a++) {
            var classname = 'nvrchacel' + a;
            document.getElementById("" + classname).querySelector("img").src = "img/preview/nvrplay.png";
            config.play_push_list.push(a - 1); //开启所有就添加所有
        }
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            openAllscrn(streamType - 0)
        } else {
            preHiddenDisplaywindowNVR(false, streamType);
        }

        thoroughfareArray = [];
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            thoroughfareArray.push(true);
        }
    });
    $("#stopchancel").click(function() {
        $("#stopchancel").addClass("activeimg");
        $("#playchancel").removeClass("activeimg");
        for (var a = 1; a <= config.deviceInfo.VideoInputChannels; a++) {
            var classname = 'nvrchacel' + a;
            document.getElementById("" + classname).querySelector("img").src = "img/preview/nvrchcel.png";
        }
        config.play_push_list = []; //关闭所有就清除所有
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            clooseAllscrn();
        } else {
            preHiddenDisplaywindowNVR(true, streamType);
        }
        thoroughfareArray = [];
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            thoroughfareArray.push(false);
        }
    });
    $("#pictureScale").click(function() {
        $("#dropdown").toggle();
        $("#dropright").toggle();
        if (document.getElementById("screendropright").style.display == "" || document.getElementById("screendropright").style.display == "inline") { //防止分频没有选择就去切其他的导致图标展示异常
            $("#screendropdown").toggle();
            $("#screendropright").toggle();
        }
        if (document.getElementById("codestreamdropright").style.display == "" || document.getElementById("codestreamdropright").style.display == "inline") { //防止码流没有选择就去切其他的导致图标展示异常
            $("#codestreamdropdown").toggle();
            $("#codestreamdropright").toggle();
        }
    });

    $("#multiscreen").click(function() {
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (document.getElementById("dropright").style.display == "" || document.getElementById("dropright").style.display == "inline") { //防止自定义没有选择就去切其他的导致图标展示异常
            $("#dropdown").toggle();
            $("#dropright").toggle();
        }
        if (document.getElementById("codestreamdropright").style.display == "" || document.getElementById("codestreamdropright").style.display == "inline") { //防止码流没有选择就去切其他的导致图标展示异常
            $("#codestreamdropdown").toggle();
            $("#codestreamdropright").toggle();
        }
    });

    $("#codestream").click(function() {
        $("#codestreamdropdown").toggle();
        $("#codestreamdropright").toggle();
        if (document.getElementById("dropright").style.display == "" || document.getElementById("dropright").style.display == "inline") { //防止自定义没有选择就去切其他的导致图标展示异常
            $("#dropdown").toggle();
            $("#dropright").toggle();
        }
        if (document.getElementById("screendropright").style.display == "" || document.getElementById("screendropright").style.display == "inline") { //防止分屏没有选择就去切其他的导致图标展示异常
            $("#screendropdown").toggle();
            $("#screendropright").toggle();
        }

    });

    $("#playstyle").click(function() {
        $("#playstyledropdown").toggle();
        $("#playstyledropright").toggle();
    });

    /**
     * 自适应
     */
    $("#selfadaptation").click(function() {
        config.original = false;
        $('#pictureScale span').text(document.getElementById("selfadaptation").innerText);
        document.getElementById('4proportion3').classList.remove('active');
        document.getElementById('16proportion9').classList.remove('active');
        document.getElementById('originalScale').classList.remove('active');
        $("#dropdown").toggle();
        $("#dropright").toggle();
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            nvrOriginalScale(config.thoroughfare, false);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName == "IPC") {
            AspectRatioControl(false);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName !== "IPC") {
            AspectRatioControl(0, config.chnelNum); //原始比例
        }
        screenMode(1, 1)
    });

    $("#originalScale").click(function() {
        $('#pictureScale span').text(document.getElementById("originalScale").innerText);
        document.getElementById('selfadaptation').classList.remove('active');
        $("#dropdown").toggle();
        $("#dropright").toggle();
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            nvrOriginalScale(config.thoroughfare, true);
            config.bine_push_list.push(config.thoroughfare); //每次切换原始比例就增加一个
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName == "IPC") {
            AspectRatioControl(true); //原始比例
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName !== "IPC") {
            AspectRatioControl(1, config.chnelNum); //原始比例
        } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
            var canvas = document.getElementById('playCanvas');
            var containerObj = document.getElementById('playparent');
            var widthFirst = canvas.width > canvas.height;
            var orgobj = useAdaptImage(canvas.width, canvas.height, containerObj.offsetWidth, containerObj.offsetHeight, widthFirst, true);
            $("#playCanvas").height(orgobj.height);
            $("#playCanvas").width(orgobj.width);
            // canvas.style.width=orgobj.width;
            // canvas.style.height=orgobj.height;
        } else { //mjpej或者是webplay
            config.original = true;
        }
    });



    /**
     * 4:3
     */
    $("#4proportion3").click(function() {
        config.original = false;
        $('#pictureScale span').text(document.getElementById("4proportion3").innerText);
        document.getElementById('selfadaptation').classList.remove('active');
        document.getElementById('16proportion9').classList.remove('active');
        $("#dropdown").toggle();
        $("#dropright").toggle();
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            nvrOriginalScale(config.thoroughfare, false);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName == "IPC") {
            AspectRatioControl(false);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName !== "IPC") {
            AspectRatioControl(0, config.chnelNum); //原始比例
        }
        screenMode(4, 3)
    });

    /**
     * 16:9
     */
    $("#16proportion9").click(function() {
        config.original = false;
        $('#pictureScale span').text(document.getElementById("16proportion9").innerText);
        document.getElementById('selfadaptation').classList.remove('active');
        document.getElementById('4proportion3').classList.remove('active');
        $("#dropdown").toggle();
        $("#dropright").toggle();
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            nvrOriginalScale(config.thoroughfare, false);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName == "IPC") {
            AspectRatioControl(false);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX" && config.deviceInfo.DeviceName !== "IPC") {
            AspectRatioControl(0, config.chnelNum); //原始比例
        }
        screenMode(16, 9)
    });
    /**
     * 切换主码流
     */
    $("#miancodestream").click(function() {
        if (config.deviceInfo.DeviceName == "NVR") {
            thoroughfareArray[config.thoroughfare - 0] = true;
            // 切换住码流去检测是否包含没有开流的
            if (config.play_push_list.indexOf(config.thoroughfare - 0) == -1) {
                // 此时表示此通道没有开流那么就去改变图标
                document.getElementById("nvrchacel" + (config.thoroughfare - 0 + 1)).querySelector("img").src = "img/preview/nvrplay.png"
            }
        }
        streamType = 1;
        $('#codestream span').text(document.getElementById("miancodestream").innerText);
        $("#codestreamdropdown").toggle();
        $("#codestreamdropright").toggle();
        var picts = document.getElementById("soundopen");
        var pictsvideo = document.getElementById("videoimg");
        var pictsdj = document.getElementById("intercom");
        if (picts.getAttribute("src", 2) == "img/preview/soundopen.png") {
            $("#soundopen").attr("title", $.i18n.prop('i18n-Openintercom'));
            picts.setAttribute("src", "img/preview/soundclose.png");
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    StopAudio(1); // 停止音频
                } else {
                    AudioContrl(-1, 0)
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    stopPreaudio();
                } else {
                    stopPreaudio(config.thoroughfare);
                }
            }
        }
        if (pictsvideo.getAttribute("src", 2) == "img/preview/videoselect.png") {
            pictsvideo.setAttribute("src", "img/preview/video.png");
            $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    StopRecord(); // 停止录像
                } else {
                    nvrStopRecord(config.chnelNum);
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    easyStopRecord();
                } else {
                    easyStopRecord(config.thoroughfare);
                }
            }
        }
        if (pictsdj.getAttribute("src", 2) == "img/preview/intercomselect.png") {
            pictsdj.setAttribute("src", "img/preview/intercom.png");
            $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    Stoptalkback();
                } else {
                    StopVoiceStream();
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    Closeintercom();
                } else {
                    Closeintercom(config.thoroughfare);
                }
            }

        }
        if (sessionStorage.getItem("stream") == "miancodestream") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    ldspecialvideos("1"); // 打开主码流视频
                } else {
                    StopVideo(config.chnelNum);
                    PlayVideo(config.chnelNum, 1);
                    ChannelShowText(config.chnelNum, "CAM" + (config.chnelNum - 0 + 1));
                    if (config.play_push_list.indexOf(config.chnelNum) == -1) {
                        config.play_push_list.push(config.chnelNum);
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // easyldspecialvideos();
                othertomain(1, config.thoroughfare);
                if (config.play_push_list.indexOf(config.thoroughfare) == -1) {
                    config.play_push_list.push(config.thoroughfare);
                }
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                // self.player.stop("main");
                // self.player = new Player("main");
            }

        } else if (sessionStorage.getItem("stream") == "codestream1" || sessionStorage.getItem("stream") == "codestream2") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    UnLoadVideo(); // 关闭视频
                    ldspecialvideos("1"); // 打开主码流视频
                } else {
                    StopVideo(config.chnelNum);
                    PlayVideo(config.chnelNum, 1);
                    ChannelShowText(config.chnelNum, "CAM" + (config.chnelNum - 0 + 1));
                    if (config.play_push_list.indexOf(config.chnelNum) == -1) {
                        config.play_push_list.push(config.chnelNum);
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // 切换主码流
                othertomain(1, config.thoroughfare);
                if (config.play_push_list.indexOf(config.thoroughfare) == -1) {
                    config.play_push_list.push(config.thoroughfare);
                }
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                if (sessionStorage.getItem("stream") == "codestream1") {
                    self.player.stop("sub1");
                    $('<canvas id="playCanvas" style="position:relative;width: 100%;height: 100%"></canvas>').appendTo(".play")
                    self.player = new Player("main");
                } else {
                    self.player.stop("sub2");
                    self.player = new Player("main");
                }

            }
        }
        sessionStorage.setItem('stream', "miancodestream");
    });

    /**
     * 切换辅码流一
     */
    $("#codestream1").click(function() {
        if (config.deviceInfo.DeviceName == "NVR") {
            thoroughfareArray[config.thoroughfare - 0] = true;
            // 切换住码流去检测是否包含没有开流的
            if (config.play_push_list.indexOf(config.thoroughfare - 0) == -1) {
                // 此时表示此通道没有开流那么就去改变图标
                document.getElementById("nvrchacel" + (config.thoroughfare - 0 + 1)).querySelector("img").src = "img/preview/nvrplay.png"
            }
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            streamType = 2;
        } else {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                streamType = 4;
            } else {
                streamType = 2;
            }
        }
        $('#codestream span').text(document.getElementById("codestream1").innerText);
        $("#codestreamdropdown").toggle();
        $("#codestreamdropright").toggle();
        var picts = document.getElementById("soundopen");
        var pictsvideo = document.getElementById("videoimg");
        var pictsdj = document.getElementById("intercom");
        if (picts.getAttribute("src", 2) == "img/preview/soundopen.png") {
            $("#soundopen").attr("title", $.i18n.prop('i18n-soundopen'));
            picts.setAttribute("src", "img/preview/soundclose.png");
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    StopAudio(1); // 停止音频
                } else {
                    AudioContrl(-1, 0)
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    stopPreaudio();
                } else {
                    stopPreaudio(config.thoroughfare);
                }
            }
        }
        if (pictsvideo.getAttribute("src", 2) == "img/preview/videoselect.png") {
            pictsvideo.setAttribute("src", "img/preview/video.png");
            $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    StopRecord(); // 停止录像
                } else {
                    nvrStopRecord(config.chnelNum);
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    easyStopRecord();
                } else {
                    easyStopRecord(config.thoroughfare);
                }
            }
        }
        if (pictsdj.getAttribute("src", 2) == "img/preview/intercomselect.png") {
            pictsdj.setAttribute("src", "img/preview/intercom.png");
            $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    Stoptalkback();
                } else {
                    StopVoiceStream();
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    Closeintercom();
                } else {
                    Closeintercom(config.thoroughfare);
                }
            }

        }
        if (sessionStorage.getItem("stream") == "miancodestream" || sessionStorage.getItem("stream") == "codestream2") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    UnLoadVideo(); // 关闭视频
                    ldspecialvideos("4"); // 打开子码流视频
                } else {
                    StopVideo(config.chnelNum);
                    PlayVideo(config.chnelNum, 4);
                    ChannelShowText(config.chnelNum, "CAM" + (config.chnelNum - 0 + 1));
                    if (config.play_push_list.indexOf(config.chnelNum) == -1) {
                        config.play_push_list.push(config.chnelNum);
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                // 切换子码流
                othertomain(2, config.thoroughfare);
                if (config.play_push_list.indexOf(config.thoroughfare) == -1) {
                    config.play_push_list.push(config.thoroughfare);
                }

            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                if (sessionStorage.getItem("stream") == "codestream2") {
                    self.player.stop("sub2");
                    self.player = new Player("sub1");
                } else {
                    self.player.stop("main");
                    $('<canvas id="playCanvas" style="position:relative;width: 100%;height: 100%"></canvas>').appendTo(".play")
                    self.player = new Player("sub1");
                }

            }
        } else if (sessionStorage.getItem("stream") == "codestream1") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    ldspecialvideos("4"); // 打开子码流视频
                } else {
                    StopVideo(config.chnelNum);
                    PlayVideo(config.chnelNum, 4);
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                //关闭所以视频
                // easyldspecialvideos();
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                // self.player.stop("sub1");
                // self.player = new Player("sub1");
            }

        }
        sessionStorage.setItem('stream', "codestream1");
    });

    /**
     * 切换辅码流二
     */
    $("#codestream2").click(function() {
        $('#codestream span').text(document.getElementById("codestream2").innerText);
        $("#codestreamdropdown").toggle();
        $("#codestreamdropright").toggle();
        var picts = document.getElementById("soundopen");
        var pictsvideo = document.getElementById("videoimg");
        var pictsdj = document.getElementById("intercom");
        if (picts.getAttribute("src", 2) == "img/preview/soundopen.png") {
            $("#soundopen").attr("title", $.i18n.prop('i18n-soundopen'));
            picts.setAttribute("src", "img/preview/soundclose.png");
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                StopAudio(1); // 停止音频
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                stopPreaudio();
            }
        }
        if (pictsvideo.getAttribute("src", 2) == "img/preview/videoselect.png") {
            pictsvideo.setAttribute("src", "img/preview/video.png");
            $("#videoimg").attr("title", $.i18n.prop('i18n-Startrecording'));
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                StopRecord(); // 停止录像
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                easyStopRecord();
            }
        }
        if (pictsdj.getAttribute("src", 2) == "img/preview/intercomselect.png") {
            pictsdj.setAttribute("src", "img/preview/intercom.png");
            $("#intercom").attr("title", $.i18n.prop('i18n-Openintercom'));
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                Stoptalkback();
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                Closeintercom();
            }

        }
        if (sessionStorage.getItem("stream") == "miancodestream" || sessionStorage.getItem("stream") == "codestream1") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                UnLoadVideo(); // 关闭视频
                ldspecialvideos("5"); // 打开第三码流视频
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                othertomain(3);
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                if (sessionStorage.getItem("stream") == "miancodestream") {
                    self.player.stop("main");
                    self.player = new Player("sub2");
                } else {
                    self.player.stop("sub1");
                    self.player = new Player("sub2");
                }

            }
        } else if (sessionStorage.getItem("stream") == "codestream2") {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                ldspecialvideos("5"); // 打开第三码流视频
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                //关闭所以视频
                // easyldspecialvideos();
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                self.player = new Player("sub2");
            }

        }
        sessionStorage.setItem('stream', "codestream2");
    });

    /**
     * 切换WebPlayer
     */
    $("#WebPlayer").click(function() {
        if (sessionStorage.getItem('file') == null || sessionStorage.getItem('file') == "null") {
            $.optionBootoast($.i18n.prop("i18n-Connectiontimeoutfw"), "danger");
            downloadwasm();
            return;
        }
        if (localStorage.getItem("reawaken") != "9999") {
            $("#selfadaptation").click();
        }
        $('#playstyle span').text(document.getElementById("WebPlayer").innerText);
        $("#playstyledropdown").toggle();
        $("#playstyledropright").toggle();
        $("#codestreamcustomize").show();
        $("#playcz").hide();
        $("#playCanvas").show();
        $("#drawCanvas").show()
        $("#axdiv").hide();
        // $("#codestream1").click();
        if (sessionStorage.getItem("playstyle") == "EasyVideo") { //上一次的播放方案是EasyVideo
            if (!document.getElementById("playCanvas")) {
                $('<canvas id="playCanvas" style="position:relative;width: 100%;height: 100%"></canvas>').appendTo(".play")
            }
            if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                if (localStorage.getItem("reawaken") != "9999") {
                    closeeasyvideo()
                }
            }

        } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
            var containerObj = document.getElementById('axdiv');
            containerObj.style.height = '100%';
            if (!document.getElementById("playCanvas")) {
                $('<canvas id="playCanvas" style="position:relative;width: 100%;height: 100%"></canvas>').appendTo(".play")
            }
            clearInterval(config.gs_interval);
            $("#axdiv").empty();
        }
        sessionStorage.setItem("playstyle", "WebPlayer");
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false);
        if ($("#3D").is(":visible")) {
            $("#switch3D").bootstrapSwitch('state', false)
        }
    });

    /**
     * 切换EasyVideo
     */
    $("#EasyVideo").click(function() {
        $("#selfadaptation").click();
        $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
        $("#playstyledropdown").toggle();
        $("#playstyledropright").toggle();
        $("#codestreamcustomize").show();
        $("#playcz").show();
        $("#playCanvas").hide();
        $("#axdiv").show();
        $("#drawCanvas").hide()
        if (sessionStorage.getItem("playstyle") == "WebPlayer") { //上一次的播放方案是WebPlayer
            closeWebPlayer();
        } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
            var containerObj = document.getElementById('axdiv');
            containerObj.style.height = '100%';
            $("#axdiv").empty();
            clearInterval(config.gs_interval)
        }
        if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
            sessionStorage.setItem("playstyle", "EasyVideo");
            if (localStorage.getItem("reawaken") == "9999") {
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "cerate", false)
            } else {
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false);
            }
            if ($("#3D").is(":visible")) {
                $("#switch3D").bootstrapSwitch('state', false)
            }
        } else {
            $("#axdiv").hide();
            $("#downlodeasyvideo").show();
        }
        // $("#miancodestream").click();
    });

    /**
     * 切换MJPEG
     */
    $("#MJPEG").click(function() {
        if (localStorage.getItem("reawaken") != "9999") {
            $("#selfadaptation").click();
        }
        $('#playstyle span').text(document.getElementById("MJPEG").innerText);
        $("#playstyledropdown").toggle();
        $("#playstyledropright").toggle();
        $("#codestreamcustomize").hide();
        $("#playcz").hide();
        $("#playCanvas").hide();
        $("#axdiv").show();
        $("#drawCanvas").show()
        if (sessionStorage.getItem("playstyle") == "WebPlayer") {
            closeWebPlayer();
        } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                if (localStorage.getItem("reawaken") != "9999") {
                    closeeasyvideo()
                }
            }
        }
        sessionStorage.setItem("playstyle", "MJPEG");
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", inember + 1);
        if ($("#3D").is(":visible")) {
            $("#switch3D").bootstrapSwitch('state', false)
        }
    });


    /**
     * 切换ActiveX
     */
    $("#ActiveX").click(function() {
        $("#selfadaptation").click();
        $('#playstyle span').text(document.getElementById("ActiveX").innerText);
        $("#playstyledropdown").toggle();
        $("#playstyledropright").toggle();
        $("#codestreamcustomize").show();
        $("#playcz").show();
        $("#playCanvas").hide();
        $("#axdiv").show();
        if (sessionStorage.getItem("playstyle") == "MJPEG") {
            $("#axdiv").empty();
            clearInterval(config.gs_interval)
        }
        sessionStorage.setItem("playstyle", "ActiveX");
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false);
    });


    /**
     * 切换单屏幕
     */
    $("#singscreenlable").click(function() {
        numberOfScreens = 1;
        document.getElementById("defaultscreen").src = document.getElementById("singscreen").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(1)
        } else {
            nvrSplitScreen(1);

        }
    });

    /**
     * 切换4屏幕
     */
    $("#screen4lable").click(function() {
        numberOfScreens = 2;
        document.getElementById("defaultscreen").src = document.getElementById("screen4").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(2)
        } else {
            nvrSplitScreen(2);
        }
    });

    /**
     * 切换6屏幕
     */
    $("#screen6lable").click(function() {
        document.getElementById("defaultscreen").src = document.getElementById("screen6").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(8)
        } else {
            nvrSplitScreen(15);
        }

    });

    /**
     * 切换8屏幕
     */
    $("#screen8lable").click(function() {
        document.getElementById("defaultscreen").src = document.getElementById("screen8").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(7)
        } else {
            nvrSplitScreen(16);
        }
    });

    /**
     * 切换9屏幕
     */
    $("#screen9lable").click(function() {
        numberOfScreens = 3;
        document.getElementById("defaultscreen").src = document.getElementById("screen9").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(3)
        } else {
            nvrSplitScreen(3);
        }
    });

    /**
     * 切换10屏幕
     */
    $("#screen10lable").click(function() {
        document.getElementById("defaultscreen").src = document.getElementById("screen10").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(9)
        } else {
            nvrSplitScreen(17);
        }
    });

    /**
     * 切换16屏幕
     */
    $("#screen16lable").click(function() {
        numberOfScreens = 4;
        document.getElementById("defaultscreen").src = document.getElementById("screen16").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(4)
        } else {
            nvrSplitScreen(4);
        }
    });

    /**
     * 切换36屏幕
     */
    $("#screen36lable").click(function() {
        numberOfScreens = 6;
        document.getElementById("defaultscreen").src = document.getElementById("screen36").src;
        $("#screendropdown").toggle();
        $("#screendropright").toggle();
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            ChangeLayout(6)
        } else {
            nvrSplitScreen(6);
        }
    });

    /**
     * easyvideo下载插件
     */

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

    for (var i = 1; i <= 256; i++) {
        var linid = "line-normal" + i;
        var linidtitle = $.i18n.prop('i18n-Presetpoint') + i;
        var preset = "presetHandle" + i;
        var setid = "set" + i;
        var backid = "back" + i;
        var removeid = "remove" + i;
        var set = $.i18n.prop('i18n-set');
        var back = $.i18n.prop('i18n-back');
        var remove = $.i18n.prop('i18n-delete');
        $("<div class='line-normal' id='" + linid + "'><span class='preset-name' title='" + linidtitle + "'>" + linidtitle + "</span><span class='presetHandle' id='" + preset + "' style='display: none'> <img src='img/holder/set.png' id='" + setid + "' title='" + set + "'> <img src='img/holder/goback.png' id='" + backid + "' title='" + back + "'> <img src='img/holder/del.png' id='" + removeid + "' title='" + remove + "'></span></div>").appendTo("#ptzPresetPointbody")
    }


    $(".line-normal").on("mouseover mouseout", function(evt) {
        evt.stopPropagation(); //函数里加入禁止冒泡
        evt.preventDefault();
        var ev = evt || window.event;
        var target = ev.currentTarget || ev.srcElement;
        var preset = $("#" + target.id).find("span").eq(1).prevObject[1].id;
        var idindex = preset.match(/\d+/g).join();
        var setid = "set" + idindex;
        var backid = "back" + idindex;
        var removeid = "remove" + idindex;
        if (ev.type == "mouseover") {
            if (!$("#" + target.id).hasClass("line-select")) {
                $("#" + target.id).addClass("line-select");
                $("#" + preset).toggle();
                if (document.getElementById(setid).getAttribute("src", 2) == "img/holder/setselect.png") {
                    document.getElementById(setid).setAttribute("src", "img/holder/set.png");
                }
                if (document.getElementById(backid).getAttribute("src", 2) == "img/holder/gobackselect.png") {
                    document.getElementById(backid).setAttribute("src", "img/holder/goback.png");
                }
                if (document.getElementById(removeid).getAttribute("src", 2) == "img/holder/delselect.png") {
                    document.getElementById(removeid).setAttribute("src", "img/holder/del.png");
                }
            }
        } else {
            $("#" + target.id).removeClass("line-select");
            $("#" + preset).toggle();
        }
    });


    $(".presetHandle img").on("click", function(evt) {
        if ("admin" == config.user || "super_admin" == config.user) {
            console.log('evt', evt);
            evt.stopPropagation(); //函数里加入禁止冒泡
            evt.preventDefault();
            var ev = evt || window.event;
            var target = ev.currentTarget || ev.srcElement;
            var index = parseInt(target.id.match(/\d+/g).join()) - 1;
            var id = target.id.replace(/[^a-z]/gi, '');
            if (id == "set") {
                if (document.getElementById(target.id).getAttribute("src", 2) == "img/holder/set.png") {
                    document.getElementById(target.id).setAttribute("src", "img/holder/setselect.png");
                }
                var cyXmlstart = "Param1=" + index;
                if (config.deviceInfo.DeviceName == "IPC") {
                    var cyURL = config.baseUrl + "/PTZ/1/Presets/Set";
                } else {
                    var cyURL = config.baseUrl + "/PTZ/" + (config.thoroughfare - 0 + 1) + "/Presets/Set";
                }
                $.ajax({
                    type: "PUT",
                    url: cyURL,
                    processData: false,
                    data: cyXmlstart,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("If-Modified-Since", "0");
                    },
                    complete: function(xhr, textStatus) {
                        var xmlDoc = xhr.responseXML;
                        var state = $(xmlDoc).find('statusCode').eq(0).text();
                        if ("0" == state) {
                            bootoast({
                                message: $.i18n.prop('i18n-Presetpoint-success'),
                                type: 'success',
                                position: 'bottom-center',
                                icon: undefined,
                                timeout: true,
                                animationDuration: 3000,
                                dismissable: true
                            })
                        } else {
                            bootoast({
                                message: $.i18n.prop('i18n-Presetpoint-fail'),
                                type: 'danger',
                                position: 'bottom-center',
                                icon: undefined,
                                timeout: true,
                                animationDuration: 3000,
                                dismissable: true
                            })

                        }
                    }
                });
            } else if (id == "back") {
                if (document.getElementById(target.id).getAttribute("src", 2) == "img/holder/goback.png") {
                    document.getElementById(target.id).setAttribute("src", "img/holder/gobackselect.png");
                }
                var cyXmlstart = "Param1=" + index;
                if (config.deviceInfo.DeviceName == "IPC") {
                    var cyURL = config.baseUrl + "/PTZ/1/Presets/Goto";
                } else {
                    var cyURL = config.baseUrl + "/PTZ/" + (config.thoroughfare - 0 + 1) + "/Presets/Goto";
                }
                $.ajax({
                    type: "PUT",
                    url: cyURL,
                    processData: false,
                    data: cyXmlstart,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("If-Modified-Since", "0");
                    },
                    complete: function(xhr, textStatus) {
                        var xmlDoc = xhr.responseXML;
                        var state = $(xmlDoc).find('statusCode').eq(0).text();
                        if ("0" == state) {
                            bootoast({
                                message: $.i18n.prop('i18n-Presetpoint-upsuccess'),
                                type: 'success',
                                position: 'bottom-center',
                                icon: undefined,
                                timeout: true,
                                animationDuration: 3000,
                                dismissable: true
                            })
                        } else {
                            bootoast({
                                message: $.i18n.prop('i18n-Presetpoint-upfail'),
                                type: 'danger',
                                position: 'bottom-center',
                                icon: undefined,
                                timeout: true,
                                animationDuration: 3000,
                                dismissable: true
                            })

                        }

                    }
                });
            } else if (id == "remove") {
                if (document.getElementById(target.id).getAttribute("src", 2) == "img/holder/del.png") {
                    document.getElementById(target.id).setAttribute("src", "img/holder/delselect.png");
                }
                var cyXmlstart = "Param1=" + index;
                if (config.deviceInfo.DeviceName == "IPC") {
                    var cyURL = config.baseUrl + "/PTZ/1/Presets/Remove";
                } else {
                    var cyURL = config.baseUrl + "/PTZ/" + (config.thoroughfare - 0 + 1) + "/Presets/Remove";
                }
                $.ajax({
                    type: "PUT",
                    url: cyURL,
                    processData: false,
                    data: cyXmlstart,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("If-Modified-Since", "0");
                    },
                    complete: function(xhr, textStatus) {
                        var xmlDoc = xhr.responseXML;
                        var state = $(xmlDoc).find('statusCode').eq(0).text();
                        if ("0" == state) {
                            $.optionBootoast($.i18n.prop('i18n-Presetpoint-delsuccess'), "success")
                        } else {
                            $.optionBootoast($.i18n.prop('i18n-Presetpoint-delfail'), "danger")
                        }
                    }
                });
            }
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }


    });
    $("#previewyt").on("mousedown mouseup", ".ptz-control-direction", function(evt) {
        if ("admin" == config.user || "super_admin" == config.user) {
            evt.stopPropagation(); //函数里加入禁止冒泡
            evt.preventDefault();
            var ev = evt || window.event;
            var target = ev.target || ev.srcElement;
            var stepValue = $("#ptzslidervalue").text();
            if (ev.type == "mousedown") {
                PTZControl(1, target.id, stepValue);
            } else if (ev.type == "mouseup") {
                PTZControl(0, target.id, stepValue);
            }
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });
    // user1用户初始化触发没有权限操作提示
    var isInitializing = true; // 标志位，表示是否是在初始化
    $('#ptzslider').jRange({
        from: 1,
        to: 10,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 180,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            if ("admin" == config.user || "super_admin" == config.user) {
                $("#ptzslidervalue").text($("#ptzslider").val());
                setPTZCfg();
            } else {
                if (isInitializing) {
                    isInitializing = false;
                    return;
                }
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
            }
        },
        onSetPosition: function() {
            // if ($("#ptzslider").val() != "undefined" && $("#ptzslider").val() != "0" && $("#ptzslider").val() != 0) {
            //     $("#ptzslidervalue").text($("#ptzslider").val());
            //     setPTZCfg();
            // }

        },
        onMouseDown: function() {},
        onMouseUp: function() {

        }
    });
    getPTZPower();
    getPTZCfg();


    function setPTZPeople(stateparam) {
        var cyURL;
        if (config.deviceInfo.DeviceName == "IPC") {
             cyURL = config.baseUrl + "/ExternalPTZ/1/TrackConfig";
        } else {
             cyURL = config.baseUrl + "/ExternalPTZ/" + (config.thoroughfare - 0 + 1) + "/TrackConfig";
        }
        var cyXml = "<?xml version='1.0' encoding='UTF-8' ?>" +
            "<ExternalPTZTrackCfg>" +
            "<AFBoardPTZTrackEnable>" + stateparam + "</AFBoardPTZTrackEnable>" +
            "</ExternalPTZTrackCfg>";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                var xmlDoc = xhr.responseXML;
                var state = $(xmlDoc).find('statusCode').eq(0).text();
                if ("0" == state) {
                    $.optionBootoast($.i18n.prop('i18n-savesuccess'), "success")
                } else {
                    $.optionBootoast($.i18n.prop('i18n-savefail'), "danger")
                }
            }
        });
    }

    $('#switchPeople').bootstrapSwitch({
        state: false, //开关状态
        size: "small", //尺寸 mini small large
        animate: true, //开启动画效果
        disabled: false, //禁用
        readonly: false,
        indeterminate: false,
        inverse: false, //方向反转
        radioAllOff: false,
        onColor: 'primary', //开启颜色 primary、info，primary，warning，warning，default
        offColor: 'default', //关闭颜色 primary、info，primary，warning，warning，default
        onText: 'ON', //开启时展示的文本
        offText: 'OFF', //关闭时展示的文本
        labelText: '&nbsp', //空白区域的文本
        handleWidth: 'auto',
        labelWidth: 'auto',
        baseClass: 'bootstrap-switch',
        wrapperClass: 'wrapper',
        onInit: function onInit() {},
        onSwitchChange: function onSwitchChange(event, state) {
            if ("admin" == config.user || "super_admin" == config.user) {
                if (state == true) {
                    //人形跟踪开启
                    setPTZPeople(true)
                } else {
                    //人形跟踪关闭
                    setPTZPeople(false)
                }
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
            }

        }
    });
    //3D定位
    $('#switch3D').bootstrapSwitch({
        state: false, //开关状态
        size: "small", //尺寸 mini small large
        animate: true, //开启动画效果
        disabled: false, //禁用
        readonly: false,
        indeterminate: false,
        inverse: false, //方向反转
        radioAllOff: false,
        onColor: 'primary', //开启颜色 primary、info，primary，warning，warning，default
        offColor: 'default', //关闭颜色 primary、info，primary，warning，warning，default
        onText: 'ON', //开启时展示的文本
        offText: 'OFF', //关闭时展示的文本
        labelText: '&nbsp', //空白区域的文本
        handleWidth: 'auto',
        labelWidth: 'auto',
        baseClass: 'bootstrap-switch',
        wrapperClass: 'wrapper',
        onInit: function onInit() {},
        onSwitchChange: function onSwitchChange(event, state) {
            if ("admin" == config.user || "super_admin" == config.user) {
                eable3d = state == true;
                if(eable3d){
                    $("#drawCanvas").show();
                    if((sessionStorage.getItem("playstyle") == "WebPlayer"||sessionStorage.getItem("playstyle") == "MJPEG")){
                        // 初始化
                        canvasRecorder = new CanvasDrawRecorder('drawCanvas');
                        var clickTimer = null;
                        // 简化的防抖处理
                        var debounceHandler = function(record) {
                            // 清除之前的定时器
                            if (clickTimer) {
                                clearTimeout(clickTimer);
                            }

                            // 设置新的定时器，1秒后执行
                            clickTimer = setTimeout(function() {
                                console.log('操作类型: ' + record.type);

                                if (record.type === 0) {
                                    console.log('中心点坐标: (' + record.centerPoint.x + ', ' + record.centerPoint.y + ')');
                                } else {
                                    console.log('中心点坐标: (' + record.centerPoint.x + ', ' + record.centerPoint.y + ')');
                                    console.log('矩形宽度: ' + record.width + ', 高度: ' + record.height);
                                }
                                set3dPos(record);
                            }, 1000);
                        };

                        // 监听记录创建事件（带防抖）
                        canvasRecorder.canvas.addEventListener('canvasRecordCreated', function(e) {
                            var record = e.detail;
                            debounceHandler(record);
                        });
                    }
                    if(sessionStorage.getItem("playstyle") == "EasyVideo"){
                        pos3d(eable3d)
                    }
                }else{
                    $("#drawCanvas").hide();
                    if((sessionStorage.getItem("playstyle") == "WebPlayer"||sessionStorage.getItem("playstyle") == "MJPEG")) {
                        canvasRecorder=null;
                    }
                        if(sessionStorage.getItem("playstyle") == "EasyVideo"){
                        pos3d(eable3d)
                    }
                }
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
            }

        }
    });

    $('#switchlight').bootstrapSwitch({
        state: false, //开关状态
        size: "small", //尺寸 mini small large
        animate: true, //开启动画效果
        disabled: false, //禁用
        readonly: false,
        indeterminate: false,
        inverse: false, //方向反转
        radioAllOff: false,
        onColor: 'primary', //开启颜色 primary、info，primary，warning，warning，default
        offColor: 'default', //关闭颜色 primary、info，primary，warning，warning，default
        onText: 'ON', //开启时展示的文本
        offText: 'OFF', //关闭时展示的文本
        labelText: '&nbsp', //空白区域的文本
        handleWidth: 'auto',
        labelWidth: 'auto',
        baseClass: 'bootstrap-switch',
        wrapperClass: 'wrapper',
        onInit: function onInit() {},
        onSwitchChange: function onSwitchChange(event, state) {
            if ("admin" == config.user || "super_admin" == config.user) {
                if (state == true) {
                    //灯光开启
                    var cyXmlstart = "Param1=1";
                    var cyURL = config.baseUrl + "/PTZ/1/Light";
                    $.ajax({
                        type: "PUT",
                        url: cyURL,
                        processData: false,
                        data: cyXmlstart,
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader("If-Modified-Since", "0");
                        },
                        complete: function(xhr, textStatus) {
                            //SaveState(xhr);
                        }
                    });

                } else {
                    //灯光关闭
                    var cyXmlstart = "Param1=0";
                    var cyURL = config.baseUrl + "/PTZ/1/Light";
                    $.ajax({
                        type: "PUT",
                        url: cyURL,
                        processData: false,
                        data: cyXmlstart,
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader("If-Modified-Since", "0");
                        },
                        complete: function(xhr, textStatus) {
                            //SaveState(xhr);
                        }
                    });
                }
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
            }

        }
    });
    $('#switchys').bootstrapSwitch({
        state: false, //开关状态
        size: "small", //尺寸 mini small large
        animate: true, //开启动画效果
        disabled: false, //禁用
        readonly: false,
        indeterminate: false,
        inverse: false, //方向反转
        radioAllOff: false,
        onColor: 'primary', //开启颜色 primary、info，primary，warning，warning，default
        offColor: 'default', //关闭颜色 primary、info，primary，warning，warning，default
        onText: 'ON', //开启时展示的文本
        offText: 'OFF', //关闭时展示的文本
        labelText: '&nbsp', //空白区域的文本
        handleWidth: 'auto',
        labelWidth: 'auto',
        baseClass: 'bootstrap-switch',
        wrapperClass: 'wrapper',
        onInit: function onInit() {},
        onSwitchChange: function onSwitchChange(event, state) {
            if ("admin" == config.user || "super_admin" == config.user) {
                //切换时的回调 state
                if (state == true) {
                    //雨刷开启
                    var cyXmlstart = "Param1=1";
                    var cyURL = config.baseUrl + "/PTZ/1/RainBrush";
                    $.ajax({
                        type: "PUT",
                        url: cyURL,
                        processData: false,
                        data: cyXmlstart,
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader("If-Modified-Since", "0");
                        },
                        complete: function(xhr, textStatus) {
                            //SaveState(xhr);
                        }
                    });
                } else {
                    //雨刷关闭
                    var cyXmlstart = "Param1=0";
                    var cyURL = config.baseUrl + "/PTZ/1/RainBrush";
                    $.ajax({
                        type: "PUT",
                        url: cyURL,
                        processData: false,
                        data: cyXmlstart,
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader("If-Modified-Since", "0");
                        },
                        complete: function(xhr, textStatus) {
                            //SaveState(xhr);
                        }
                    });
                }
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
            }

        }
    });

    if (config.deviceCap[inember].imageMode == "true") {
        $("#imageType").select2({
            minimumResultsForSearch: -1
        });
        $("#imagemody").show();
        if (config.deviceCap[inember].normalMode === "true") {
            icimagestr.push("normal");
            str_ic_imagestr.push($.i18n.prop('i18n-Standardmode'))
        }
        if (config.deviceCap[inember].faceMode === "true") {
            icimagestr.push("facenoexposure");
            str_ic_imagestr.push($.i18n.prop('i18n-facenotmode'))
        }
        if (config.deviceCap[inember].licenseMode === "true") {
            icimagestr.push("licenseplate");
            str_ic_imagestr.push($.i18n.prop('i18n-carnotmode'))
        }

        for (var i = 0; i < icimagestr.length; i++) {
            $("<option value='" + icimagestr[i] + "'>" + str_ic_imagestr[i] + "</option>").appendTo("#imageType");
        }

    } else {
        $("#imagemody").hide();
    }
    if (config.deviceCap[inember].PowerLineFrequency == "true") {
        $("#flashoverresistance").show();
    } else {
        $("#flashoverresistance").hide();
    }

    if (config.deviceCap[inember].wdrClose == "true") {
        for (var i = 0; i < icbwstrd.length; i++) {
            $("<option value='" + icbwstrd[i] + "'>" + str_ic_bwd[i] + "</option>").appendTo("#wideDynamic");
        }
    } else {
        for (var i = 0; i < icbwstr.length; i++) {
            $("<option value='" + icbwstr[i] + "'>" + str_ic_bw[i] + "</option>").appendTo("#wideDynamic");
        }

    }

    $("#imagemody").change(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setIrCutFilter();
        } else {
            bootoast({
                message: $.i18n.prop('i18n-propoe'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        }
    });

    $("#videosave").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            if ("1" == $("#codestreamselect").val()) {
                setMainstream();
            } else if ("2" == $("#codestreamselect").val()) {
                setSubstream()
            } else if ("3" == $("#codestreamselect").val()) {
                setMobilestream()
            }
        } else {
            bootoast({
                message: $.i18n.prop('i18n-propoe'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        }
    });

    //3D,BLC,WDR,Flip更改事件
    $("#wideDynamic,:radio[name=icpowermode],:radio[name=icpowermodes]").change(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setImageBasic();
        } else {
            bootoast({
                message: $.i18n.prop('i18n-propoe'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        }
    });
    if (config.deviceInfo.DeviceName == 'IPC') {
        for (var i = 0; i <= config.deviceCap[inember].StreamCount.length; i++) {
            var s = i + 1;
            $("<option value='" + s + "'>" + str_ic_codestream[i] + "</option>").appendTo("#codestreamselect");
        }
    } else {
        for (var i = 0; i < 2; i++) {
            var s = i + 1;
            $("<option value='" + s + "'>" + str_ic_codestream[i] + "</option>").appendTo("#codestreamselect");
        }
    }
    //码率切换
    $("#bitratecontrol").change(function() {
        changeVCbr();
    });
    $("#bitrate").change(function() {
        changemBitPU();
    });

    $("#codestreamselect").change(function() {
        changecodestream();
    });


    if (config.deviceInfo.DeviceName == 'IPC') {
        if (config.deviceCap[inember].osd2support == "true") { //支持新的osd能力
            if (config.deviceCap[inember].osd2maxcnt == 1) { //cnt为1只能取到osd1,osd2不显示
                $(".isshowosd2").hide();
                osdline1 = config.deviceCap[inember].osdline; //支持osd1 总共支持多少行
                osdline2 = 0; //osd2支持多少行
                osdchar1 = config.deviceCap[inember].osd1linechar; //单行osd1支持的长度
                osdchar2 = 0; //osd2总长度

            } else if (config.deviceCap[inember].osd2maxcnt == 2) { //cnt为2可以取到osd2，显示osd2
                $(".isshowosd2").show();
                osdline1 = config.deviceCap[inember].osdline; //支持osd1 总共支持多少行
                osdline2 = config.deviceCap[inember].osdTwoline; //osd2支持多少行
                osdchar1 = config.deviceCap[inember].osd1linechar; //单行osd1支持的长度
                osdchar2 = config.deviceCap[inember].odTwo; //osd2总长度
            }

        } else { //不支持新的osd能力取到老的逻辑
            $(".isshowosd2").hide();
            osdline1 = config.deviceCap[inember].osdline; //支持osd1 总共支持多少行
            osdline2 = 0; //osd2支持多少行
            osdchar1 = config.deviceCap[inember].osdchar; //单行osd1支持的长度
            osdchar2 = 0; //osd2总长度
        }
    } else { //nvr因为能力问题暂时先默认,后续需要添加额外的nvr对ipcV2接口去适配
        $(".isshowosd2").hide();
        osdline1 = 5;
        osdline2 = 0;
        osdchar1 = 30;
        osdchar2 = 0;
    }

    if (config.deviceCap[inember].osdShowd == "true") {
        $("#osd2displays").show();
    } else {
        $("#osd2displays").hide();
    }

    // 加
    $("#addRow").click(function() {
        if ($('.nName-1').length >= osdline1 - 1) {
            $.optionBootoast($.i18n.prop('i18n-morethen'), "danger");
            return false;
        }
        var lesshtml = '<div class="form-group less"><div class="col-md-12"><input type="text" class="nName-1 form-control"  name="osd1" style="width: 80%;display: inline-block"><input type="button" class="btndel"/></div></div>';
        $("#osd2Id").before(lesshtml);
    });


    // 减
    $('#osdForm').on('click', '.btndel', function(e) {
        $(this).parents('.form-group').remove();
    });

    $("#osdsave").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setOSD();
        } else {
            bootoast({
                message: $.i18n.prop('i18n-propoe'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        }
    });

    $("#dzmore").click(function() {
        $("#top-nav-menu .navbar-nav li#preview").removeClass("active");
        document.getElementById("previewicon").setAttribute("src", "img/icon/yl.png");
        document.getElementById("configurationicon").setAttribute("src", "img/icon/pzcheck.png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            Router.redirect("ipc/pages/events/IntelligentVigilance.html?m=1")
        } else if (config.deviceInfo.DeviceName == "NVR") {
            Router.redirect("nvr/pages/events/IntelligentVigilance.html?m=1")
        } else {
            Router.redirect("hvr/pages/events/IntelligentVigilance.html?m=1")
        }

    });

    $("#yjmore").click(function() {
        $("#top-nav-menu .navbar-nav li#preview").removeClass("active");
        document.getElementById("previewicon").setAttribute("src", "img/icon/yl.png");
        document.getElementById("configurationicon").setAttribute("src", "img/icon/pzcheck.png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            Router.redirect("ipc/pages/events/IntelligentVigilance.html?m=2")
        } else if (config.deviceInfo.DeviceName == "NVR") {
            Router.redirect("nvr/pages/events/IntelligentVigilance.html?m=2")
        } else {
            Router.redirect("hvr/pages/events/IntelligentVigilance.html?m=2")
        }

    });

    $("#lgmore").click(function() {
        $("#top-nav-menu .navbar-nav li#preview").removeClass("active");
        document.getElementById("previewicon").setAttribute("src", "img/icon/yl.png");
        document.getElementById("configurationicon").setAttribute("src", "img/icon/pzcheck.png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            Router.redirect("ipc/pages/events/IntelligentVigilance.html?m=3")
        } else if (config.deviceInfo.DeviceName == "NVR") {
            Router.redirect("nvr/pages/events/IntelligentVigilance.html?m=3")
        } else {
            Router.redirect("hvr/pages/events/IntelligentVigilance.html?m=3")
        }

    });

    $("#klmore").click(function() {
        $("#top-nav-menu .navbar-nav li#preview").removeClass("active");
        document.getElementById("previewicon").setAttribute("src", "img/icon/yl.png");
        document.getElementById("configurationicon").setAttribute("src", "img/icon/pzcheck.png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            Router.redirect("ipc/pages/events/IntelligentVigilance.html?m=4")
        } else if (config.deviceInfo.DeviceName == "NVR") {
            Router.redirect("nvr/pages/events/IntelligentVigilance.html?m=4")
        } else {
            Router.redirect("hvr/pages/events/IntelligentVigilance.html?m=4")
        }

    });

    $("#facezpmore").click(function() {
        $("#top-nav-menu .navbar-nav li#preview").removeClass("active");
        document.getElementById("previewicon").setAttribute("src", "img/icon/yl.png");
        document.getElementById("configurationicon").setAttribute("src", "img/icon/pzcheck.png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            Router.redirect("ipc/pages/events/FaceCapture.html")
        } else if (config.deviceInfo.DeviceName == "NVR") {
            Router.redirect("nvr/pages/events/FaceCapture.html")
        } else {
            Router.redirect("hvr/pages/events/FaceCapture.html")
        }

    });

    // $(".FaceReco").show();
    // $(".FaceSnapshotCfg").hide();

    localStorage.setItem("rule", "0");
    // getMotionSchedule();

    $("#algorithmselect").change(function() {
        if ("FaceRecognition" == $("#algorithmselect").val()) {
            $(".FaceReco").hide(); //没有能力暂时写死
            $(".FaceSnapshotCfg").hide();
            // getMotionSchedule();
        } else {
            $(".FaceSnapshotCfg").show();
            $(".FaceReco").hide();
            getfacetime();
        }
    });


    $("#algorithmsave").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            if ("FaceRecognition" == $("#algorithmselect").val()) {
                setAlgorithmStoreCf("FaceRecognition");
                // setMotionSchedule();
            } else {
                setAlgorithmStoreCf("FaceCapture");
                // setfacetronic();
            }
        } else {
            bootoast({
                message: $.i18n.prop('i18n-propoe'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        }
    });

    $("#facerule").change(function() {
        if ("2" == $("#facerule").val()) {
            $("#facethresholdcode").hide()
        } else {
            $("#facethresholdcode").show()
        }
        localStorage.setItem("rule", $("#facerule").val());
    });

    //算法仓库和智能警戒都不支持
    if ((config.deviceAiCap[inember].isSupportAlgorithmWarehouse == "" || config.deviceAiCap[inember].isSupportAlgorithmWarehouse == "false") && (config.deviceCap[inember].PolygonRegion == "" || config.deviceCap[inember].PolygonRegion == "false")) {
        $("#ck").hide();
        $("#zn").hide();
        $("#previewznli").hide();
    }
    //算法仓库
    if (config.deviceAiCap[inember].isSupportAlgorithmWarehouse == "true") {
        if (config.deviceAiCap[inember].algorithmFaceSnap) {
            $("<option value='FaceCapture'>" + $.i18n.prop('i18n-Facecapture') + "</option>").appendTo("#algorithmselect"); //人脸抓拍
        }
        if (config.deviceAiCap[inember].algorithmFaceReco) {
            $("<option value='FaceRecognition'>" + $.i18n.prop('i18n-Facerecognition') + "</option>").appendTo("#algorithmselect"); //人脸识别
        }
        getAlgorithmStoreCf();
        $("#ck").show()
    } else {
        $("#ck").hide()
    }

    //智能警戒展示
    if (config.deviceCap[inember].isSupportPolygonRegion == "true") {
        $("#zn").show()
    } else {
        $("#zn").hide()
    }
    if (config.deviceAiCap[inember].Electronsupport == "true") {
        $(".electronic").show()
    } else {
        $(".electronic").hide()
    }

    if (config.deviceAiCap[inember].Traversesupport == "true") {
        $(".cross").show()
    } else {
        $(".cross").hide()
    }

    if (config.deviceAiCap[inember].OffDetectsupport == "true") {
        $(".offs").show()
    } else {
        $(".offs").hide()
    }

    if (config.deviceAiCap[inember].PassengerFlowsupport == "true") {
        $(".flow").show()
    } else {
        $(".flow").hide()
    }

    $("#enberdz").on("change", function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setelectronic()
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });

    $("#enberyj").on("change", function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setcrossdetect()
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }

    });

    $("#enberlg").on("change", function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setoffDutyDetec()
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }

    });

    $("#enberkl").on("change", function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            setpassengerFlow()
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });

    $("#collapseBasePaneimage").on("show.bs.collapse", function() {
        $("#imageup").show();
        $("#imagedown").hide();
    });

    $("#collapseBasePaneimage").on("hide.bs.collapse", function() {
        $("#imageup").hide();
        $("#imagedown").show();
    });

    $("#collapseBasePaneosd").on("show.bs.collapse", function() {
        $("#osdup").show();
        $("#osddown").hide();
    });

    $("#collapseBasePaneosd").on("hide.bs.collapse", function() {
        $("#osdup").hide();
        $("#osddown").show();
    });

    $("#collapseBasePanevideo").on("show.bs.collapse", function() {
        $("#videoup").show();
        $("#videodown").hide();
    });

    $("#collapseBasePanevideo").on("hide.bs.collapse", function() {
        $("#videoup").hide();
        $("#videodown").show();
    });

    $("#collapseBasealgorithm").on("show.bs.collapse", function() {
        $("#Basealgorithmup").show();
        $("#Basealgorithmdown").hide();
    });

    $("#collapseBasealgorithm").on("hide.bs.collapse", function() {
        $("#Basealgorithmup").hide();
        $("#Basealgorithmdown").show();
    });


    $("#collapseBasevigilance").on("show.bs.collapse", function() {
        $("#Basevigilanceup").show();
        $("#Basevigilancedown").hide();
    });

    $("#collapseBasevigilance").on("hide.bs.collapse", function() {
        $("#Basevigilanceup").hide();
        $("#Basevigilancedown").show();
    });

    $('#previewTab a').click(function(e) {
        e.preventDefault();
        if ($(this).attr("aria-controls") == "previewcommon") {
            getIrCutFilter();
            getImageBasic();
            $("#codestreamselect").select2("val", "1");
            getCapabilityV2();
            getMainstream();
            getOSD();
            getTimeinfo();
        } else if ($(this).attr("aria-controls") == "previewzn") {
            if (config.isSupportMultiChannel == true) {
                getelectronic();
                getcrossdetect();
            } else {
                getelectronic();
                getcrossdetect();
                getoffDutyDetec();
                getpassengerFlow();

            }
        }
    });
});
// 抓图和录像之后调用针对火狐浏览器会断开socket链接但是playvideo又存在
function huifuPreview() {
    self.playervideo = null;
    $("#playcz").show();
    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", 0, false);
    for (var a = 1; a <= config.deviceInfo.VideoInputChannels; a++) {
        var classname = 'nvrchacel' + a;
        document.getElementById("" + classname).querySelector("img").src = "img/preview/nvrchcel.png";
    }
    config.play_push_list = []; //关闭所有就清除所有
    thoroughfareArray = [];
    for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
        thoroughfareArray.push(false);
    }
}

// 获取各个通道下的osd配置
function CHOSDGetSel(ch) {
    var cyURL = window.config.baseUrl + "/Pictures/" + ch + "/OSD";
    $.ajax({
        type: "GET",
        url: cyURL,
        processData: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, xhr, textStatus) {
            var osdName = $(xmlDoc).find('OSD').eq(0).find('DisplayName').eq(0).find('Name').eq(0).text();
            //console.log('osdName',osdName);
            $("#nvrchacel" + ch + " .preview-left-name").text(osdName);

        }
    });
}


function changeVCbr() {
    if ("CBR" == $("#bitratecontrol").val()) {
        $("#bitratefrom").show();
        $("#inputbitrate").hide();
        $("#selectbitrate").show();
        changemBitPU();
    } else {
        $("#bitratefrom").hide();
        $("#inputbitrate").hide();
        $("#selectbitrate").hide();
        // $("#Main_bit_rate").hide();
    }

}

/*************************************************
 Function:     changemBitPU
 Description:  选择主码流手动或下拉列表位率
 **************************************************/
function changemBitPU() {
    if ("1" == $("#bitrate").val()) {
        $("#inputbitrate").hide();
        $("#selectbitrate").show();
    } else {
        $("#inputbitrate").show();
        $("#selectbitrate").hide();
    }
}

function changecodestream() {
    if ("1" == $("#codestreamselect").val()) {
        $("#inputbitratejy").text("(256~12288Kbps)");
        getCapabilityV2();
        getMainstream();
    } else if ("2" == $("#codestreamselect").val()) {
        $("#inputbitratejy").text("(64~2048Kbps)");
        //根据主码流的分辨率来插入子码流的分辨率（包括了所有的子码流）
        RefreshSubStreamResolutionDataByMainStreamResulution();
        // $("#resolution").empty();
        $("#defaultvalue").empty();
        for (var i = 0; i < bit.length; i++) {
            if (3072 > bit[i]) {
                $("<option value='" + bit[i] + "'>" + bit[i] + "</option>").appendTo("#defaultvalue"); //子码位
            }
        }
        getSubstream();
    } else if ("3" == $("#codestreamselect").val()) {
        $("#inputbitratejy").text("(64~2048Kbps)");
        //根据主码流的分辨率来插入子码流的分辨率（包括了所有的子码流）
        RefreshSubStreamResolutionDataByMainStreamResulution();
        // $("#resolution").empty();
        $("#defaultvalue").empty();
        for (var i = 0; i < bit.length; i++) {
            if (3072 > bit[i]) {
                $("<option value='" + bit[i] + "'>" + bit[i] + "</option>").appendTo("#defaultvalue"); //子码位
            }
        }
        getMobilestream();
    }
}
/*************************************************
 Function:        InitPreview
 Description:    切换插件（针对）
 Input:            无
 Output:            无
 return:            无
 *************************************************/
function InitPreview() {

    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
    //监测当前系统来动态的改变当前支持的插件
    if ((navigator.platform.toLowerCase() == "win32" || navigator.platform.toLowerCase() == "win64") && g_bIsIE) {
        $("#downloadeasyplay").hide();
        $("#downlodeasyvideo").hide();
        $("#playCanvas").hide();
        $("#axdiv").show();
        $("<label class='btn btn-groupbtnplay active' id='ActiveX'><input type='radio' name='options' id='ActiveXcheck' checked>ActiveX</label>").appendTo("#playstyleoption");
        $("<label class='btn btn-groupbtnplay' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck'>MJPEG</label>").appendTo("#playstyleoption");
        $('#playstyle span').text(document.getElementById("ActiveX").innerText);
        sessionStorage.setItem("playstyle", "ActiveX");

    } else if (getBrowserType()) {
        var ua = navigator.userAgent.toLocaleLowerCase();
        if (config.playMode.length == 3) {
            if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null || ua.match(/metasr/) != null || ua.match(/ubrowser/) != null) {
                $("#playCanvas").hide();
                $("#axdiv").show();
                //唤醒成功
                if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                    $("<label class='btn btn-groupbtnplay active' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck' checked>EasyVideo</label>").appendTo("#playstyleoption");
                    $("<label class='btn btn-groupbtnplay' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck'>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
                    sessionStorage.setItem("playstyle", "EasyVideo");
                } else { //唤醒失败
                    $("#downloadeasyplay").show();
                    $("<label class='btn btn-groupbtnplay' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck'>EasyVideo</label>").appendTo("#playstyleoption");
                    $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                    sessionStorage.setItem("playstyle", "MJPEG");
                }

            } else {
                if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                    $("#playCanvas").hide();
                    $("#axdiv").show();
                    $("<label class='btn btn-groupbtnplay active' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck' checked>EasyVideo</label>").appendTo("#playstyleoption");
                    $("<label class='btn btn-groupbtnplay' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck'>WebPlayer</label>").appendTo("#playstyleoption");
                    $("<label class='btn btn-groupbtnplay' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck'>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
                    sessionStorage.setItem("playstyle", "EasyVideo");
                } else { //唤醒失败
                    $("#downloadeasyplay").show();
                    if (sessionStorage.getItem('file') == null || sessionStorage.getItem('file') == "null") {
                        $("#playCanvas").hide();
                        $("#axdiv").show();
                        $("<label class='btn btn-groupbtnplay' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck'>EasyVideo</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck' >WebPlayer</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                        $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                        sessionStorage.setItem("playstyle", "MJPEG");
                    } else {
                        $("#playCanvas").show();
                        $("#axdiv").hide();
                        $("<label class='btn btn-groupbtnplay' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck'>EasyVideo</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay active' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck' checked>WebPlayer</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck'>MJPEG</label>").appendTo("#playstyleoption");
                        $('#playstyle span').text(document.getElementById("WebPlayer").innerText);
                        sessionStorage.setItem("playstyle", "WebPlayer");
                    }

                }
            }
        } else if (config.playMode.length == 2) {
            if (!config.playMode.includes("EasyVideo")) {
                if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null || ua.match(/metasr/) != null || ua.match(/ubrowser/) != null) {
                    $("#playCanvas").hide();
                    $("#axdiv").show();
                    $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                    sessionStorage.setItem("playstyle", "MJPEG");
                } else {
                    if (sessionStorage.getItem('file') == null || sessionStorage.getItem('file') == "null") {
                        $("#playCanvas").hide();
                        $("#axdiv").show();
                        $("<label class='btn btn-groupbtnplay' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck' >WebPlayer</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                        $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                        sessionStorage.setItem("playstyle", "MJPEG");
                    } else {
                        $("#playCanvas").show();
                        $("#axdiv").hide();
                        $("<label class='btn btn-groupbtnplay active' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck' checked>WebPlayer</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck'>MJPEG</label>").appendTo("#playstyleoption");
                        $('#playstyle span').text(document.getElementById("WebPlayer").innerText);
                        sessionStorage.setItem("playstyle", "WebPlayer");
                    }
                }

            } else if (!config.playMode.includes("WebPlayer")) {
                $("#playCanvas").hide();
                $("#axdiv").show();
                //唤醒成功
                if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                    $("<label class='btn btn-groupbtnplay active' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck' checked>EasyVideo</label>").appendTo("#playstyleoption");
                    $("<label class='btn btn-groupbtnplay' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck'>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
                    sessionStorage.setItem("playstyle", "EasyVideo");
                } else { //唤醒失败
                    $("#downloadeasyplay").show();
                    $("<label class='btn btn-groupbtnplay' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck'>EasyVideo</label>").appendTo("#playstyleoption");
                    $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                    sessionStorage.setItem("playstyle", "MJPEG");
                }

            } else if (!config.playMode.includes("MJPEG")) {
                if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null || ua.match(/metasr/) != null || ua.match(/ubrowser/) != null) {
                    $("#playCanvas").hide();
                    $("#axdiv").show();
                    $("<label class='btn btn-groupbtnplay active' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck' checked>EasyVideo</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
                    if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                        sessionStorage.setItem("playstyle", "EasyVideo");
                    } else {
                        $("#downloadeasyplay").show();
                        $("#downlodeasyvideo").show();
                        console.log(678888);
                        $("#playcz").hide();
                    }
                } else {
                    if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                        $("#playCanvas").hide();
                        $("#axdiv").show();
                        $("<label class='btn btn-groupbtnplay active' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck' checked>EasyVideo</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck'>WebPlayer</label>").appendTo("#playstyleoption");
                        $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
                        sessionStorage.setItem("playstyle", "EasyVideo");
                    } else { //唤醒失败
                        $("#downloadeasyplay").show();
                        $("#playCanvas").show();
                        $("#axdiv").hide();
                        $("<label class='btn btn-groupbtnplay' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck'>EasyVideo</label>").appendTo("#playstyleoption");
                        $("<label class='btn btn-groupbtnplay active' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck' checked>WebPlayer</label>").appendTo("#playstyleoption");
                        $('#playstyle span').text(document.getElementById("WebPlayer").innerText);
                        sessionStorage.setItem("playstyle", "WebPlayer");
                    }

                }
            }

        } else if (config.playMode.length == 1) {
            if (config.playMode.includes("EasyVideo")) {
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("<label class='btn btn-groupbtnplay active' id='EasyVideo'><input type='radio' name='options' id='EasyVideocheck' checked>EasyVideo</label>").appendTo("#playstyleoption");
                $('#playstyle span').text(document.getElementById("EasyVideo").innerText);
                if (sessionStorage.getItem('isWakeupeasyvideo') == "true") {
                    sessionStorage.setItem("playstyle", "EasyVideo");
                } else {
                    $("#downloadeasyplay").show();
                    $("#downlodeasyvideo").show();
                    console.log("9000000000");
                    $("#playcz").hide();
                }

            } else if (config.playMode.includes("WebPlayer")) {
                if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null || ua.match(/metasr/) != null || ua.match(/ubrowser/) != null) {
                    $("#playCanvas").hide();
                    $("#axdiv").show();
                    $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                    sessionStorage.setItem("playstyle", "MJPEG");
                } else {
                    $("#playCanvas").show();
                    $("#axdiv").hide();
                    $("<label class='btn btn-groupbtnplay active' id='WebPlayer'><input type='radio' name='options' id='WebPlayercheck' checked>WebPlayer</label>").appendTo("#playstyleoption");
                    $('#playstyle span').text(document.getElementById("WebPlayer").innerText);
                    sessionStorage.setItem("playstyle", "WebPlayer");
                }
            } else {
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
                $('#playstyle span').text(document.getElementById("MJPEG").innerText);
                sessionStorage.setItem("playstyle", "MJPEG");
            }

        } else {
            $("#playCanvas").hide();
            $("#axdiv").show();
            $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
            $('#playstyle span').text(document.getElementById("MJPEG").innerText);
            sessionStorage.setItem("playstyle", "MJPEG");
        }

    } else //其他操作系统
    {
        $("#downloadeasyplay").hide();
        $("#downlodeasyvideo").hide();
        $("#playCanvas").hide();
        $("#axdiv").show();
        $("<label class='btn btn-groupbtnplay active' id='MJPEG'><input type='radio' name='options' id='MJPEGcheck' checked>MJPEG</label>").appendTo("#playstyleoption");
        sessionStorage.setItem("playstyle", "MJPEG");
    }
}


/*************************************************
 Function:        getOSD
 Description:     获取OSD信息
 *************************************************/
function getOSD() {
    if (config.deviceCap[inember].osdTag == "true" || config.deviceInfo.DeviceName == "NVR") { //之所以加这个判断是因为此版本还没有添加通道能力，暂时让nvr默认使用v2,实际需要按能力
        var xvURL
        if (config.deviceInfo.DeviceName == "IPC") {
            xvURL = config.baseUrl + "/Pictures/" + (inember - 0 + 1) + "/MultiOSDV2"
        } else {
            xvURL = config.baseUrl + "/Pictures/" + (config.thoroughfare - 0 + 1) + "/MultiOSDV2"
        }
        $.ajax({
            url: xvURL,
            type: "GET",
            async: true,
            timeout: 15000,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            success: function(xmlDoc) {
                get_osdxml_doc = xmlDoc;
                if (config.deviceCap[inember].osddoit == "true") {
                    dot = $(xmlDoc).find("OSDKind").text() == "PictureOSD" ? true : false
                    if (dot) {
                        fontsizce=$(xmlDoc).find("OSDBmp").eq(0).find('FontSize').text()
                    }
                }else{
                    dot=false;
                    fontsizce=0;
                }
                var osdName = $(xmlDoc).find("OSD").eq(0).find("Text").text();
                var arr = osdName.split("^");
                var eable = $(xmlDoc).find("OSD").eq(0).find("Enable").eq(0).text();
                if (eable == "true") {
                    $("#djsod").prop('checked', true)
                } else {
                    $("#djsod").prop('checked', false)
                }
                if ($(xmlDoc).find("DisplayTime").eq(0).find("Enable").eq(0).text() == "true") {
                    $("#djtime").prop('checked', true)
                } else {
                    $("#djtime").prop('checked', false)
                }

                if (jQuery.inArray("[RES]", arr) > -1 || jQuery.inArray("[BPS]", arr) > -1 || jQuery.inArray("[RES] [BPS]", arr) > -1) {
                    var type = arr.pop();
                }
                var lesshtml = '';
                $("#osd1").val(arr[0]);
                config.osdname = arr[0];
                $(".less").remove();
                for (var i = 1; i < arr.length; i++) {
                    lesshtml += "<div class='form-group less'><div class='col-md-12'><input type='text' class='nName-1 form-control'  name='osd1' value='" + arr[i] + "' style='width: 80%;display: inline-block' /><input type='button' class='btndel'/></div></div>";
                }
                $("#osd1fromgroup").after(lesshtml);
                switch (type) {
                    case "[RES]":
                        $("#djother").select2("val", "2");
                        break;
                    case "[BPS]":
                        $("#djother").select2("val", "3");
                        break;
                    case "[RES] [BPS]":
                        $("#djother").select2("val", "4");
                        break;
                    default:
                        $("#djother").select2("val", "1");
                }
                //osd2
                if (config.deviceCap[inember].osd2support == "true") {
                    var osd2Name = $(xmlDoc).find("OSD").eq(1).find("Text").text();
                    // 检查有无^ 有就去掉第一个^
                    var index = osd2Name.indexOf("^");
                    if (index == -1) { //无 直接显示，，，，用户没有输入换行符且没超过30个字符
                        $("#osd2Text").val(osd2Name);
                    } else { //有换行符     用户输入了 或者超过30个字符
                        var chartlength = 0,
                            chieseCode = -1; //字符长度
                        var flagosd2 = false; // 判断换行符的位置是否在31 或者30
                        for (var j = 0; j < osd2Name.length; j++) {
                            chieseCode = osd2Name.charCodeAt(j); //字符串.charCodeAt(index)>255 就是中文，否则是英文。
                            if (chieseCode > 255) chartlength += 2;
                            else chartlength += 1;
                            if (chartlength == 30 || chartlength == 31) { //判断第一个出现的^是不是在第30或者31处
                                if (osd2Name.slice(j).slice(0, 1) == "^" && j == index) {
                                    flagosd2 = true;
                                } else {
                                    flagosd2 = false;
                                };
                            }
                        };
                        if (flagosd2) {
                            var str = osd2Name.replace('^', ''); //去掉第一个
                            $("#osd2Text").val(str); //文本框显示
                        } else { //用户加的 直接显示文本
                            $("#osd2Text").val(osd2Name);
                        }

                    }
                    var osd2Enable = $(xmlDoc).find("OSD").eq(1).find('Enable').eq(0).text();
                    $("#osd2Enable").prop('checked', JSON.parse(osd2Enable));

                }

            },

            error: function(xhr, textStatus, errorThrown) {}
        });
    } else {
        $.ajax({
            url: config.baseUrl + "/Pictures/1/OSD",
            type: "GET",
            async: true,
            timeout: 15000,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            success: function(xmlDoc) {
                get_osdxml_doc = xmlDoc;
                var osdName = $(xmlDoc).find('DisplayName').eq(0).find('Name').text();
                if (osdName.split("^").length == 1) {
                    $("#osd1").val(osdName);
                    config.osdname = osdName;
                    $(".less").remove();
                } else {
                    var arr = osdName.split("^");
                    var lesshtml = '';
                    $("#osd1").val(osdName.split("^")[0]);
                    config.osdname = osdName.split("^")[0];
                    $(".less").remove();
                    for (var i = 1; i < arr.length; i++) {
                        lesshtml += "<div class='form-group less'><div class='col-md-12'><input type='text' class='nName-1 form-control'  name='osd1'  value='" + arr[i] + "' style='width: 80%;display: inline-block' /><input type='button' class='btndel'/></div></div>";
                    }
                    $("#osd1fromgroup").after(lesshtml);

                }
            },
            error: function(xhr, textStatus, errorThrown) {}
        });
    }
}

//最终的base64点阵信息
function getOSDtricValuepre() {
    var cyXml = get_osdxml_doc;
    $(cyXml).find("OSDKind").eq(0).text(isosdType);
    $(cyXml).find("OSD").eq(1).find("Text").text(osd2);
    $(cyXml).find("OSD").eq(1).find("Enable").eq(0).text($("#osd2Enable").is(':checked'));
    if ($("#djsod").is(':checked')) {
        $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(true);
    } else {
        $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(false);
    }
    $(cyXml).find("OSD").eq(0).find("Text").text(osd1);
    // $(cyXml).find("OSDName").eq(0).find("Text").text(nName2);
    if ($("#djtime").is(':checked')) {
        $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(true);
    } else {
        $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(false)
    }
    $(cyXml).find("OSDBmp").eq(0).find("BmpW").text( keepdoit.width);
    $(cyXml).find("OSDBmp").eq(0).find("BmpH").text( keepdoit.height);
    $(cyXml).find("OSDBmp").eq(0).find("OSDBmpBase64").text( keepdoit.base64 );
    $(cyXml).find("OSDBmp").eq(0).find("OSDBmpBase64Len").text(keepdoit.length);


    $(cyXml).find("OSDBmp").eq(1).find("BmpW").text( keepdoit2.width);
    $(cyXml).find("OSDBmp").eq(1).find("BmpH").text( keepdoit2.height);
    $(cyXml).find("OSDBmp").eq(1).find("OSDBmpBase64").text( keepdoit2.base64 );
    $(cyXml).find("OSDBmp").eq(1).find("OSDBmpBase64Len").text(keepdoit2.length);

    setOsdReally(cyXml)

}
//osd1回调
function keepditowpre(data) {
    keepdoit2.width = data.OSD.width;
    keepdoit2.base64 = data.OSD.base64;
    keepdoit2.height = data.OSD.height;
    keepdoit2.length = data.OSD.length;
    if (config.deviceCap[inember].osddoitWidth2 < keepdoit2.width || config.deviceCap[inember].osddoitHeight2 < keepdoit2.height) {
        return  $.optionBootoast($.i18n.prop('i18n-dain-osd2'), "danger");
    } else {
        getOSDtricValuepre();
    }
}
//osd2回调
function keepditpre(data) {
    keepdoit.width = data.OSD.width;
    keepdoit.base64 = data.OSD.base64;
    keepdoit.height = data.OSD.height;
    keepdoit.length = data.OSD.length;
    if (config.deviceCap[inember].osddoitWidth < keepdoit.width || config.deviceCap[inember].osddoitHeight < keepdoit.height) {
        return  $.optionBootoast($.i18n.prop('i18n-dain-osd'), "danger");
    } else {
        console.log(osd2, "2222");
        osdgetDianzline(osd2, fontsizce, 1);
    }

}


/*************************************************
 Function:        setOSD
 Description:     保存OSD
 *************************************************/
function setOSD() {
    if (config.deviceCap[inember].osdTag == "true" || config.deviceInfo.DeviceName == "NVR") { //之所以加这个判断是因为此版本还没有添加通道能力，暂时让nvr默认使用v2,实际需要按能力
        // osd1
        var nName;
        //获取页面的值
        var vArr = [];
        var nameArr = $("input[name='osd1']");
        for (var i = 0; i < nameArr.length; i++) {
            var value = $(nameArr[i]).val();
            if (value != "") {
                vArr.push(value);
            }

        }
        if (config.deviceCap[inember].osdTag == "true" && config.deviceCap[inember].osdShowd == "true") {
            var infoval = $("#djother").select2("val");
        } else {
            var infoval = "1";
        }
        switch (infoval) {
            case "2":
                vArr.push("[RES]");
                break;
            case "3":
                vArr.push("[BPS]");
                break;
            case "4":
                vArr.push("[RES] [BPS]");
                break;
            default:
                vArr;
                break;
        }

        nName = vArr.join("^");
        osd1=nName
        var arrInput = $("input[name='osd1']");
        for (var i = 0; i < arrInput.length; i++) {
            var realLength = 0,
                charCode = -1;
            for (var j = 0; j < $(arrInput[i]).val().length; j++) {
                //字符串.charCodeAt(index)>255 就是中文，否则是英文。
                charCode = $(arrInput[i]).val().charCodeAt(j);
                if (charCode > 255) realLength += 2;
                else realLength += 1
            }

            if (realLength > osdchar1) {
                var str = $.i18n.prop('i18n-max40');
                var newStr = str.replace(/\d+/g, function() {
                    return arguments[0] = osdchar1;
                });
                bootoast({
                    message: newStr,
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return;
            }
        }
        // osd2
        var nName2;
        //获取页面的值
        var osd2text = $("#osd2Text").val();
        if(osd2text.split("^").length - 1>osdline2-1){
          return   $.optionBootoast("osd2"+$.i18n.prop('i18n-morethen'), "danger");
        }
        var chartlength = 0,
            chieseCode = -1; //字符长度
        var chartJ;
        for (var j = 0; j < osd2text.length; j++) {
            chieseCode = osd2text.charCodeAt(j); //字符串.charCodeAt(index)>255 就是中文，否则是英文。
            if (chieseCode > 255) chartlength += 2;
            else chartlength += 1;
            if (chartlength == 30) { //可能没有30
                chartJ = j + 1;
            } else if (chartlength == 29) { //取31
                chartJ = j + 1;
            }

        } //如果用户输入的字符大于30个，查看用户前30个字符是否输入了^每天
        if (chartlength >= config.deviceCap[inember].odTwol) { //单行长度
            if (osd2text.slice(0, chartJ).indexOf("^") == -1 && osd2text.slice(chartJ).slice(0, 1) !== "^") { //前30个字符 用户没有输入换行符 自己加 特殊情况 用户在第二行第一处加^
                if (chartlength > config.deviceCap[inember].odTwo) { //总长度
                    $.optionBootoast($.i18n.prop('i18n-osd2-alllength') + '\xa0' + config.deviceCap[inember].odTwo + '\xa0' + $.i18n.prop('i18n-osd2multis'), "danger");
                    return;
                }
                localStorage.setItem("osd2flag", "true");
                osd2 = osd2text.slice(0, chartJ) + "^" + osd2text.slice(chartJ);
            } else { //超过30字符 用户输入了换行符 从换行符算后算第二行
                var indexs = osd2text.indexOf("^");
                var slicelength = osd2text.slice(indexs + 1);
                var chartL = chartlengths(slicelength); //获取第二行字符长度
                if (chartL > config.deviceCap[inember].odTwol) {
                    $.optionBootoast($.i18n.prop('i18n-multi-single-row-osd2-line') + '\xa0' + config.deviceCap[inember].odTwol + '\xa0' + $.i18n.prop('i18n-osd2multis'), "danger");
                    return;
                }
                osd2 = osd2text;
            }
        } else { //小于30个字符 不用管用户输入换行符没
            osd2 = osd2text;
        }

        var cyXml = get_osdxml_doc;
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            if (dot) {
                if ($("#djother").val() != '1') {
                    vArr.pop()
                }
                osdgetDianzline(vArr.join('^'), fontsizce);
                isosdType = 'PictureOSD'
            } else {
                // osdputV();
                isosdType = 'TextOSD';
                $(cyXml).find("OSDKind").eq(0).text(isosdType);
                $(cyXml).find("OSD").eq(1).find("Text").text(osd2);
                $(cyXml).find("OSD").eq(1).find("Enable").eq(0).text($("#osd2Enable").is(':checked'));
                if ($("#djsod").is(':checked')) {
                    $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(true);
                } else {
                    $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(false);
                }
                $(cyXml).find("OSD").eq(0).find("Text").text(nName);
                // $(cyXml).find("OSDName").eq(0).find("Text").text(nName2);
                if ($("#djtime").is(':checked')) {
                    $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(true);
                } else {
                    $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(false)
                }
                setOsdReally(cyXml);
            }
        }
       else  if (sessionStorage.getItem("playstyle") == "ActiveX") {
            // 获取点阵信息
            if (dot) {
                if ($("#djother").val() != '1') {
                    vArr.pop()
                }
                var k = fontsizce
                if (k == '32') {
                    var ke = 16
                    var ge = 32
                } else if (k == '16') {
                    var ke = 8
                    var ge = 16
                } else if (k == '8') {
                    var ke = 4
                    var ge = 8
                } else if (k == '12') {
                    var ke = 6
                    var ge = 12
                } else {
                    var ke = 24
                    var ge = 46
                }
                var xml = '<?xml version="1.0" encoding="UTF-8" ?>' +
                    '<StringToLattice_In><FontName>宋体</FontName><FontUnderline>false</FontUnderline>' +
                    '<FontItalic>false</FontItalic><FontStrikeOut>false</FontStrikeOut><FontBold>false</FontBold>' +
                    '<SourceText>' + vArr.join('^') + '</SourceText><Width>' + ke + '</Width><Height>' + ge + '</Height></StringToLattice_In>'

                var dotxmlDox = setlattice(xml);
                console.log($(dotxmlDox).find('ImageData').text(), "5555555555");
                isosdType = 'PictureOSD'
            } else {
                isosdType = 'TextOSD'
            }
            $(cyXml).find("OSDKind").eq(0).text(isosdType);
            $(cyXml).find("OSD").eq(1).find("Text").text(osd2);
            $(cyXml).find("OSD").eq(1).find("Enable").eq(0).text($("#osd2Enable").is(':checked'));
            if ($("#djsod").is(':checked')) {
                $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(true);
            } else {
                $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(false);
            }
            $(cyXml).find("OSD").eq(0).find("Text").text(nName);
            // $(cyXml).find("OSDName").eq(0).find("Text").text(nName2);
            if ($("#djtime").is(':checked')) {
                $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(true);
            } else {
                $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(false)
            }
            $(cyXml).find("OSDBmp").eq(0).find("BmpW").text($(dotxmlDox).find('ImageWidth').text());
            $(cyXml).find("OSDBmp").eq(0).find("BmpH").text($(dotxmlDox).find('ImageHeight').text());
            $(cyXml).find("OSDBmp").eq(0).find("OSDBmpBase64").text($(dotxmlDox).find('ImageData').text());
            $(cyXml).find("OSDBmp").eq(0).find("OSDBmpBase64Len").text($(dotxmlDox).find('ImageData').text().length);
            setOsdReally(cyXml)
        }else{
            isosdType = 'TextOSD';
            $(cyXml).find("OSDKind").eq(0).text(isosdType);
            $(cyXml).find("OSD").eq(1).find("Text").text(osd2);
            $(cyXml).find("OSD").eq(1).find("Enable").eq(0).text($("#osd2Enable").is(':checked'));
            if ($("#djsod").is(':checked')) {
                $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(true);
            } else {
                $(cyXml).find("OSD").eq(0).find("Enable").eq(0).text(false);
            }
            $(cyXml).find("OSD").eq(0).find("Text").text(nName);
            // $(cyXml).find("OSDName").eq(0).find("Text").text(nName2);
            if ($("#djtime").is(':checked')) {
                $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(true);
            } else {
                $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(false)
            }
            setOsdReally(cyXml)
        }

    } else {
        //这里应该根据对应通道能力来判断是否走此接口老的
        var nName;
        nName = $("#nName").val();
        if (nName.length > 40) {
            bootoast({
                message: $.i18n.prop('i18n-max40'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
            return
        }
        if ($(".less").length > 0) {
            if ($(".nName-1").val() != "") {
                nName = nName + "^" + $(".nName-1").val();
                var nName1 = $(".nName-1").val();
                if (nName1.length > 40) {
                    bootoast({
                        message: $.i18n.prop('i18n-max40'),
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return
                }
            }
        }
        var cyXml = get_osdxml_doc;
        if ($("#djsod").is(':checked')) {
            $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(true);
        } else {
            $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(false);
        }
        $(cyXml).find("OSD").eq(0).find("Text").text(nName);
        if ($("#djtime").is(':checked')) {
            $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(true);
        } else {
            $(cyXml).find("DisplayTime").eq(0).find("Enable").eq(0).text(false)
        }

        var cyURL = config.baseUrl + "/Pictures/1/OSD";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr) {
                if ($("#djtime").is(':checked')) {
                    setDateTimeFormat();
                    getOSD();
                } else {
                    SaveState(xhr);
                    getOSD();
                }
            }
        });
    }
}


function setOsdReally(cyXml){
    var cyURL;
    if (config.deviceInfo.DeviceName == "IPC") {
         cyURL = config.baseUrl + "/Pictures/1/MultiOSDV2";
    } else {
         cyURL = config.baseUrl + "/Pictures/" + (config.thoroughfare + 1) + "/MultiOSDV2";
    }
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr) {
            if ($("#djtime").is(':checked')) {
                setDateTimeFormat();
                getOSD();
            } else {
                SaveState(xhr);
                getOSD();
            }

        }
    });
}

function chartlengths(str) {
    var chartlength = 0,
        chieseCode = -1; //字符长度
    for (var j = 0; j < str.length; j++) {
        chieseCode = str.charCodeAt(j); //字符串.charCodeAt(index)>255 就是中文，否则是英文。
        if (chieseCode > 255) chartlength += 2;
        else chartlength += 1;
    };
    return chartlength;
};

/*************************************************
 Function:        setDateTimeFormat
 Description:     保存设备日期时间显示格式
 *************************************************/
function setDateTimeFormat() {
    var cyXml = get_timexml_doc;
    $(cyXml).find('Time').eq(0).find('DateTimeFormat').eq(0).text($("#djtimestyle").select2("val"));
    $(cyXml).find('Time').eq(0).find('TimeFormat').eq(0).text($("#hourselect input:radio:checked").val());
    var cyURL = config.baseUrl + "/System/Time";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getTimeinfo();
        }
    });
}
function getPTZPeople() {
    var cyURL;
    if (config.deviceInfo.DeviceName == "IPC") {
        cyURL = config.baseUrl + "/ExternalPTZ/1/TrackConfig";
    } else {
        cyURL = config.baseUrl + "/ExternalPTZ/" + (config.thoroughfare - 0 + 1) + "/TrackConfig";
    }
    $.ajax({
        url: cyURL,
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var AFBoardPTZTrackEnable = $(xmlDoc).find('ExternalPTZTrackCfg').eq(0).find('AFBoardPTZTrackEnable').text();
            AFBoardPTZTrackEnable === "true" ? $("#switchPeople").bootstrapSwitch('state', true,true) : $("#switchPeople").bootstrapSwitch('state', false,true);
        },
        error: function(xhr, textStatus, errorThrown) {
        }
    });
}

// 获取ptz能力配置
function getPTZPower() {
    var cvurl = config.baseUrl + "/System/PTZCap";
    $.ajax({
        url: cvurl,
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var ptzspeed = $(xmlDoc).find('Channel').eq(0).find('Extend').eq(0).find('Support').text();
            var light = $(xmlDoc).find('Channel').eq(0).find('Light').eq(0).find('Support').text();
            var wipe = $(xmlDoc).find('Channel').eq(0).find('Wipe').eq(0).find('Support').text();
            var eable3d=$(xmlDoc).find('Channel').eq(0).find('Position3D').eq(0).find('Support').text();//3D定位能力
            light === "true"?$("#dg").show():$("#dg").hide();
            wipe === "true"?$("#ys").show():$("#ys").hide();
            eable3d === "true"?$("#3D").show():$("#3D").hide();
            var ptzpeople = $(xmlDoc).find('Channel').eq(0).find('ExPTZTargetTracking').eq(0).find('Support').text();
            if ("admin" == config.user || "super_admin" == config.user) {
                light === "true" ? $("#switchlight").bootstrapSwitch('state', false) : "";
                wipe === "true" ? $("#switchys").bootstrapSwitch('state', false) : "";
            }
            if (ptzpeople=="true"){
                $("#people").show();
                getPTZPeople();
            }else{
                $("#people").hide()
            }
            if (ptzspeed == "true") {
                $('#TurnUpLeft').show();
                $('#TurnUpRight').show();
                $('#TurnDownLeft').show();
                $('#TurnDownRight').show();
            } else { //nvr没有获取speed参数，根据项目经理需求默认五
                $('#TurnUpLeft').hide();
                $('#TurnUpRight').hide();
                $('#TurnDownLeft').hide();
                $('#TurnDownRight').hide();
            }

        },
        error: function(xhr, textStatus, errorThrown) {
            $("#switchlight").bootstrapSwitch('state', false);
            $("#switchys").bootstrapSwitch('state', false);
        }
    });
}

function getPTZCfg() {
    var cvurl;
    if (config.deviceInfo.DeviceName == "IPC") {
        cvurl = config.baseUrl + "/PTZ/1/Config";
    } else {
        cvurl = config.baseUrl + "/PTZ/" + (config.thoroughfare - 0 + 1) + "/Config";
    }
    $.ajax({
        url: cvurl,
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            gs_ptz_cfg = xmlDoc;
            var ptzspeed = $(xmlDoc).find('PTZConfigChannel').eq(0).find('Speed').text();
            if (config.deviceInfo.DeviceName == "IPC") {
                $('#ptzslider').jRange('setValue', ptzspeed);
            } else { //nvr没有获取speed参数，根据项目经理需求默认五
                $('#ptzslider').jRange('setValue', 5);
            }

        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


function setPTZCfg() {
    $(gs_ptz_cfg).find("PTZConfigChannel").eq(0).find("Speed").eq(0).text($("#ptzslider").val());
    var cvurl;
    if (config.deviceInfo.DeviceName == "IPC") {
        cvurl = config.baseUrl + "/PTZ/1/Config";
    } else {
        cvurl = config.baseUrl + "/PTZ/" + (config.thoroughfare - 0 + 1) + "/Config";
    }
    $.ajax({
        type: "PUT",
        url: cvurl,
        processData: false,
        data: gs_ptz_cfg,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // SaveState(xhr);
        }
    });
}


/*************************************************
 Function:        getTimeinfo
 Description:     获取时间
 *************************************************/
function getTimeinfo() {
    $.ajax({
        url: config.baseUrl + "/System/Time",
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            get_timexml_doc = xmlDoc;
            $("#djtimestyle").select2("val", $(xmlDoc).find('Time').eq(0).find('DateTimeFormat').eq(0).text());
            var f = $(xmlDoc).find('Time').eq(0).find('TimeFormat').eq(0).text();
            if (f == "12hour") {
                $("#12hour").click();
            } else if (f == "24hour") {
                $("#24hour").click();
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


/*************************************************
 Function:        getIrCutFilter
 Description:     获取IrCutFilter信息
 *************************************************/
function getIrCutFilter() {
    $.ajax({
        url: config.baseUrl + "/Images/" + (inember - 0 + 1) + "/IrCutFilter",
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) { //图像模式
            get_xml_doc = xmlDoc;
            $("#imageType").select2("val", $(xmlDoc).find('IrCutFillter').eq(0).find('ImageMode').eq(0).text());
            // $("#imageType").val($(xmlDoc).find('IrCutFillter').eq(0).find('ImageMode').eq(0).text()).select2();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function getImageBasic() {

    $.ajax({
        url: config.baseUrl + "/Images/" + (inember - 0 + 1) + "/Basic",
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            getBasic_xml_doc = xmlDoc;
            var s = $(xmlDoc).find('Basic').eq(0).find('powerLineFrequencyMode').eq(0).text();
            var s1 = $(xmlDoc).find('Basic').eq(0).find('powerLineFrequencyStrength').eq(0).text();
            $(':radio[name=icpowermode][value=' + s + ']').parent().addClass('active');
            // $(':radio[name=icpowermode][value='+s+']').setAttribute("checked","checked");
            $(':radio[name=icpowermodes][value=' + s1 + ']').parent().addClass('active');
            // $(':radio[name=icpowermodes][value='+s1+']').setAttribute("checked","checked");
            $("#wideDynamic").select2("val", $(xmlDoc).find('Basic').eq(0).find('WDR').eq(0).text());
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


function setIrCutFilter() {
    var cyXml = get_xml_doc;
    $(cyXml).find('IrCutFillter').eq(0).find('ImageMode').eq(0).text($("#imageType").select2("val"));
    var cyURL = config.baseUrl + "/Images/1/IrCutFilter";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getIrCutFilter();
        }
    });
}

function setImageBasic() {
    var cyXml = getBasic_xml_doc;
    $(cyXml).find('Basic').eq(0).find('WDR').eq(0).text($("#wideDynamic").select2("val"));
    $(cyXml).find('Basic').eq(0).find('powerLineFrequencyMode').eq(0).text($("#icpowermode input:radio:checked").val());
    $(cyXml).find('Basic').eq(0).find('powerLineFrequencyStrength').eq(0).text($("#icpowermodes input:radio:checked").val());
    var cyURL = config.baseUrl + "/Images/1/Basic";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {

            SaveState(xhr);
            getImageBasic();
        }
    });
}


function getCapabilityV2() {
    var cvurl
    if (config.deviceInfo.DeviceName == "IPC") {
        cvurl = config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/CapabilityV2"
    } else {
        cvurl = config.baseUrl + "/Streams/" + (config.thoroughfare - 0 + 1) + "/CapabilityV2"
    }
    $.ajax({
        url: cvurl,
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            gs_stream_cap_xml = xmlDoc;
            InitUIByStreamCap();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


/*************************************************
 Function:        getMainstream
 Description:     获取主码流信息
 *************************************************/
function getMainstream() {
    var cvurl
    if (config.deviceInfo.DeviceName == "IPC") {
        cvurl = config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/1"
    } else {
        cvurl = config.baseUrl + "/Streams/" + (config.thoroughfare - 0 + 1) + "/1"
    }
    $.ajax({
        url: cvurl,
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            gs_main_stream_xml = xmlDoc;
            var rlWidth = $(gs_main_stream_xml).find('StreamConfig').eq(0).find('ResolutionWidth').eq(0).text();
            var rlHeight = $(gs_main_stream_xml).find('StreamConfig').eq(0).find('ResolutionHeigth').eq(0).text();
            $("#resolution").select2("val", rlWidth + '*' + rlHeight);
            $("#bitratecontrol").select2("val", $(gs_main_stream_xml).find('StreamConfig').eq(0).find('BitrateType').eq(0).text());
            var flg = '0';
            for (var i = 0; i < bit.length; i++) {
                if ($(gs_main_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text() == bit[i]) {
                    flg = '1';
                    break;
                }
            }
            // if("CBR" == $("#bitratecontrol").val()){
            $("#bitrate").select2("val", flg);
            changeVCbr();
            $("#defaultvalue").select2("val", $(gs_main_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text());
            $("#mBitrate").val($(gs_main_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text());
            // changemBitPU();
            // }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


/*************************************************
 Function:        getSubstream
 Description:     获取子码流信息
 *************************************************/
function getSubstream() {
    var cvurl
    if (config.deviceInfo.DeviceName == "IPC") {
        cvurl = config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/2"
    } else {
        cvurl = config.baseUrl + "/Streams/" + (config.thoroughfare - 0 + 1) + "/2"
    }
    $.ajax({
        url: cvurl,
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            gs_first_stream_xml = xmlDoc;
            var rlWidth = $(gs_first_stream_xml).find('StreamConfig').eq(0).find('ResolutionWidth').eq(0).text();
            var rlHeight = $(gs_first_stream_xml).find('StreamConfig').eq(0).find('ResolutionHeigth').eq(0).text();
            $("#resolution").select2("val", rlWidth + '*' + rlHeight);
            $("#bitratecontrol").select2("val", $(gs_first_stream_xml).find('StreamConfig').eq(0).find('BitrateType').eq(0).text());
            // changeVCbr();
            var flg = '0';
            for (var i = 0; i < bit.length; i++) {
                if ($(gs_first_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text() == bit[i]) {
                    flg = '1';
                    break;
                }
            }
            $("#bitrate").select2("val", flg);
            changeVCbr();
            $("#defaultvalue").select2("val", $(gs_first_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text());
            $("#mBitrate").val($(gs_first_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text());

        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


/*************************************************
 Function:        getMobilestream
 Description:     获取手机码流信息
 *************************************************/
function getMobilestream() {
    $.ajax({
        url: config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/3",
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            gs_second_stream_xml = xmlDoc;
            var rlWidth = $(gs_second_stream_xml).find('StreamConfig').eq(0).find('ResolutionWidth').eq(0).text();
            var rlHeight = $(gs_second_stream_xml).find('StreamConfig').eq(0).find('ResolutionHeigth').eq(0).text();
            $("#resolution").select2("val", rlWidth + '*' + rlHeight);
            $("#bitratecontrol").select2("val", $(gs_second_stream_xml).find('StreamConfig').eq(0).find('BitrateType').eq(0).text());
            // changeVCbr();
            var flg = '0';
            for (var i = 0; i < bit.length; i++) {
                if ($(gs_second_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text() == bit[i]) {
                    flg = '1';
                    break;
                }
            }
            $("#bitrate").select2("val", flg);
            changeVCbr();
            $("#bitrate").select2("val", $(gs_second_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text());
            $("#mBitrate").val($(gs_second_stream_xml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text());
            // if("CBR" == $("#bitratecontrol").val()){
            //     $("#bitrate").val(flg);
            //     changemBitPU();
            // }

        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


/*************************************************
 Function:        getStreamCap
 Description:     获取主码流分辨率的个数
 *************************************************/
function getMainStreamTypeCount() {
    return $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').length;
}


/*************************************************
 Function:        getStreamCap
 Description:     根据码流的能力初始化页面数据
 *************************************************/
function InitUIByStreamCap() {
    //根据能力来插入主码流的分辨率
    $("#resolution").empty();
    $("#defaultvalue").empty();
    for (var i = 0; i < bit.length; i++) {
        if (bit[i] >= 256) {
            $("<option value='" + bit[i] + "'>" + bit[i] + "</option>").appendTo("#defaultvalue"); //主码位
        }
    }
    var ResolutionH = "";
    var ResolutionW = "";
    var MainStreamTypeCount = getMainStreamTypeCount();
    for (var i = 0; i < MainStreamTypeCount; i++) {
        ResolutionH = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(i).find('ResolutionHeigth').eq(0).text();
        ResolutionW = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(i).find('ResolutionWidth').eq(0).text();
        for (var j = 0; j < config.gs_arrResolution.length; j++) {
            if (config.gs_arrResolution[j].Resolution == ResolutionW + "*" + ResolutionH) {
                $("<option value='" + config.gs_arrResolution[j].Resolution + "'>" + config.gs_arrResolution[j].ResolutionVal + "</option>").appendTo("#resolution");
                break;
            }
        }
    }
}

/*************************************************
 Function:        getStreamCap
 Description:     根据选择的主码流的分辨率获取主码流的位置
 *************************************************/
function getMainStreamPosByMainStreamResolutin(MainStreamResolution) {
    var index = 0;
    var MainStreamCount = getMainStreamTypeCount();
    var ResolutionH = "";
    var ResolutionW = "";
    for (var i = 0; i < MainStreamCount; i++) {
        ResolutionH = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(i).find('ResolutionHeigth').eq(0).text();
        ResolutionW = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(i).find('ResolutionWidth').eq(0).text();
        if (MainStreamResolution == ResolutionW + "*" + ResolutionH) {
            index = i;
            break;
        }
    }
    return index;
}

/*************************************************
 Function:        getStreamCap
 Description:     根据当前选择的主码流的分辨率，来确定子码流的分辨率
 *************************************************/
function RefreshSubStreamResolutionDataByMainStreamResulution() {
    $("#resolution").empty();
    var subStreamTypeCount = config.deviceCap[inember].StreamCount - 1;
    //获取当前界面选择的主码流的分辨率
    var selectedMainResolution = $("#resolution").val();
    //根据选择的主码流的分辨率获取主码流在xml的位置
    var index = getMainStreamPosByMainStreamResolutin(selectedMainResolution);
    for (var i = 0; i < subStreamTypeCount; i++) {
        //获取当前选择的主码流对应的支持的子码流的个数
        if (subStreamTypeCount == '3' && i == '2') {
            var subCount = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(index).find(gs_stream_type_map_table[i].strXMLStreamName + "List").find('StreamCapability').length;
            for (var j = 0; j < subCount; j++) {
                var subResolutionW = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(index).find(gs_stream_type_map_table[i].strXMLStreamName + "List").find('StreamCapability').eq(j).find('ResolutionWidth').eq(0).text();
                var subResolutionH = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(index).find(gs_stream_type_map_table[i].strXMLStreamName + "List").find('StreamCapability').eq(j).find('ResolutionHeigth').eq(0).text();
                for (var k = 0; k < config.gs_arrResolution.length; k++) {
                    if (config.gs_arrResolution[k].Resolution == subResolutionW + "*" + subResolutionH) {
                        $("<option value='" + config.gs_arrResolution[k].Resolution + "'>" + config.gs_arrResolution[k].ResolutionVal + "</option>").appendTo("#" + gs_stream_type_map_table[i + 1].strResolutionID);
                        break;
                    }
                }
            }
        } else {
            var subCount = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(index).find(gs_stream_type_map_table[i + 1].strXMLStreamName + "List").find('StreamCapability').length;
            for (var j = 0; j < subCount; j++) {
                var subResolutionW = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(index).find(gs_stream_type_map_table[i + 1].strXMLStreamName + "List").find('StreamCapability').eq(j).find('ResolutionWidth').eq(0).text();
                var subResolutionH = $(gs_stream_cap_xml).find('StreamCapability').find('MainStreamCapabilityList').find('MainStreamCapability').eq(index).find(gs_stream_type_map_table[i + 1].strXMLStreamName + "List").find('StreamCapability').eq(j).find('ResolutionHeigth').eq(0).text();
                for (var k = 0; k < config.gs_arrResolution.length; k++) {
                    if (config.gs_arrResolution[k].Resolution == subResolutionW + "*" + subResolutionH) {
                        $("<option value='" + config.gs_arrResolution[k].Resolution + "'>" + config.gs_arrResolution[k].ResolutionVal + "</option>").appendTo("#" + gs_stream_type_map_table[i + 1].strResolutionID);
                        break;
                    }
                }
            }
        }

    }
}

/*************************************************
 Function:        setMainstream
 Description:     保存主码流信息
 *************************************************/
function setMainstream() {
    var rlWidth = $("#resolution").select2("val").split('*')[0];
    var rlHeight = $("#resolution").select2("val").split('*')[1];
    var cyXml = gs_main_stream_xml;
    $(cyXml).find('StreamConfig').eq(0).find('ResolutionWidth').eq(0).text(rlWidth);
    $(cyXml).find('StreamConfig').eq(0).find('ResolutionHeigth').eq(0).text(rlHeight);
    $(cyXml).find('StreamConfig').eq(0).find('BitrateType').eq(0).text($("#bitratecontrol").select2("val"));
    if ($("#bitratecontrol").select2("val") == "CBR") {
        if ($("#bitrate").val() == "0") {
            if ((parseInt($("#mBitrate").val()) >= 256) && (parseInt($("#mBitrate").val()) <= 12288)) {
                var reg = /^[1-9]\d*$/;
                if (!reg.test($("#mBitrate").val())) {
                    bootoast({
                        message: $.i18n.prop('i18n-inputrange'),
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return;
                } else {
                    $(cyXml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text($("#mBitrate").val());
                }
            } else {
                bootoast({
                    message: $.i18n.prop('i18n-inputrange'),
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return;
            }

        } else {
            $(cyXml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text($("#defaultvalue").select2("val"))
        }
    }
    if (config.deviceInfo.DeviceName == "IPC") {
        var cyURL = config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/1";
    } else {
        var cyURL = config.baseUrl + "/Streams/" + (config.thoroughfare - 0 + 1) + "/1";
    }
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getMainstream();
        }
    });
}


/*************************************************
 Function:        setSubstream
 Description:     保存子码流信息
 *************************************************/
function setSubstream() {
    var rlWidth = $("#resolution").select2("val").split('*')[0];
    var rlHeight = $("#resolution").select2("val").split('*')[1];
    var cyXml = gs_first_stream_xml;
    $(cyXml).find('StreamConfig').eq(0).find('ResolutionWidth').eq(0).text(rlWidth);
    $(cyXml).find('StreamConfig').eq(0).find('ResolutionHeigth').eq(0).text(rlHeight);
    $(cyXml).find('StreamConfig').eq(0).find('BitrateType').eq(0).text($("#bitratecontrol").select2("val"));
    if ($("#bitratecontrol").select2("val") == "CBR") {
        if ($("#bitrate").val() == "0") {
            if ((parseInt($("#mBitrate").val()) >= 64) && (parseInt($("#mBitrate").val()) <= 2048)) {
                var reg = /^[1-9]\d*$/;
                if (!reg.test($("#mBitrate").val())) {
                    bootoast({
                        message: $.i18n.prop('i18n-inputrange'),
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return;
                } else {
                    $(cyXml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text($("#mBitrate").val());
                }
            } else {
                bootoast({
                    message: $.i18n.prop('i18n-inputrange'),
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return;
            }
        } else {
            $(cyXml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text($("#defaultvalue").select2("val"))
        }
    }
    if (config.deviceInfo.DeviceName == "IPC") {
        var cyURL = config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/2";
    } else {
        var cyURL = config.baseUrl + "/Streams/" + (config.thoroughfare - 0 + 1) + "/2";
    }
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getSubstream();
        }
    });
}

/*************************************************
 Function:        setMobilestream
 Description:     保存手机码流信息
 *************************************************/
function setMobilestream() {
    var rlWidth = $("#resolution").select2("val").split('*')[0];
    var rlHeight = $("#resolution").select2("val").split('*')[1];
    var cyXml = gs_second_stream_xml;
    $(cyXml).find('StreamConfig').eq(0).find('ResolutionWidth').eq(0).text(rlWidth);
    $(cyXml).find('StreamConfig').eq(0).find('ResolutionHeigth').eq(0).text(rlHeight);
    $(cyXml).find('StreamConfig').eq(0).find('BitrateType').eq(0).text($("#bitratecontrol").select2("val"));
    if ($("#bitratecontrol").select2("val") == "CBR") {
        if ($("#bitrate").val() == "0") {
            if ((parseInt($("#mBitrate").val()) >= 64) && (parseInt($("#mBitrate").val()) <= 2048)) {
                var reg = /^[1-9]\d*$/;
                if (!reg.test($("#mBitrate").val())) {
                    bootoast({
                        message: $.i18n.prop('i18n-inputrange'),
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return;
                } else {
                    $(cyXml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text($("#mBitrate").val());
                }
            } else {
                bootoast({
                    message: $.i18n.prop('i18n-inputrange'),
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return;
            }
        } else {
            $(cyXml).find('StreamConfig').eq(0).find('Bitrate').eq(0).text($("#defaultvalue").select2("val"))
        }
    }
    var cyURL = config.baseUrl + "/Streams/" + (inember - 0 + 1) + "/3";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getMobilestream();
        }
    });
}

// 电子围栏获取
function getelectronic() {
    $.ajax({
        url: config.baseUrl + "/System/" + (inember - 0 + 1) + "/ElectronicDenceUIDesignCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocelec = xmlDoc;
            if ($(xmlDoc).find('ElectronicDenceUIDesignCfg').eq(0).find('Enable').eq(0).text() == "true") {
                $("#enberdz").prop('checked', true)
            } else {
                $("#enberdz").prop('checked', false)
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


// 电子围栏下发
function setelectronic() {
    var cyXml = xmlDocelec;
    if ($("#enberdz").is(':checked')) {
        $(cyXml).find('ElectronicDenceUIDesignCfg').eq(0).find('Enable').eq(0).text(true)
    } else {
        $(cyXml).find('ElectronicDenceUIDesignCfg').eq(0).find('Enable').eq(0).text(false)
    }

    var cyURL = config.baseUrl + "/System/" + (inember - 0 + 1) + "/ElectronicDenceUIDesignCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getelectronic();
            getcrossdetect();
            getoffDutyDetec();
            getpassengerFlow();
        }
    });
}

// 越界侦测获取
function getcrossdetect() {
    $.ajax({
        url: config.baseUrl + "/System/" + (inember - 0 + 1) + "/CrossBorderDetectUIDesignInfo",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDoccross = xmlDoc;
            if ($(xmlDoc).find('CrossBorderDetectUIDesignInfo').eq(0).find('Enable').eq(0).text() == "true") {
                $("#enberyj").prop('checked', true)
            } else {
                $("#enberyj").prop('checked', false)
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


// 越界侦测下发
function setcrossdetect() {
    var cyXml = xmlDoccross;
    if ($("#enberyj").is(':checked')) {
        $(cyXml).find('CrossBorderDetectUIDesignInfo').eq(0).find('Enable').eq(0).text(true)
    } else {
        $(cyXml).find('CrossBorderDetectUIDesignInfo').eq(0).find('Enable').eq(0).text(false)
    }
    var cyURL = config.baseUrl + "/System/" + (inember - 0 + 1) + "/CrossBorderDetectUIDesignInfo";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getelectronic();
            getcrossdetect();
            getoffDutyDetec();
            getpassengerFlow();
        }
    });
}

// 离岗侦测获取
function getoffDutyDetec() {
    $.ajax({
        url: config.baseUrl + "/System/OffDutyDetectUIDesignCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocoffDuty = xmlDoc;
            if ($(xmlDoc).find('OffDutyDetecUIDesignCfg').eq(0).find('Enable').eq(0).text() == "true") {
                $("#enberlg").prop('checked', true)
            } else {
                $("#enberlg").prop('checked', false)
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


// 离岗侦测下发
function setoffDutyDetec() {
    var cyXml = xmlDocoffDuty;
    if ($("#enberlg").is(':checked')) {
        $(cyXml).find('OffDutyDetecUIDesignCfg').eq(0).find('Enable').eq(0).text(true)
    } else {
        $(cyXml).find('OffDutyDetecUIDesignCfg').eq(0).find('Enable').eq(0).text(false)
    }
    var cyURL = config.baseUrl + "/System/OffDutyDetectUIDesignCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getelectronic();
            getcrossdetect();
            getoffDutyDetec();
            getpassengerFlow();
        }
    });
}


// 客流统计获取
function getpassengerFlow() {
    $.ajax({
        url: config.baseUrl + "/System/PassengerFlowStatisticsUIDesignCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlflow = xmlDoc;
            if ($(xmlDoc).find('PassengerFlowStatisticsUIDesignCfg').eq(0).find('Enable').eq(0).text() == "true") {
                $("#enberkl").prop('checked', true)
            } else {
                $("#enberkl").prop('checked', false)
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


function setpassengerFlow() {
    var cyXml = xmlflow;
    if ($("#enberkl").is(':checked')) {
        $(cyXml).find('PassengerFlowStatisticsUIDesignCfg').eq(0).find('Enable').eq(0).text(true)
    } else {
        $(cyXml).find('PassengerFlowStatisticsUIDesignCfg').eq(0).find('Enable').eq(0).text(false)
    }
    var cyURL = config.baseUrl + "/System/PassengerFlowStatisticsUIDesignCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getelectronic();
            getcrossdetect();
            getoffDutyDetec();
            getpassengerFlow();
        }
    });
}

// 人脸抓拍获取
function getfacetime() {
    if (config.deviceCap[inember].FaceSnapshot != "true") {
        $("#electron").hide();
        return;
    }
    $.ajax({
        url: config.baseUrl + "/AI/FaceSnapshotCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlface = xmlDoc;
            if ($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('Enable').eq(0).text() == "true") {
                $("#enberfacezp").prop('checked', true)
            } else {
                $("#enberfacezp").prop('checked', false)
            }
            $("#zpstyle").select2("val", $(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('SnapshotMode').eq(0).text()); //抓拍模式
            $("#facecode").select2("val", $(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('FaceQuality').eq(0).text()); //人脸质量
            isFaceSnapEnable = $(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('Enable').eq(0).text();
            config.IsPushFaceFeatures = $(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('IsPushFaceFeatures').eq(0).text().toLowerCase();
            // 根据使能显示/隐藏人脸事件按钮
            if (isFaceSnapEnable == 'true') {
                $("#electron").show();
            } else {
                $("#electron").hide();
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


// 人脸抓拍下发
function setfacetronic() {
    var cyXml = xmlface;
    if ($("#enberfacezp").is(':checked')) {
        $(cyXml).find('AIFaceSnapshotCfg').eq(0).find('Enable').eq(0).text(true)
    } else {
        $(cyXml).find('AIFaceSnapshotCfg').eq(0).find('Enable').eq(0).text(false)
    }
    $(cyXml).find('AIFaceSnapshotCfg').eq(0).find('SnapshotMode').eq(0).text($("#zpstyle").select2("val"));
    $(cyXml).find('AIFaceSnapshotCfg').eq(0).find('FaceQuality').eq(0).text($("#facecode").select2("val"));
    var cyURL = config.baseUrl + "/AI/FaceSnapshotCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getfacetime();
        }
    });
}


/*************************************************
 Function:        getMotionSchedule
 Description:     获取motioSchedulen信息 ChannelID是个变量
 *************************************************/
function getMotionSchedule() {
    $.ajax({
        url: config.baseUrl + "/FaceReco/1/RecoRuleList",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            xmlFaceReco = xmlDoc;
            if (localStorage.getItem("rule") == "0") { //白名单
                $("#facerule").select2("val", "0");
                if ($(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Enable').eq(0).text() == "true") {
                    $("#enberfacesb").prop('checked', true)
                } else {
                    $("#enberfacesb").prop('checked', false)
                }
                $("#facethreshold").val($(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('RecoThresholdScheduleList').eq(0).find('RecoThresholdSchedule').eq(0).find('RecoThreshold').eq(0).text())

                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('NotifyAMS').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('BeepAlert').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('FullScreen').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('Ftp').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('Push').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('Mail').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('AlarmOut').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('AlarmOut').eq(0).find('AlarmOutMask').text(); //联动项目
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('Snapshot').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('Snapshot').eq(0).find('SnapshotMask').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('Record').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Trigger').eq(0).find('PTZ').eq(0).find('Enable').text();


            } else if (localStorage.getItem("rule") == "1") { //黑名单
                $("#facerule").select2("val", "1");
                if ($(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Enable').eq(0).text() == "true") {
                    $("#enberfacesb").prop('checked', true)
                } else {
                    $("#enberfacesb").prop('checked', false)
                }
                $("#facethreshold").val($(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('RecoThresholdScheduleList').eq(0).find('RecoThresholdSchedule').eq(0).find('RecoThreshold').eq(0).text())

                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('NotifyAMS').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('BeepAlert').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('FullScreen').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('Ftp').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('Push').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('Mail').eq(0).find('Enable').text();
                var AlarmOutenble = $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('AlarmOut').eq(0).find('Enable').text(); //报警输出
                var AlarmOutMask = $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('AlarmOut').eq(0).find('AlarmOutMask').text(); //联动项目
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('Snapshot').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('Snapshot').eq(0).find('SnapshotMask').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('Record').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Trigger').eq(0).find('PTZ').eq(0).find('Enable').text();

                if (AlarmOutenble == "true" && AlarmOutMask.indexOf("1") != -1) {
                    $("#linkagedoor").prop('checked', true)
                }


            } else if (localStorage.getItem("rule") == "2") { //未注册
                $("#facerule").select2("val", "2");
                if ($(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Enable').eq(0).text() == "true") {
                    $("#enberfacesb").prop('checked', true)
                } else {
                    $("#enberfacesb").prop('checked', false)
                }
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('NotifyAMS').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('BeepAlert').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('FullScreen').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('Ftp').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('Push').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('Mail').eq(0).find('Enable').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('AlarmOut').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('AlarmOut').eq(0).find('AlarmOutMask').text(); //联动项目
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('Snapshot').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('Snapshot').eq(0).find('SnapshotMask').text();
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('Record').eq(0).find('Enable').text(); //报警输出
                $(xmlDoc).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Trigger').eq(0).find('PTZ').eq(0).find('Enable').text();

            }


        },
        error: function(xhr, textStatus, errorThrown) {}
    })
}



// 人脸识别下发
function setMotionSchedule() {
    var cyXml = xmlFaceReco;
    if (localStorage.getItem("rule") == "0") { //白名单
        if ($("#enberfacesb").is(':checked')) {
            $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Enable').eq(0).text(true)
        } else {
            $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('Enable').eq(0).text(false)
        }
        $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(0).find('RecoThresholdScheduleList').eq(0).find('RecoThresholdSchedule').eq(0).find('RecoThreshold').eq(0).text($("#facethreshold").val())
    } else if (localStorage.getItem("rule") == "1") { //黑名单
        if ($("#enberfacesb").is(':checked')) {
            $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Enable').eq(0).text(true)
        } else {
            $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('Enable').eq(0).text(false)
        }
        $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(1).find('RecoThresholdScheduleList').eq(0).find('RecoThresholdSchedule').eq(0).find('RecoThreshold').eq(0).text($("#facethreshold").val())
    } else if (localStorage.getItem("rule") == "2") { //未注册
        if ($("#enberfacesb").is(':checked')) {
            $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Enable').eq(0).text(true)
        } else {
            $(cyXml).find('RecoRuleList').eq(0).find('RecoRule').eq(2).find('Enable').eq(0).text(false)
        }
    }
    var cyURL = config.baseUrl + "/FaceReco/1/RecoRuleList";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            getMotionSchedule();
        }
    });
}


function PTZControl(param, cmd, speed) {
    var cyXml = "Param1=" + param + "&Param2=" + speed;

    var channel = 1;
    if (config.deviceInfo.DeviceName == "NVR") {
        channel = config.thoroughfare - 0 + 1
    }
    var cyURL = config.baseUrl + "/PTZ/" + channel + "/" + cmd;
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function() {}
    });
}


//获取算法仓库配置
function getAlgorithmStoreCf() {
    var cyURL = config.baseUrl + "/System/AlgorithmStoreCfg";
    $.ajax({
        url: cyURL,
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            var type = $(xmlDoc).find('AlgorithmStoreCfg').eq(0).find('AlgorithmType').eq(0).text();
            $("#algorithmselect").select2("val", type);
            if ("FaceRecognition" == $("#algorithmselect").val()) {
                $(".FaceReco").hide();
                $(".FaceSnapshotCfg").hide();
                // getMotionSchedule();
            } else {
                $(".FaceSnapshotCfg").show();
                $(".FaceReco").hide();
                getfacetime();
            }
        },
        error: function(xhr) {

        }
    })
}


// 下发算法仓库配置
function setAlgorithmStoreCf(current) {
    var cyXml = "<AlgorithmStoreCfg><AlgorithmType>" + current + "</AlgorithmType><AlgorithmStoreCfg>";
    $.ajax({
        type: "PUT",
        url: config.baseUrl + "/System/AlgorithmStoreCfg",
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xhr) {
            var xmlDoc = xhr.responseXML;
            var state = $(xmlDoc).find("statusCode").eq(0).text();
            if ("0" == state) {
                if (current == "FaceRecognition") {
                    bootoast({
                        message: $.i18n.prop('i18n-savesuccess'),
                        type: 'success',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                } else {
                    setfacetronic();
                }
                getAlgorithmStoreCf();

            } else {
                bootoast({
                    message: $.i18n.prop('i18n-savefail'),
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
            }
        },
    });
}


//查询所有脸库作为查询条件之一
function faceGroupsQueryAll() {
    var cyURL = window.config.baseUrl + "/FaceGroups/QueryAll";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                xhr.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(xmlDoc, textStatus, xhr) { //在这里获取所有人脸库的值并且渲染页面
            recordlistData = []; //数组重置
            var xmlDocobj = parseXmlFromStr(xmlDoc);
            var statusflg = $(xmlDocobj).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if ("401" == statusflg) {
                top.location.href = "/";
            }
            var sl = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').length;
            for (var i = 0; i < sl; i++) {
                var faceGroupobj = {};
                faceGroupobj.GroupName = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('GroupName').text();
                faceGroupobj.GroupID = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('GroupID').text();
                recordlistData.push(faceGroupobj);
            }

        },
        error: function(xhr, textStatus, errorThrown) {
            if ("401" == xhr.status) {
                top.location.href = "/";
            }
        }
    });
}

// 获取车牌配置（只用使能）
function getCarPlateSnap() {
    if (config.deviceCap[inember].carSupport != "true") {
        // $("#carctron").hide();
        // return;
        getCarctronDeploySnap(false);
        return;
    }
    $.ajax({
        url: window.config.baseUrl + "/AI/CarPlateSnap",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            isCarPlateSnapEnable = $(xmlDoc).find('CarPlateSnapCfg').eq(0).find('Enable').eq(0).text();
            // 根据使能显示/隐藏车牌抓拍按钮
            if (isCarPlateSnapEnable == 'true') {
                $("#carctron").show();
                getCarctronDeploySnap(true)
            } else {
                // $("#carctron").hide();
                getCarctronDeploySnap(false)
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


// 获取车牌布控配置（只用使能）
function getCarctronDeploySnap(ishow) {
    if (config.deviceCap[inember].lincenPlate != "true") {
        $("#carctron").hide();
        return;
    }
    $.ajax({
        url: window.config.baseUrl + "/System/LicensePlateSurveillanceUIDesignCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            isCarctronSnapenable = $(xmlDoc).find('LicensePlateSurveillanceUIDesignCfg').eq(0).find('Enable').eq(0).text();
            if (!ishow) {
                if (isCarctronSnapenable == 'true') {
                    $("#carctron").show();
                } else {
                    $("#carctron").hide();
                }
            }
        },
        error: function(xhr, textStatus, errorThrown) {

        }
    });
}


// 绘制3D框
// Canvas鼠标交互记录器 - ES5语法，兼容IE10+（无网格背景）
function CanvasDrawRecorder(canvasId) {
    if (!(this instanceof CanvasDrawRecorder)) {
        return new CanvasDrawRecorder(canvasId);
    }

    // 属性定义
    this.canvas = document.getElementById(canvasId);
    if (!this.canvas) {
        throw new Error('Canvas with id "' + canvasId + '" not found');
    }

    this.ctx = this.canvas.getContext('2d');
    this.isDrawing = false;
    this.startX = 0;
    this.startY = 0;
    this.currentX = 0;
    this.currentY = 0;
    // this.records = [];
    // 设置绘制canvas为可穿透点击
    this.canvas.style.pointerEvents = 'auto';
    var self = this;

    // 初始化
    this.resizeCanvas();

    // 绑定事件
    this.bindEvents();

    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        self.resizeCanvas();
    });
}

// 调整Canvas尺寸为实际显示尺寸
CanvasDrawRecorder.prototype.resizeCanvas = function() {
    var videoCanvas;
    if(sessionStorage.getItem("playstyle") == "WebPlayer"){
        videoCanvas = document.getElementById('playCanvas');
    }else{
        videoCanvas = document.getElementById('axdiv');
    }

    if (videoCanvas) {
        var rect = videoCanvas.getBoundingClientRect();
        this.canvas.width = rect.width;
        this.canvas.height  = rect.height;
        this.canvas.style.width = rect.width + 'px';
        this.canvas.style.height = rect.height + 'px';
    }
    this.clearCanvas();
};

// 清除画布
CanvasDrawRecorder.prototype.clearCanvas = function() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
};

// 绑定事件
CanvasDrawRecorder.prototype.bindEvents = function() {
    var self = this;

    this.canvas.addEventListener('mousedown', function(e) {
        self.handleMouseDown(e);
    });

    this.canvas.addEventListener('mousemove', function(e) {
        self.handleMouseMove(e);
    });

    this.canvas.addEventListener('mouseup', function(e) {
        self.handleMouseUp(e);
    });

};

// 修改事件处理，确保坐标正确
CanvasDrawRecorder.prototype.handleMouseDown = function(e) {
    var videoCanvas;
    if(sessionStorage.getItem("playstyle") == "WebPlayer"){
        videoCanvas = document.getElementById('playCanvas');
    }else{
        videoCanvas = document.getElementById('axdiv');
    }
    var rect = videoCanvas ? videoCanvas.getBoundingClientRect() : this.canvas.getBoundingClientRect();

    this.startX = e.clientX - rect.left;
    this.startY = e.clientY - rect.top;
    this.isDrawing = true;

    this.clearCanvas();
    this.drawPoint(this.startX, this.startY, '#FF0000');
};

CanvasDrawRecorder.prototype.handleMouseMove = function(e) {
    if (!this.isDrawing) return;

    var videoCanvas;
    if(sessionStorage.getItem("playstyle") == "WebPlayer"){
        videoCanvas = document.getElementById('playCanvas');
    }else{
        videoCanvas = document.getElementById('axdiv');
    }
    var rect = videoCanvas ? videoCanvas.getBoundingClientRect() : this.canvas.getBoundingClientRect();

    this.currentX = e.clientX - rect.left;
    this.currentY = e.clientY - rect.top;

    this.clearCanvas();
    this.drawRectangle(this.startX, this.startY, this.currentX, this.currentY);
    this.drawPoint(this.startX, this.startY, '#FF0000');
    this.drawPoint(this.currentX, this.currentY, '#FF0000');
};

// 鼠标释放事件
CanvasDrawRecorder.prototype.handleMouseUp = function(e) {
    if (!this.isDrawing) return;

    var rect = this.canvas.getBoundingClientRect();
    this.currentX = e.clientX - rect.left;
    this.currentY = e.clientY - rect.top;

    // 判断操作类型
    var actionType = this.determineActionType();

    // 记录坐标信息
    this.recordCoordinates(actionType);

    // 清除临时绘制
    this.clearCanvas();

    this.isDrawing = false;
};



// 绘制矩形
CanvasDrawRecorder.prototype.drawRectangle = function(x1, y1, x2, y2) {
    var rectX = Math.min(x1, x2);
    var rectY = Math.min(y1, y2);
    var rectWidth = Math.abs(x2 - x1);
    var rectHeight = Math.abs(y2 - y1);

    // 设置矩形样式
    this.ctx.strokeStyle = '#33FF00';
    this.ctx.lineWidth = 2;
    // this.ctx.fillStyle = 'red';

    // 绘制矩形
    // this.ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
    this.ctx.strokeRect(rectX, rectY, rectWidth, rectHeight);

    // 绘制中心点
    var centerX = rectX + rectWidth / 2;
    var centerY = rectY + rectHeight / 2;
    this.drawPoint(centerX, centerY, '#FF0000', 2);
};

// 绘制点
CanvasDrawRecorder.prototype.drawPoint = function(x, y, color, size) {
    if (typeof size === 'undefined') {
        size = 2;
    }

    this.ctx.fillStyle = color;
    this.ctx.beginPath();
    this.ctx.arc(x, y, size, 0, 360);
    this.ctx.fill();
};

// 判断操作类型
CanvasDrawRecorder.prototype.determineActionType = function() {
    var distance = Math.sqrt(
        Math.pow(this.currentX - this.startX, 2) +
        Math.pow(this.currentY - this.startY, 2)
    );

    // 如果移动距离很小，认为是点击
    if (distance < 2) {
        return 0;
    }

    // 根据Y轴移动方向判断放大/缩小
    return this.currentY > this.startY ? 2 : 1;
};

// 记录坐标信息
CanvasDrawRecorder.prototype.recordCoordinates = function(actionType) {
    if (actionType === 0) {
        // 点击操作，只记录一个点
        var record = {
            type: 0,
            startPoint: {
                x: this.startX,
                y: this.startY
            },
            endPoint: {
                x: this.startX,
                y: this.startY
            },
            topLeft: {
                x: this.startX,
                y: this.startY
            },
            topRight: {
                x: this.startX,
                y: this.startY
            },
            bottomLeft: {
                x: this.startX,
                y: this.startY
            },
            bottomRight: {
                x: this.startX,
                y: this.startY
            },
            centerPoint: {
                x: this.startX,
                y: this.startY
            },
            timestamp: new Date().toISOString(),
            // id: this.records.length + 1
        };
        // this.records.push(record);
        this.onRecordCreated(record);
        return;
    }

    // 矩形操作，记录四个顶点和中心点
    var rectX = Math.min(this.startX, this.currentX);
    var rectY = Math.min(this.startY, this.currentY);
    var rectWidth = Math.abs(this.currentX - this.startX);
    var rectHeight = Math.abs(this.currentY - this.startY);

    var record = {
        type: actionType,
        startPoint: {
            x: this.startX,
            y: this.startY
        },
        endPoint: {
            x: this.currentX,
            y: this.currentY
        },
        topLeft: {
            x: rectX,
            y: rectY
        },
        topRight: {
            x: rectX + rectWidth,
            y: rectY
        },
        bottomLeft: {
            x: rectX,
            y: rectY + rectHeight
        },
        bottomRight: {
            x: rectX + rectWidth,
            y: rectY + rectHeight
        },
        centerPoint: {
            x: rectX + rectWidth / 2,
            y: rectY + rectHeight / 2
        },
        width: rectWidth,
        height: rectHeight,
        timestamp: new Date().toISOString(),
        // id: this.records.length + 1
    };

    // this.records.push(record);
    this.onRecordCreated(record);
};

// 记录创建时的回调
CanvasDrawRecorder.prototype.onRecordCreated = function(record) {
    console.log('坐标记录已创建:', record);

    // 兼容IE的CustomEvent实现
    var event;
    try {
        if (typeof CustomEvent === 'function') {
            // 现代浏览器
            event = new CustomEvent('canvasRecordCreated', {
                detail: record
            });
        } else {
            // IE兼容
            event = document.createEvent('CustomEvent');
            event.initCustomEvent('canvasRecordCreated', false, false, record);
        }
        this.canvas.dispatchEvent(event);
    } catch (error) {
        // 如果CustomEvent也不支持，使用传统事件
        console.warn('CustomEvent not supported, using fallback');
        var fallbackEvent = document.createEvent('Event');
        fallbackEvent.initEvent('canvasRecordCreated', false, false);
        fallbackEvent.detail = record;
        this.canvas.dispatchEvent(fallbackEvent);
    }
};






