// JavaScript Document
document.charset = "utf-8";
var playWay = sessionStorage.getItem("playstyle");
var xML;
var currentchannel = 0;
var saveTimes = 0,
    copyFlag = false;
var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
/*************************************************
 Function:
 Description:  初始化程序
**************************************************/
$(document).ready(function() {
    if (config.isSupportMultiChannel) {
        $(".isShowMultiChannel").show();
        // 初始化通道数
        $("#channel").empty(); //Channel
        if (config.deviceInfo.VideoInputChannels > 1 && config.deviceInfo.VideoInputChannels <= 2) {
            $("#channel").append('<option class="option" value="1">' + $.i18n.prop("i18n-tracking") + '</option>');
            $("#channel").append('<option class="option" value="2">' + $.i18n.prop("i18n-panoramic") + '</option>');
            $("#coppyInds").append('<option class="option" value="1">' + $.i18n.prop("i18n-tracking") + '</option>');
            $("#coppyInds").append('<option class="option" value="2">' + $.i18n.prop("i18n-panoramic") + '</option>');
        } else {
            for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                $("#channel").append('<option class="option" value="' + i + '">' + i + '</option>');
                if (i != 1) {
                    $("#coppyInds").append('<option class="option" value="' + i + '">' + i + '</option>');
                }
            }

        }
        $("#channel").val("1").trigger('change.select2');
        $("#channel").change(function() {
            currentchannel = $(this).val() - 1;
            var chid = $(this).val() * 1;
            $("#coppyInds").empty();
            $("#coppyInds").append('<option class="option" value="00">' + $.i18n.prop("i18n-video-all") + '</option>');

            if (config.deviceInfo.VideoInputChannels > 1 && config.deviceInfo.VideoInputChannels <= 2) {
                $("#coppyInds").append('<option class="option" value="1">' + $.i18n.prop("i18n-tracking") + '</option>');
                $("#coppyInds").append('<option class="option" value="2">' + $.i18n.prop("i18n-panoramic") + '</option>');
            } else {
                for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                    if (i != chid) {
                        $("#coppyInds").append('<option class="option" value="' + i + '">' + i + '</option>');
                    }
                }
            }
            if (g_bIsIE) {
                if (sessionStorage.getItem("playstyle") == 'MJPEG') {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, '', chid);
                } else {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, '', chid - 1);
                    SetActiveXMode(1);
                    setAdaptiveResolution(0);
                    StartDrawRegion(); //开始绘制
                    SetBrushColor(0); //设置画刷颜
                    SetDisplayRegionsEnable(); //显示选中区域
                }

            } else {
                if (sessionStorage.getItem("playstyle") == 'EasyVideo') {
                    easyldspecialvideos(true);
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, '', chid - 1);
                } else {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, '', chid);

                }
            }
            getPrivacyZone(chid); //获取PrivacyZoneD信息
        });
        // 复制到
        $("#copyTo").click(function() {
            copyFlag = true;
            saveTimes = 0;
            if ($("#coppyInds").val() == "00") {
                copyType = 'all';
                for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                    if ("admin" == config.user || "super_admin" == config.user) {
                        setPrivacyZone(i);
                    } else {
                        $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
                    }
                }
            } else {
                copyType = 'one';
                if ("admin" == config.user || "super_admin" == config.user) {
                    setPrivacyZone($("#channel").val() - 0);
                    setPrivacyZone($("#coppyInds").val() - 0);
                } else {
                    $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
                }
            }
        })
    } else {
        $(".isShowMultiChannel").hide();
    }
    var bls = getRatio();
    var ppi = window.innerWidth;
    if (ppi < 1920) {
        if (bls > 100) {
            var newHs = (420 * 100 / bls) * 0.75;
            var newWs = (560 * 100 / bls) * 0.75;
        } else {
            var newHs = 420 * 100 / bls;
            var newWs = 560 * 100 / bls;
        }
        var divds = document.getElementById("box-border");
        if (divds) {
            divds.style.height = newHs + "px";
            divds.style.width = newWs + "px";

            if ((sessionStorage.getItem("language") !== "zh" && sessionStorage.getItem("language") !== "tw")) {
                if (window.devicePixelRatio >= 1.75) {
                    $(".btn-center").css({ 'text-align': 'left' });
                    $("#feyie").width(1000);
                } else {
                    $("#feyie").width(newWs + 5);
                }
            } else {
                if (window.devicePixelRatio > 1.75) {
                    $(".btn-center").css({ 'text-align': 'left' });
                    $("#feyie").width(1000);
                } else {
                    $("#feyie").width(newWs + 5);
                }
            }
        }
    }

    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
        });
    }
    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/image/privacySettings.html") !== -1 && sessionStorage.getItem('dpiRadio') != null) {
                var bl = getRatio()
                var newH = 420 * 100 / bl
                var newW = 560 * 100 / bl
                var divd = document.getElementById("box-border")
                if (divd) {
                    divd.style.height = newH + "px"
                    divd.style.width = newW + "px"
                }
                preWindowfollowing('', '', $("#channel").val() - 1)
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/image/privacySettings.html") {
                var bl = getRatio()
                if (bl > 100) {
                    var newH = (420 * 100 / bl) * 0.75;
                    var newW = (560 * 100 / bl) * 0.75;
                    $('.control-label').css('font-size', '12px');
                } else {
                    var newH = 420 * 100 / bl;
                    var newW = 560 * 100 / bl;
                }
                var divd = document.getElementById("box-border")
                if (divd) {
                    divd.style.height = newH + "px"
                    divd.style.width = newW + "px"
                }
                preWindowfollowing('', '', $("#channel").val() - 1)
            } else if (window.location.hash == "#ipc/pages/image/privacySettings.html") {
                var bl = getRatio()
                var newH = 420 * 100 / bl
                var newW = 560 * 100 / bl
                var divd = document.getElementById("box-border")
                if (divd) {
                    divd.style.height = newH + "px"
                    divd.style.width = newW + "px"
                }
            }
        }
    });
    if (g_bIsIE && !config.forceEV) {
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            clearInterval(config.gs_interval);
            $("#playCanvas").hide();
            $("#axdiv").show();
            $("#revo").hide()
            SetActiveXMode(1);
            setAdaptiveResolution(0);
            StartDrawRegion(); //开始绘制
            SetBrushColor(0); //设置画刷颜
            SetDisplayRegionsEnable(); //显示选中区域
        } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
            $("#playCanvas").hide();
            $("#axdiv").show();
            $("#axdiv").empty();



            clearInterval(config.gs_interval)
        }
        getPrivacyZone(1); //获取PrivacyZoneD信息
    } else {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            config.refreshplayvideo = true;
            $("#playCanvas").hide();
            $("#axdiv").show();
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 4, "", true);
            // getPrivacyZone(); //获取PrivacyZoneD信息
        } 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, 4, "", true);
                getPrivacyZone(1); //获取PrivacyZoneD信息
            } else {
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    refershPlayer("privay")
                }

            }
        }
    }
    $("#isShowys").change(function(e) {
        if ($(this).is(":checked")) {
            $(".btn-center").show();
            $("#spsetsave").hide();
            $(".yulan").show();
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preHiddenDisplaywindow(5)
            }
        } else {
            $(".btn-center").hide()
            $(".yulan").hide();
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preHiddenDisplaywindow(4)
            }
            $("#spsetsave").show()
        }
    })
    $("#psetsave,#spsetsave").click(function(e) {
        copyFlag = false;
        if ("admin" == config.user || "super_admin" == config.user) {
            copyType = 'save'; //保存
            if (config.isSupportMultiChannel) {
                setPrivacyZone($("#channel").val() - 0);
            } else {
                setPrivacyZone(1);
            }
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });
    // 清除全部
    $("#revoall").click(function() {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                pracyFuntins(3, 1, 4)
            } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
                ClearDrawRegions();
            }
        })
        // 单个删除
    $("#revo").click(function() {
        pracyFuntins(2, 1, 4)
    })
});

function getprivacyValue(v) {
    xML = setPloit(v)
    var cyXml = "<?xml version='1.0' encoding='UTF-8' ?><Mosaic Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><Enable>" + $("#isShowys").is(":checked") + "</Enable><MosaicRegionList Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>"
    cyXml = cyXml + xML + "</MosaicRegionList></Mosaic>";

    var baseURL = window.config.baseUrl + "/Pictures/";
    var channels = [];
    if (copyType === 'all') {
        // 复制所有通道  
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            channels.push(i);
        }
    } else if (copyType === 'one') {
        // 复制当前通道与复制选中的  
        channels.push($("#channel").val(), $("#coppyInds").val());
    } else if (copyType === 'save') {
        // 点击保存, 保存当前通道  
        if ($("#channel").val()) {
            channels.push($("#channel").val());
        } else {
            channels.push(1);
        }
    }
    for (let index = 0; index < channels.length; index++) {
        var cyURL = baseURL + channels[index] + "/Mosaic";
        mosaicURL(cyURL, cyXml);

    }
    copyType = '';

}

function mosaicURL(cyURL, cyXml) {
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            if (copyFlag) {
                //保证复制时候保存成功只显示一次
                saveTimes++;
                if (saveTimes == config.deviceInfo.VideoInputChannels) {
                    SaveState(xhr);
                    saveTimes = 0;
                }
            } else {
                SaveState(xhr);
            }
        }
    });
}

function setPloit(v) {
    var Xml;
    if (v.privacyCover.bottom) {
        for (var i = 0; i < v.privacyCover.bottom.length; i++) {
            Xml += "<Region Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
            Xml += "<ID>" + (i + 1) + "</ID>";
            Xml += "<TopLeftX>" + v.privacyCover.left[i] + "</TopLeftX>";
            Xml += "<TopLeftY>" + v.privacyCover.top[i] + "</TopLeftY>";
            Xml += "<BottomRightX>" + v.privacyCover.right[i] + "</BottomRightX>";
            Xml += "<BottomRightY>" + v.privacyCover.bottom[i] + "</BottomRightY>";
            Xml += "</Region>";
        }
    } else {
        Xml = ""
    }
    return Xml
}
/*************************************************
 Function:        getPrivacyZone
 Description:     获取PrivacyZoneD信息
 *************************************************/
function getPrivacyZone(ch) {
    console.log("111111111111111");
    ch = ch || 1;
    $.ajax({
        url: window.config.baseUrl + "/Pictures/" + ch + "/Mosaic",
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            // if ("true" == $(xmlDoc).find('Mosaic').eq(0).find('Enable').eq(0).text()) {
            $("#isShowys").prop("checked", JSON.parse($(xmlDoc).find('Mosaic').eq(0).find('Enable').eq(0).text()));
            if ($("#isShowys").is(":checked")) {
                $(".btn-center").show();
                $("#spsetsave").hide();
                $(".yulan").show();
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    preHiddenDisplaywindow(5)
                }
            } else {
                $(".btn-center").hide()
                $(".yulan").hide()
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    preHiddenDisplaywindow(4)
                }
                $("#spsetsave").show()
            }
            var regionLength = $(xmlDoc).find('Mosaic').eq(0).find('MosaicRegionList').eq(0).find('Region').length;
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                var leftArr = []
                var rightArr = []
                var topArr = []
                var bottomArr = []
                for (var i = 0; i < regionLength; i++) {
                    leftArr.push(parseInt($(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('TopLeftX').eq(0).text()));
                    topArr.push(parseInt($(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('TopLeftY').eq(0).text()));
                    rightArr.push(parseInt($(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('BottomRightX').eq(0).text()));
                    bottomArr.push(parseInt($(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('BottomRightY').eq(0).text()));
                }
                if (regionLength > 0 || regionLength == 0) {
                    pracyFuntins(1, 1, regionLength, leftArr, topArr, rightArr, bottomArr)
                }
            } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (0 < regionLength) {
                    SetDisplayRegionsEnable(); //显示选中区域
                    for (var i = 0; i < regionLength; i++) {
                        AddDrawRegion(
                            $(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('TopLeftX').eq(0).text(),
                            $(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('TopLeftY').eq(0).text(),
                            $(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('BottomRightX').eq(0).text(),
                            $(xmlDoc).find('MosaicRegionList').eq(0).find('Region').eq(i).find('BottomRightY').eq(0).text()
                        );
                    }
                }

            }
            // } else {
            // $("#isShowys").prop("checked", false);
            // }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

/*************************************************
 Function:        setPrivacyZone
 Description:     保存PrivacyZone
 *************************************************/
function setPrivacyZone(num) {
    var cyXml = "<?xml version='1.0' encoding='UTF-8' ?><Mosaic Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><Enable>" + $("#isShowys").is(":checked") + "</Enable><MosaicRegionList Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>"
    if (sessionStorage.getItem("playstyle") == "ActiveX") {
        var RegionList = GetDrawRegions();
        var xmlDoc = parseXmlFromStr(RegionList);
        var elementLength = xmlDoc.getElementsByTagName("Region").length;
        if (0 < elementLength) {
            for (var i = 0; i < elementLength; i++) {
                var TopLeftX = parseInt(xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftX"));
                var TopLeftY = parseInt(xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftY"));
                var BottomRightX = parseInt(xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightX"));
                var BottomRightY = parseInt(xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightY"));
                if (TopLeftX < BottomRightX && TopLeftY < BottomRightY) {
                    cyXml += "<Region Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
                    cyXml += "<ID>" + (i + 1) + "</ID>";
                    cyXml += "<TopLeftX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftX") + "</TopLeftX>";
                    cyXml += "<TopLeftY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftY") + "</TopLeftY>";
                    cyXml += "<BottomRightX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightX") + "</BottomRightX>";
                    cyXml += "<BottomRightY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightY") + "</BottomRightY>";
                    cyXml += "</Region>";
                } else if (TopLeftX > BottomRightX && TopLeftY < BottomRightY) {
                    cyXml += "<Region Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
                    cyXml += "<ID>" + (i + 1) + "</ID>";
                    cyXml += "<TopLeftX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightX") + "</TopLeftX>";
                    cyXml += "<TopLeftY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftY") + "</TopLeftY>";
                    cyXml += "<BottomRightX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftX") + "</BottomRightX>";
                    cyXml += "<BottomRightY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightY") + "</BottomRightY>";
                    cyXml += "</Region>";
                } else if (TopLeftX < BottomRightX && TopLeftY > BottomRightY) {
                    cyXml += "<Region Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
                    cyXml += "<ID>" + (i + 1) + "</ID>";
                    cyXml += "<TopLeftX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftX") + "</TopLeftX>";
                    cyXml += "<TopLeftY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightY") + "</TopLeftY>";
                    cyXml += "<BottomRightX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightX") + "</BottomRightX>";
                    cyXml += "<BottomRightY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftY") + "</BottomRightY>";
                    cyXml += "</Region>";
                } else {
                    cyXml += "<Region Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
                    cyXml += "<ID>" + (i + 1) + "</ID>"
                    cyXml += "<TopLeftX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightX") + "</TopLeftX>";
                    cyXml += "<TopLeftY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("BottomRightY") + "</TopLeftY>";
                    cyXml += "<BottomRightX>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftX") + "</BottomRightX>";
                    cyXml += "<BottomRightY>" + xmlDoc.getElementsByTagName("Region")[i].getAttribute("TopLeftY") + "</BottomRightY>";
                    cyXml += "</Region>";
                }
            }
        }
        cyXml += "</MosaicRegionList></Mosaic>";

        var cyURL = window.config.baseUrl + "/Pictures/" + num + "/Mosaic";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                if (copyFlag) {
                    //保证复制时候保存成功只显示一次
                    saveTimes++;
                    if (saveTimes == config.deviceInfo.VideoInputChannels) {
                        SaveState(xhr);
                        saveTimes = 0;
                    }
                } else {
                    SaveState(xhr);
                }

            }
        });

    } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
        pracyFuntins(1, 2, 4);
    }
}