// JavaScript source code. record search and download.

//工具函数---start
function CreateEmptyString(l) {
    var a = [];
    for (var i = 0; i < l; i++) {
        a[i] = '*';
    }
    return a.join('');
}

//向列表中添加表项
function AddList(sel, text, value) {
    var option = document.createElement("option");
    option.appendChild(document.createTextNode(text));
    option.setAttribute("value", value);
    sel.appendChild(option);
}

//去除时间格式内的HTTP关键字
function FormatTime(time) {
    var tmp_string = time.split(' ');
    var tmp_string_cp = tmp_string[1].split(':');
    return tmp_string[0] + '%20' + tmp_string_cp[0] + '%3A' + tmp_string_cp[1] + '%3A' + tmp_string_cp[2];
}

var IS_SHOW_DEBUG = 0;  //0-关闭, 1-开启

function DebugAlert(str) {
    if (IS_SHOW_DEBUG == 1) {
        alert(str);
    }
}

String.prototype.replaceAll = function (f, r) {
    var s = new String(this);
    while (s.indexOf(f) != -1) {
        s = s.replace(f, r);
    }
    return s.toString();
}

/**
 * 解析从控件返回的xml字符串
 */
function loadXML(xmlString) {
    if (!g_xmlActive) {
        return;
    }
    g_xmlActive.loadXML(xmlString);
    if (0 == g_xmlActive.parseError.errorCode) {
        return g_xmlActive;
    }
    else {
        //alert("xml解析错误:" + g_xmlActive.parseError.reason);
        return null;
    }
}

function getElementById(dom, tagName) {
    for (var i = 0; i < dom.childNodes.length; i++) {
        var node = dom.childNodes[i];
        if (node.baseName == tagName) {
            return node.nodeTypedValue;
        }
        else {
            if (node.childNodes.length != 0) {
                getElementById(dom.childNodes[i], tagName);
            }
        }
    }
}

//工具函数---end

//全局变量---start
var g_UserLoginId = '';
var g_UserName = '';    //登录用户名
var g_PassWord = '';    //登录用户密码
var g_ServerIP = '';    //服务器IP地址
var g_imosActivePlayer = null;
var g_curFrameNum = '';
var g_xmlActive = null;
//全局变量---end

//================>功能函数---start
//检查控件
function Init() {
    initPage(); // 初始化gis地图
    InitActiveX();
}

// 初始化ActiveX
function InitActiveX(){
    g_imosActivePlayer = document.all.h3c_IMOS_ActiveX;
    if (!g_imosActivePlayer) {
        alert("未安装控件，请先安装后再使用本页面");
    }

    var xmldoc;
    try {
        xmldoc = new ActiveXObject("Microsoft.XMLDOM");
        if (!xmldoc) {
            xmldoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
        }
    }
    catch (e) {
    }
    g_xmlActive = xmldoc;
    if (!g_xmlActive) {
       // alert("xml解析器获取错误，将导致某些功能不可用");
    }
    else {
        g_xmlActive.async = "false";
    }
}

//登录    
function DoLogin() {
    if (!g_imosActivePlayer) {
        alert("未安装控件，请先安装后再使用本页面");
        return;
    }
    var serverIP = document.getElementById("ServerIPText").value;
    var userName = document.getElementById("UserNameText").value;
    var passWd = document.getElementById("PassWordText").value.toString();
    if (passWd == "") {
        passWd = "";
    }
    //alert(typeof passWd);
    var flag = g_imosActivePlayer.IMOSAX_InitOCX(serverIP, "8800", userName, passWd, 1);

    //获取用户信息
    var retStr = g_imosActivePlayer.IMOSAX_GetUserLoginInfo();
    var userObj = loadXML(retStr);
    g_UserLoginId = userObj.documentElement.selectNodes("//LOGININFO/UserLoginIDInfo/UserLoginCode")[0].text;
}
//退出登录
function DoLogout() {
    if (g_imosActivePlayer) {
        var flag = g_imosActivePlayer.IMOSAX_UnregOCX();
        if (0 != flag) {
            //暂时不提示
        }
    }
}
//启动实况
function DoStartPlay() {
    if (!g_imosActivePlayer) {
        alert("未安装控件，请先安装后再使用本页面");
        return;
    }
    var cameraId = document.getElementById("CamIDText").value;
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var flag = g_imosActivePlayer.IMOSAX_StartFrameLive(frameNum, cameraId);
    if (0 == flag) {
        alert("实况播放成功");
    }
    else {
        alert("播放实况失败，错误码：" + flag);
    }
}

//释放实况
function DoStopPlay() {
    if (!g_imosActivePlayer) {
        alert("未安装控件，请先安装后再使用本页面");
        return;
    }
    var frameNum = g_curFrameNum;
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请选择一个窗格");
        return;
    }
    var flag = g_imosActivePlayer.IMOSAX_StopFrameLive(frameNum);
    if (0 == flag) {
        alert("停止实况成功");
    }
    else {
        alert("停止实况失败，错误码：" + flag);
    }
}

//获取摄像机列表
//相关说明详见摄像机列表说明.txt
function DoGetCamList() {
}

//发送云台指令
function DoStartPtz() {
    //开始云台控制    /* 发送云台控制指令*/
    if (!g_imosActivePlayer) {
        alert("未安装控件，请先安装后再使用本页面");
        return;
    }
    //摄像机名称
    var cameraId = document.getElementById("CamIDText").value;
    var PtzCmd = parseInt(document.getElementById("PtzCmdText").value, 16);
    var ptzSpeed = 6;
    var flag = g_imosActivePlayer.IMOSAX_SendPtzCtrlCommand(cameraId, PtzCmd, ptzSpeed, ptzSpeed, 0);
    if (0 != flag) {
        alert("云台控制出错，错误码：" + flag);
    }
}

function DoStopPtz() {
    if (!g_imosActivePlayer) {
        alert("未安装控件，请先安装后再使用本页面");
        return;
    }
    //摄像机名称
    var cameraId = document.getElementById("CamIDText").value;
    var PtzCmd = 0x0901;
    var ptzSpeed = 6;
    var flag = g_imosActivePlayer.IMOSAX_SendPtzCtrlCommand(cameraId, PtzCmd, ptzSpeed, ptzSpeed, 0);
    if (0 != flag) {
        alert("云台控制出错，错误码：" + flag);
    }
}

function DoQueryRecord(cameraId) {
    //var cameraId = document.getElementById("CamIDText").value;
    var startQueryTime = document.getElementById("startTimeText").value;
    var endQueryTime = document.getElementById("endTimeText").value;
    var retStr = g_imosActivePlayer.IMOSAX_QueryRecord(cameraId, startQueryTime, endQueryTime);
    // test
    //var FileListObj = document.all.videolist;
    AddVideoItem(startQueryTime + '~' + endQueryTime);

    if (!retStr) {
        return;
    }
    var recordListObj = loadXML(retStr);
    var RecordObjArray = recordListObj.documentElement.selectNodes("//RESLIST/item");

    var FileListObj = document.all.videolist;
    for (i = 0; i < RecordObjArray.length; i++) {
        var FileName = RecordObjArray[i].selectSingleNode("FileName").text;
        var StartTime = RecordObjArray[i].selectSingleNode("StartTime").text;
        var EndTime = RecordObjArray[i].selectSingleNode("EndTime").text;
        AddVideoItem(StartTime + '~' + EndTime);
    }
}

function DoPlayRecord() {
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var cameraId = document.getElementById("CamIDText").value;
    var FileListObj = document.all.FileList;
    var file_name = FileListObj.value;
    var start_time;
    var stop_time;
    var time_array;
    // 从列表中获取当前选择的文件起止时间
    for (var i = 0; i < FileListObj.options.length; i++) {
        if (FileListObj.options[i].value == FileListObj.value) {
            time_array = FileListObj.options[i].innerText.split("~");
            start_time = time_array[0];
            stop_time = time_array[1];
            DebugAlert(start_time + ":" + stop_time);
            break;
        }
    }
    if ("" == time_array) {
        return;
    }
    var flag = g_imosActivePlayer.IMOSAX_StartVodReplay(frameNum, cameraId, start_time, stop_time);
    if (0 != flag) {
        alert("回放失败，错误码：" + flag);
    }
}

//停止录像回放
function DoStopPlayRecord() {
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var flag = g_imosActivePlayer.IMOSAX_StopReplay(frameNum);
    if (0 != flag) {
        alert("关闭回放失败，错误码：" + flag);
    }
}

//获取播放进度
function GetReplayPos() {
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var posTime = g_imosActivePlayer.IMOSAX_GetReplayPos(frameNum);
    alert(posTime);
}

//回放控制
function ReplayControl(cmd) {
}

//回放跳转
function SetPos() {
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var pos = document.all.PosText.value;   //时间格式为：yyyy-mm-dd hh:mm:ss
    var flag = g_imosActivePlayer.IMOSAX_DragPlay(frameNum, pos)
    if (0 != flag) {
        alert("拖动回放失败，错误码：" + flag);
    }
}

//设置播放速度
function SetPlaySpeed(speed) {
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var flag = g_imosActivePlayer.IMOSAX_SetPlaySpeed(frameNum, speed);
    if (0 != flag) {
        alert("设置回放速度失败，错误码：" + flag);
    }
}

//抓拍
//抓拍图片将保存在指定路径下, 以当天日期为名称的文件夹内
function DoSnatch() {
    var frameNum = g_curFrameNum;
    frameNum = parseInt(frameNum, 10);
    if (isNaN(frameNum) || frameNum < 1 || frameNum > 25) {
        alert("请先选择一个窗格");
        return;
    }
    var flag = g_imosActivePlayer.IMOSAX_SnatchOnce(frameNum);
    if (0 != flag) {
        alert("抓拍失败，错误码：" + flag);
    }
}

//================>功能函数---end

//================>事件处理函数event---start

/**
 * 窗格单击事件的处理函数
 */
function dealEventClickFrame(ulFrameNum, pcFrameInfo) {
    //当前窗格
    g_curFrameNum = ulFrameNum;
    pcFrameInfo = pcFrameInfo.replaceAll("\"", "\'");
    var tmpXmlDoc = loadXML(pcFrameInfo);
    if (!tmpXmlDoc) {
        return;
    }
    //将需要的数据从xml中获取，方便后续使用
}

function SearchVideo() {
    //AddVideoItem();
    // 清空录像列表
    var FileListObj = document.all.videolisttable;
    FileListObj.innerHTML = '';

    //录像查询，并显示
    DoQueryRecord();
    ShowVideoList(true);
}

var index = 0;
function AddVideoItem(fileName) {
    var table = document.getElementById("videolisttable");

    var row = table.insertRow(-1);
    var cell;
    var cell_child;

    cell = row.insertCell(-1);
    cell_child = document.createElement("input");
    cell_child.type = "checkbox";
    cell_child.id = "checkbox" + index;
    cell_child.checked = 'checked';
    cell_child.defaultChecked = 'checked';
    cell.appendChild(cell_child);

    cell = row.insertCell(-1);
    cell.setAttribute("width", "85%");
    cell.appendChild(document.createTextNode(fileName));

    cell = row.insertCell(-1);
    cell_child = document.createElement("input");
    cell_child.type = "button";
    cell_child.id = "video" + index;
    cell_child.value = " 下载 ";
    cell_child.onclick = DownLoadVideo;
    cell.appendChild(cell_child);

    cell = row.insertCell(-1);
    cell.setAttribute("width", "8em");
    cell_child = document.createElement("span");
    cell.appendChild(cell_child);

    index++;
}

function DownLoadVideo() {
    alert("click download");
}

// JavaScript source code. google map control
var map, layer, markers, drawControl;
var size, icon;
var popupContentHTML;
var startPoint, endPoint;
var cameraList = []; // 摄像机数组
var lonlatList = []; // 经纬度数据
//================>事件处理函数event---end

//================>google map---start
// body初始化
function initPage() {
    // map
    map = new OpenLayers.Map('map');
    layer = new OpenLayers.Layer.Google("Google Streets", { numZoomLevels: 20, layers: 'basic' });    
    map.addLayer(layer);

    // marker
    markers = new OpenLayers.Layer.Markers("Markers");
    map.addLayer(markers); 

    // draw box
    var boxLayer = new OpenLayers.Layer.Vector("Box layer");
    map.addLayers(boxLayer);
    map.addControl(new OpenLayers.Control.MousePosition());
    drawControl = new OpenLayers.Control.DrawFeature(boxLayer,OpenLayers.Handler.RegularPolygon, {
        handlerOptions: { sides: 4, irregular: true }
    });
    map.addControl(drawControl);
    document.getElementById('cbxDrawBox').checked = false;

    // mouse position  
    map.events.register("mousedown", this, this.mapMousedown, { extension: true });
    map.events.register("mouseup", this, this.mapMouseup, { extension: true });

    size = new OpenLayers.Size(21, 25);
    calculateOffset = function (size) {
        return new OpenLayers.Pixel(-(size.w / 2), -size.h);
    };

    // test
    var ll = new OpenLayers.LonLat(114.483333333333, 37.05).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    addMarker(ll,"摄像机1");
    ll = new OpenLayers.LonLat(114.483333333331, 37.06).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    addMarker(ll, "摄像机2");

    map.addControl(new OpenLayers.Control.LayerSwitcher());
    //map.zoomToMaxExtent();
    map.setCenter(new OpenLayers.LonLat(114.483333333333, 37.05).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()), 12);
}

/**
        * Function: addMarker
        * Add a new marker to the markers layer given the following lonlat, 
        *     popupClass, and popup contents HTML. Also allow specifying 
        *     whether or not to give the popup a close box.
        * 
        * Parameters:
        * ll - {<OpenLayers.LonLat>} Where to place the marker
        * popupClass - {<OpenLayers.Class>} Which class of popup to bring up 
        *     when the marker is clicked.
        * popupContentHTML - {String} What to put in the popup
        * closeBox - {Boolean} Should popup have a close box?
        * overflow - {Boolean} Let the popup overflow scrollbars?
        */
function addMarker(ll,name) {
    cameraList[cameraList.length] = name;
    lonlatList[lonlatList.length] = ll;
    var feature = new OpenLayers.Feature(markers, ll);
    feature.closeBox = true;
    feature.popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, { 'autoSize': true });
    //feature.data.popupContentHTML = '<img src="img/small.jpg"></img>';
    feature.data.popupContentHTML = generatePopupContentHTML(name);
    feature.data.overflow = "auto";

    var marker = feature.createMarker();
    var markerClick = function (evt) {
        if (this.popup == null) {
            this.popup = this.createPopup(this.closeBox);
            map.addPopup(this.popup);
            this.popup.show();
        } else {
            this.popup.toggle();
        }
        currentPopup = this.popup;
        OpenLayers.Event.stop(evt);
    };
    marker.events.register("mousedown", feature, markerClick);
    markers.addMarker(marker);
}

function resize() {
    size = new OpenLayers.Size(size.w + 10, size.h + 10);
    icon.setSize(size);
}

function generatePopupContentHTML(cameraname) {
    var myDate = new Date();
    var strHTML = "<div>" + cameraname;
    strHTML += "<hr>开始时间: <input type='text' id='startTimeText' value='" + myDate.toLocaleString() + "' size='20'/><br>";
    strHTML += "结束时间: <input type='text' id='endTimeText' value='" + myDate.toLocaleString() + "' size='20'/><br>";
    strHTML += " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='button' onclick='SearchVideo()' value='查询'/></div>";
    
    return strHTML;
}
//================>google map---end

//================>页面处理---start
// 全选
function btnSelectAll_click() {
    map_checkboxes(function (c, id) {
        c.checked = true;
    });
}

// 取消选择
function btnUnSelect_click() {
    map_checkboxes(function (c, id) {
        c.checked = false;
    });
}

// 下载已选录像
function btnDownload_click() {
    DownLoadVideo();
}

map_checkboxes = function (f) {
    var selectlist = document.getElementById("videolisttable");
    var checks = selectlist.getElementsByTagName("INPUT");
    for (var i = 0; i < checks.length; ++i) {
        if (checks[i].type == "checkbox" && checks[i].id.match(/^checkbox(\d+)$/)) {
            f(checks[i], RegExp.$1);
        }
    }
};

var isShow = false;
// 显示/隐藏录像列表
function btnVideoList_click() {
    ShowVideoList(!isShow);
}

function ShowVideoList(boolShow) {
    isShow = boolShow;
    var videoList = document.getElementById("col1");
    var videoListButton = document.getElementById("btnVideoList");
    if (boolShow) {
        videoList.style.width = "27em";
        videoListButton.setAttribute("value", "<<隐藏录像列表");
    }
    else {
        videoList.style.width = "0em";
        videoListButton.setAttribute("value", ">>显示录像列表");
    }
}

// 启动/关闭框选摄像机
var isChecked = false;
function toggleControl(element) {
    if (drawControl == null) return;
    if (element.checked) {
        drawControl.activate();
        isChecked = true;
        //drawControl.handler.stopDown = true;
        //drawControl.handler.stopUp = true;
    } else {
        drawControl.deactivate();
        isChecked = false;
        //drawControl.handler.stopDown = false;
        //drawControl.handler.stopUp = false;
    }
}

// 鼠标按下事件，捕获鼠标位置(经纬度),如果框选摄像机未选中，则不执行
function mapMousedown(evt) {
    if (!isChecked) {
        return;
    }
    startPoint = this.map.getLonLatFromPixel(evt.xy);
    // 转换为经纬度
    //startPoint = this.map.getLonLatFromPixel(evt.xy).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
}

// 鼠标弹起事件，捕获鼠标位置(经纬度),如果框选摄像机未选中，则不执行
function mapMouseup(evt) {
    if (!isChecked) {
        return;
    }
    endPoint = this.map.getLonLatFromPixel(evt.xy);
    // 转换为经纬度
    //endPoint = this.map.getLonLatFromPixel(evt.xy).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
    SelectCamera();
}

this.transform = function (lon, lat) {
    var proj = new OpenLayers.Projection("EPSG:4326");
    var lonlat = new OpenLayers.LonLat(lon, lat);
    lonlat.transform(proj, this.map.getProjectionObject());
    return lonlat;
}

// 根据框选范围，选择摄像机
function SelectCamera() {
    var lonlat;
    var isCamera = false;

    document.getElementById("cameralist").innerHTML = "";

    for (var i = 0; i < cameraList.length; i++)
    {
        lonlat = lonlatList[i];
        
        if (startPoint.lon > endPoint.lon) {
            isCamera = (startPoint.lon > lonlat.lon && endPoint.lon < lonlat.lon) 
        }
        else {
            isCamera = (startPoint.lon <= lonlat.lon && endPoint.lon >= lonlat.lon)
        }

        if (!isCamera) {
            return;
        }

        if (startPoint.lat > endPoint.lat) {
            isCamera = (startPoint.lat > lonlat.lat && endPoint.lat < lonlat.lat)
        }
        else {
            isCamera = (startPoint.lat <= lonlat.lat && endPoint.lat >= lonlat.lat)
        }

        if (!isCamera) {
            return;
        }

        // 添加到摄像机列表
        document.getElementById("cameralist").innerHTML += cameraList[i] + "</br>";
        isCamera = false;
    }
    ShowVideoList(true);   
}

//================>页面处理---end
