var lmd = ['high', 'middle', 'low'];
var sylx = ['custom', 'alarm', 'dog', 'warning area', 'monitoring area', 'welcome', 'Deep Water Warning', 'Private territory', 'danger zone', 'Valuable objects', 'High Warning', 'Private Parking']
var bcs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var bcm = ['5', '10', '20', '30'];
var imgindex, xmlDocmotiontetect, xmlAudioAlarmConfig, xmlDocPolygon;
var menbfrx = 9999 / 560;
var menbfry = 9999 / 420;
var newPointList;
var newLineList = [];
var newPersonList = [];
var pum; //保留边数
var timeplaned, timeplandvoice;
var xhrState;
var motionD = true;
var ktrgleFour = [{
    x: 80,
    y: 80
}, {
    x: 250,
    y: 80
}, {
    x: 250,
    y: 200
}, {
    x: 80,
    y: 200
}]
var trgle = [{
    x: 30,
    y: 30
}, {
    x: 200,
    y: 30
}, {
    x: 30,
    y: 200
}]; //三角形默认位置
var trgleFour = [{
    x: 30,
    y: 30
}, {
    x: 300,
    y: 30
}, {
    x: 300,
    y: 200
}, {
    x: 30,
    y: 200
}]; //四边形默认位置
var trgleFive = [{
    x: 180,
    y: 30
}, {
    x: 30,
    y: 130
}, {
    x: 60,
    y: 250
}, {
    x: 300,
    y: 250
}, {
    x: 330,
    y: 130
}]; //五边形默认位置
var trgleSex = [{
    x: 30,
    y: 30
}, {
    x: 300,
    y: 30
}, {
    x: 300,
    y: 50
}, {
    x: 150,
    y: 50
}, {
    x: 150,
    y: 100
}, {
    x: 30,
    y: 100
}]; //六边形默认位置
var trgleSeven = [{
    x: 60,
    y: 100
}, {
    x: 100,
    y: 70
}, {
    x: 200,
    y: 80
}, {
    x: 250,
    y: 160
}, {
    x: 200,
    y: 220
}, {
    x: 100,
    y: 200
}, {
    x: 50,
    y: 150
}]; //七边形默认位置
var trgleEight = [{
    x: 100,
    y: 50
}, {
    x: 300,
    y: 50
}, {
    x: 300,
    y: 100
}, {
    x: 250,
    y: 100
}, {
    x: 250,
    y: 150
}, {
    x: 150,
    y: 150
}, {
    x: 150,
    y: 100
}, {
    x: 100,
    y: 100
}, ]; //八边形默认位置
$(document).ready(function() {
    motionLink();
    ScalePitch("box-border");
    // 监听滚动条滚动改变easyvideo位置
    $(".facezgun").scroll(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash.indexOf("#ipc/pages/events/motionDetection.html")!==-1 && sessionStorage.getItem('dpiRadio') != null) {
                if (motionD) {
                    var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                    if (pt.Top > 80) {
                        preHiddenDisplaywindow(5);
                        preWindowfollowing(true);
                    } else {
                        preHiddenDisplaywindow(4);
                    }
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/events/motionDetection.html") {
                if (motionD) {
                    var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                    if (pt.Top > 127) {
                        preHiddenDisplaywindow(5);
                        preWindowfollowing(true);
                    } else {
                        preHiddenDisplaywindow(4);
                    }
                }
            }
        }
    });

    $("#sensitivity,#DefensePlan,#FrequencyBroadcast,#deploymentTime,#FrequencyDelay").select2({
        minimumResultsForSearch: -1,
        width: 360,
    });
    $("#SoundType").select2({
        minimumResultsForSearch: -1,
        width: 320,
    });

    // 初始化时间选择
    var mq = $("#recordDiv").TimePlan({
        sectionNum: 6
    });
    var mh = $("#Broadcast").TimePlan({
        sectionNum: 6
    });
    timeplaned = mq;
    timeplandvoice = mh;
    selectvalue();
    changeTab(); //进来默认点击
    // 切换栏目
    $("#place").click(function() {
        motionD = true;
        config.dzld = false
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(5)
        }
        changeTab()
    });
    $("#liand").click(function() {
        motionD = false;
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        config.dzld = true
        var qu = document.getElementById('place')
        var ld = document.getElementById('liand')
        ld.classList.add('qutable')
        qu.classList.remove('qutable')
        $("#LinkageMode").show()
        $("#Regional").hide()
    });
    // 是否展示时间控件
    $('#DefensePlan').change(function(v) {
        if (v.val == 'false') {
            $('#recordDiv').show()
        } else {
            $('#recordDiv').hide()
        }
    });
    $('#deploymentTime').change(function(v) {
        if (v.val == 'false') {
            $('#Broadcast').show()
        } else {
            $('#Broadcast').hide()
        }
    });
    $('#chuBeepAlert').change(function() {
        if ($(this).is(':checked') == false) {
            $(".lgelecheck").hide();
        } else {
            $(".lgelecheck").show();
        }
    });
    if (config.deviceCap.motionAudio == "true") {
        $(".lgelecheck").show();
    } else {
        $(".lgelecheck").hide();
    }

    // 清除区域
    $("#clearbtn").click(function() { //清除区域
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            PolygonConfigFautil(2, 2, imgindex);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            PolygonProtectionControl(5, 0, ""); //清除现有多边形
            PolygonProtectionControl(2, imgindex, ""); //重新设置多边形
        } else {
            var c = document.getElementById("myCanvas");
            c.width = c.width
        }
    });
    if (config.devicelose) {
        addEventListener("resize", function(event) {});
    }

    $(window).resize(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (window.location.hash.indexOf("#ipc/pages/events/motionDetection.html")!==-1 && sessionStorage.getItem('dpiRadio') != null) {
                ScalePitch("box-border");
                if (motionD) {
                    preWindowfollowing();
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/events/motionDetection.html") {
                ScalePitch("box-border");
                if (motionD) {
                    preWindowfollowing();
                }
            } else if (window.location.hash == "#ipc/pages/events/motionDetection.html" && sessionStorage.getItem("playstyle") == "MJPEG") {
                ScalePitch("box-border")
                getRegionCfg()
            } else if (window.location.hash == "#ipc/pages/events/motionDetection.html" && sessionStorage.getItem("playstyle") == "WebPlayer") {
                ScalePitch("box-border")
                getRegionCfg()
            }
        }
    });

    // 选择旁边的预定义区域
    $("#motionpolygonimg li img").click(function(e) {
        var imgindex = $(this).attr("imgindex");
        for (var i = 0; i < $("#motionpolygonimg li img").length; i++) {
            if (i + 3 == imgindex) {
                continue
            } else {
                $("#motionpolygonimg li img")[i].src = "ipc/img/eventTips/xz_mr_0" + (i + 1) + ".png"
            }
        }
        $(this).attr("src", "ipc/img/eventTips/xz_xz_0" + (imgindex - 2) + ".png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            PolygonConfigFautil(2, 3, imgindex);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            PolygonProtectionControl(5, 1, ""); //清除
            PolygonProtectionControl(2, imgindex, "");
        } else {
            if (imgindex == 4) {
                for (var i = 0; i < trgleFour.length; i++) {
                    trgleFour[i].x = Math.floor(trgleFour[i].x * 100 / getRatio())
                    trgleFour[i].y = Math.floor(trgleFour[i].y * 100 / getRatio())
                }
                createdPitch(trgleFour, "myCanvas")
            } else if (imgindex == 3) {
                for (var i = 0; i < trgle.length; i++) {
                    trgle[i].x = Math.floor(trgle[i].x * 100 / getRatio())
                    trgle[i].y = Math.floor(trgle[i].y * 100 / getRatio())
                }
                createdPitch(trgle, "myCanvas")
            } else if (imgindex == 5) {
                for (var i = 0; i < trgleFive.length; i++) {
                    trgleFive[i].x = Math.floor(trgleFive[i].x * 100 / getRatio())
                    trgleFive[i].y = Math.floor(trgleFive[i].y * 100 / getRatio())
                }
                createdPitch(trgleFive, "myCanvas")
            } else if (imgindex == 6) {
                for (var i = 0; i < trgleSex.length; i++) {
                    trgleSex[i].x = Math.floor(trgleSex[i].x * 100 / getRatio())
                    trgleSex[i].y = Math.floor(trgleSex[i].y * 100 / getRatio())
                }
                createdPitch(trgleSex, "myCanvas")
            } else if (imgindex == 7) {
                for (var i = 0; i < trgleSeven.length; i++) {
                    trgleSeven[i].x = Math.floor(trgleSeven[i].x * 100 / getRatio())
                    trgleSeven[i].y = Math.floor(trgleSeven[i].y * 100 / getRatio())
                }
                createdPitch(trgleSeven, "myCanvas")
            } else {
                for (var i = 0; i < trgleEight.length; i++) {
                    trgleEight[i].x = Math.floor(trgleEight[i].x * 100 / getRatio())
                    trgleEight[i].y = Math.floor(trgleEight[i].y * 100 / getRatio())
                }
                createdPitch(trgleEight, "myCanvas")
            }

        }
    });
    // 点击试听按钮
    $("#motionbtn").click(function() {
        setTryvoice('Motion')
    });
    // 点击保存
    $("#chusave,#svhusave").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            var timeArrp = takeZero(mq.getvalue()); //普通布防
            var timeArr = takeZero(mh.getvalue()); //声音布防
            setMotionconfig(timeArrp, timeArr);
            setRegionCfg();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }

    })
    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
   if (g_bIsIE&&!config.forceEV) {
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            $("#playCanvas").hide();
            $("#axdiv").show();
            clearInterval(config.gs_interval);
        } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
            $("#playCanvas").hide();
            $("#axdiv").show();
            $("#axdiv").empty();
            clearInterval(config.gs_interval)
        }
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
        SetActiveXMode(1);
        getMotionconfig(mq, mh); //进来获取配置
        setTimeout(function() {
            getRegionCfg();
        }, 100)
    } else {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            config.refreshplayvideo = true;
            $("#playCanvas").hide();
            $("#axdiv").show();
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 5);
            getMotionconfig(mq, mh); //进来获取配置
            getRegionCfg();
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                $("#playCanvas").hide();
                $("#axdiv").show();
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                $("#playCanvas").show();
                $("#axdiv").hide();
                if (self.player) {
                    if (sessionStorage.getItem("stream") == "codestream1") {
                        self.player.stop("sub1");
                    } else {
                        self.player.stop("sub2");
                    }
                }

            } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("#axdiv").empty();
                clearInterval(config.gs_interval)
            }

            if (config.refreshplayvideo) {
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 5);
                getMotionconfig(mq, mh); //进来获取配置
                if (config.devicelose == false || sessionStorage.getItem("playstyle") != "EasyVideo") {
                    getRegionCfg();
                }

            } else {
                if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                    $("#downloadeasyplay").hide();
                    if (config.playMode.indexOf("WebPlayer")!==-1) {
                        $.getScript("js/webPlayer/player.js", function() { //请求成功后的回调函数
                            $.getScript("js/webPlayer/webgl.js", function() { //请求成功后的回调函数
                                $.getScript("js/webPlayer/pcm-player.js", function() {
                                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
                                    getMotionconfig(mq, mh); //进来获取配置
                                    getRegionCfg();
                                });
                            });
                        });
                    }
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    refershPlayer("motion")
                    getMotionconfig(mq, mh); //进来获取配置
                } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
                    getMotionconfig(mq, mh); //进来获取配置
                    getRegionCfg();
                }

            }
        }
    }

});

function motionLink() {
    $(".email").toggle(config.deviceCap.motionEmail == "true");
    $(".isChuTriggerpush").toggle(config.deviceCap.motionPush == "true");
    $(".isChuBeepAlert").toggle(config.deviceCap.motionAudio == "true");
    $(".isChuftp").toggle(config.deviceCap.motionFtp == "true");
    $(".isChuAlarmOut").toggle(config.deviceCap.motionAlarmOut == "true");
    $(".isSD").toggle(config.deviceCap.diskEnable == "true");

    if (config.deviceAiCap.ControlModeText == '' || config.deviceAiCap.ControlModeText == 'Duration') {
        $(".Frequency-broadcast").toggle(false);
        $(".Delay-time").toggle(true);
    } else {
        $(".Frequency-broadcast").toggle(true);
        $(".Delay-time").toggle(false);
    }
}
// 栏目切换
function changeTab() {
    var qu = document.getElementById('place')
    var ld = document.getElementById('liand')
    qu.classList.add('qutable')
    ld.classList.remove('qutable')
    $("#Regional").show()
    $("#LinkageMode").hide()
}
// 初始化下拉框数据
function selectvalue() {
    $("<option value='true'>" + $.i18n.prop("i18n-allday") + "</option>").appendTo("#DefensePlan");
    $("<option value='false'>" + $.i18n.prop("i18n-customize") + "</option>").appendTo("#DefensePlan");
    var ni = $.i18n.prop("i18n-sensitivity-value").split(",")
    for (var i = 0; i < ni.length; i++) {
        $("<option value='" + lmd[i] + "'>" + ni[i] + "</option>").appendTo("#sensitivity");
    }
    // 声音类型
    if (config.deviceAiCap.voiceAlarmint == 'true') {
        soundType('SoundType', config.deviceCap.AudioAlarmType);
    } else {
        soundType('SoundType', config.deviceCap.ydzcAudioAlarmType);
    }


    // 播报次数
    var bc = $.i18n.prop("i18n-broadcast").split(",")
    for (var i = 0; i < bc.length; i++) {
        $("<option value='" + bcs[i] + "'>" + bc[i] + "</option>").appendTo("#FrequencyBroadcast");
    }

    // 延长时间
    var bm = $.i18n.prop("i18n-broadcast-miao").split(",")
    for (var i = 0; i < bm.length; i++) {
        $("<option value='" + bcm[i] + "'>" + bm[i] + "</option>").appendTo("#FrequencyDelay");
    }
}
//试听
function setTryvoice(v) {
    var voiceXmldoc = '<?xml version="1.0" encoding="UTF-8" ?>' +
        "<AudioAlarmConfig><ChannelID>1</ChannelID>" +
        "<PeopleAudioType></PeopleAudioType><CarAudio></CarAudio>" +
        "<FireAudioType></FireAudioType><AudioOutputDelay></AudioOutputDelay>" +
        "<AudioVolume></AudioVolume>" +
        "<TryListenType>" + v + "</TryListenType>" +
        "<AlarmInExAudioType></AlarmInExAudioType>" +
        "<VideoShelterAudioType></VideoShelterAudioType>" +
        "<MotionAudioType>" + $("#SoundType").val() + "</MotionAudioType>" +
        "<ElectronicDenceAudioType></ElectronicDenceAudioType>" +
        "<CrossBorderDetectAudioType></CrossBorderDetectAudioType>" +
        "<OffDutyDetectAudioType></OffDutyDetectAudioType>" +
        "</AudioAlarmConfig>"
    var cyURL = window.config.baseUrl + "/System/1/TryListenSelectedAlarmAudioV1";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: voiceXmldoc,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
        }
    });
}
// 获取移动侦测配置
function getMotionconfig(mq, mh) {
    $.ajax({
        url: window.config.baseUrl + "/Pictures/1/Motion",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocmotiontetect = xmlDoc;
            $("#sensitivity").val($(xmlDoc).find('Motion').eq(0).find('Senstive').eq(0).text()).trigger('change');
            $("#motionCheck").prop('checked', JSON.parse($(xmlDoc).find('Motion').eq(0).find('Enable').eq(0).text()));
            $("#DefensePlan").val($(xmlDoc).find('Motion').eq(0).find('AllDay').eq(0).text()).trigger('change'); //普通布防
            if ($("#DefensePlan").val() == 'false') {
                $("#recordDiv").show()
            } else {
                $("#recordDiv").hide()
            }
            // 联动
            $("#chudpick").prop('checked', JSON.parse($(xmlDoc).find("Snapshot").find("Enable").text())); //触发sd卡抓图
            $("#chudvdeo").prop('checked', JSON.parse($(xmlDoc).find("Record").find("Enable").text())); //触发sd卡录像
            $("#chuBeepAlert").prop('checked', JSON.parse($(xmlDoc).find('Motion').eq(0).find('BeepAlert').eq(0).find('Enable').text())); //触发声音报警
            if ($("#chuBeepAlert").is(':checked') == false) {
                $(".lgelecheck").hide();
            } else {
                $(".lgelecheck").show();
            }
            $("#chuAlarmOut").prop('checked', JSON.parse($(xmlDoc).find('Motion').eq(0).find('AlarmOut').eq(0).find('Enable').text())); //触发报警输出
            $("#chuemail").prop('checked', JSON.parse($(xmlDoc).find("Mail").find("Enable").text())); //触发邮件
            $("#chuftp").prop('checked', JSON.parse($(xmlDoc).find("Ftp").find("Enable").text())); //触发FTP
            $("#chuTriggerpush").prop('checked', JSON.parse($(xmlDoc).find("Push").find("Enable").text())); //触发推送
            setScheduleXp(xmlDoc, mq);
            if (config.deviceAiCap.voiceAlarmint == 'false') { //按次数
                // 声音报警
                $("#SoundType").val($(xmlDoc).find('Motion').eq(0).find('VoiceType').eq(0).text()).trigger('change'); //声音报警类型
                $("#FrequencyBroadcast").val($(xmlDoc).find('Motion').eq(0).find('BroadcastCount').eq(0).text()).trigger('change'); //播报次数
                var o = $(xmlDoc).find('Motion').eq(0).find('DayMode').eq(0).text(); //声音报警布防时间
                if (o == "disable") {
                    $("#deploymentTime").val($(xmlDoc).find('Motion').eq(0).find('AllDay').eq(1).text()).trigger('change');
                } else {
                    $("#deploymentTime").val(o).trigger('change')
                }
                // 声音报警布防时间
                if ($("#deploymentTime").val() == 'false') {
                    $("#Broadcast").show()
                } else {
                    $("#Broadcast").hide()
                }
                setScheduleX(1, xmlDoc, mh);
            } else {
                getAudioAlarmConfig();
                getAlarmSchedule(mh);
            }

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


function getAudioAlarmConfig() {
    $.ajax({
        url: window.config.baseUrl + "/System/AudioAlarmConfig",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlAudioAlarmConfig = xmlDoc;
            // 声音报警
            $("#SoundType").val($(xmlDoc).find('Type').eq(0).text()).trigger('change'); //声音报警类型
            $("#FrequencyDelay").val($(xmlDoc).find('Delay').eq(0).text() + '').trigger('change'); //播报次数
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function getAlarmSchedule(mh) {
    $.ajax({
        url: window.config.baseUrl + "/Alarm/1/AlarmSchedule",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocpeopletetect = xmlDoc;
            var o = $(xmlDoc).find('DayMode').eq(0).text(); //声音报警布防时间
            if (o == "disable") {
                $("#deploymentTime").val($(xmlDoc).eq(0).find('AllDay').eq(0).text()).trigger('change');
            } else {
                $("#deploymentTime").val(o).trigger('change')
            }
            // 声音报警布防时间
            if ($("#deploymentTime").val() == 'false') {
                $("#Broadcast").show()
            } else {
                $("#Broadcast").hide()
            }

            setScheduleX(0, xmlDoc, mh);
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 获取布防区域
function getRegionCfg() {
    $.ajax({
        url: window.config.baseUrl + "/Alarm/1/PolygonConfig",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocPolygon = xmlDoc
            var pointnum = $(xmlDoc).find("PolygonLineNum").text();
            imgindex = pointnum;
            var urlImage = "ipc/img/eventTips/xz_xz_0" + (pointnum - 2) + ".png"
            $("#motionpolygonimg li img").each(function() {
                if ($(this).attr("imgindex") == pointnum) {
                    $(this).attr("src", urlImage);
                };
            });
            var str = "";
            if (sessionStorage.getItem("playstyle") == "ActiveX") { //使用老插件画框
                for (i = 1; i <= pointnum; i++) {
                    str += '<Point' + i + '_X>' + $(xmlDoc).find('Point').eq(i - 1).find('PosX').text() + '</Point' + i + '_X><Point' + i + '_Y>' + $(xmlDoc).find('Point').eq(i - 1).find('PosY').text() + '</Point' + i + '_Y>'
                };
                var xml = '<?xml version="1.0" encoding="UTF-8"?><PolygonProtection>' +
                    '<PolygonCount>1</PolygonCount><Flags>0</Flags><PolygonList><Polygon1><EdgesCount>' + pointnum + '</EdgesCount>' +
                    '<Vertexes>' + str + '</Vertexes>' +
                    '</Polygon1>' +
                    '</PolygonList>' +
                    '</PolygonProtection>'
                PolygonProtectionControl(1, 0, xml);
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") { //使用easyVideo画框
                var xArr = []
                var yArr = []
                for (var o = 0; o < pointnum; o++) {
                    xArr.push($(xmlDoc).find('Point').eq(o).find('PosX').text() - 0)
                    yArr.push($(xmlDoc).find('Point').eq(o).find('PosY').text() - 0)
                }
                PolygonConfig(2, pointnum, xArr, yArr);
            } else { //不使用插件画框
                var lineChse = []
                for (var i = 0; i < pointnum; i++) {
                    var obj = {
                        x: "",
                        y: ""
                    }
                    var a = $(xmlDoc).find('Point').eq(i).find('PosX').text() - 0;
                    var b = $(xmlDoc).find('Point').eq(i).find('PosY').text() - 0;
                    obj.x = Math.floor((a / menbfrx) * 100 / getRatio());
                    obj.y = Math.floor((b / menbfry) * 100 / getRatio());
                    lineChse.push(obj);
                }
                createdPitch(lineChse, "myCanvas");
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
};
// 设置声音报警布防区域
function setScheduleX(nmb, d, btimecaset) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('TimeBlock_' + i).eq(nmb).text()
        for (var o = 0; o < 24; o++) {
            if (timeArr[i].charAt(2 * o) == 1) {
                time.push(1)
            } else {
                time.push(0)
            }
        }
    }
    btimecaset.setValue(changetimeFool(group(time, 24)));
}
// 设置普通布防区域
function setScheduleXp(d, btimecasetp) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('TimeBlock_' + i).eq(0).text()
        for (var o = 0; o < 24; o++) {
            if (timeArr[i].charAt(2 * o) == 1) {
                time.push(1)
            } else {
                time.push(0)
            }
        }
    }
    btimecasetp.setValue(changetimeFool(group(time, 24)));
}
// 保存移动侦测配置
function setMotionconfig(vale, quert, mq, mh) {
    $(xmlDocmotiontetect).find("Motion").eq(0).find("Senstive").eq(0).text($("#sensitivity").val());
    $(xmlDocmotiontetect).find("Motion").eq(0).find("Enable").eq(0).text($("#motionCheck").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('Schedule').eq(0).find('AllDay').text($("#DefensePlan").val());
    $(xmlDocmotiontetect).find('Motion').eq(0).find('BeepAlert').eq(0).find('Enable').text($("#chuBeepAlert").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('AlarmOut').eq(0).find('Enable').text($("#chuAlarmOut").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('Push').eq(0).find('Enable').text($("#chuTriggerpush").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('Mail').eq(0).find('Enable').text($("#chuemail").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('Ftp').eq(0).find('Enable').text($("#chuftp").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('Snapshot').eq(0).find('Enable').text($("#chudpick").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('Record').eq(0).find('Enable').text($("#chudvdeo").is(':checked'));
    $(xmlDocmotiontetect).find('Motion').eq(0).find('VoiceType').text($("#SoundType").val()); //声音报警布防类型
    if (config.deviceAiCap.voiceAlarmint == 'false') {
        $(xmlDocmotiontetect).find('Motion').eq(0).find('BroadcastCount').text($("#FrequencyBroadcast").val()); //播报次数
    }

    var d, t
    d = $("#deploymentTime").val()
    if (d == "false") {
        d = "false"
        t = "disable"
    } else if (d == "true") {
        d = "true"
        t = "disable"
    } else if (d == "evening") {
        d = "true"
        t = "evening"
    } else {
        d = "true"
        t = "day"
    }
    $(xmlDocmotiontetect).find('Motion').eq(0).find('AllDay').eq(1).text(d);
    $(xmlDocmotiontetect).find('Motion').eq(0).find('DayMode').eq(0).text(t);
    var adarr = vale[vale.length - 1]
    vale.unshift(adarr)
    vale.pop()
        // 原本的布防区域
    for (i = 0; i < 7; i++) {
        $(xmlDocmotiontetect).find('Motion').eq(0).find('Schedule').find('TimeBlock_' + i).eq(0).text(vale[i]);
    };

    var quertTwo = quert;



    if (config.deviceAiCap.voiceAlarmint != 'false') {
        setAudioAlarmConfig();
        setAlarmSchedule(quertTwo);
    }

    var pdarr = quert[quert.length - 1]
    quert.unshift(pdarr)
    quert.pop()
        // 声音报警布防区域
    for (k = 0; k < 7; k++) {
        $(xmlDocmotiontetect).find('Motion').eq(0).find('VoiceAlarmSchedule').find('TimeBlock_' + k).eq(0).text(quert[k]);
    };

    var cyURL = window.config.baseUrl + "/Pictures/1/Motion";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocmotiontetect,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            getMotionconfig(timeplaned, timeplandvoice)
            xhrState = xhr

        }
    });

}


function setAlarmSchedule(quert) {

    var d, t
    d = $("#deploymentTime").val()
    if (d == "false") {
        d = "false"
        t = "disable"
    } else if (d == "true") {
        d = "true"
        t = "disable"
    } else if (d == "evening") {
        d = "true"
        t = "evening"
    } else {
        d = "true"
        t = "day"
    }

    var pdarr = quert[quert.length - 1]
    quert.unshift(pdarr)
    quert.pop()
    var xmldocx = '<AlarmSchedule Version="1.0">' +
        '<ChannelID>1</ChannelID>' +
        '<AllDay>' + d + '</AllDay>' +
        '<DayMode>' + t + '</DayMode>' +
        '<TimeBlockList Version="1.0">';
    var str = '';

    for (k = 0; k < 7; k++) {
        str += '<TimeBlock_' + k + '>' + quert[k] + '</TimeBlock_' + k + '>';
    };

    xmldocx += (str + '</TimeBlockList></AlarmSchedule>');
    $.ajax({
        url: window.config.baseUrl + "/Alarm/1/AlarmSchedule",
        type: "PUT",
        async: false,
        processData: false,
        data: xmldocx,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}


function setAudioAlarmConfig() {

    var xmldocxConfig = '<?xml version="1.0" encoding="utf-8"?>' +
        '<AudioAlarm Version="1.0">' +
        '<Enable>true</Enable>' +
        '<Type>' + $("#SoundType").val() + '</Type>' +
        '<Delay>' + $("#FrequencyDelay").val() + '</Delay>' +
        '<Volume>50</Volume>' +
        '</AudioAlarm>';

    $.ajax({
        url: window.config.baseUrl + "/System/AudioAlarmConfig",
        type: "PUT",
        async: false,
        processData: false,
        data: xmldocxConfig,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}




// 保存坐标
function setRegionCfg() {
    var focusdex;
    $("#motionpolygonimg li img").each(function() {
        if ($(this).attr("src").indexOf('xz_xz') != -1) {
            focusdex = $(this).attr("imgindex");
        };
    });
    pum = focusdex
    if (sessionStorage.getItem("playstyle") == "ActiveX") {
        var xml = PolygonProtectionControl(3, 0, "");
        var strxml = "";
        for (i = 0; i < focusdex; i++) {
            strxml += '<Point Version="1.0"><PosX>' + $(xml).find("Point" + (i + 1) + "_X").eq(0).text() + '</PosX><PosY>' + $(xml).find("Point" + (i + 1) + "_Y").eq(0).text() + '</PosY></Point>'
        };
    } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
        PolygonConfigBlack(2, focusdex);
    } else {
        var strxml = ""
        for (var k = 0; k < focusdex; k++) {
            strxml += '<Point Version="1.0"><PosX>' + Math.floor((newPointList[k].x * menbfrx) * 100 / getRatio()) + '</PosX><PosY>' + Math.floor((newPointList[k].y * menbfry) * 100 / getRatio()) + '</PosY></Point>'
        }
    }
    if (sessionStorage.getItem("playstyle") != "EasyVideo") {
        var xmldocx = '<?xml version="1.0" encoding="utf-8"?>' +
            '<PolygonConfig Version="1.0"><ChannelID>1</ChannelID>' +
            '<PolygonLineNum>' + focusdex + '</PolygonLineNum><Direction>two_way</Direction>' +
            '<TrackZoom>false</TrackZoom>' + strxml + '<PolygonUseful Version="1.0">' +
            '<UseForMotionDetect>' + $("#motionCheck").is(':checked') + '</UseForMotionDetect>' +
            '<UseForPeopleDetect>' + $(xmlDocPolygon).find("UseForPeopleDetect").text() + '</UseForPeopleDetect>' +
            '<UseForFaceDetect>false</UseForFaceDetect>' +
            '<UseForCarDetect>true</UseForCarDetect>' +
            '</PolygonUseful>' +
            '<Trigger Version="1.0">' +
            '<NotifyAMS Version="1.0">' +
            '<Enable>false</Enable>' +
            '</NotifyAMS>' +
            '<BeepAlert Version="1.0"><Enable>' + $("#chuBeepAlert").is(':checked') + '</Enable></BeepAlert>' +
            '<FullScreen Version="1.0"><Enable>false</Enable></FullScreen>' +
            '<Mail Version="1.0"><Enable>' + $("#chuemail").is(':checked') + '</Enable></Mail>' +
            '<Ftp Version="1.0"><Enable>' + $("#chuftp").is(':checked') + '</Enable></Ftp>' +
            '<Push Version="1.0"><Enable>' + $("#chuTriggerpush").is(':checked') + '</Enable></Push>' +
            '<AlarmOut Version="1.0"><Enable>' + $("#chuAlarmOut").is(':checked') + '</Enable><AlarmOutMask>1</AlarmOutMask></AlarmOut>' +
            '<Snapshot Version="1.0"><Enable>' + $("#chudpick").is(':checked') + '</Enable><SnapshotMask>1</SnapshotMask></Snapshot>' +
            '<Record Version="1.0"><Enable>' + $("#chudvdeo").is(':checked') + '</Enable><RecordMask>1</RecordMask></Record>' +
            '<PTZ Version="1.0"><Enable>false</Enable><PTZActionList Version="1.0"><PTZAction Version="1.0">' +
            '<ChannelID>1</ChannelID><ActionName>none</ActionName><ActionNum>0</ActionNum></PTZAction></PTZActionList></PTZ>' +
            '<LightAlarm Version="1.0"><Enable>' + $("#humanalarm").is(':checked') + '</Enable></LightAlarm></Trigger></PolygonConfig>'

        var cyURL = window.config.baseUrl + "/Alarm/1/PolygonConfig";
        $.ajax({
            type: "PUT",
            url: cyURL,
            async: false,
            processData: false,
            data: xmldocx,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                SaveStateTwo(xhrState, xhr)

            }
        });

    }
};

function getmottricValue(data) {
    var strxml = ""
    for (i = 0; i < data.motion.edge; i++) {
        strxml += '<Point Version="1.0"><PosX>' + data.motion.x[i] + '</PosX><PosY>' + data.motion.y[i] + '</PosY></Point>'
    };
    var xmldocx = '<?xml version="1.0" encoding="utf-8"?>' +
        '<PolygonConfig Version="1.0"><ChannelID>1</ChannelID>' +
        '<PolygonLineNum>' + pum + '</PolygonLineNum><Direction>two_way</Direction>' +
        '<TrackZoom>false</TrackZoom>' + strxml + '<PolygonUseful Version="1.0">' +
        '<UseForMotionDetect>' + $("#motionCheck").is(':checked') + '</UseForMotionDetect>' +
        '<UseForPeopleDetect>' + $(xmlDocPolygon).find("UseForPeopleDetect").text() + '</UseForPeopleDetect>' +
        '<UseForFaceDetect>false</UseForFaceDetect>' +
        '<UseForCarDetect>true</UseForCarDetect>' +
        '</PolygonUseful>' +
        '<Trigger Version="1.0">' +
        '<NotifyAMS Version="1.0">' +
        '<Enable>false</Enable>' +
        '</NotifyAMS>' +
        '<BeepAlert Version="1.0"><Enable>' + $("#chuBeepAlert").is(':checked') + '</Enable></BeepAlert>' +
        '<FullScreen Version="1.0"><Enable>false</Enable></FullScreen>' +
        '<Mail Version="1.0"><Enable>' + $("#chuemail").is(':checked') + '</Enable></Mail>' +
        '<Ftp Version="1.0"><Enable>' + $("#chuftp").is(':checked') + '</Enable></Ftp>' +
        '<Push Version="1.0"><Enable>' + $("#chuTriggerpush").is(':checked') + '</Enable></Push>' +
        '<AlarmOut Version="1.0"><Enable>' + $("#chuAlarmOut").is(':checked') + '</Enable><AlarmOutMask>1</AlarmOutMask></AlarmOut>' +
        '<Snapshot Version="1.0"><Enable>' + $("#chudpick").is(':checked') + '</Enable><SnapshotMask>1</SnapshotMask></Snapshot>' +
        '<Record Version="1.0"><Enable>' + $("#chudvdeo").is(':checked') + '</Enable><RecordMask>1</RecordMask></Record>' +
        '<PTZ Version="1.0"><Enable>false</Enable><PTZActionList Version="1.0"><PTZAction Version="1.0">' +
        '<ChannelID>1</ChannelID><ActionName>none</ActionName><ActionNum>0</ActionNum></PTZAction></PTZActionList></PTZ>' +
        '<LightAlarm Version="1.0"><Enable>' + $("#humanalarm").is(':checked') + '</Enable></LightAlarm></Trigger></PolygonConfig>'
    var cyURL = window.config.baseUrl + "/Alarm/1/PolygonConfig";
    $.ajax({
        type: "put",
        url: cyURL,
        async: false,
        processData: false,
        data: xmldocx,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveStateTwo(xhrState, xhr)

        }
    });

}
// 画点封装
function createdot(x, y, c) {
    c.beginPath()
    c.arc(x, y, 2, 0, 360)
    c.closePath()
    c.fillStyle = "red"
    c.fill()
}
// 连线
function creatdTriangle(trgle, c) {
    c.strokeStyle = '#33FF00' //设置线条颜色
    c.beginPath()
    if (trgle.length == 3) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 4) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 5) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 6) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 7) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线

    }
}
//多边形主方法
function createdPitch(trgle, ids) {
    newPointList = trgle
    var c = document.getElementById(ids);
    var ctx = c.getContext("2d");
    c.width = c.width
    for (var i = 0; i < trgle.length; i++) {
        createdot(trgle[i].x, trgle[i].y, ctx)
    }
    creatdTriangle(trgle, ctx)
    var tx, ty, stx, sty, oldx, oldy
    c.onmousedown = function(event) {
        var rect = c.getBoundingClientRect();
        tx = event.clientX - rect.left
        ty = event.clientY - rect.top
        oldx = tx
        oldy = ty
        var qe = chooseDot(tx, ty, trgle)
        if (qe || qe == 0) {
            if (tx - trgle[qe].x <= 2 && tx - trgle[qe].x >= -2) {
                stx = true
            } else {
                stx = !stx
            }
            if (ty - trgle[qe].y <= 2 && ty - trgle[qe].y >= -2) {
                sty = true
            } else {
                sty = !stx
            }
            if (stx == true && sty == true) {
                c.onmousemove = function(event) {
                    var rect = c.getBoundingClientRect();
                    c.width = c.width
                    trgle[qe].x = event.clientX - rect.left
                    trgle[qe].y = event.clientY - rect.top
                    for (var l = 0; l < trgle.length; l++) {
                        createdot(trgle[l].x, trgle[l].y, ctx)
                    }
                    creatdTriangle(trgle, ctx)

                }
                c.onmouseup = function(event) {
                    var b = chooseArr(trgle, qe)
                    var pp = allLineche(b)
                    var statusd = chooseINline(trgle[qe].x, trgle[qe].y, pp) //是否在线上
                    var km = null
                    if (trgle.length > 3) {
                        if (qe == 0) {
                            var kt = false
                            for (var i = 1; i < trgle.length - 1; i++) {
                                if (qe == i || qe + 1 == i) {
                                    kt = LineSegmentsIntersect(trgle[qe], trgle[trgle.length - 1], trgle[i], trgle[i + 1])
                                    continue
                                } else {
                                    if (i == trgle.length - 1) {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[trgle.length - 1], trgle[0])
                                    } else {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[i], trgle[i + 1])
                                    }
                                }
                                if (st || kt) {
                                    km = true
                                    break
                                }
                            }
                        } else if (qe == trgle.length - 1) {
                            var st = false
                            for (var t = 0; t < trgle.length - 2; t++) {
                                if (qe == t || qe - 2 == t) {
                                    kt = LineSegmentsIntersect(trgle[qe], trgle[0], trgle[t], trgle[t + 1])
                                    if (st || kt) {
                                        km = true
                                    }
                                    continue
                                } else {
                                    st = LineSegmentsIntersect(trgle[qe], trgle[qe - 1], trgle[t], trgle[t + 1])
                                }
                                if (st || kt) {
                                    km = true
                                    break
                                }
                            }

                        } else {
                            for (var t = qe; t < trgle.length + qe - 1; t++) {
                                if (qe + 1 == t + 1) {
                                    if (t + 2 >= trgle.length) {
                                        kt = LineSegmentsIntersect(trgle[qe], trgle[qe - 1], trgle[t + 1], trgle[t + 2 - trgle.length])
                                    } else {
                                        kt = LineSegmentsIntersect(trgle[qe], trgle[qe - 1], trgle[t + 1], trgle[t + 2])
                                    }
                                    if (st || kt) {
                                        km = true
                                        break
                                    } else {
                                        continue

                                    }
                                } else {
                                    if (t + 2 == trgle.length) {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[t + 1], trgle[t + 2 - trgle.length])
                                    } else if (t + 1 == trgle.length) {
                                        continue
                                    } else if (t + 2 > trgle.length) {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[t - trgle.length], trgle[t + 1 - trgle.length])
                                    } else {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[t + 1], trgle[t + 2])
                                    }
                                }
                                if (st || kt) {
                                    km = true
                                    break
                                }
                            }

                        }

                    }
                    if (km || statusd) {
                        c.onmousemove = null;
                        c.onmouseup = null;
                        c.width = c.width
                        trgle[qe].x = oldx
                        trgle[qe].y = oldy
                        for (var z = 0; z < trgle.length; z++) {
                            createdot(trgle[z].x, trgle[z].y, ctx)
                        }
                        newPointList = trgle
                        creatdTriangle(trgle, ctx)

                    } else {
                        newPointList = trgle
                        c.onmousemove = null;
                        c.onmouseup = null;
                    }
                };

            }
        }
    }
}
// 判断是哪个点
function chooseDot(a, b, trgle) {
    for (var i = 0; i < trgle.length; i++) {
        var o = trgle[i].x - a
        var p = trgle[i].y - b
        if (o >= -2 && o <= 2 && p >= -2 && p <= 2) {
            return i
        }
    }
}
// 判断点是否在线段上
function chooseINline(a, b, trgle) {
    for (var i = 0; i < trgle.length; i++) {
        if ((a - trgle[i].a.x) * (trgle[i].b.y - trgle[i].a.y) == (trgle[i].b.x - trgle[i].a.x) * (b - trgle[i].a.y)) {
            return true
        }
    }
}
// 重组数组
function chooseArr(d, qe) {
    var newArr = []
    for (var i = 0; i < d.length; i++) {
        if (i == qe) {
            continue
        } else {
            newArr.push(d[i])
        }
    }
    return newArr
}
// 组合线段数组
function allLineche(e) {
    var pArr = []
    for (var i = 0; i < e.length; i++) {
        for (var j = i + 1; j < e.length; j++) {
            pArr.push({
                a: e[i],
                b: e[j]
            })
        }
    }
    return pArr
}

function LineSegmentsIntersect(lh, lt, th, tt) {
    if (!(Math.min(lh.x, lt.x) <= Math.max(th.x, tt.x) && Math.min(th.y, tt.y) <= Math.max(lh.y, lt.y) && Math.min(th.x, tt.x) <= Math.max(lh.x, lt.x) && Math.min(lh.y, lt.y) <= Math.max(th.y, tt.y))) {
        return false;
    }
    if ((((lh.x - th.x) * (tt.y - th.y) - (lh.y - th.y) * (tt.x - th.x)) *
            ((lt.x - th.x) * (tt.y - th.y) - (lt.y - th.y) * (tt.x - th.x))) > 0 ||
        (((th.x - lh.x) * (lt.y - lh.y) - (th.y - lh.y) * (lt.x - lh.x)) *
            ((tt.x - lh.x) * (lt.y - lh.y) - (tt.y - lh.y) * (lt.x - lh.x))) > 0) {
        return false;
    } else {
        return true;
    }
}
