var timeFlag;
var win1Mark, win2Mark = false,
    win3Mark = false;
var nEnable = "";
var tEnable = "";
var easyName, valueLenth;
var get_timexml_doc;
var xhrState;
var window1_left = "";
var window1_top = "";
var window2_left = "";
var window2_top = "";
var window3_left = "";
var window3_top = "";
var osd2Enable = "";
var osd2, osdCount = 1;
var currentchannel = 0;
var copyType = '';
var isosdType = '';
var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
var saveTimes = 0,
    copyFlag = false;
var keepdoit = {
    width: '',
    base64: '',
    height: '',
    length: ''
}
var keepdoit2 = {
    width: '',
    base64: '',
    height: '',
    length: ''
};
var doyto2 = [];
$(document).ready(function() {
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220,
        });
    }
    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) {
                getVideoPlugin('MJPEG', 1, "", true, 2, '', chid);

            } 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);

                }
            }

            getTimeinfo(chid);
            getTimeselect(chid);
            getOSD(chid);
        });
        // 复制到
        $("#coppyto").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) {
                        setDatetype(i);
                        setOSD(i);
                    } else {
                        $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
                    }
                }
            } else {
                copyType = 'one';
                if ("admin" == config.user || "super_admin" == config.user) {
                    setDatetype($("#channel").val() - 0);
                    setDatetype($("#coppyInds").val() - 0);
                    setOSD($("#channel").val() - 0);
                    setOSD($("#coppyInds").val() - 0);
                } else {
                    $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
                }
            }
        })
    } else {
        $(".isShowMultiChannel").hide();
    }
    config.lastnav = "configuration";
    if (config.deviceCap[currentchannel].osd2support == 'true' && config.deviceCap[currentchannel].osd2maxcnt == 2) {
        $('.osd2display').show();
        osdCount = 2;
    } else {
        $('.osd2display').hide();
        osdCount = 1;
    }
    if (config.deviceCap[currentchannel].osdShowd == "true") {
        $("#osdShowd").show();
    } else {
        $("#osdShowd").hide();
    }
    if (config.deviceCap[currentchannel].osdTwoline == "1") {
        $("#osd2Msg1").show();
    } else {
        $("#osd2Msg").show();
    }
    if (config.deviceCap[currentchannel].osddoit == 'true') {
        $(".doitosd").show();
    } else {
        $(".doitosd").hide();
    }
    ScalePitch("box-border")
    ScalePitch("display")
    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/osd.html") != -1 && sessionStorage.getItem('dpiRadio') != null) {
                ScalePitch("box-border");
                preWindowfollowing(true, '', $("#channel").val() - 1);
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/image/osd.html") {
                ScalePitch("box-border");
                preWindowfollowing(true, '', $("#channel").val() - 1);
            } else if (window.location.hash == "#ipc/pages/image/osd.html" && sessionStorage.getItem("playstyle") == "WebPlayer") {
                ScalePitch("box-border");
                // getOSD();
                if (config.isSupportMultiChannel) {
                    getOSD($("#channel").val() - 0);
                } else {
                    getOSD();
                }
            } else if (window.location.hash == "#ipc/pages/image/osd.html" && sessionStorage.getItem("playstyle") == "MJPEG") {
                ScalePitch("box-border");
                // getOSD();
                if (config.isSupportMultiChannel) {
                    getOSD($("#channel").val() - 0);
                } else {
                    getOSD();
                }
            }
        }
    });
    // 监听滚动条滚动改变easyvideo位置
    $(".osd-gun").scroll(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash.indexOf("#ipc/pages/image/osd.html") != -1 && sessionStorage.getItem('dpiRadio') != null) {
                var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                if (pt.Top > 80) {
                    preHiddenDisplaywindow(5, $("#channel").val() - 1);
                    preWindowfollowing(true, '', $("#channel").val() - 1);
                } else {
                    preHiddenDisplaywindow(4, $("#channel").val() - 1);
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/image/osd.html") {
                var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                if (pt.Top > 127) {
                    preHiddenDisplaywindow(5, $("#channel").val() - 1);
                    preWindowfollowing(true, '', $("#channel").val() - 1);
                } else {
                    preHiddenDisplaywindow(4, $("#channel").val() - 1);
                }
            }
        }
    });
    if (g_bIsIE && !config.forceEV) {
        $("#playCanvas").hide();
        $("#axdiv").show();
        $("#axdiv").empty();
        clearInterval(config.gs_interval);
        insertDrags();
        // getTimeinfo();
        getVideoPlugin("MJPEG", 1, "", true);
        SetActiveXMode(1);
        // getTimeselect();
        // getOSD()
        if (config.isSupportMultiChannel) {
            getTimeinfo(1);
            getTimeselect(1);
            getOSD(1);
        } else {
            getTimeinfo();
            getTimeselect();
            getOSD();

        }
    } else {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            config.refreshplayvideo = true;
            $("#playCanvas").hide();
            $("#axdiv").show();
            $("#display").hide();
            if (self.playervideo) {
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2);
                if (config.isSupportMultiChannel) {
                    getOSD(1);
                } else {
                    getOSD();
                }
            } else {
                refershPlayer("osd");
            }
            if (config.isSupportMultiChannel) {
                getTimeselect(1);
            } else {
                getTimeselect();
            }
            // getTimeselect();
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                config.refreshplayvideo = true;
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("#display").hide();
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                $("#playCanvas").show();
                $("#axdiv").hide();
                $("#axdiv").empty();
                if (self.player) {
                    if (sessionStorage.getItem("stream") == "codestream1") {
                        self.player.stop("sub1");
                    } else {
                        self.player.stop("sub2");
                    }
                }
                insertDrags();
                // getTimeinfo();
                if (config.isSupportMultiChannel) {
                    getTimeinfo(1);
                } else {
                    getTimeinfo();
                }
            } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("#axdiv").empty();
                clearInterval(config.gs_interval);
                insertDrags();
                if (config.isSupportMultiChannel) {
                    getTimeinfo(1);
                } else {
                    getTimeinfo();
                }
            }
            if (config.refreshplayvideo) {
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 2, "", true);
                if (sessionStorage.getItem("playstyle") != "EasyVideo") {
                    // getOSD();
                    if (config.isSupportMultiChannel) {
                        getOSD(1);
                    } else {
                        getOSD();
                    }
                }
                // getTimeselect();
                if (config.isSupportMultiChannel) {
                    getTimeselect(1);
                } else {
                    getTimeselect();
                }
            } 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);
                                    // getOSD();
                                    // getTimeselect();
                                    if (config.isSupportMultiChannel) {
                                        getOSD(1);
                                        getTimeselect(1);
                                    } else {
                                        getOSD();
                                        getTimeselect();
                                    }
                                });
                            });
                        });
                    }
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    refershPlayer("osd")
                        // getTimeselect()
                    if (config.isSupportMultiChannel) {
                        getTimeselect(1);
                    } else {
                        getTimeselect();
                    }
                } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
                    // getOSD();
                    // getTimeselect();
                    if (config.isSupportMultiChannel) {
                        getOSD(1);
                        getTimeselect(1);
                    } else {
                        getOSD();
                        getTimeselect();
                    }
                }

            }

        }
    }
    $("#dotosd").change(function() {
        if ($(this).is(':checked')) {
            $(".isShowDotosd").show();
        } else {
            $(".isShowDotosd").hide();
        }
    });
    // 点击保存
    $("#osdSave").click(function(e) {
        copyType = 'save';
        copyFlag = false;
        if ("admin" == config.user || "super_admin" == config.user) {
            e.stopPropagation();
            e.preventDefault();
            // setDatetype();
            // setOSD();
            if (config.isSupportMultiChannel) {
                setDatetype($("#channel").val() - 0);
                setOSD($("#channel").val() - 0);
            } else {
                setDatetype();
                setOSD();
            }

        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    });
    // 点击添加osd
    $("#addipt").click(function() {
        addlist()
    });
    // 点击添加osd2
    $("#addipttow").click(function() {
        addlisttow()
    });

    // getOSD();
});
// 缩放保持100%大小方法
function ScalePitch(data) {
    var ppi = window.innerWidth;
    var bl = getRatio();
    if (ppi < 1920) {
        if (bl > 100) {
            var newH = (420 * 100 / bl) * 0.75;
            var newW = (560 * 100 / bl) * 0.75;
        } else {
            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(num) {
    var cyXml = get_timexml_doc;
    var cyXm1 = "<?xml version='1.0' encoding='UTF-8' ?><Time Version='1.0'>" +
        "<DateTimeFormat>" + $("#Stackingtime").val() + "</DateTimeFormat>" +
        "<TimeFormat>" + $("#Timeformat").val() + "</TimeFormat>" +
        "<SystemTime>" + $(cyXml).find('Time').eq(0).find('SystemTime').eq(0).text() + "</SystemTime>" +
        "<SyncNTPFlag>" +$(cyXml).find('Time').eq(0).find('SyncNTPFlag').eq(0).text() + "</SyncNTPFlag>" +
        "<UpdateFlag>2</UpdateFlag></Time>";

    var cyURL;
    if (num) {
        cyURL = window.config.baseUrl + "/System/" + num + "/Time";
    } else {
        cyURL = window.config.baseUrl + "/System/Time";
    }
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXm1,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // SaveState(xhr);
            xhrState = xhr
        }
    });
}
// 获取日期格式
function getTimeselect(ch) {
    var url;
    if (config.isSupportMultiChannel) {
        url = window.config.baseUrl + "/System/" + ch + "/Time";
    } else {
        url = window.config.baseUrl + "/System/Time";
    }
    $.ajax({
        url: url,
        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 addlist() {
    var i = 0;
    var osdSL = document.getElementsByClassName('osdlists').length;
    valueLenth = osdSL
    if (config.deviceCap[currentchannel].osdTag == 'true') {
        if (osdSL > config.deviceCap[currentchannel].osdline - 1 || osdSL == (config.deviceCap[currentchannel].osdline - 1)) {
            $.optionBootoast($.i18n.prop('i18n-morethen'), "danger");
        } else {
            i = osdSL
            var lesshtml = '<div class="osdlists"><input type="text" name="nName" class="form-control osdinput"><div onclick="cleaup(event)" style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
            $("#osdlisd").append(lesshtml);
        }
    } else {
        if (osdSL > 1) {
            $.optionBootoast($.i18n.prop('i18n-morethen'), "danger");
        } else {
            i = osdSL
            var lesshtml = '<div class="osdlists"><input type="text" name="nName" class="form-control osdinput"><div onclick="cleaup(event)" style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
            $("#osdlisd").append(lesshtml);
        }
    }
}

function addlisttow() {
    var i = 0;
    var osdSL = document.getElementsByClassName('osdlisttow').length;
    valueLenth = osdSL
    if (osdSL > config.deviceCap[currentchannel].osdTwoline - 2) {
        $.optionBootoast($.i18n.prop('i18n-morethen'), "danger");
    } else {
        i = osdSL
        var lesshtml = '<div class="osdlisttow"><input type="text" name="tName" class="form-control osdinput"><div onclick="cleaup(event,2)" style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
        $("#osdlisdtow").append(lesshtml);
    }

}

function cleaup(e, d) {
    if (d) {
        var collection = document.getElementsByClassName("osdlisttow");
    } else {
        var collection = document.getElementsByClassName("osdlists");
    }
    var requiredElement = null;
    if (collection.length) {
        for (var k = 0; k < collection.length; k++) {
            if (collection[k].childNodes[0].value == e.target.parentNode.parentNode.childNodes[0].value) {
                requiredElement = collection[k]
            }
        }
    }
    requiredElement.parentNode.removeChild(requiredElement);
}
// 初始化时间
function getTimeinfo(ch) {
    var url;
    if (config.isSupportMultiChannel) {
        url = window.config.baseUrl + "/System/" + ch + "/Time";
    } else {
        url = window.config.baseUrl + "/System/Time";
    }
    $.ajax({
        url: url,
        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 insertDrags() {
    var display = $("#display");
    $('<div id="window1" class="window1"  style="position:absolute; height:16px; line-height: 16px; border:1px solid #FF0000;font-weight:bold;color:#FF0000;cursor: pointer;"></div>').prependTo(display);
    $('<div id="window2" class="window1"  style="white-space:nowrap;position:absolute; line-height: 16px; border:1px solid #FF0000;font-weight:bold;color:#FF0000;cursor: pointer;text-align:left;"></div>').prependTo(display);
    $('<div id="window3" class="window1"  style="white-space:nowrap;position:absolute; line-height: 16px; border:1px solid #FF0000;font-weight:bold;color:#FF0000;cursor: pointer;text-align:left;"></div>').prependTo(display);
    $(".window1").resizable({
        containment: "parent"
    }).draggable({
        containment: "parent"
    });
    $(".window2").resizable({
        containment: "parent"
    }).draggable({
        containment: "parent"
    });
    $("#window1").on("drag", function() {
        win1Mark = true;
    })
    $("#window2").on("drag", function() {
        win2Mark = true;
    })
    $("#window3").on("drag", function() {
        win3Mark = true;
    });
}

//获取osd哦配置
function getOSD(ch) {
    if (config.deviceCap[currentchannel].osdTag == "true") {
        var url;
        if (config.isSupportMultiChannel) {
            if (!ch) {
                ch = $("#channel").val();
            }
            url = window.config.baseUrl + "/Pictures/" + ch + "/MultiOSDV2";
        } else {
            url = window.config.baseUrl + "/Pictures/1/MultiOSDV2";
        }
        $.ajax({
            url: url,
            type: "GET",
            async: true,
            timeout: 15000,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            success: function(xmlDoc) {
                var state = $(xmlDoc).find('statusCode').eq(0).text();
                if (state.indexOf('160') !== -1) {
                    $.optionBootoast($.i18n.prop('i18n-deviceerror'), "danger")
                } else {
                    if (config.deviceCap[currentchannel].osddoit == "true") {
                        var dot = $(xmlDoc).find("OSDKind").text() == "PictureOSD" ? true : false
                        $("#dotosd").prop('checked', JSON.parse(dot));
                        if (dot) {
                            $(".isShowDotosd").show();
                        }
                        $("#fontsizce").val($(xmlDoc).find("OSDBmp").eq(0).find('FontSize').text()).trigger('change.select2')
                    }
                    win1Mark = false;
                    win2Mark = false;
                    win3Mark = false;
                    //时间坐标与是否勾选
                    var tEnable = $(xmlDoc).find("DisplayTime").eq(0).find("Enable").eq(0).text(); //时间
                    window1_left = $(xmlDoc).find('DisplayTime').eq(0).find('PosX').eq(0).text();
                    window1_top = $(xmlDoc).find('DisplayTime').eq(0).find('PosY').eq(0).text();
                    $("#osdt").prop('checked', JSON.parse(tEnable));
                    //获取osd1文本坐标 与是否勾选osd1
                    var osdName = $(xmlDoc).find("OSD").eq(0).find("Text").text();
                    var arr = osdName.split("^");
                    var text = arr.join("<br>");
                    if (jQuery.inArray("[RES]", arr) > -1 || jQuery.inArray("[BPS]", arr) > -1 || jQuery.inArray("[RES] [BPS]", arr) > -1) {
                        var type = arr.pop();
                    };
                    var lesshtml = '';
                    $("#osdlisd").empty()
                    $("#osdna").val(arr[0]);
                    for (var i = 1; i < arr.length; i++) {
                        // 使用转义后的值
                        var escapedValue = htmlEscape(arr[i]);
                        lesshtml += '<div class="osdlists"><input type="text" name="nName" value="' + escapedValue  + '" class="form-control osdinput"><div onclick="cleaup(event)" style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
                    }
                    $("#osdlisd").append(lesshtml);
                    switch (type) {
                        case "[RES]":
                            $('#additional').val("2").trigger('change.select2')
                            break;
                        case "[BPS]":
                            $('#additional').val("3").trigger('change.select2')
                            break;
                        case "[RES] [BPS]":
                            $('#additional').val("4").trigger('change.select2')
                            break;
                        default:
                            $('#additional').val("1").trigger('change.select2')
                    };
                    nEnable = $(xmlDoc).find("OSD").eq(0).find('Enable').eq(0).text();
                    $("#osdw").prop('checked', JSON.parse(nEnable));
                    window2_left = $(xmlDoc).find('OSD').eq(0).find('x').eq(0).text();
                    window2_top = $(xmlDoc).find('OSD').eq(0).find('y').eq(0).text();
                    //osd2 文本坐标
                    var osd2Name = $(xmlDoc).find("OSD").eq(1).find("Text").text();
                    var osd2Texts, osd2text;
                    // 检查有无^ 有就去掉第一个^
                    var index = osd2Name.indexOf("^");
                    if (index == -1) { //无 直接显示，，，，用户没有输入换行符且没超过30个字符
                        osd2Texts = osd2Name;
                        osd2text = osd2Name;
                        $("#osd2Text").val(osd2Texts);
                    } else { //有换行符
                        var add = osd2Name.split("^");
                        $("#osdlisdtow").empty();
                        $("#osd2Text").val(add[0]);
                        var lesshtml = '<div class="osdlisttow"><input type="text" name="tName" value="' + add[1] + '" class="form-control osdinput"><div onclick="cleaup(event,2)" style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
                        $("#osdlisdtow").append(lesshtml);
                        // var chartlength = 0,
                        //     chieseCode = -1; //字符长度
                        // var flagosd2 = false; // 判断换行符的位置是否在31 或者30
                        // for (var j = 0; j < osd2Name.length; j++) {
                        //     chieseCode = osd2Name.charCodeAt(j); //字符串.charCodeAt(index)>255 就是中文，否则是英文。
                        //     if (chieseCode > 255) chartlength += 2;
                        //     else chartlength += 1;
                        //     if (chartlength == 30 || chartlength == 31) { //判断第一个出现的^是不是在第30或者31处
                        //         if (osd2Name.slice(j).slice(0, 1) == "^" && j == index) {
                        //             flagosd2 = true;
                        //         } else {
                        //             flagosd2 = false;
                        //         };
                        //     }
                        // };
                        // if (flagosd2) {
                        //     var str = osd2Name.replace('^', ''); //去掉第一个
                        //     $("#osd2Text").val(str); //文本框显示
                        // } else { //用户加的 直接显示文本
                        //     $("#osd2Text").val(osd2Name);
                        // }
                        // var osd2arr = [];
                        // osd2arr.push(osd2Name.slice(0, index));
                        // osd2arr.push(osd2Name.slice(index + 1));
                        // osd2text = osd2arr.join("<br>");
                        osd2Texts = osd2Name;

                    }
                    osd2Enable = $(xmlDoc).find("OSD").eq(1).find('Enable').eq(0).text();
                    if (osd2Enable) {
                        $("#osd2Enable").prop('checked', JSON.parse(osd2Enable));
                    }
                    window3_left = $(xmlDoc).find('OSD').eq(1).find('x').eq(0).text();
                    window3_top = $(xmlDoc).find('OSD').eq(1).find('y').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(window2_left));
                        windowTopArr.push(parseInt(window2_top));
                        //osd2
                        if (config.deviceCap[currentchannel].osd2support == "true" && config.deviceCap[currentchannel].osd2maxcnt == 2) {
                            textArr.push(osd2Texts);
                            windowLeftArr.push(parseInt(window3_left));
                            windowTopArr.push(parseInt(window3_top));
                        }
                        //初始化
                        osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, 1, osdCount);
                        // 时间的显示隐藏
                        var osdtChecked = $("#osdt").is(':checked');
                        osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, osdtChecked ? 7 : 8, osdCount);

                        // osd1显示隐藏
                        var osdwChecked = $("#osdw").is(':checked');
                        osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, osdwChecked ? 5 : 6, osdCount, 0);

                        // osd2显示隐藏
                        if (config.deviceCap[currentchannel].osd2support == "true" && config.deviceCap[currentchannel].osd2maxcnt == 2) {
                            var osd2EnableChecked = $("#osd2Enable").is(':checked'); //5: 显示 OSD 文本6: 隐藏 OSD 文本
                            osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, osd2EnableChecked ? 5 : 6, osdCount, 1);
                        }
                    } else {
                        //时间坐标
                        if ($("#osdt").is(':checked')) {
                            $("#window1").show(); //叠加时间的显示隐藏
                            $("#window1").css("left", (560 * (window1_left / 703)) * 100 / getRatio());
                            $("#window1").css("top", (420 * (window1_top / 575)) * 100 / getRatio());
                        } else {
                            $("#window1").hide();
                            $("#window1").css("left", (560 * (window1_left / 703)) * 100 / getRatio());
                            $("#window1").css("top", (420 * (window1_top / 575)) * 100 / getRatio());

                        }
                        //osd1坐标与文本
                        $("#window2").html(text);
                        if ($("#osdw").is(':checked')) {
                            $("#window2").show();
                            if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                                if (window2_left / 703 * $("#display").width() + $("#window2").width() > $("#display").width()) {
                                    $("#window2").css("left", (window2_left / 703 * $("#display").width() - (window2_left / 703 * $("#display").width() + $("#window2").width() - $("#display").width())));
                                } else {
                                    $("#window2").css("left", (window2_left / 703 * $("#display").width()));
                                }
                                $("#window2").css("top", (window2_top / 575) * $("#display").height());
                                if ($("#window2").position().top + $("#window2").height() > $("#display").height()) {
                                    var ny = $("#window2").position().top;
                                    $("#window2").css("top", (ny - (ny + $("#window2").height() - $("#display").height())));
                                }
                            } else { //这里表示mjpeg
                                if (window2_left / 703 * $("#axdiv").width() + $("#window2").width() > $("#axdiv").width()) {
                                    $("#window2").css("left", (window2_left / 703 * $("#axdiv").width() - (window2_left / 703 * $("#axdiv").width() + $("#window2").width() - $("#axdiv").width())));
                                } else {
                                    $("#window2").css("left", (window2_left / 703 * $("#axdiv").width()));
                                }
                                $("#window2").css("top", (window2_top / 575) * $("#axdiv").height());
                                if ($("#window2").position().top + $("#window2").height() > $("#axdiv").height()) {
                                    var ny = $("#window2").position().top;
                                    $("#window2").css("top", (ny - (ny + $("#window2").height() - $("#axdiv").height())));
                                }
                            }
                        } else {
                            $("#window2").hide();
                            if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                                if (window2_left / 703 * $("#display").width() + $("#window2").width() > $("#display").width()) {
                                    $("#window2").css("left", (window2_left / 703 * $("#display").width() - (window2_left / 703 * $("#display").width() + $("#window2").width() - $("#display").width())));
                                } else {
                                    $("#window2").css("left", (window2_left / 703 * $("#display").width()));
                                }
                                $("#window2").css("top", (window2_top / 575) * $("#display").height());
                                if ($("#window2").position().top + $("#window2").height() > $("#display").height()) {
                                    var ny = $("#window2").position().top;
                                    $("#window2").css("top", (ny - (ny + $("#window2").height() - $("#display").height())));
                                }

                            } else {
                                if (window2_left / 703 * $("#axdiv").width() + $("#window2").width() > $("#axdiv").width()) {
                                    $("#window2").css("left", (window2_left / 703 * $("#axdiv").width() - (window2_left / 703 * $("#axdiv").width() + $("#window2").width() - $("#axdiv").width())));
                                } else {
                                    $("#window2").css("left", (window2_left / 703 * $("#axdiv").width()));
                                }
                                $("#window2").css("top", (window2_top / 575) * $("#axdiv").height());
                                if ($("#window2").position().top + $("#window2").height() > $("#axdiv").height()) {
                                    var ny = $("#window2").position().top;
                                    $("#window2").css("top", (ny - (ny + $("#window2").height() - $("#axdiv").height())));
                                }

                            }
                        };
                        // osd2坐标与文本
                        $("#window3").html(osd2text);
                        if ($("#osd2Enable").is(':checked')) {
                            $("#window3").show();
                            $("#window3").css("left", ((560) * ((window3_left / 703))) * 100 / getRatio());
                            $("#window3").css("top", (420 * (window3_top / 575)) * 100 / getRatio());
                            if ($("#window3").position() != undefined) {
                                var ny = $("#window3").position().top;
                                if (ny + $("#window3").height() > 420) {
                                    $("#window3").css("top", (420 - $("#window3").height()) * 100 / getRatio());
                                }
                            }
                        } else {
                            $("#window3").hide();
                            $("#window3").css("left", ((560) * ((window3_left / 703))) * 100 / getRatio());
                            $("#window3").css("top", (420 * (window3_top / 575)) * 100 / getRatio());
                            var ny = $("#window3").position().top;
                            if (ny + $("#window3").height() > 420) {
                                $("#window3").css("top", (420 - $("#window3").height()) * 100 / getRatio());
                            }
                        };


                    }

                }
            },
            error: function(xhr, textStatus, errorThrown) {}
        });
    } else {
        if (config.isSupportMultiChannel) {
            url = window.config.baseUrl + "/Pictures/" + ch + "/OSD";
        } else {
            url = window.config.baseUrl + "/Pictures/1/OSD";
        }
        $.ajax({
            url: url,
            type: "GET",
            async: true,
            timeout: 15000,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            success: function(xmlDoc) {
                var state = $(xmlDoc).find('statusCode').eq(0).text();
                if (state.indexOf('160') !== -1) {
                    $.optionBootoast($.i18n.prop('i18n-deviceerror'), "danger")
                } else {
                    win1Mark = false;
                    win2Mark = false;
                    if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                        //时间坐标与是否勾选
                        var tEnable = $(xmlDoc).find("DisplayTime").eq(0).find("Enable").eq(0).text(); //时间
                        window1_left = $(xmlDoc).find('DisplayTime').eq(0).find('PosX').eq(0).text();
                        window1_top = $(xmlDoc).find('DisplayTime').eq(0).find('PosY').eq(0).text();
                        $("#osdt").prop('checked', JSON.parse(tEnable));
                        //获取osd1文本坐标 与是否勾选osd1
                        var osdName = $(xmlDoc).find("DisplayName").eq(0).find("Name").text();
                        var arr = osdName.split("^");
                        var text = arr.join("<br>");
                        if (jQuery.inArray("[RES]", arr) > -1 || jQuery.inArray("[BPS]", arr) > -1 || jQuery.inArray("[RES] [BPS]", arr) > -1) {

                            var type = arr.pop();

                        };
                        var lesshtml = '';
                        $("#osdlisd").empty()
                        $("#osdna").val(arr[0]);
                        for (var i = 1; i < arr.length; i++) {
                            lesshtml += '<div class="osdlists"><input type="text" name="nName" value="' + arr[i] + '" class="form-control osdinput"><div onclick="cleaup(event)" style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
                        }
                        $("#osdlisd").append(lesshtml);
                        switch (type) {
                            case "[RES]":
                                $('#additional').val("2").trigger('change.select2')
                                break;
                            case "[BPS]":
                                $('#additional').val("3").trigger('change.select2')
                                break;
                            case "[RES] [BPS]":
                                $('#additional').val("4").trigger('change.select2')
                                break;
                            default:
                                $('#additional').val("1").trigger('change.select2')
                        };
                        nEnable = $(xmlDoc).find("DisplayName").eq(0).find('Enable').eq(0).text();
                        $("#osdw").prop('checked', JSON.parse(nEnable));
                        window2_left = $(xmlDoc).find('DisplayName').eq(0).find('PosX').eq(0).text();
                        window2_top = $(xmlDoc).find('DisplayName').eq(0).find('PosY').eq(0).text();
                        // 获取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(window2_left));
                        windowTopArr.push(parseInt(window2_top));

                        //初始化
                        osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, 1, osdCount);
                        // 时间的显示隐藏
                        var osdtChecked = $("#osdt").is(':checked');
                        osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, osdtChecked ? 7 : 8, osdCount);

                        // osd1显示隐藏
                        var osdwChecked = $("#osdw").is(':checked');
                        osdinit(textArr, windowLeftArr, windowTopArr, window1_left, window1_top, osdwChecked ? 5 : 6, osdCount, 0);

                    } else {
                        var osdName = $(xmlDoc).find('DisplayName').eq(0).find('Name').text();
                        if (osdName.split("^").length == 1) {
                            $("#osdlisd").empty()
                            $("#osdna").val(osdName);
                            $("#window2").html(osdName);
                        } else {
                            $("#osdlisd").empty()
                            var lesshtml = '<div class="osdlists"><input type="text" name="nName" value="' + osdName.split("^")[1] + '" class="form-control osdinput"><div onclick="cleaup1 style="display: inline-block;margin-left: 16px;"><img src="ipc/img/icon/set_del.png" alt=""></div></div>';
                            $("#osdlisd").append(lesshtml);
                            $("#window2").html(osdName.split("^")[0] + "<br> " + osdName.split("^")[1]);
                        }

                        nEnable = $(xmlDoc).find('OSD').eq(0).find('DisplayName').eq(0).find('Enable').eq(0).text();
                        $("#osdw").prop('checked', JSON.parse(nEnable));
                        if ($("#osdw").is(':checked') == true) {
                            $("#window2").show();
                        } else {
                            $("#window2").hide();
                        }
                        tEnable = $(xmlDoc).find('OSD').eq(0).find('DisplayTime').eq(0).find('Enable').eq(0).text();
                        $("#osdt").prop('checked', JSON.parse(tEnable));
                        if ($("#osdt").is(':checked') == true) {
                            $("#window1").show();
                        } else {
                            $("#window1").hide();
                        }
                        window2_left = $(xmlDoc).find('OSD').eq(0).find('DisplayName').eq(0).find('PosX').eq(0).text();
                        window2_top = $(xmlDoc).find('OSD').eq(0).find('DisplayName').eq(0).find('PosY').eq(0).text();
                        window1_left = $(xmlDoc).find('OSD').eq(0).find('DisplayTime').eq(0).find('PosX').eq(0).text();
                        window1_top = $(xmlDoc).find('OSD').eq(0).find('DisplayTime').eq(0).find('PosY').eq(0).text();

                        $("#window2").css("left", 560 * ((window2_left / 703)));
                        $("#window2").css("top", 420 * (window2_top / 575));
                        $("#window1").css("left", 560 * (window1_left / 703));
                        $("#window1").css("top", 420 * (window1_top / 575));
                        var ny = $("#window2").position().top;
                        if (ny + $("#window2").height() > 420) {
                            $("#window2").css("top", 420 - $("#window2").height());
                            //$("#window2").position().top = 264 - $("#window2").height();
                        }

                    }

                }
            },
            error: function(xhr, textStatus, errorThrown) {}
        });
    }
}
// HTML 转义函数
function htmlEscape(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}
// 保存osd配置
function setOSD(num) {
    if (config.deviceCap[currentchannel].osdTag == "true") { //支持多行osd
        if (sessionStorage.getItem("playstyle") != "EasyVideo") {
            if (nEnable == "false" || $("#osdw").is(':checked') == false) {
                var nx = window2_left;
                var ny = window2_top;
            } else {
                var nx = $("#window2").position().left / $("#axdiv").width() * 703;
                var ny = $("#window2").position().top / $("#axdiv").height() * 575;
            }
            if (osd2Enable == "false" || $("#osd2Enable").is(':checked') == false) {
                var osd2nx = window3_left;
                var osd2ny = window3_top;
            } else {
                var osd2nx = $("#window3").position().left / (560) * 703;
                var osd2ny = $("#window3").position().top / 420 * 575;
            }
            if (tEnable == "false" || $("#osdt").is(':checked') == false) {
                var tx = window1_left;
                var ty = window1_top;
            } else {
                var tx = $("#window1").position().left / (560) * 703;
                var ty = $("#window1").position().top / 420 * 575;
            }

        }
        var nName;
        //获取页面的值
        var vArr = [];
        var nameArr = $("input[name='nName']");
        for (var i = 0; i < nameArr.length; i++) {
            var value = $(nameArr[i]).val();
            if (value != "") {
                if (value.indexOf('^') > -1) {
                    value = value.replace("^", "")
                    value = value.replace(/</g, "&lt;").replace(/>/g, "&gt;")
                    vArr.push(value);
                } else {
                    value = value.replace(/</g, "&lt;").replace(/>/g, "&gt;")
                    vArr.push(value);
                }
            }
        };
        var lengC = false
        for (var i = 0; i < vArr.length; i++) {
            var add = 0
            var charCode = -1
            for (var k = 0; k < vArr[i].length; k++) {
                charCode = vArr[i][k].charCodeAt()
                if (charCode > 255) {
                    add += 2
                } else {
                    add += 1
                }
            }
            if (add > config.deviceCap[currentchannel].osdchar) {
                lengC = true
                break
            }
        }
        if (lengC) {
            $.optionBootoast($.i18n.prop('i18n-addrule'), "danger")
        } else {
            if (config.deviceCap[currentchannel].osdTag == "true" && config.deviceCap[currentchannel].osdShowd == "true") {
                var infoval = $("#additional").val();
            } else {
                var infoval = "1";
            }
            switch (infoval) {
                case "2":
                    vArr.push("[RES]")
                    break;
                case "3":
                    vArr.push("[BPS]")
                    break;
                case "4":
                    vArr.push("[RES] [BPS]")
                    break;
                default:
                    vArr;
                    break;
            };
            //alert(vArr)
            nName = vArr.join("^");
            easyName = nName
            var arrInput = $("input[name='nName']")
            for (var i = 0; i < arrInput.length; i++) {
                var realLength = 0,
                    charCode = -1
                for (var j = 0; j < $(arrInput[i]).val().length; j++) {
                    charCode = $(arrInput[i]).val().charCodeAt(j)
                    if (charCode > 255) realLength += 2
                    else realLength += 1
                }
            }
            //设置osd2
            // var osd2text = $("#osd2Text").val();
            var vArr2 = [];
            var nameArr2 = $("input[name='tName']");
            for (var q = 0; q < nameArr2.length; q++) {
                var value = $(nameArr2[q]).val();
                if (value != "") {
                    if (value.indexOf('^') > -1) {
                        value = value.replace("^", "")
                        value = value.replace(/</g, "&lt;").replace(/>/g, "&gt;")
                        vArr2.push(value);
                    } else {
                        value = value.replace(/</g, "&lt;").replace(/>/g, "&gt;")
                        vArr2.push(value);
                    }
                }
            };
            osd2 = vArr2.join('^')
            doyto2 = vArr2
            var lengC2 = false
            for (var l = 0; l < vArr2.length; l++) {
                var add = 0
                var charCode = -1
                for (var k = 0; k < vArr2[l].length; k++) {
                    charCode = vArr2[l][k].charCodeAt()
                    if (charCode > 255) {
                        add += 2
                    } else {
                        add += 1
                    }
                }
                if (add > config.deviceCap[currentchannel].odTwol) {
                    lengC2 = true
                    break
                }
            }
            if (lengC2) {
                $.optionBootoast($.i18n.prop('i18n-addrule'), "danger");
                return
            }

            if (!win2Mark) {
                var nx = window2_left;
                var ny = window2_top;
            }
            if (!win1Mark) {
                var tx = window1_left;
                var ty = window1_top;
            }
            if (!win3Mark) {
                var osd2nx = window3_left;
                var osd2ny = window3_top;
            }
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if ($("#dotosd").is(':checked')) {
                    if ($("#additional").val() != '1') {
                        vArr.pop()
                    }
                    osdgetDianzline(vArr.join('^'), $("#fontsizce").val());
                    isosdType = 'PictureOSD'
                } else {
                    osdputV();
                    isosdType = 'TextOSD'
                }
            }
            if (sessionStorage.getItem("playstyle") != "EasyVideo") {
                // 获取点阵信息
                if ($("#dotosd").is(':checked')) {
                    if ($("#additional").val() != '1') {
                        vArr.pop()
                    }
                    var k = $("#fontsizce").val()
                    if (k == '32') {
                        var ke = 16
                        var ge = 32
                    } else if (k == '16') {
                        var ke = 8
                        var ge = 16
                    } else if (k == '8') {
                        var ke = 4
                        var ge = 8
                    } else if (k == '12') {
                        var ke = 6
                        var ge = 12
                    } else {
                        var ke = 24
                        var ge = 46
                    }
                    var xml = '<?xml version="1.0" encoding="UTF-8" ?>' +
                        '<StringToLattice_In><FontName>宋体</FontName><FontUnderline>false</FontUnderline>' +
                        '<FontItalic>false</FontItalic><FontStrikeOut>false</FontStrikeOut><FontBold>false</FontBold>' +
                        '<SourceText>' + vArr.join('^') + '</SourceText><Width>' + ke + '</Width><Height>' + ge + '</Height></StringToLattice_In>'

                    var dotxmlDox = setlattice(xml);
                    console.log($(dotxmlDox).find('ImageData').text(), "5555555555");
                    isosdType = 'PictureOSD'
                } else {
                    isosdType = 'TextOSD'
                }
                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>' + nName + '</Text><x>' + nx + '</x><y>' + ny + '</y></OSD>' +
                    '<OSD Version="1.0"><ID>2</ID><Enable>' + $("#osd2Enable").is(':checked') + '</Enable><Text>' + osd2 + '</Text><x>' + osd2nx + '</x><y>' + osd2ny + '</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 >' +
                    '<OSDBmp><ID>1</ID><FontSize>' + $("#fontsizce").val() + '</FontSize><BmpW>' + $(dotxmlDox).find('ImageWidth').text() + '</BmpW><BmpH>' + $(dotxmlDox).find('ImageHeight').text() + '</BmpH>' +
                    '<OSDBmpBase64>' + $(dotxmlDox).find('ImageData').text() + '</OSDBmpBase64>' +
                    '<OSDBmpBase64Len>' + $(dotxmlDox).find('ImageData').text().length + '</OSDBmpBase64Len></OSDBmp></MultiLineOSD>'
                var cyURL;
                if (num) {
                    cyURL = window.config.baseUrl + "/Pictures/" + num + "/MultiOSDV2";
                } else {
                    cyURL = window.config.baseUrl + "/Pictures/1/MultiOSDV2";
                }
                $.ajax({
                    type: "PUT",
                    url: cyURL,
                    processData: false,
                    data: cyXml,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("If-Modified-Since", "0");
                    },
                    complete: function(xhr) {
                        if (copyFlag) {
                            //保证复制时候保存成功只显示一次
                            saveTimes++;
                            console.log(saveTimes, "saveTimes");
                            if (saveTimes == config.deviceInfo.VideoInputChannels) {
                                SaveStateTwo(xhrState, xhr);
                                saveTimes = 0;
                            }
                        } else {
                            SaveStateTwo(xhrState, xhr);
                        }
                        if (sessionStorage.getItem("playstyle") != "EasyVideo") {
                            getOSD(num);
                        }

                    }
                });

            }

        }
    } else {
        if (sessionStorage.getItem("playstyle") != "EasyVideo") {
            if (nEnable == "false" || $("#osdt").is(':checked') == false) {
                var nposx = window2_left;
                var nposy = window2_top;
            } else {
                var nposx = $("#window2").position().left / (560) * 703;
                var nposy = $("#window2").position().top / 420 * 575;
            }
            if (tEnable == "false" || $("#osdw").is(':checked') == false) {
                var tposx = window1_left;
                var tposy = window1_top;
            } else {
                var tposx = $("#window1").position().left / (560) * 703;
                var tposy = $("#window1").position().top / 420 * 575;
            }
            var nName;
            nName = $("#osdna").val();
            if (document.getElementsByClassName('osdlists').length > 0) {
                if (nName.length > config.deviceCap[currentchannel].osdchar) {
                    $.optionBootoast($.i18n.prop('i18n-addrule'), "danger");
                    return
                }
                if ($(".osdlists").length > 0) {
                    if ($(".osdlists input").val() != "") {
                        nName = nName + "^" + $(".osdlists input").val();
                        var nName1 = $(".osdlists input").val();
                        if (nName1.length > config.deviceCap[currentchannel].osdchar) {
                            $.optionBootoast($.i18n.prop('i18n-addrule'), "danger");
                            return
                        }
                    }
                }

            } else {
                if (nName.length > 40) {
                    $.optionBootoast($.i18n.prop('i18n-addrule'), "danger");
                    return;
                }
            }
            if (!win2Mark) {
                var nposx = window2_left;
                var nposy = window2_top;
            }
            if (!win1Mark) {
                var tposx = window1_left;
                var tposy = window1_top;
            }

            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>" + $("#osdt").is(':checked') + "</Enable>" +
                "<PosX>" + nposx + "</PosX>" +
                "<PosY>" + nposy + "</PosY>" +
                "<Name>" + nName + "</Name>" +
                "</DisplayName>" +
                "<DisplayTime Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
                "<Enable>" + $("#osdw").is(':checked') + "</Enable>" +
                "<PosX>" + tposx + "</PosX>" +
                "<PosY>" + tposy + "</PosY>" +
                "</DisplayTime>" +
                "</OSD>";
            var cyURL;
            if (num) {
                cyURL = config.baseUrl + "/Pictures/" + num + "/OSD";
            } else {
                cyURL = config.baseUrl + "/Pictures/1/OSD";
            }
            $.ajax({
                type: "PUT",
                url: cyURL,
                processData: false,
                data: cyXml,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("If-Modified-Since", "0");
                },
                complete: function(xhr) {
                    if (copyFlag) {
                        //保证复制时候保存成功只显示一次
                        saveTimes++;
                        console.log(saveTimes, "saveTimes");
                        if (saveTimes == config.deviceInfo.VideoInputChannels) {
                            SaveState(xhr);
                            saveTimes = 0;
                        }
                    } else {
                        SaveState(xhr);
                    }
                    getOSD();
                }
            });

        } else {
            var nName;
            //获取页面的值
            var vArr = [];
            var nameArr = $("input[name='nName']");
            for (var i = 0; i < nameArr.length; i++) {
                var value = $(nameArr[i]).val();
                if (value != "") {
                    if (value.indexOf('^') > -1) {
                        value = value.replace("^", "")
                        value = value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                        vArr.push(value);
                    } else {
                        value = value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                        vArr.push(value);
                    }
                }
            };
            var lengC = false
            for (var i = 0; i < vArr.length; i++) {
                var add = 0
                var charCode = -1
                for (var k = 0; k < vArr[i].length; k++) {
                    charCode = vArr[i][k].charCodeAt()
                    if (charCode > 255) {
                        add += 2
                    } else {
                        add += 1
                    }
                }
                if (add > config.deviceCap[currentchannel].osdchar && config.deviceCap[currentchannel].osdchar != "") {
                    lengC = true
                    break
                }
            }
            if (lengC) {
                $.optionBootoast($.i18n.prop('i18n-addrule'), "danger")
            } else {
                if (config.deviceCap[currentchannel].osdTag == "true" && config.deviceCap[currentchannel].osdShowd == "true") {
                    var infoval = $("#additional").val();
                } else {
                    var infoval = "1";
                }
                switch (infoval) {
                    case "2":
                        vArr.push("[RES]")
                        break;
                    case "3":
                        vArr.push("[BPS]")
                        break;
                    case "4":
                        vArr.push("[RES] [BPS]")
                        break;
                    default:
                        vArr;
                        break;
                };
                //alert(vArr)
                nName = vArr.join("^");
                easyName = nName
                var arrInput = $("input[name='nName']")
                for (var i = 0; i < arrInput.length; i++) {
                    var realLength = 0,
                        charCode = -1
                    for (var j = 0; j < $(arrInput[i]).val().length; j++) {
                        charCode = $(arrInput[i]).val().charCodeAt(j)
                        if (charCode > 255) realLength += 2
                        else realLength += 1
                    }
                }
                if (!win2Mark) {
                    var nx = window2_left;
                    var ny = window2_top;
                }
                if (!win1Mark) {
                    var tx = window1_left;
                    var ty = window1_top;
                }
            }
            if ($("#dotosd").is(':checked')) {
                if ($("#additional").val() != '1') {
                    vArr.pop()
                }
                osdgetDianzline(vArr.join('^'), $("#fontsizce").val());
                isosdType = 'PictureOSD'
            } else {
                osdputV();
                isosdType = 'TextOSD'
            }
        }
    }
}
//获取字符串总字符个数
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 keepdit(data) {
    keepdoit.width = data.OSD.width;
    keepdoit.base64 = data.OSD.base64;
    keepdoit.height = data.OSD.height;
    keepdoit.length = data.OSD.length;
    if (config.deviceCap[currentchannel].osddoitWidth < keepdoit.width || config.deviceCap[currentchannel].osddoitHeight < keepdoit.height) {
        $.optionBootoast($.i18n.prop('i18n-dain-osd'), "danger");
        return
    } else {
        if (config.deviceCap[currentchannel].osd2support != 'true' || $("#osd2Enable").is(':checked') != true) {
            osdputV();
        } else {
            console.log(doyto2, "2222");
            osdgetDianzline(doyto2.join('^'), $("#fontsizce").val(), 1);
        }

    }
}

function keepditow(data) {
    keepdoit2.width = data.OSD.width;
    keepdoit2.base64 = data.OSD.base64;
    keepdoit2.height = data.OSD.height;
    keepdoit2.length = data.OSD.length;
    if (config.deviceCap[currentchannel].osddoitWidth2 < keepdoit2.width || config.deviceCap[currentchannel].osddoitHeight2 < keepdoit2.height) {
        $.optionBootoast($.i18n.prop('i18n-dain-osd2'), "danger");
        return
    } else {
        osdputV();
    }
}

function getOSDtricValue(data) {
    var osd2ty = '',
        osd2tx = '';
    var ny = (data.OSD.text_y ? data.OSD.text_y[0] : 0);
    var nx = (data.OSD.text_x ? data.OSD.text_x[0] : 0);
    var tx = data.OSD.datetime_x;
    var ty = data.OSD.datetime_y;
    if (config.deviceCap[currentchannel].osd2support == 'true' && config.deviceCap[currentchannel].osd2maxcnt == 2) {
        osd2ty = ((data.OSD.text_y ? data.OSD.text_y[1] : 0));
        osd2tx = ((data.OSD.text_x ? data.OSD.text_x[1] : 0));
    }
    if (config.deviceCap[currentchannel].osdTag == "true") {
        var cyXml = '<?xml version="1.0" encoding="UTF-8" ?>' +
            '<MultiLineOSD Version="1.0"><OSDKind>' + isosdType + '</OSDKind>' +
            '<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>' + easyName + '</Text><x>' + nx + '</x><y>' + ny + '</y></OSD>' +
            '<OSD Version="1.0"><ID>2</ID><Enable>' + $("#osd2Enable").is(':checked') + '</Enable><Text>' + osd2 + '</Text><x>' + osd2tx + '</x><y>' + osd2ty + '</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>' +
            '<OSDBmp><ID>1</ID><FontSize>' + $("#fontsizce").val() + '</FontSize><BmpW>' + keepdoit.width + '</BmpW><BmpH>' + keepdoit.height + '</BmpH>' +
            '<OSDBmpBase64>' + keepdoit.base64 + '</OSDBmpBase64>' +
            '<OSDBmpBase64Len>' + keepdoit.length + '</OSDBmpBase64Len></OSDBmp>' +
            '<OSDBmp><ID>2</ID><FontSize>' + $("#fontsizce").val() + '</FontSize><BmpW>' + keepdoit2.width + '</BmpW><BmpH>' + keepdoit2.height + '</BmpH>' +
            '<OSDBmpBase64>' + keepdoit2.base64 + '</OSDBmpBase64>' +
            '<OSDBmpBase64Len>' + keepdoit2.length + '</OSDBmpBase64Len></OSDBmp></MultiLineOSD>'
        if (config.isSupportMultiChannel) {
            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') {
                // 点击保存, 保存当前通道
                channels.push($("#channel").val());
            }
            for (let index = 0; index < channels.length; index++) {
                var cyURL = baseURL + channels[index] + "/MultiOSDV2";
                setURlOSD(cyURL, cyXml, channels[index]);

            }
            copyType = '';
        } else {
            var cyURL = window.config.baseUrl + "/Pictures/1/MultiOSDV2";
            setURlOSD(cyURL, cyXml, 1);

        }


    } 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>" + easyName + "</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>";
        if (config.isSupportMultiChannel) {
            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') {
                // 点击保存, 保存当前通道
                channels.push($("#channel").val());
            }
            for (let index = 0; index < channels.length; index++) {
                var cyURL = baseURL + channels[index] + "/OSD";
                setURlOSD(cyURL, cyXml, channels[index]);

            }
            copyType = '';
        } else {
            var cyURL = window.config.baseUrl + "/Pictures/1/OSD";
            setURlOSD(cyURL, cyXml, 1);

        }


    }

}

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