var tTimeBar = null; //时间条对象
var gs_RecordInfo = [];
var RecordInfos = "";
var m_dtCalendarDate = ""; //当前日历的日期
var newMon = "";
var newYear = "";
var iType = "";
var m_year, m_month, m_day;
var m_szTime = [];
var m_szStartTimeSet = []; //开始时间集合
var m_szEndTimeSet = []; //结束时间集合
var m_szStartTimeSeconds = 0;
var m_szEndTimeSeconds = 0;
var numberOfScreens = 1;
var keeptimeisNow = null; //保留双击的时间
var SelDate = "";
var TimeBarSelDate = "";
var ip = location.hostname;
var m_bWndPause = false; //当前为暂停状态         暂停/播放
var m_bIsPlaying = false; //当前为停止状态	       未播放状态/播放状态
var m_bWndFrame = false; //单帧状态
var m_bSound = false;
var searchFlag = false;
var selclkTime = 0;
var m_iWndSpeed = 1; //播放速度
var number = 0;
var options = {};
$(document).ready(function() {
    config.lastnav = "remoteplayback";
    if (sessionStorage.getItem("playstyle") == "ActiveX") {
        if (config.deviceInfo.DeviceName == "IPC") {
            getVideoPlugin(sessionStorage.getItem("playstyle"), 2, "", true);
            SetActiveXMode(1);
        } else {
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", false, "", "", 0)
            initPlayback();
        }
    } else if (sessionStorage.getItem("playstyle") == "MJPEG" || sessionStorage.getItem("playstyle") == "WebPlayer") {
        $("#remotesearch").attr("disabled", true);
        document.getElementById("downloadvideo").setAttribute("src", "img/remoteplayback/downvideodis.png");
        $("#notplaymodel").show();
        $("#axdiv").hide();
    }
    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
    if (g_bIsIE) {
        $("#downloadvideo").hide()
    } else {
        $("#downloadvideo").show()
    }
    // 这里需要判断max存在否，不存在及不持支快放和慢进，nvr目前不支持
    if (config.deviceCap[number].Max == 0 && config.deviceInfo.DeviceName == 'NVR') {
        $("#fastForward").hide()
        $("#slowadvance").hide()
    }
    if (config.deviceInfo.DeviceName == "NVR") {
        $("#main").removeClass("showchancel");
        $("#select-channel").show();

        $(".videochancel").show();
        $("#videochancel").select2({
            width: '100%',
            minimumResultsForSearch: -1,
        });
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            $("#videochancel").append('<option class="option" value="' + i + '">' + i + '</option>'); //Channel列表
        }

        var liveHtml = "";
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            liveHtml += '<label class="btn btn-select-channel" id="select-channel-id' + i + '" data-id=' + i + '>' +
                '<div style="float: left;margin-top: -10px;margin-left: -6px;margin-right: -6px;">' +
                '<input type="radio" name="icpowermodes" id="resistancestrong" value="' + i + '">' +
                '</div>' +
                '<div style="float: left;">D' + i + '</div>' +
                '</label>';
        }
        $(".select-channel").html(liveHtml);
    }
    $("#select-channel-id1").addClass("active");
    $("input[name=icpowermodes]").eq(0).prop('checked', true);
    $(".select-channel label").on("click", function(evt) {
        for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
            $("#select-channel-id" + i).removeClass("active");
        }
        numberOfScreens = evt.currentTarget.getAttribute('data-id');
        $("#select-channel-id" + numberOfScreens).addClass("active");
        //playbackChannel('', false, "", "", 1,channel - 1)

    });

    $("#remoteslideleftId").toggle();
    $("#remotesliderightId").toggle();
    $(".remotepreviewRight").toggle();
    $(".remotemain").toggleClass("showyt");
    $("#content").toggleClass("showbj");
    $("#main").toggleClass("nopadding");
    $(".leftdiv ").toggleClass("showyt");

    $("#remoteslideleftId").click(function() {
        $("#remoteslideleftId").toggle();
        $("#remotesliderightId").toggle();
        $(".remotepreviewRight").toggle();
        $(".remotemain").toggleClass("showyt");
        $("#content").toggleClass("showbj");
        $("#main").toggleClass("nopadding");
        $(".leftdiv ").toggleClass("showyt");

    });
    $("#remotesliderightId").click(function() {
        $("#remoteslideleftId").toggle();
        $("#remotesliderightId").toggle();
        $(".remotepreviewRight").toggle();
        $(".remotemain").toggleClass("showyt");
        $("#content").toggleClass("showbj");
        $("#main").toggleClass("nopadding");
        $(".leftdiv ").toggleClass("showyt");
    });
    var canvas = document.getElementById("timeBar");
    if (canvas.getContext) { //判断浏览器是否支持canvas获取上下文
        tTimeBar = new TimeBar(canvas, window.innerWidth - 20, 76);
        // 给两个按钮增加提示
        $(".time-narrow")[0].title = $.i18n.prop("i18n-hf-fd");
        $(".time-expand")[0].title = $.i18n.prop("i18n-hf-sx");
    }
    var myDate = new Date();
    m_dtCalendarDate = myDate;
    newMon = myDate.getMonth() + 1;
    newYear = myDate.getFullYear();
    getRecordInfoByMonth(newYear, newMon);
    m_year = newYear;
    m_month = newMon;
    m_day = myDate.getDate();
    $("#remotetime").datepicker({
        todayHighlight: true, //设置当天日期高亮
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN',
        beforeShowDay: function(date) {
            var d = date;
            var curr_date = d.getDate();
            var curr_month = d.getMonth() + 1;
            var curr_year = d.getFullYear();
            var formatDate = curr_year + "-" + (curr_month < 10 ? "0" + curr_month : curr_month) + "-" + (curr_date < 10 ? "0" + curr_date : curr_date);
            //特殊日期的匹配
            if ($.inArray(formatDate, unique(gs_RecordInfo)) != -1) {
                return {
                    classes: 'daypoint',
                };
            } else {
                return;
            }
        },
    });

    $("<i class='specaildate'></i>").appendTo(".daypoint");


    $("#stratTime").datetimepicker({
        format: "yyyy-mm-dd hh:ii:ss",
        autoclose: true, // 选择日期后关闭
        language: 'zh-CN', //显示语言为中文
        todayBtn: true,
        minView: 0,
        minuteStep: 1,
        todayHighlight: true, //高亮显示当前日期
        endDate: $("#endTime").val()
    }).click(function(e) {
        e.currentTarget.blur();
    }).on('changeDate', function(ev) {
        var startDate = $("#stratTime").val();
        $("#endTime").datetimepicker('setStartDate', startDate);
    });

    $("#endTime").datetimepicker({
        format: "yyyy-mm-dd hh:ii:ss",
        autoclose: true, // 选择日期后关闭
        language: 'zh-CN', //显示语言为中文
        todayBtn: true,
        minuteStep: 1,
        minView: 0,
        todayHighlight: true, //高亮显示当前日期
        startDate: $("#stratTime").val()
    }).click(function(e) {
        e.currentTarget.blur();
    }).on('changeDate', function(ev) {
        var endDate = $("#endTime").val();
        $("#stratTime").datetimepicker('setEndDate', endDate);
    });

    $(window).resize(function() {
        tTimeBar = new TimeBar(canvas, window.innerWidth - 20, 76);
        tTimeBar.setMidLineTime(m_year + '-' + m_month + '-' + m_day + ' ' + '00:00:00');
        for (var k = 0; k < m_szTime.length; k++) {
            tTimeBar.addFile(m_szTime[k].start, m_szTime[k].end, m_szTime[k].type);
        }
        tTimeBar.m_tClickCurTime = selclkTime;
        tTimeBar.repaint();
        if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#remoteplayback.html") {
            remoteWindowfollowing();
        }
    });


    //绑定changeDate事件
    $('#remotetime').datepicker().on('changeDate', function(e) {
        m_dtCalendarDate = e.date;
        m_day = e.date.Format('yyyy-MM-dd').split("-")[2];
        $("<i class='specaildate'></i>").appendTo(".daypoint");
    });

    //绑定changeMonth事件
    $('#remotetime').datepicker().on('changeMonth', function(e) {
        newMon = e.date.Format('yyyy-MM-dd').split("-")[1];
        getRecordInfoByMonth(newYear, newMon);
        setTimeout(function() {
            $("<i class='specaildate'></i>").appendTo(".daypoint");
        }, 1000)
    });
    //绑定changeYear事件
    $('#remotetime').datepicker().on('changeYear', function(e) {
        // gs_RecordInfo = [];
        newYear = e.date.Format('yyyy-MM-dd').split("-")[0];
        getRecordInfoByMonth(newYear, newMon);
        setTimeout(function() {
            $("<i class='specaildate'></i>").appendTo(".daypoint");
        }, 1000)
    });

    //录像查找
    $("#remotesearch").click(function() {
        if (config.timebarSave) {
            // 清除setInterval
            clearInterval(config.timebarSave);
        }
        if (m_bIsPlaying) {
            StopPlayBack();
        }
        m_year = newYear;
        m_month = newMon;
        getRecordInfoByDay(newYear, newMon, m_day);
    });

    //开始播放
    $("#StartPlayBack").click(function() {
        if (document.getElementById("StartPlayBack").getAttribute("src", 2) == "img/remoteplayback/playdis.png") {
            return
        }
        if (m_szStartTimeSet.length === 0) {
            return
        }
        if (config.deviceInfo.DeviceName == "IPC") {
            var xml = "<Channel>1</Channel>"
        } else {
            var xml = "<Channel>" + (numberOfScreens - 1) + "</Channel>"
        }
        var strRemotePlaybackRequest = "<?xml version='1.0' encoding='UTF-8' ?>" +
            "<RemotePlaybackRequest>" +
            xml +
            "<StreamType>0</StreamType>" +
            "<EnableEndTime>false</EnableEndTime>" +
            "<StartTime>" +
            "<Year>" + m_szStartTimeSet[0].substr(0, 4) + "</Year>" +
            "<Month>" + m_szStartTimeSet[0].substr(5, 2) + "</Month>" +
            "<Day>" + m_szStartTimeSet[0].substr(8, 2) + "</Day>" +
            "<Hour>" + m_szStartTimeSet[0].substr(11, 2) + "</Hour>" +
            "<Minute>" + m_szStartTimeSet[0].substr(14, 2) + "</Minute>" +
            "<Second>" + m_szStartTimeSet[0].substr(17, 2) + "</Second>" +
            "</StartTime>" +
            "<EndTime>" +
            "<Year>" + m_szEndTimeSet[0].substr(0, 4) + "</Year>" +
            "<Month>" + m_szEndTimeSet[0].substr(5, 2) + "</Month>" +
            "<Day>" + m_szEndTimeSet[0].substr(8, 2) + "</Day>" +
            "<Hour>" + m_szEndTimeSet[0].substr(11, 2) + "</Hour>" +
            "<Minute>" + m_szEndTimeSet[0].substr(14, 2) + "</Minute>" +
            "<Second>" + m_szEndTimeSet[0].substr(17, 2) + "</Second>" +
            "</EndTime>" +
            "</RemotePlaybackRequest>";
        $("#pause").show();
        $("#StartPlayBack").hide();
        document.getElementById("stopplayremotevideo").setAttribute("src", "img/remoteplayback/stop.png");
        document.getElementById("slowadvance").setAttribute("src", "img/remoteplayback/slowadvance.png");
        document.getElementById("fastForward").setAttribute("src", "img/remoteplayback/fastforward.png");
        document.getElementById("singleframe").setAttribute("src", "img/remoteplayback/singleframe.png");
        document.getElementById("closeround").setAttribute("src", "img/remoteplayback/soundopen.png");
        document.getElementById("openround").setAttribute("src", "img/remoteplayback/soundclose.png");
        document.getElementById("remotefacepic").setAttribute("src", "img/remoteplayback/capture.png");
        // document.getElementById("downloadvideo").setAttribute("src","img/remoteplayback/downvideo.png");
        if (!m_bIsPlaying) {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    var ncx = document.getElementById("previewocx");
                    ncx.InitPreviewParameters(config.MacAddress, config.Network.mediaPort, config.deviceCap[number].StreamCount);
                    ncx.StartRemotePlayback(ip, config.Network.commandPort, config.user, config.password, strRemotePlaybackRequest);
                } else {
                    playbackstart(strRemotePlaybackRequest);
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    remoteplay(m_szStartTimeSet[0], "");
                } else { //此时是nvr回放需要传递通道号参数
                    remoteplay(m_szStartTimeSet[0], "", numberOfScreens);
                }
            }
            tTimeBar.m_tClickCurTime = m_szStartTimeSeconds;
            selclkTime = m_szStartTimeSeconds;
            config.SaveCavans = tTimeBar;
            tTimeBar.repaint();
            m_bIsPlaying = true;
            m_bWndFrame = false;
            m_bWndPause = false;
            m_iWndSpeed = 1;
            $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));
        } else {
            if (m_bWndPause && !m_bWndFrame) {
                ResumePlayback();
            } else {
                if (sessionStorage.getItem("playstyle") == "ActiveX") {
                    if (config.deviceInfo.DeviceName == "IPC") {
                        var ncx = document.getElementById("previewocx");
                        ncx.ResumeRemotePlayback();
                    } else {
                        PlayByFrameRemotePlayback(numberOfScreens - 1, 1)
                    }
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    if (config.deviceInfo.DeviceName == 'IPC') {
                        remoteplay(m_szStartTimeSet[0], "");
                    } else { //此时是nvr回放需要传递通道号参数
                        remoteplay(m_szStartTimeSet[0], "", numberOfScreens);
                    }
                }
                if (m_iWndSpeed < 1) {
                    $("#speed").text($.i18n.prop('i18n-Currentstate') + "1/" + (1 / m_iWndSpeed) + $.i18n.prop('i18n-Doublespeed'));
                } else {
                    $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));
                }
                m_bWndPause = false;
                m_bWndFrame = false;
            }
        }
        if( config.timebarSave===null){
            config.timebarSave = setInterval((function(currentScreens) {
                return function() {
                    if (sessionStorage.getItem("playstyle") == "ActiveX") {
                        PlaybackGetPos(currentScreens);
                    } else {
                        serchVideoCounts(currentScreens);
                    }
                };
            })(numberOfScreens), 1000);
        }
    });
    //停止播放
    $("#stopplayremotevideo").click(function() {
        clearInterval(config.timebarSave);
        if (document.getElementById("stopplayremotevideo").getAttribute("src", 2) == "img/remoteplayback/stopdis.png") {
            return
        }
        StopPlayBack();
        m_bIsPlaying = false;
    });
    //暂停播放
    $("#pause").click(function() {
        clearInterval(config.timebarSave);
        if (m_bIsPlaying) {
            $("#pause").hide();
            $("#StartPlayBack").show();
            if (!m_bWndPause && !m_bWndFrame) {

                if (sessionStorage.getItem("playstyle") == "ActiveX") {
                    if (config.deviceInfo.DeviceName == "IPC") {
                        var ncx = document.getElementById("previewocx");
                        ncx.PauseRemotePlayback();
                    } else {
                        RemotePlaybackSuspend(1, numberOfScreens - 1)
                    }
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    if (config.deviceInfo.DeviceName == "IPC") {
                        remotepause();
                    } else {
                        remotepause(numberOfScreens);
                    }
                }
                m_iWndSpeed = 1;
                $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));
                // m_bIsPlaying = false;
                m_bWndPause = true;
            }
        }
    });
    //快进
    $("#fastForward").click(function() {
        if (document.getElementById("fastForward").getAttribute("src", 2) == "img/remoteplayback/fastforwarddis.png") {
            return
        }
        if (m_bIsPlaying && !m_bWndPause && !m_bWndFrame) {
            if (m_iWndSpeed < config.deviceCap[number].Max) {
                m_bWndFrame = false;
                m_iWndSpeed = 2 * m_iWndSpeed;
                if (sessionStorage.getItem("playstyle") == "ActiveX") {
                    var ncx = document.getElementById("previewocx");
                    ncx.SpeedUpRemotePlayback();
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    if (config.deviceInfo.DeviceName == "IPC") {
                        fastForward();
                    } else {
                        fastForward(numberOfScreens);
                    }
                }
            }
            if (m_iWndSpeed < 1) {
                $("#speed").text($.i18n.prop('i18n-Currentstate') + "1/" + (1 / m_iWndSpeed) + $.i18n.prop('i18n-Doublespeed'));
            } else {
                $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));
            }
        }
    });
    //慢进
    $("#slowadvance").click(function() {
        if (document.getElementById("slowadvance").getAttribute("src", 2) == "img/remoteplayback/slowadvancedis.png") {
            return
        }
        if (m_bIsPlaying && !m_bWndPause && !m_bWndFrame) {
            if (m_iWndSpeed > 1 / config.deviceCap[number].Max) {
                m_bWndFrame = false;
                m_iWndSpeed = 1 / 2 * m_iWndSpeed;
                if (sessionStorage.getItem("playstyle") == "ActiveX") {
                    var ncx = document.getElementById("previewocx");
                    ncx.SpeedDownRemotePlayback();
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    if (config.deviceInfo.DeviceName == "IPC") {
                        remoteslowadvance();
                    } else {
                        remoteslowadvance(numberOfScreens);
                    }
                }
            }
            if (m_iWndSpeed < 1) {
                $("#speed").text($.i18n.prop('i18n-Currentstate') + "1/" + (1 / m_iWndSpeed) + $.i18n.prop('i18n-Doublespeed'));
            } else {
                $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));
            }
        }
    });
    //单帧
    $("#singleframe").click(function() {
        if (document.getElementById("singleframe").getAttribute("src", 2) == "img/remoteplayback/singleframedis.png") {
            return
        }
        if (m_bIsPlaying) {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    var ncx = document.getElementById("previewocx");
                    ncx.PlayByFrameRemotePlayback();
                } else {
                    PlayByFrameRemotePlayback(numberOfScreens - 1, 0)
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    remotesingleframe();
                } else {
                    remotesingleframe(numberOfScreens);
                }
            }
            $("#pause").hide();
            $("#StartPlayBack").show();
            m_bWndFrame = true;
            // m_bIsPlaying = false;
            m_bIsPlaying = true;
            m_iWndSpeed = 1;
            $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));

        }
    });
    //关闭声音
    $("#closeround").click(function() {
        if (document.getElementById("closeround").getAttribute("src", 2) == "img/remoteplayback/soundopendis.png") {
            return
        }
        if (m_bIsPlaying) {
            $("#closeround").hide();
            $("#openround").show();
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    var ncx = document.getElementById("previewocx");
                    ncx.PlaySoundRemotePlayback(0);
                } else {
                    PlaySoundRemotePlayback(0, numberOfScreens - 1)
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    remotecloseround();
                } else {
                    remotecloseround(numberOfScreens);
                }
            }

        }
    });
    //打开声音
    $("#openround").click(function() {
        if (document.getElementById("openround").getAttribute("src", 2) == "img/remoteplayback/soundclosedis.png") {
            return
        }
        if (m_bIsPlaying) {
            $("#closeround").show();
            $("#openround").hide();
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    var ncx = document.getElementById("previewocx");
                    ncx.PlaySoundRemotePlayback(1);
                } else {
                    PlaySoundRemotePlayback(1, numberOfScreens - 1)
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    remoteopenround();
                } else {
                    remoteopenround(numberOfScreens);
                }

            }

        }
    });
    //抓图
    $("#remotefacepic").click(function() {
        if (document.getElementById("remotefacepic").getAttribute("src", 2) == "img/remoteplayback/capturedis.png") {
            return
        }
        if (m_bIsPlaying) {
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                if (config.deviceInfo.DeviceName == "IPC") {
                    try {
                        var ncx = document.getElementById("previewocx");
                        var nRet = ncx.CaptureImageRemotePlayback(1);
                    } catch (e) {}
                } else {
                    CaptureImageRemotePlayback(numberOfScreens - 1)
                }
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                if (config.deviceInfo.DeviceName == 'IPC') {
                    easyCaptureImage(false);
                } else {
                    easyCaptureImage(false, numberOfScreens - 1); //nvr的抓图
                }

            }

        }
    });
    //下载录像
    $("#downloadvideo").click(function() {
        clearInterval(config.timebarSave);
        config.isdown = 2;
        if (document.getElementById("downloadvideo").getAttribute("src", 2) == "img/remoteplayback/downvideodis.png") {
            return
        }
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            remoteHiddenDisplaywindow(4)
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            $("#axdiv").hide();
        }
        $('#dowloadvideoModal').attr("confirm", "false").modal({
            backdrop: 'static',
            keyboard: false
        });
        $("#dowloadvideoModal").modal("show");
    });
    //关闭那个模态框要把定时器清掉
    $('#claosedown').click(function() {
        $("#nowdoloadBtn").prop("disabled", false);
        config.isdown = 1;
        $("#dowloadvideoModal").modal("hide");
        $("#nowdoloadBtn").text($.i18n.prop('i18n-Downloadnow'));
        $("#stratTime").val(""); //重置表单
        $("#endTime").val(""); //重置表单
        // 关闭模态框清除时间选择限制
        $("#endTime").datetimepicker('setStartDate', null);
        $("#stratTime").datetimepicker('setEndDate', null);
        clearInterval(config.doloadInterval);
        // 明显有问题的逻辑不清楚写在这儿干嘛？注释掉
        // config.timebarSave = setInterval(function() {
        //     if (sessionStorage.getItem("playstyle") == "ActiveX") {
        //         PlaybackGetPos(numberOfScreens);
        //     } else {
        //         serchVideoCounts(numberOfScreens);
        //     }
        // }, 1000);
        // if (sessionStorage.getItem("playstyle") == "EasyVideo") {
        //     rmotedownloadvideo(3);
        //     remoteHiddenDisplaywindow(3)
        // } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
        //     $("#axdiv").show();
        // }
    });
    //立即下载
    $("#nowdoloadBtn").click(function() {
        if ($("#stratTime").val() == "" || $("#endTime").val() == "") {
            bootoast({
                message: $.i18n.prop('i18n-selectDownloading'),
                type: 'danger',
                position: 'bottom-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        } else {
            if (document.getElementById("nowdoloadBtn").innerText.toString() == $.i18n.prop('i18n-Downloadnow')) { //立即下载
                config.isdown = 2;
                $("#nowdoloadBtn").prop("disabled", true);
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    if (config.deviceInfo.DeviceName == "NVR") {
                        rmotedownloadvideo(1, $("#videochancel").val() - 1)
                    } else {
                        rmotedownloadvideo(1)
                    }
                } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
                    if (config.deviceInfo.DeviceName == "IPC") {} else {
                        var path = "C:\Users\Administrator\Desktop"
                        var xml = "<?xml version='1.0' encoding='UTF-8' ?>" +
                            "<RemoteDownloadRequest>" +
                            "<Channel>" + ($("#videochancel").val() - 1) + "</Channel>" +
                            "<StreamType>11111</StreamType>" +
                            "<EnableEndTime>1</EnableEndTime>" +
                            "<StartTime>" + $("#stratTime").val() + "</StartTime>" +
                            "<EndTime>" + $("#endTime").val() + "</EndTime>" +
                            "<DataType>0</DataType>" +
                            "<MaxSize>31457280</MaxSize>" +
                            "<FolderName>" + path + "</FolderName>" +
                            "<DiskType>1</DiskType>" +
                            "<StreamMediaType>0</StreamMediaType>" +
                            "</RemoteDownloadRequest>";
                        var nRet = StartHistroyStreamDownload(xml);
                        if (nRet == 0) {
                            config.doloadInterval = setInterval("getRemoteDownloadPercent()", 3000);
                        }
                    }
                }
            } else if (document.getElementById("nowdoloadBtn").innerText.toString() == $.i18n.prop('i18n-Downloadsuccess')) { //下载完成
                config.isdown = 1;
                $("#nowdoloadBtn").prop("disabled", false);
                $("#dowloadvideoModal").modal("hide");
                $("#nowdoloadBtn").text($.i18n.prop('i18n-Downloadnow'));
                $("#stratTime").val(""); //重置表单
                $("#endTime").val(""); //重置表单
                clearInterval(config.doloadInterval);
                // config.timebarSave = setInterval(function() {
                //     if (sessionStorage.getItem("playstyle") == "ActiveX") {
                //         PlaybackGetPos(numberOfScreens);
                //     } else {
                //         serchVideoCounts(numberOfScreens);
                //     }
                // }, 1000);
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    rmotedownloadvideo(3);
                    remoteHiddenDisplaywindow(3)
                } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
                    $("#axdiv").show();
                }
            } else { //下载中
                config.isdown = 2;
                $("#nowdoloadBtn").prop("disabled", true);
            }
        }
    });


    $(".timeGoTo").click(function() {
        GoTime();
    });


});

function refsh() {
    self.playervideo = null;
    remoteplay(m_szStartTimeSet[0], "", numberOfScreens);
}

function getRemoteDownloadPercent() {
    var nCet = GetRemoteDownloadPercent();
    if (0 < nCet && nCet < 100) {
        $('#nowdoloadBtn').text($.i18n.prop('i18n-Downloading') + nCet / 100 + "%");
    } else if (nCet == -12) {
        $('#nowdoloadBtn').text($.i18n.prop('i18n-Downloadsuccess'));
        $("#nowdoloadBtn").prop("disabled", false);
    }
}

/*******************************************************************************
 * Function GoTime 功能: 回放时间点定位
 ******************************************************************************/
function GoTime() {
    var hour = $('#timeHour').val();
    var min = $('#timeMin').val();
    var sec = $('#timeSec').val();
    var posTime = new Date(m_dtCalendarDate.getFullYear(), m_dtCalendarDate.getMonth(), m_dtCalendarDate.getDate(), hour, min, sec).getTime();
    if (m_bIsPlaying) {
        if (posTime < m_szStartTimeSeconds) {
            tTimeBar.m_tClickCurTime = m_szStartTimeSeconds;
            tTimeBar.repaint();
        } else if (posTime > m_szEndTimeSeconds) {
            return;
        } else {
            tTimeBar.m_tClickCurTime = posTime;
            tTimeBar.repaint();
        }
        var strRemotePlaybackSetPos = "<?xml version='1.0' encoding='UTF-8' ?>" +
            "<RemotePlaybackPosTimeInfo>" +
            "<Year>" + m_dtCalendarDate.getFullYear() + "</Year>" +
            "<Month>" + (m_dtCalendarDate.getMonth() + 1) + "</Month>" +
            "<Day>" + m_dtCalendarDate.getDate() + "</Day>" +
            "<Hour>" + hour + "</Hour>" +
            "<Minute>" + min + "</Minute>" +
            "<Second>" + sec + "</Second>" +
            "</RemotePlaybackPosTimeInfo>";

        var month = m_dtCalendarDate.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }

        var newPos = m_dtCalendarDate.getFullYear() + "-" + month + "-" + m_dtCalendarDate.getDate() + " " + hour + ":" + min + ":" + sec;

        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            if (config.deviceInfo.DeviceName == "IPC") {
                var ncx = document.getElementById("previewocx");
                ncx.RemotePlaybackSetPos(strRemotePlaybackSetPos);

            } else {
                RemotePlaybackSetPos(numberOfScreens - 1, strRemotePlaybackSetPos)
            }

        } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            if (config.deviceInfo.DeviceName == 'IPC') {
                gotimepos(newPos);
            } else {
                gotimepos(newPos, numberOfScreens);
            }

        }

        if (m_bWndPause) {
            ResumePlayback();
        }

    }
}

/**
 * 停止播放
 * @constructor
 */
function StopPlayBack() {
    if (config.timebarSave) {
        // 清除setInterval
        clearInterval(config.timebarSave);
    }
    if (m_bIsPlaying) {
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            if (config.deviceInfo.DeviceName == 'IPC') {
                var ncx = document.getElementById("previewocx");
                ncx.StopRemotePlayback();
            } else {
                StopRemotePlayback();
            }
        } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            if (config.deviceInfo.DeviceName == 'IPC') {
                remotestopplay();
            } else {
                remotestopplay(numberOfScreens);
            }
        }
        m_bIsPlaying = false;
        m_bSound = false;
        m_bWndFrame = false;
        m_iWndSpeed = 1;
        searchFlag = false;
        $("#speed").text($.i18n.prop('i18n-Currentstate') + m_iWndSpeed + $.i18n.prop('i18n-Doublespeed'));
        $("#pause").hide();
        $("#StartPlayBack").show();
        document.getElementById("stopplayremotevideo").setAttribute("src", "img/remoteplayback/stopdis.png");
        document.getElementById("slowadvance").setAttribute("src", "img/remoteplayback/slowadvancedis.png");
        document.getElementById("fastForward").setAttribute("src", "img/remoteplayback/fastforwarddis.png");
        document.getElementById("singleframe").setAttribute("src", "img/remoteplayback/singleframedis.png");
        document.getElementById("closeround").setAttribute("src", "img/remoteplayback/soundopendis.png");
        document.getElementById("openround").setAttribute("src", "img/remoteplayback/soundclosedis.png");
        document.getElementById("remotefacepic").setAttribute("src", "img/remoteplayback/capturedis.png");
        // document.getElementById("downloadvideo").setAttribute("src","img/remoteplayback/downvideodis.png");
    }
}


function getRecordInfoByMonth(y, m) {
    if (m.toString().indexOf("0") != -1) {
        var mon = m
    } else {
        var mon = m >= 10 ? m : '0' + m;

    }
    $.ajax({
        type: "get",
        url: config.baseUrl + "/Playback/GetRecordInfoByMonth?Year=" + y + "&Month=" + mon,
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            var RecordInfoByMonth = $(xmlDoc).find('RecordInfo').text();
            RecordInfos = RecordInfoByMonth.split('');
            for (var i = 0; i < RecordInfos.length; i++) {
                if (RecordInfos[i] === "1") {
                    var day = i + 1;
                    var str_date = y + "-" + mon + "-" + (day < 10 ? "0" + day : day);
                    gs_RecordInfo.push(str_date);

                }
            }

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

        }
    });
}



function ResumePlayback() {
    if (sessionStorage.getItem("playstyle") == "ActiveX") {
        if (config.deviceInfo.DeviceName == "IPC") {
            var ncx = document.getElementById("previewocx");
            ncx.ResumeRemotePlayback();
        } else {
            RemotePlaybackSuspend(0, numberOfScreens - 1)
        }
    } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
        if (config.deviceInfo.DeviceName == "IPC") {
            remoteplay(m_szStartTimeSet[0], "");
        } else {
            remoteplay(m_szStartTimeSet[0], "", numberOfScreens);
        }
    }
    m_bIsPlaying = true;
    m_bWndPause = false;
}

/**
 * 增加时间格
 */
function addtime() {
    tTimeBar.addtime();
}

/**
 * 减少时间格
 */
function jstime() {
    tTimeBar.jstime();
}

/**
 * 数组去重
 * @param arr
 * @returns {Array}
 */
function unique(arr) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i])
        }
    }
    return newArr
}



/*************************************************
 Function:        SearchRecordFile
 Description:     搜索录像文件
 year:            当前年份
 month:           当前月份
 day:             当前日期
 Output:            无
 *************************************************/
function getRecordInfoByDay(year, month, day) {
    if (numberOfScreens == 0) {
        bootoast({
            message: "先选择通道！",
            type: 'success',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
        return;
    }
    SelDate = new Date(year, month - 1, day, 0, 0, 0);
    TimeBarSelDate = new Date(year, month, day, 0, 0, 0);

    bootoast({
        message: $.i18n.prop('i18n-Insearch'),
        type: 'success',
        position: 'bottom-center',
        timeout: true,
        animationDuration: 3000,
        dismissable: true
    });
    m_szStartTimeSet.length = [];
    m_szEndTimeSet = [];
    m_szTime = [];
    tTimeBar.m_iSelWnd = 0;
    tTimeBar.clearWndFileList(0);
    tTimeBar.repaint();
    $.ajax({
        type: "get",
        url: config.baseUrl + "/Playback/GetRecordInfoByDay?Channel=" + numberOfScreens + "&RecordType=255&Year=" + year + "&Month=" + month + "&Day=" + day,
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            var RecordFile = $(xmlDoc).find('RecordInfo').length;
            if (RecordFile === 0) {
                bootoast({
                    message: $.i18n.prop('i18n-hf-tups'),
                    type: 'success',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return;
            }
            for (var i = 0; i < RecordFile; i++) {
                var szStartTime = $(xmlDoc).find('StartTime').eq(i).text();
                var formatStartTime = szStartTime.substr(0, 4) + '-' + szStartTime.substr(4, 2) + '-' + szStartTime.substr(6, 2) + ' ' + szStartTime.substr(8, 2) + ':' + szStartTime.substr(10, 2) + ':' + szStartTime.substr(12, 2);
                m_szStartTimeSet.push(formatStartTime);

                var szStopTime = $(xmlDoc).find('EndTime').eq(i).text();
                var formatStopTime = szStopTime.substr(0, 4) + '-' + szStopTime.substr(4, 2) + '-' + szStopTime.substr(6, 2) + ' ' + szStopTime.substr(8, 2) + ':' + szStopTime.substr(10, 2) + ':' + szStopTime.substr(12, 2);
                m_szEndTimeSet.push(formatStopTime);

                var szType = $(xmlDoc).find('RecordType').eq(i).text();
                switch (szType) {
                    case 'general':
                        iType = "1";
                        break;
                    case 'manual':
                        iType = "2";
                        break;
                    case 'alarm':
                        iType = "3";
                        break;
                    case 'motion':
                        iType = "4";
                        break;
                    case 'ai':
                        iType = "5";
                        break;
                    default:
                        iType = "1";
                        break;
                }
                m_szTime.push(new objTime(iType, formatStartTime, formatStopTime));
            }
            m_szTime.sort(compare('start'));
            var fileLength = m_szTime.length;
            var startTimeSeconds = new Date(m_szTime[0].start.substr(0, 4), m_szTime[0].start.substr(5, 2) - 1, m_szTime[0].start.substr(8, 2), m_szTime[0].start.substr(11, 2), m_szTime[0].start.substr(14, 2), m_szTime[0].start.substr(17, 2));
            m_szStartTimeSeconds = startTimeSeconds.getTime();
            var endTimeSeconds = new Date(m_szTime[fileLength - 1].end.substr(0, 4), m_szTime[fileLength - 1].end.substr(5, 2) - 1, m_szTime[fileLength - 1].end.substr(8, 2), m_szTime[fileLength - 1].end.substr(11, 2), m_szTime[fileLength - 1].end.substr(14, 2), m_szTime[fileLength - 1].end.substr(17, 2));
            m_szEndTimeSeconds = endTimeSeconds.getTime();

            for (var k = 0; k < fileLength; k++) {
                tTimeBar.addFile(m_szTime[k].start, m_szTime[k].end, m_szTime[k].type);
            }
            tTimeBar.setMidLineTime(year + '-' + month + '-' + day + ' ' + '00:00:00');
            config.SaveCavans = tTimeBar;
            config.RemoteplayPosin = tTimeBar.FileInfoSet.slice();
            tTimeBar.repaint();
            if (fileLength > 0) {
                document.getElementById("StartPlayBack").setAttribute("src", "img/remoteplayback/play.png");
            }
        },
        error: function(xhr, textStatus, errorThrown) {

        }
    });
}


function compare(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if (value2 < value1) {
            return 1;
        } else if (value2 > value1) {
            return -1;
        } else {
            return 0;
        }
    };
}


function objTime(rType, sTime, eTime) {
    this.type = rType;
    this.start = sTime;
    this.end = eTime;
}

function getMidnightTimestamp(date) {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
}
