var nEnable = "";
var tEnable = "";
var easyName, valueLenth;
var get_timexml_doc, osdxml_doc;
var xhrState, g_bIsIE;
var namePosX, namePosY, timePosX, timePosY;
var tnumber = 0;
$(document).ready(function() {
    if (window.performance.navigation.type == 1 && navigator.userAgent.indexOf("Firefox") !== -1) {
        self.playervideo.destroy();
        self.playervideo = undefined; // 判断是否刷新页面原来的刷新逻辑在火狐中有问题，强制给它清除.刷新后触发
        config.refreshplayvideo = false;
        config.deviceloseSte = true
    }
    ScalePitch("box-border");
    $("#NVR_ChnOSDChannelMask").select2({
        width: 266,
        minimumResultsForSearch: -1,
    });
    for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
        $("#NVR_ChnOSDChannelMask").append('<option class="option" value="' + i + '">' + i + '</option>'); //Channel列表
    }
    // 默认第一个通道
    $("#NVR_ChnOSDChannelMask").val("1").trigger('change.select2')
    if (config.devicelose) {
        addEventListener("resize", function(event) {});
    }
    $(window).resize(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (window.location.hash.indexOf("#hvr/pages/image/osd.html")!==-1 && sessionStorage.getItem('dpiRadio') != null) {
                ScalePitch("box-border");
                preWindowfollowing(true);
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#hvr/pages/image/osd.html") {
                ScalePitch("box-border");
                preWindowfollowing(true);
            }
        }
    });
    // 监听滚动条滚动改变easyvideo位置
    $(".osd-gun").scroll(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash.indexOf("#hvr/pages/image/osd.html")!==-1 && sessionStorage.getItem('dpiRadio') != null) {
                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 == "#hvr/pages/image/osd.html") {
                var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                if (pt.Top > 127) {
                    preHiddenDisplaywindow(5);
                    preWindowfollowing(true);
                } else {
                    preHiddenDisplaywindow(4);
                }
            }
        }
    });
    g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
   if (g_bIsIE&&!config.forceEV) {
        $("#playCanvas").hide();
        $("#axdiv").show();
        $("#axdiv").empty();
        // insertDrags();
        getTimeinfo();
        getVideoPlugin("ActiveX", 1, "", true, 2, "", 0);
        ChangeLayout(1)
        SetActiveXMode(1);
        // setTimeout(function() {
        CloseAllChannels();
        PreviewSpecificChannelInFirstWindow(0, 4);
        // getTimeselect();
        // getOSD();
        CHOSDGetSel(1)
            // }, 1500);
    } else {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            config.refreshplayvideo = true;
            $("#playCanvas").hide();
            $("#axdiv").show();
            if (self.playervideo) {
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, "", 0);
                // getOSD();
            } else {
                refershPlayer("osd");
            }
            // if (self.playervideo) {
            //     // NVReasyldspecialvideos(true, "");
            // }
            // getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, "", 0);
            // refershPlayer("osd");
            getTimeselect();
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                $("#playCanvas").hide();
                $("#axdiv").show();
            }
            if (config.refreshplayvideo && window.performance.navigation.type != 1) {
                NVReasyldspecialvideos(true, '');
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, "", 0);
                if (config.devicelose == false || sessionStorage.getItem("playstyle") != "EasyVideo") {
                    CHOSDGetSel(1);
                }
                getTimeselect();
            } else {
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    refershPlayer("osd", "", "", 2)
                    getTimeselect()
                }
            }

        }
    }
    // 点击保存
    $("#iamgeSave").click(function() {
        // setDatetype();
        CHOSDSaveSel($("#NVR_ChnOSDChannelMask").val());
    });
    // 通道号改变，再开流
    $("#NVR_ChnOSDChannelMask").change(function() {
        var chid = $("#NVR_ChnOSDChannelMask").val() * 1;
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            NVReasyldspecialvideos(true, tnumber)
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, "", chid - 1)
            tnumber = chid - 1;
            CHOSDGetSel(chid)
        } else {
            StopVideo(0);
            PreviewSpecificChannelInFirstWindow(chid - 1, 4);
            CHOSDGetSel(chid);
            config.chnelNum = chid;
        }
    });
});
// 获取各个通道下的osd配置
function CHOSDGetSel(ch) {
    if (config.deviceCap.osdTag == null || config.deviceCap.osdTag == "") {
        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('DisplayName').eq(0).find('Name').eq(0).text();
                var arr = osdName.split("^");
                $("#osdna").val("")
                for (var i = 1; i < 5; i++) {
                    $("#osdna" + i).val("")
                }
                $("#osdna").val(arr[0]);
                for (var i = 1; i < arr.length; i++) {
                    $("#osdna" + i).val(arr[i])
                }
                $("#osdw").prop('checked', JSON.parse($(xmlDoc).find('DisplayName').eq(0).find('Enable').eq(0).text()));
                namePosX = $(xmlDoc).find('DisplayName').eq(0).find('PosX').eq(0).text();
                namePosY = $(xmlDoc).find('DisplayName').eq(0).find('PosY').eq(0).text();
                $("#osdt").prop('checked', JSON.parse($(xmlDoc).find('DisplayTime').eq(0).find('Enable').eq(0).text()));
                timePosX = $(xmlDoc).find('DisplayTime').eq(0).find('PosX').eq(0).text();
                timePosY = $(xmlDoc).find('DisplayTime').eq(0).find('PosY').eq(0).text();
                if (sessionStorage.getItem('playstyle') == "EasyVideo") {
                    // 获取osd1文本坐标数组
                    var textArr = [],
                        windowLeftArr = [],
                        windowTopArr = [];
                    if (osdName.indexOf("[")!==-1) {
                        var newText = osdName.split("^").slice(0, -1).join("^");
                    } else {
                        var newText = osdName;
                    }
                    textArr.push(newText);
                    windowLeftArr.push(parseInt(namePosX));
                    windowTopArr.push(parseInt(namePosY));
                    //初始化
                    osdinit(textArr, windowLeftArr, windowTopArr, timePosX, timePosY, 1, 1);
                    // 时间的显示隐藏
                    var osdtChecked = $("#osdt").is(':checked');
                    osdinit(textArr, windowLeftArr, windowTopArr, timePosX, timePosY, osdtChecked ? 7 : 8, 1);
                    // osd1显示隐藏
                    var osdwChecked = $("#osdw").is(':checked');
                    osdinit(textArr, windowLeftArr, windowTopArr, namePosX, namePosY, osdwChecked ? 5 : 6, 1, 0);
                } else {
                    var xml = "<?xml version='1.0' encoding='utf-8'?><DisplayOsdControl>" +
                        "<ShowText>1</ShowText>" +
                        "<TimeFormat>1</TimeFormat>" +
                        "<TextPosX>" + namePosX + "</TextPosX>" +
                        "<TextPosY>" + namePosY + "</TextPosY>" +
                        "<TimePosX>" + timePosX + "</TimePosX>" +
                        "<TimePosY>" + timePosY + "</TimePosY>" +
                        "<OsdText>" + osdName + "</OsdText>" +
                        "</DisplayOsdControl>";
                    DisplayOsdControl(1, ch - 1, xml);
                }
            }
        });
    } else {
        var cyURL = window.config.baseUrl + "/Pictures/" + ch + "/MultiOSDV2";
        $.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('Text').eq(0).text();
                var arr = osdName.split("^");
                $("#osdna").val("")
                for (var i = 1; i < 5; i++) {
                    $("#osdna" + i).val("")
                }
                $("#osdna").val(arr[0]);
                for (var i = 1; i < arr.length; i++) {
                    $("#osdna" + i).val(arr[i])
                }
                $("#osdw").prop('checked', JSON.parse($(xmlDoc).find('OSD').eq(0).find('Enable').eq(0).text()));
                namePosX = $(xmlDoc).find('OSD').eq(0).find('x').eq(0).text();
                namePosY = $(xmlDoc).find('OSD').eq(0).find('y').eq(0).text();
                $("#osdt").prop('checked', JSON.parse($(xmlDoc).find('DisplayTime').eq(0).find('Enable').eq(0).text()));
                timePosX = $(xmlDoc).find('DisplayTime').eq(0).find('PosX').eq(0).text();
                timePosY = $(xmlDoc).find('DisplayTime').eq(0).find('PosY').eq(0).text();
                if (sessionStorage.getItem('playstyle') == "EasyVideo") {
                    // 获取osd1文本坐标数组
                    var textArr = [],
                        windowLeftArr = [],
                        windowTopArr = [];
                    if (osdName.indexOf("[")!==-1) {
                        var newText = osdName.split("^").slice(0, -1).join("^");
                    } else {
                        var newText = osdName;
                    }
                    textArr.push(newText);
                    windowLeftArr.push(parseInt(namePosX));
                    windowTopArr.push(parseInt(namePosY));
                    //初始化
                    osdinit(textArr, windowLeftArr, windowTopArr, timePosX, timePosY, 1, 1);
                    // 时间的显示隐藏
                    var osdtChecked = $("#osdt").is(':checked');
                    osdinit(textArr, windowLeftArr, windowTopArr, timePosX, timePosY, osdtChecked ? 7 : 8, 1);
                    // osd1显示隐藏
                    var osdwChecked = $("#osdw").is(':checked');
                    osdinit(textArr, windowLeftArr, windowTopArr, namePosX, namePosY, osdwChecked ? 5 : 6, 1, 0);
                } else {
                    var xml = "<?xml version='1.0' encoding='utf-8'?><DisplayOsdControl>" +
                        "<ShowText>1</ShowText>" +
                        "<TimeFormat>1</TimeFormat>" +
                        "<TextPosX>" + namePosX + "</TextPosX>" +
                        "<TextPosY>" + namePosY + "</TextPosY>" +
                        "<TimePosX>" + timePosX + "</TimePosX>" +
                        "<TimePosY>" + timePosY + "</TimePosY>" +
                        "<OsdText>" + osdName + "</OsdText>" +
                        "</DisplayOsdControl>";
                    DisplayOsdControl(1, ch - 1, xml);
                }
            }
        });

    }
}
// 组文本数据
function alltheText() {
    var str = "";
    str += $("#osdna").val();
    for (var o = 1; o <= 4; o++) {
        if ($("#osdna" + o).val() != "") {
            str = str + '^' + $("#osdna" + o).val()
        }
    }
    return str
}
// 下发各个通道下的osd配置
function CHOSDSaveSel(ch) {
   if (g_bIsIE&&!config.forceEV) {
        if (config.deviceCap.osdTag == "true") { //因为没有能力默认使用v2接口去获取
            var nRet = GetDisplayOsdPosition(ch - 1);
            var cyXml = '<?xml version="1.0" encoding="UTF-8" ?>' +
                '<MultiLineOSD Version="1.0">' +
                '<DisplayTime Version="1.0"><Enable>' + $("#osdt").is(':checked') + '</Enable><PosX>' + nRet.getItem(2) + '</PosX><PosY>' + nRet.getItem(3) + '</PosY></DisplayTime>' +
                '<OSD Version="1.0"><ID>1</ID><Enable>' + $("#osdw").is(':checked') + '</Enable><Text>' + alltheText() + '</Text><x>' + nRet.getItem(0) + '</x><y>' + nRet.getItem(1) + '</y></OSD>' +
                '<OSD Version="1.0"><ID>2</ID><Enable>false</Enable><Text/><x>0</x><y>0</y></OSD>' +
                '<OSD Version="1.0"><ID>3</ID><Enable>false</Enable><Text/><x>0</x><y>0</y></OSD>' +
                '<OSD Version="1.0"><ID>4</ID><Enable>false</Enable><Text/><x>0</x><y>0</y></OSD></MultiLineOSD >'
            var cyURL = window.config.baseUrl + "/Pictures/" + ch + "/MultiOSDV2";
            $.ajax({
                type: "PUT",
                url: cyURL,
                processData: false,
                data: cyXml,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("If-Modified-Since", "0");
                },
                complete: function(xhr) {
                    SaveState(xhr);
                    CHOSDGetSel(ch);
                }
            });
        } else {
            var nRet = GetDisplayOsdPosition(ch - 1);
            var cyXml = "<?xml version='1.0' encoding='UTF-8' ?>" +
                "<OSD Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
                "<DisplayName Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
                "<Enable>" + $("#osdw").is(':checked') + "</Enable>" +
                "<PosX>" + nRet.getItem(0) + "</PosX>" +
                "<PosY>" + nRet.getItem(1) + "</PosY>" +
                "<Name>" + alltheText() + "</Name>" +
                "</DisplayName>" +
                "<DisplayTime Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
                "<Enable>" + $("#osdt").is(':checked') + "</Enable>" +
                "<PosX>" + nRet.getItem(2) + "</PosX>" +
                "<PosY>" + nRet.getItem(3) + "</PosY>" +
                "</DisplayTime>" +
                "</OSD>";
            var cyURL = window.config.baseUrl + "/Pictures/" + ch + "/OSD";
            $.ajax({
                type: "PUT",
                url: cyURL,
                processData: false,
                async: true,
                data: cyXml,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("If-Modified-Since", "0");
                },
                complete: function(xhr, textStatus) {
                    SaveState(xhr);
                    CHOSDGetSel(ch)

                }
            });

        }

    } else {
        osdputV();
    }

}

// 缩放保持100%大小方法
function ScalePitch(data) {
    var bl = getRatio()
    var newH = 420 * 100 / bl
    var newW = 560 * 100 / bl
    var divd = document.getElementById(data)
    if (divd) {
        divd.style.height = newH + "px"
        divd.style.width = newW + "px"
    }

}
// 保存日期格式
function setDatetype() {
    var cyXml = get_timexml_doc;
    $(cyXml).find('Time').eq(0).find('DateTimeFormat').eq(0).text($("#Stackingtime").val());
    $(cyXml).find('Time').eq(0).find('TimeFormat').eq(0).text($("#Timeformat").val());
    $(cyXml).find('Time').eq(0).find('UpdateFlag').eq(0).text(2);
    var cyURL = window.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);
            xhrState = xhr
        }
    });
}
// 获取日期格式
function getTimeselect() {
    $.ajax({
        url: window.config.baseUrl + "/System/Time",
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            get_timexml_doc = xmlDoc;
            $("#Stackingtime").val($(xmlDoc).find('Time').eq(0).find('DateTimeFormat').eq(0).text()).trigger('change.select2')
            $("#Timeformat").val($(xmlDoc).find('Time').eq(0).find('TimeFormat').eq(0).text()).trigger('change.select2')
        }
    })
}
// 初始化时间
function getTimeinfo() {
    $.ajax({
        url: window.config.baseUrl + "/System/Time",
        type: "GET",
        async: true,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            w_year = 0;
            w_month = 0;
            w_day = 0;
            w_hour = 0;
            w_minute = 0;
            w_second = 0;

            var t = $(xmlDoc).find('Time').eq(0).find('SystemTime').eq(0).text();
            w_year = Number(t.substring(0, 4));
            w_month = Number(t.substring(4, 6));
            w_day = Number(t.substring(6, 8));
            w_hour = Number(t.substring(9, 11));
            w_minute = Number(t.substring(11, 13));
            w_second = Number(t.substring(13, 15));
            clearTimeout(config.inttime);
            Watch();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function Watch() {
    webTimeUp();
    config.inttime = setTimeout("Watch()", 1000);
}
/*******************************************************
 Function:        webTimeUp
 Description:     更新web显示时间
 Input:             无
 Output:            无
 return:            无
 ********************************************************/

function webTimeUp() {
    w_second = w_second + 1;
    if (w_second == 60) {
        w_second = 0;
        w_minute = w_minute + 1;
    }
    if (w_minute == 60) {
        w_minute = 0;
        w_hour = w_hour + 1;
    }
    if (w_hour == 24) {
        w_hour = 0;
        switch (w_month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                w_day = w_day + 1;
                if (w_day == 32) {
                    w_day = 1;
                    w_month = w_month + 1;
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                w_day = w_day + 1;
                if (w_day == 31) {
                    w_day = 1;
                    w_month = w_month + 1;
                }
                break;
            case 2:
                w_day = w_day + 1;
                amari = w_year % 4;
                amari1 = w_year % 100;
                amari4 = w_year % 400;
                if (amari4 == 0) {
                    if (w_day == 30) {
                        w_day = 1;
                        w_month = w_month + 1;
                    }
                } else if (amari1 == 0) {
                    if (w_day == 29) {
                        w_day = 1;
                        w_month = w_month + 1;
                    }
                } else if (amari == 0) {
                    if (w_day == 30) {
                        w_day = 1;
                        w_month = w_month + 1;
                    }
                } else {
                    if (w_day == 29) {
                        w_day = 1;
                        w_month = w_month + 1;
                    }
                }
                break;
        }
    }
    if (w_month == 13) {
        w_month = 1;
        w_year = w_year + 1;
    }
    if (w_month < 10) D1month = "0" + w_month;
    else D1month = "" + w_month;
    if (w_day < 10) D1day = "0" + w_day;
    else D1day = "" + w_day;
    if (w_hour < 10) D1hour = "0" + w_hour;
    else D1hour = "" + w_hour;
    if (w_minute < 10) D1minute = "0" + w_minute;
    else D1minute = "" + w_minute;
    if (w_second < 10) D1second = "0" + w_second;
    else D1second = "" + w_second;

    $("#window1").text(w_year + '-' + D1month + '-' + D1day + ' ' + D1hour + ':' + D1minute + ':' + D1second);
}
//获取字符串总字符个数
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 getOSDtricValue(data) {

    var cch = $("#NVR_ChnOSDChannelMask").val()
    var ny = parseInt(data.OSD.text_y[0]);
    var nx = parseInt(data.OSD.text_x[0]);
    var tx = parseInt(data.OSD.datetime_x);
    var ty = parseInt(data.OSD.datetime_y);
    if (config.deviceCap.osdTag == "true") {
        var cyXml = '<?xml version="1.0" encoding="UTF-8" ?>' +
            '<MultiLineOSD Version="1.0">' +
            '<DisplayTime Version="1.0"><Enable>' + $("#osdt").is(':checked') + '</Enable><PosX>' + tx + '</PosX><PosY>' + ty + '</PosY></DisplayTime>' +
            '<OSD Version="1.0"><ID>1</ID><Enable>' + $("#osdw").is(':checked') + '</Enable><Text>' + alltheText() + '</Text><x>' + nx + '</x><y>' + ny + '</y></OSD>' +
            '<OSD Version="1.0"><ID>2</ID><Enable>false</Enable><Text/><x>0</x><y>0</y></OSD>' +
            '<OSD Version="1.0"><ID>3</ID><Enable>false</Enable><Text/><x>0</x><y>0</y></OSD>' +
            '<OSD Version="1.0"><ID>4</ID><Enable>false</Enable><Text/><x>0</x><y>0</y></OSD></MultiLineOSD >'
        var cyURL = window.config.baseUrl + "/Pictures/" + cch + "/MultiOSDV2";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr) {
                SaveState(xhr);
                CHOSDGetSel(cch);
            }
        });
    } else {
        var cyXml = "<?xml version='1.0' encoding='UTF-8' ?>" +
            "<OSD Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
            "<DisplayName Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
            "<Enable>" + $("#osdw").is(':checked') + "</Enable>" +
            "<PosX>" + nx + "</PosX>" +
            "<PosY>" + ny + "</PosY>" +
            "<Name>" + alltheText() + "</Name>" +
            "</DisplayName>" +
            "<DisplayTime Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
            "<Enable>" + $("#osdt").is(':checked') + "</Enable>" +
            "<PosX>" + tx + "</PosX>" +
            "<PosY>" + ty + "</PosY>" +
            "</DisplayTime>" +
            "</OSD>";
        var cyURL = window.config.baseUrl + "/Pictures/" + cch + "/OSD";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr) {
                SaveState(xhr);
                CHOSDGetSel(cch)
            }
        });

    }

}
