/*----------------------------------------------------------------
 文件名：mainControl.js
 文件功能描述：主页相关操作对象
 ----------------------------------------------------------------*/
var main_ctrl = (function($){
    //地图位置对象，用来记录匹配地图的放大级别和中心点
    function MapLocation(mapId, zoomLevel, center){
        this.mapId = mapId;
        this.zoomLevel = zoomLevel;
        this.center = center;
    }
    var page = { //当前页面，区分预览和编辑
        view: "view",
        edit: "edit"
    };
    var mapArray = new Array();//地图数组
    var devArray = new Array();//设备数组
    var selectedMapMarker = null;//选中的地图标记
    var selectedDevices = new Array();//选中的设备标记
    var map;//地图对象
    var overview = null;//地图鹰眼
    var curMapId;//当前显示的地图
    var mapMarkers;//地图标记点
    var devMarkers;//设备标记点
    var mapLocationArray = new Array();//地图位置对象数组
    var bounds;//边界值
    var popup = null;//弹出框
    var options = {//地图初始化控制对象
        controls: [new OpenLayers.Control.DHNavigation({
            documentDrag: true
        }), new OpenLayers.Control.DHPanZoomBar()],
        numZoomLevels: 11
    }
    var maxDevUpdateCount = 8;//供一次提交修改的最大设备数
    var imageFile = null;//地图存放路径
    var zTree, treeNodes;//设备数对象
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        view: {
            fontCss: {
                color: "#DDD"
            },
            showLine: false,
            selectedMulti: true,
            autoCancelSelected: false
        },
        callback: {
            onExpand: zTreeOnExpand,
            onClick: zTreeOnClick,
            onDblClick: zTreeOnDblClick
        }
    };
    
    var curType = {//拖拽鼠标形状
        dev_drag_add: "inc/img/cur/dev_drag_add.cur", //设备拖拽（添加）
        dev_drag_del: "inc/img/cur/dev_drag_del.cur", //设备拖拽（删除）
        dev_drag_able: "inc/img/cur/dev_drag_able.cur" //设备允许拖拽
    };
    
    var images = {//标记图片
        map: "inc/img/map_marker.png",
        selectedMap: "inc/img/map_marker_selected.png",
        dev: "inc/img/video_b_normal.png",
        selectedDev: "inc/img/video_b_select.png",
        flashDev: "inc/img/alarm.gif"
    };
    
    /**
     * 树点击触发此事件
     * @param event 	标准的 js event 对象
     * @param treeId 	对应zTree的treeId
     * @param treeNode	被点击的节点JSON 数据对象
     * @author jq_zhang
     */
    function zTreeOnClick(event, treeId, treeNode){
        $("a.curSelectedNode").removeClass("curSelectedNode");
        zTree.selectNode(treeNode);
    }
    
    /**
     * zTree zTreeOnNodeCreated事件,判断是否为通道,是则允许拖拽
     * @param  event 	js event 对象
     * @param  treeId	zTree的treeId
     * @param  treeNode	节点JSON数据对象
     * @author  jq_zhang
     */
    function zTreeOnExpand(event, treeId, treeNode){
        var nodes = treeNode.children;
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i] && nodes[i].type && nodes[i].type == "channel") {
                dragChaToMap(nodes[i]);
            }
        }
    }
    
    /**
     * zTree zTreeOnDblClick事件，预览情况下弹出视频，编辑状态下选中设备并居中
     * @param  event 	js event 对象
     * @param  treeId	zTree的treeId
     * @param  treeNode	节点JSON数据对象
     * @author  jq_zhang
     */
    function zTreeOnDblClick(event, treeId, treeNode){
        if (treeNode.type != "channel") 
            return;
        if (main_ctrl.curPage == page.view) {
            var jsonObj = {
                channelId: treeNode.id.toString(),
				name: treeNode.name,
                screenX: ($(window).width() / 2).toString(),
                screenY: ($(window).height() / 2).toString()
            }
            var tempArray = new Array();
            tempArray.push(jsonObj);
            openVedio(JSON.stringify(tempArray));
            var pNode = treeNode.getParentNode();
            for (var i = 0; i < devMarkers.markers.length; i++) {
                if (devMarkers.markers[i].id == treeNode.id + "#" + pNode.id) {
                    map.setCenter(devMarkers.markers[i].lonlat);
                }
            }
        }
        else {
            var pNode = treeNode.getParentNode();
            for (var i = 0; i < devMarkers.markers.length; i++) {
                if (devMarkers.markers[i].id == treeNode.id + "#" + pNode.id) {
                    if (!devMarkers.markers[i].selected) {
                        devMarkers.markers[i].selected = true;
                        devMarkers.markers[i].setUrl(images.selectedDev);
                        selectedDevices.push(devMarkers.markers[i]);
                    }
                    map.setCenter(devMarkers.markers[i].lonlat);
                }
            }
        }
    };
    
    /**
     * 设置树节点的图片路径
     * @author jq_zhang
     */
    function setTreeIcon(){
        treeNodes = getTreeData();
        $(treeNodes).each(function(i){
            if (this.type && this.type == "org") {
                this.icon = "inc/img/tree/org.png";
            }
            else 
                if (this.type && this.type == "channel") {
                    this.icon = "inc/img/tree/channel.png";
                }
                else if(this.type && this.type == "device"){
                	 this.icon = "inc/img/tree/device.png";
                }
                
        });
    }
    
    
    /**
     * 深度克隆
     * @param  obj
     * @return cloneObj
     * @author  jq_zhang
     */
    function deepClone(obj){
        var cloneObj = {};
        for (var name in obj) {
            cloneObj[name] = obj[name];
        }
        return cloneObj;
    }
    
    /**
     * 获取主地图
     * @return localMap
     * @author  jq_zhang
     */
    function getLocalMap(){
        var localMap = null;
        if (mapArray && mapArray.length > 0) {
            for (var i = 0; i < mapArray.length; i++) {
                if (mapArray[i].pId == "" || mapArray[i].pId == null) {
                    localMap = deepClone(mapArray[i]);
                    break;
                }
            }
        }
        return localMap;
    }
    
    /**
     * 根据id获取子地图
     * @param  id		当前地图ID
     * @return maps		子地图数组
     * @author jq_zhang
     */
    function getChildMaps(id){
        var maps = new Array();
        if (mapArray && mapArray.length > 0) {
            for (var i = 0; i < mapArray.length; i++) {
                if (mapArray[i].pId == id) {
                    maps.push(deepClone(mapArray[i]));
                }
            }
        }
        return maps;
    }
    
    /**
     * 根据id获取地图
     * @param  id		地图ID
     * @return backMap	地图
     * @author jq_zhang
     */
    function getMapById(id){
        var backMap = null;
        if (mapArray && mapArray.length > 0) {
            for (var i = 0; i < mapArray.length; i++) {
                if (mapArray[i].id == id) {
                    backMap = mapArray[i];
                    break;
                }
            }
        }
        return backMap;
    }
    
    /**
     * 根据mapId获取记录的地图位置对象
     * @param  mapId		地图	ID
     * @return mapLocation	地图位置对象
     * @author jq_zhang
     */
    function getMapLocationById(mapId){
        var mapLocation = new MapLocation();
        if (mapLocationArray && mapLocationArray.length > 0) {
            for (var i = 0; i < mapLocationArray.length; i++) {
                if (mapLocationArray[i].mapId == mapId) {
                    mapLocation = deepClone(mapLocationArray[i]);
                    break;
                }
            }
        }
        return mapLocation;
    }
    
    /**
     * 根据mapID获取设备
     * @param  mapId	地图ID
     * @return devices	地图上的设备
     * @author jq_zhang
     */
    function getDevicesByMapId(mapId){
        var devices = new Array();
        if (devArray && devArray.length > 0) {
            for (var i = 0; i < devArray.length; i++) {
                if (devArray[i].mapId == mapId) {
                    devices.push(deepClone(devArray[i]));
                }
            }
        }
        return devices;
    }
    
    /**
     * 根据保存的地图位置对象数组初始化左下角的控件
     * @author jq_zhang
     */
    function initBackBar(){
        var array = mapLocationArray;
        if (!array | array.length < 0) {
            $("#backBar").empty();
            return;
        }
        var backHtmlStr = "";
        for (var i = 0; i < array.length; i++) {
            var styleCss = "";
            if (i == 0) {
                styleCss = "border:3px solid #E5E6E7;";
            }
            else {
                styleCss = "border:3px solid #E5E6E7;border-left:none;";
            }
            backHtmlStr += "<a javascript:'void(0);' onclick='main_ctrl.gotoSelectedMap(" + array[i].mapId + ");'><img alt='" + getMapById(array[i].mapId).name + "' src='" + pathToUrl(getMapById(array[i].mapId).path) + "' height='75px' width='75px' style='" + styleCss + "' ></img></a>";
        }
        $("#backBar").html(backHtmlStr);
        $("#backBar").find("a").hover(function(){
            $("#map>div").append("<img id='backShowImg' src='" + $(this).find("img").attr("src") + "' width='520px' height='450px' style='position:absolute;bottom:0;z-index:9998;border-top:4px solid #E5E6E7;border-right:4px solid #E5E6E7'></img>");
        }, function(){
            $("#backShowImg").remove();
        });
    }
    
    /**
     * 判断是否是父级的地图位置
     * @param  mapId
     * @param  mapLocation
     * @return bool
     * @author jq_zhang
     */
    function isParent(mapId, mapLocation){
        var tempMap = getMapById(mapId);
        if (tempMap.pId == null || tempMap.pId == "") 
            return false;
        if (tempMap.pId == mapLocation.mapId) {
            return true;
        }
        else {
            return isParent(tempMap.pId, mapLocation);
        }
    }
    
    /**
     * 根据当前地图ID整理地图位置对象数组
     * @param  mapId
     * @author jq_zhang
     */
    function sortMapLocation(mapId){
        mapLocationArray = $.grep(mapLocationArray, function(n){
            return isParent(mapId, n);
        });
    }
    
    /**
     * 拖拽通道至地图中，结束拖拽可录入点位信息
     * @param  treeNode	节点JSON数据对象
     * @author  jq_zhang
     */
    function dragChaToMap(treeNode){
        $("#" + treeNode.tId + "_a").draggable({
            cursorAt: {
                top: $("#" + treeNode.tId + "_ico").height() / 2,
                left: $("#" + treeNode.tId + "_ico").width() / 2
            },
            snap: '#map',
            revert: true,
            scroll: false,
            helper: function(){
                var nodeClone = $("#" + treeNode.tId + "_a").clone();
                $("body").append(nodeClone);
                $(nodeClone).css({
                    "position": "absolute",
                    "z-index": 10000
                });
                $(nodeClone).find("button").css({
                    "width": "18px",
                    "border-width": 0
                });
                return $(nodeClone);
            },
            start: function(){
            },
            drag: function(){
                if (isOver($("#map"))) {
                    var ev = window.event || e;
                    var pos = mouseCoords(ev);
                    var testLonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(pos.x - $(map.div).offset().left, pos.y - $(map.div).offset().top));
                    if (map.baseLayer.extent.containsLonLat(testLonlat, false)) {
                        $("#" + treeNode.tId + "_a").draggable("option", "revert", false);
                    }
                    else {
                        $("#" + treeNode.tId + "_a").draggable("option", "revert", true);
                    }
                }
                else {
                    $("#" + treeNode.tId + "_a").draggable("option", "revert", true);
                }
                if (main_ctrl.curPage == page.view) {
                    $("#" + treeNode.tId + "_a").draggable("option", "revert", true);
                }
            },
            stop: function(){
                if (!$("#" + treeNode.tId + "_a").draggable("option", "revert")) {
                    var pNode = treeNode.getParentNode();
                    if (isExisted(treeNode.id, pNode.id)) {
                        $.dialog({
                            title: bitmap_lang.js.tip,
                            time: 2,
                            icon: 'warning.png',
                            content: bitmap_lang.js.devExisted
                        });
                        return;
                    }
                    var ev = window.event || e;
                    var pos = mouseCoords(ev);
                    var lonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(pos.x - $(map.div).offset().left, pos.y + 15 - $(map.div).offset().top));
                    jsonObj = {
                        channelId: treeNode.id.toString(),
                        mapX: lonlat.lon.toString(),
                        mapY: lonlat.lat.toString(),
                        mapId: curMapId.toString(),
                        name: treeNode.name,
                        devName: pNode.name,
                        devCode: pNode.id.toString()
                    }
                    try {
                        var tempArray = new Array();
                        tempArray.push(jsonObj);
                        updateDeviceLocation(JSON.stringify(tempArray));
                    } 
                    catch (e) {
                        $.dialog({
                            title: bitmap_lang.js.alert,
                            time: 2,
                            icon: 'warning.png',
                            content: bitmap_lang.js.devAddError
                        });
                    }
                    var mk = main_ctrl.addCustomMarker(treeNode.id + "#" + pNode.id, lonlat.lon, lonlat.lat, treeNode.name, "dev");
                    onMarker(mk);
                    devArray.push(jsonObj);
                }
            }
        });
    }
    
    /**
     * 判断地图上是否已经存在该摄像头
     * @param 	channelId
     * @param   devCode
     * @return 	bool
     * @author	jquan_zhang
     */
    function isExisted(channelId, devCode){
        for (var i = 0; i < devMarkers.markers.length; i++) {
            if (devMarkers.markers[i].id == channelId + "#" + devCode) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取鼠标点
     * @param 	ev			系统触发事件
     * @return  obj			含xy值的对象
     * @author	jquan_zhang
     */
    function mouseCoords(ev){
        if (ev.pageX || ev.pageY) {
            return {
                x: ev.pageX,
                y: ev.pageY
            };
        }
        return {
            x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y: ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    }
    
    
    /**
     * 判断鼠标点是否在某DOM之上
     * @param  target 	DOM元素
     * @return 	bool
     * @author jq_zhang
     */
    function isOver(target){
        var e, t, pos;
        e = window.event ? window.event : null;
        if (!event || !target) 
            return;
        if (target instanceof jQuery || target.length > 1) 
            t = target[0];
        pos = [e.clientX ? e.clientX : (e.pageX ? e.pageX : 0), e.clientY ? e.clientY : (e.pageY ? e.pageY : 0)];
        pos = [pos[0] + document.documentElement.scrollLeft, pos[1] + document.documentElement.scrollTop];
        if (pos[0] < $(t).offset().left | pos[0] > ($(t).offset().left + $(t).outerWidth())) 
            return false;
        if (pos[1] < $(t).offset().top | pos[1] > ($(t).offset().top + $(t).outerHeight())) 
            return false;
        return true;
    }
    
    
    /**
     * 根据id显示地图
     * @param  id		地图ID
     * @author jq_zhang
     */
    function setCurShowMap(id){
        var curLayer = map.getLayer(id);
        curLayer.div.style.display = "block";
        map.setBaseLayer(curLayer);
        map.restrictedExtent = map.baseLayer.extent;
        curMapId = id;
        if (!overview) {
            var scale = $("#map").height() / $("#map").width();
            var oSize = new OpenLayers.Size(200, parseInt(200 * scale));
            overview = new OpenLayers.Control.DHOverviewMap({
                maximized: true,
                size: oSize,
                layer: curLayer
            });
            map.addControl(overview);
        }
        else {
            var ovmapLayer = new OpenLayers.Layer.Image(curLayer.name, curLayer.url, curLayer.extent, curLayer.size);
            var wMax = parseFloat(map.div.style.width) / parseFloat(overview.mapDiv.style.width);
            var hMax = parseFloat(map.div.style.height) / parseFloat(overview.mapDiv.style.height);
            var resolutionMax = wMax > hMax ? wMax : hMax;
            overview.ovmap.resolutions = [resolutionMax * map.resolutions[1]];
            overview.ovmap.addLayer(ovmapLayer);
            overview.ovmap.removeLayer(overview.ovmap.baseLayer);
            overview.ovmap.restrictedExtent = curLayer.extent;
            overview.update();
            $(overview.ovmap.div).find("img").parent().show();
        }
    }
    
    /**
     * 展示子地图
     * @param  id		地图ID
     * @author jq_zhang
     */
    function showChildMap(id){
        mapMarkers.clearMarkers();
        selectedMapMarker = null;//选中的地图标记
        var childMaps = getChildMaps(id);
        if (childMaps != null && childMaps.length > 0) {
            for (var i = 0; i < childMaps.length; i++) {
                var size = new OpenLayers.Size(32, 32);
                var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
                var icon = new OpenLayers.Icon(images.map, size, offset);
                var ll = new OpenLayers.LonLat(childMaps[i].mapX, childMaps[i].mapY);
                var marker = new OpenLayers.DHMarker(childMaps[i].id, ll, icon, childMaps[i].name, 'map');
                mapMarkers.addMarker(marker);
            }
        }
    }
    
    /**
     * 展示设备
     * @param  mapId
     * @author jq_zhang
     */
    function showMapDevices(mapId){
        devMarkers.clearMarkers();
        selectedDevices.length = 0;//选中的设备标记
        var mapDevices = getDevicesByMapId(mapId);
        if (mapDevices != null && mapDevices.length > 0) {
            for (var i = 0; i < mapDevices.length; i++) {
                var size = new OpenLayers.Size(30, 30);
                var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
                var icon = new OpenLayers.Icon(images.dev, size, offset);
                var lonlat = new OpenLayers.LonLat(mapDevices[i].mapX, mapDevices[i].mapY);
                var marker = new OpenLayers.DHMarker(mapDevices[i].channelId + "#" + mapDevices[i].devCode, lonlat, icon, mapDevices[i].name, 'dev');
                devMarkers.addMarker(marker);
            }
        }
    }
    
    /**
     * 给标记添加事件
     * @param  marker
     * @author jq_zhang
     */
    function onMarker(marker){
        if (main_ctrl.curPage == page.view) {
            if (marker.markerType == 'map') {
                marker.events.register("dblclick", marker, function(e){
                    main_ctrl.gotoChildMap(this.id);
                });
            }
            else {
                marker.events.register("dblclick", marker, function(e){
                    main_ctrl.openVideo(marker);
                });
            }
        }
        else {
            if (marker.markerType == 'map') {
                marker.events.register("dblclick", marker, function(e){
                    main_ctrl.gotoChildMap(this.id);
                });
            }
            marker.events.register("click", marker, function(e){
                toggleSelect(this);
            });
            marker.events.register("mousedown", marker, function(e){
                if (e.button == 2) 
                    return false;//辨别右键
                marker_drag.start(marker, e, map, null, null, function(){
                    if (marker.markerType == 'map') {
                        var mapObj = getMapById(marker.id);
                        mapObj.mapX = marker.lonlat.lon.toString();
                        mapObj.mapY = marker.lonlat.lat.toString();
                        updateMap(JSON.stringify(mapObj));
                    }
                    else {
                        var jsonObj = getCupMapDeviceByMkId(marker.id);
                        jsonObj.mapX = marker.lonlat.lon.toString();
                        jsonObj.mapY = marker.lonlat.lat.toString();
                        try {
                            var tempArray = new Array();
                            tempArray.push(jsonObj);
                            updateDeviceLocation(JSON.stringify(tempArray));
                        } 
                        catch (e) {
                            $.dialog({
                                title: bitmap_lang.js.alert,
                                time: 2,
                                icon: 'warning.png',
                                content: bitmap_lang.js.devAddError
                            });
                        }
                    }
                });
            });
        }
    }
    
    /**
     * 取消标记事件
     * @param  marker
     * @author jq_zhang
     */
    function unMarker(marker){
        marker.events.remove("mousedown");
        marker.events.remove("click");
        marker.events.remove("dblclick");
    }
    
    /**
     * 切换选中标记点
     * @param  mk
     * @author jquan_zhang
     */
    function toggleSelect(mk){
        if (mk.markerType == "map") {
            if (selectedMapMarker) {
                if (mk.id == selectedMapMarker.id) {
                    if (selectedMapMarker.selected) {
                        selectedMapMarker.selected = false;
                        selectedMapMarker.setUrl(images.map);
                        selectedMapMarker = null;
                    }
                    else {
                        selectedMapMarker.selected = true;
                        selectedMapMarker.setUrl(images.selectedMap);
                    }
                }
                else {
                    selectedMapMarker.setUrl(images.map);
                    selectedMapMarker.selected = false;
                    mk.setUrl(images.selectedMap);
                    mk.selected = true;
                    selectedMapMarker = mk;
                }
            }
            else {
                selectedMapMarker = mk;
                mk.setUrl(images.selectedMap);
                selectedMapMarker.selected = true;
            }
        }
        else {
            if (!mk.selected) {
                mk.selected = true;
                mk.setUrl(images.selectedDev)
                selectedDevices.push(mk);
            }
            else {
                mk.selected = false;
                mk.setUrl(images.dev);
                selectedDevices.splice($.inArray(mk, selectedDevices), 1);
            }
        }
        
    }
    
    /**
     * 根据地图标记ID获取当前地图上的设备
     * @param  mkId		标记ID
     * @return device	设备信息
     * @author jquan_zhang
     */
    function getCupMapDeviceByMkId(mkId){
        var channelId = (mkId.split("#"))[0];
        var devCode = (mkId.split("#"))[1];
        var device = null;
        if (devArray && devArray.length > 0) {
            for (var i = 0; i < devArray.length; i++) {
                if (devArray[i].channelId == channelId && devArray[i].devCode == devCode && devArray[i].mapId == curMapId) {
                    device = devArray[i];
                }
            }
        }
        return device;
    }
    
    /**
     * 根据通道获取当前地图上的点位
     * @param  channelId
     * @return backMarkers
     * @author jquan_zhang
     */
    function getDevMarkersByChannelId(channelId){
        var backMarkers = new Array();
        var mkArray = devMarkers.markers;
        var temps;
        for (var i = 0; i < mkArray.length; i++) {
            temps = mkArray[i].id.split("#");	
            if (temps[0]==channelId) {
                backMarkers.push(mkArray[i]);
            }
        }
        return backMarkers;
    }
    
    /**
     * 预加载地图，传递相关参数和执行回调函数
     * @param  url
     * @param  callback
     * @param  option
     * @author jquan_zhang
     */
    function loadImage(url, callback, option ,errorHandle){
        var img = new Image();
        img.src = url;
        if (img.complete) {
            callback.call(this, img, option);
            return;
        }
        img.onload = function(){
            callback.call(this, img, option);
        }
		img.onerror = function(){
			if(errorHandle)	errorHandle.call(this);
		}
    }
    
    /**
     * 计算当前地图在第几层
     * @param  callback
     * @param  option
     * @author jquan_zhang
     */
    function countFloor(currentMap, count){
        if (currentMap.pId != null && currentMap.pId != "") {
            count++;
            return countFloor(getMapById(currentMap.pId), count);
        }
        else {
            return count;
        }
    }
    
    /**
     * 批量修改设备信息
     * @param  array  需要修改的设备数组
     * @author jquan_zhang
     */
    function batchUpdateDevice(array){
        var len = array.length;
        if (len <= maxDevUpdateCount) {
            updateDeviceLocation(JSON.stringify(array));
        }
        else {
            var num = parseInt(len / maxDevUpdateCount);
            var numOther = len % maxDevUpdateCount;
            for (var i = 0; i < num; i++) {
                updateDeviceLocation(JSON.stringify(array.slice(i * maxDevUpdateCount, (i + 1) * maxDevUpdateCount)));
            }
            if (numOther != 0) {
                updateDeviceLocation(JSON.stringify(array.slice(num * maxDevUpdateCount, num * maxDevUpdateCount + numOther)));
            }
        }
    }
    
    /**
     * 将绝对路径转换成url格式
     * @param  path
     * @return url
     * @author jquan_zhang
     */
    function pathToUrl(path){
        var url = 'file:///' + path;
        url = url.replace(/\\/g, '/');
        return url;
    }
    
    /**
     * 格式化路径
     * @param  info 地图信息
     * @return path
     * @author jquan_zhang
     */
    function formatPath(info){
        var tempPath = info.path.replace(/\\/g, '/');
        var tempArray = tempPath.split("/");
        var backPath = tempArray[tempArray.length - 1];
        return imageFile + info.id + "_" + backPath;
    }
    
    return {
        curPage: "",//当前页面 预览或编辑
        /**
         * 初始化
         * @param  p	页面
         * @author jq_zhang
         */
        init: function(p){
            this.curPage = p;
            $("a[page='" + p + "']").parent().addClass("current");
            mapArray = getAllMap();
            var localMap = getLocalMap();
            imageFile = getEmapImagePath();
            if (localMap) {//先判断是否存在主地图，存在则显示主地图,不存在则显示添加页面
                $("#lockMapForAdd").hide();
                $("#wrapper").show();
                this.initLocalMap();
            }
            else {
                $("#wrapper").hide();
                $("#lockMapForAdd").show();
            }
        },
        
        /**
         * 设备树查询
         * @author jq_zhang
         */
        treeSearch: function(){
            $("a.curSelectedNode").removeClass("curSelectedNode");
            var keyVal = $("#zTreeSearchKey").val();
            if (keyVal == "") {
                return;
            }
            var nodes = zTree.getNodesByParamFuzzy("name", keyVal, null);
            if (nodes.length > 0) {
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].type == "channel") {
                        if (!nodes[i].getParentNode().open) {
                            zTree.expandNode(nodes[i].getParentNode(), true, true, false, true);
                        }
                        $("#" + nodes[i].tId + "_a").addClass("curSelectedNode");
                    }
                }
            }
        },
        
        /**
         * 初始化主地图
         * @author jq_zhang
         */
        initLocalMap: function(){
            var localMap = getLocalMap();
            loadImage(pathToUrl(localMap.path), main_ctrl.localImgLoadedHandle, {
                localMap: localMap
            },function(){
				curMapId = localMap.id;
				$.dialog({
					title: bitmap_lang.js.tip,
					icon: 'warning.png',
					content: bitmap_lang.js.mapError
				});
			});
        },
        
        /**
         * 加载主地图
         * @param  img	loadImage返回的图片对象
         * @param  o	loadImage传递过来的参数对象
         * @author jq_zhang
         */
        localImgLoadedHandle: function(img, o){
            var kg = {
                w: img.width ? img.width : 0,
                h: img.height ? img.height : 0
            }
            var localMap = o.localMap;
            devArray = getAllGisChannels();
            bounds = new OpenLayers.Bounds(-kg.w / 2, -kg.h / 2, kg.w / 2, kg.h / 2);
            var maxRes = kg.w / $("#map").width() > kg.h / $("#map").height() ? kg.w / $("#map").width() : kg.h / $("#map").height();
            var curtRes = (maxRes - 0.1) / 9;
            options.resolutions = [maxRes * 1.5, maxRes, maxRes - curtRes, maxRes - 2 * curtRes, maxRes - 3 * curtRes, maxRes - 4 * curtRes, maxRes - 5 * curtRes, maxRes - 6 * curtRes, maxRes - 7 * curtRes, maxRes - 8 * curtRes, 0.1];
            map = new OpenLayers.Map('map', options);
            var localMapLayer = new OpenLayers.Layer.Image(localMap.name, pathToUrl(localMap.path), bounds, new OpenLayers.Size(kg.w, kg.h));
            localMapLayer.id = localMap.id;
            mapMarkers = new OpenLayers.Layer.Markers("mapMarkers");
            devMarkers = new OpenLayers.Layer.Markers("devMarkers");
            map.addLayers([localMapLayer, mapMarkers, devMarkers]);
            setCurShowMap(localMap.id);
            showChildMap(localMap.id);
            showMapDevices(localMap.id);
            map.zoomToExtent(bounds);
            main_ctrl.resetPage();
            setTreeIcon();
            zTree = $.fn.zTree.init($("#devTree"), setting, treeNodes);
            $.dh.addNotice($("#zTreeSearchKey"), bitmap_lang.js.searchTip);
            $("#map>div").append("<label id='backBar' style='position:absolute;bottom:0;z-index:9999;'></label>");
        },
        
        /**
         * 进入子地图
         * @param  mapId
         * @author jq_zhang
         */
        gotoChildMap: function(mapId){
            var childMap = getMapById(mapId);
            if (childMap) {
                loadImage(pathToUrl(childMap.path), main_ctrl.subImgLoadedHandle, {
                    childMap: childMap,
                    mapId: mapId
                },function(){
					$.dialog({
						title: bitmap_lang.js.tip,
						icon: 'warning.png',
						content: bitmap_lang.js.mapError
					});
				});
            }
        },
        
        /**
         * 加载子地图
         * @param  img	loadImage返回的图片对象
         * @param  o	loadImage传递过来的参数对象
         * @author jq_zhang
         */
        subImgLoadedHandle: function(img, o){
            var kg = {
                w: img.width ? img.width : 0,
                h: img.height ? img.height : 0
            }
            var childMap = o.childMap;
            var mapId = o.mapId;
            var mapLocation = new MapLocation(childMap.pId, map.getZoom(), map.getCenter());
            mapLocationArray.push(mapLocation);
            bounds = new OpenLayers.Bounds(-kg.w / 2, -kg.h / 2, kg.w / 2, kg.h / 2);
            var maxRes = kg.w / $("#map").width() > kg.h / $("#map").height() ? kg.w / $("#map").width() : kg.h / $("#map").height();
            var curtRes = (maxRes - 0.1) / 9;
            map.resolutions = [maxRes * 1.5, maxRes, maxRes - curtRes, maxRes - 2 * curtRes, maxRes - 3 * curtRes, maxRes - 4 * curtRes, maxRes - 5 * curtRes, maxRes - 6 * curtRes, maxRes - 7 * curtRes, maxRes - 8 * curtRes, 0.1];
            var childMapLayer = new OpenLayers.Layer.Image(childMap.name, pathToUrl(childMap.path), bounds, new OpenLayers.Size(kg.w, kg.h));
            childMapLayer.id = mapId;
            map.addLayer(childMapLayer);
            setCurShowMap(mapId);
            showChildMap(mapId);
            showMapDevices(mapId);
            map.zoomToExtent(bounds);
            initBackBar();
            main_ctrl.resetPage();
        },
        
        /**
         * 进入指定的地图
         * @param  mapId
         * @author jq_zhang
         */
        gotoSelectedMap: function(mapId){
            map.removeLayer(map.getLayer(curMapId));
			
			var needDelArray = $.grep(mapLocationArray, function(n){
				return !isParent(mapId, n);
			});
			
			for(var i=0;i<needDelArray.length;i++){
				if(needDelArray[i].mapId != mapId){
					var needDelLayer = map.getLayer(needDelArray[i].mapId);
					if(needDelLayer){
						map.removeLayer(needDelLayer,false);
					}
				}
			}
			
            $("#backShowImg").remove();
            var selectedLayer = map.getLayer(mapId);
			var selectedMap = getMapById(mapId);
			var selectedMapUrl = pathToUrl(selectedMap.path);
			if(selectedLayer.url != selectedMapUrl){//如果地址有变动，则重新加载图片
				loadImage(selectedMapUrl, main_ctrl.reloadImageHandle, {
					selectedMapUrl: selectedMapUrl,
					selectedLayer: selectedLayer,
					selectedMapId: mapId
				});
			}else{
				main_ctrl.mapSwitchHandle(selectedLayer,mapId);
			}
            
        },
        
		/**
		* 重新加载地图
		* @param  img
		* @param  o
		* @author jq_zhang
		*/
		reloadImageHandle:function(img,o){
			var kg = {
				w: img.width ? img.width : 0,
				h: img.height ? img.height : 0
			};
			var selectedLayer = o.selectedLayer;
			bounds = new OpenLayers.Bounds(-kg.w / 2, -kg.h / 2, kg.w / 2, kg.h / 2);
			var curUpdateLayer = new OpenLayers.Layer.Image(selectedLayer.name, o.selectedMapUrl, bounds, new OpenLayers.Size(kg.w, kg.h));
			map.removeLayer(selectedLayer);
			curUpdateLayer.id = o.selectedMapId;
			map.addLayer(curUpdateLayer);
			map.setBaseLayer(curUpdateLayer);
			setTimeout(function(){
				main_ctrl.mapSwitchHandle(curUpdateLayer,o.selectedMapId);
			},50);
		},
		
		/**
         * 进入选择的地图
         * @param  selectedLayer
		 * @param  mapId
         * @author jq_zhang
         */
		mapSwitchHandle:function(selectedLayer,mapId){
			var maxRes = selectedLayer.size.w / $("#map").width() > selectedLayer.size.h / $("#map").height() ? selectedLayer.size.w / $("#map").width() : selectedLayer.size.h / $("#map").height();
			var curtRes = (maxRes - 0.1) / 9;
			map.resolutions = [maxRes * 1.5, maxRes, maxRes - curtRes, maxRes - 2 * curtRes, maxRes - 3 * curtRes, maxRes - 4 * curtRes, maxRes - 5 * curtRes, maxRes - 6 * curtRes, maxRes - 7 * curtRes, maxRes - 8 * curtRes, 0.1];
			setCurShowMap(mapId);
			showChildMap(mapId);
			showMapDevices(mapId);
			var selectedMapLocation = getMapLocationById(mapId);
			map.zoomTo(selectedMapLocation.zoomLevel);
			map.setCenter(selectedMapLocation.center);
			sortMapLocation(mapId);
			initBackBar();
			main_ctrl.resetPage();
		},
        
        /**
         * 添加主地图
         * @author jq_zhang
         */
        addLocalMap: function(){
            var json = {
                pId: "",
                mapX: "",
                mapY: ""
            }
            $.dialog({
                id: 'map_add',
                title: bitmap_lang.js.addMap,
                content: 'url:add.html',
                data: json,
                width: '400px',
                height: '225px',
                max: false,
                min: false,
                lock: true,
                resize: false
            });
            
        },
        
        /**
         * 修改当前地图
         * @author jq_zhang
         */
        updateCurMap: function(){
            var currentMapObject = getMapById(curMapId);
	    var pId = currentMapObject.pId;
	    var childMaps = getChildMaps(pId);
            var json = {
                id: currentMapObject.id,
                mapX: currentMapObject.mapX,
                mapY: currentMapObject.mapY,
                pId: currentMapObject.pId,
                currentMap: currentMapObject,
		childMaps: childMaps,
                type: 'cur'
            }
            $.dialog({
                id: 'map_mdy',
                title: bitmap_lang.js.editMap,
                content: 'url:modify.html',
                data: json,
                width: '400px',
                height: '225px',
                max: false,
                min: false,
                lock: true,
                resize: false
            });
        },
        
        /**
         * 删除当前地图
         * @author jq_zhang
         */
        delCurMap: function(){
            this.delMapAndDev(curMapId);
            var curMapObj = getMapById(curMapId);
            if (curMapObj.pId == "") {//删除主地图
                window.location.reload();
            }
            else {
                mapArray = getAllMap();
                devArray = getAllGisChannels();
                this.gotoSelectedMap(curMapObj.pId);//跳到父类地图
            }
        },
        
        /**
         * 添加子地图
         * @author jq_zhang
         */
        addChildMap: function(){
            var currentMapObject = getMapById(curMapId);
            var count = countFloor(currentMapObject, 1);
            if (count && count >= 7) {
                $.dialog({
                    title: bitmap_lang.js.tip,
                    time: 2,
                    icon: 'warning.png',
                    content: bitmap_lang.js.areaAddTip
                });
                return;
            }
            var pId = currentMapObject.id;
            var mapX = map.getCenter().lon;
            var mapY = map.getCenter().lat;
	    var childMaps = getChildMaps(curMapId);
            var json = {
                pId: pId,
                mapX: mapX,
                mapY: mapY,
		childMaps:childMaps
            }
            $.dialog({
                id: 'map_add',
                title: bitmap_lang.js.addArea,
                content: 'url:add.html',
                data: json,
                width: '400px',
                height: '225px',
                max: false,
                min: false,
                lock: true,
                resize: false
            });
            
        },
        
        /**
         * 添加子地图后的处理事件
         * @param  jsonStr
         * @author jq_zhang
         */
        addChildMapHandle: function(jsonStr){
            var info = eval("(" + jsonStr + ")").array;
            var jsonObj = {
                source: info[0].path,
                target: formatPath(info[0])
            }
            copyMap(JSON.stringify(jsonObj));
            info[0].path = formatPath(info[0]);
            updateMap(JSON.stringify(info[0]));
            mapArray.push(info[0]);
            var marker = this.addCustomMarker(info[0].id, info[0].mapX, info[0].mapY, info[0].name, 'map');
            onMarker(marker);
        },
        
        /**
         * 添加主地图后的处理事件
         * @param  jsonStr
         * @author jq_zhang
         */
        addLocalMapHandle: function(jsonStr){
            var info = eval("(" + jsonStr + ")").array;
            var jsonObj = {
                source: info[0].path,
                target: formatPath(info[0])
            };
            copyMap(JSON.stringify(jsonObj));
            info[0].path = formatPath(info[0]);
            updateMap(JSON.stringify(info[0]));
            this.init(this.curPage);
        },
        
        /**
         * 修改子地图
         * @author jq_zhang
         */
        updateChildMap: function(){
            var mk = selectedMapMarker;
            if (!mk || !mk.selected) {
                $.dialog({
					drag:false,
                    title: bitmap_lang.js.tip,
                    time: 2,
                    icon: 'warning.png',
                    content: bitmap_lang.js.noAreaTip
                });
                return;
            }
            var currentMapObject = getMapById(mk.id);
            var pId = currentMapObject.pId;
	    var childMaps = getChildMaps(pId);
            var json = {
                id: mk.id,
                mapX: mk.lonlat.lon,
                mapY: mk.lonlat.lat,
                pId: pId,
                currentMap: currentMapObject,
		childMaps: childMaps,
                type: 'child'
            }
            $.dialog({
                id: 'map_mdy',
                title: bitmap_lang.js.editArea,
                content: 'url:modify.html',
                data: json,
                width: '400px',
                height: '225px',
                max: false,
                min: false,
                lock: true,
                resize: false
            });
        },
        
        /**
         * 修改地图后的处理事件
         * @param  jsonStr
         * @param  type
         * @author jq_zhang
         */
        updateMapHandle: function(jsonStr, type, oldPath){
            var data = eval('(' + jsonStr + ')');
            if (data.path != oldPath) {
                var tempArray = new Array();
                delMapByPath(JSON.stringify({
                    path: oldPath
                }));
                copyMap(JSON.stringify({
                    source: data.path,
                    target: formatPath(data)
                }));
                data.path = formatPath(data);
                updateMap(JSON.stringify(data));
            }
            var mapObj = getMapById(data.id);
            var index = ($.dh.arrayCheckItem(mapArray, mapObj));
            mapArray[index] = data;
            if (type == "cur") {
                var layerUrl = pathToUrl(getMapById(curMapId).path);
                loadImage(layerUrl, main_ctrl.updateCurMapHandle, {
                    layerUrl: layerUrl
                },function(){
					$.dialog({
						title: bitmap_lang.js.tip,
						icon: 'warning.png',
						content: bitmap_lang.js.mapError
					});
				});
            }
            else {
                $(selectedMapMarker.icon.imageDiv).find("label[name=markerTitle]").text(data.name);
					var childLayer = map.getLayer(data.id);
					if (childLayer){
						var childMapUrl = pathToUrl(getMapById(data.id).path);
						if(childMapUrl != childLayer.url){
							loadImage(childMapUrl, main_ctrl.updateChildMapHandle, {
								childMapUrl: childMapUrl,
								childLayer: childLayer,
								childMapId: data.id
						});
					}
				}
            }
        },
		
		/**
         * 修改子地图后的的处理事件
         * @param  img	预加载的图片
         * @param  o	保留参
         * @author jq_zhang
         */
		updateChildMapHandle: function(img,o){
			var kg = {
				w: img.width ? img.width : 0,
				h: img.height ? img.height : 0
			};
			var childLayer = o.childLayer;
			bounds = new OpenLayers.Bounds(-kg.w / 2, -kg.h / 2, kg.w / 2, kg.h / 2);
			var curUpdateLayer = new OpenLayers.Layer.Image(childLayer.name, o.childMapUrl, bounds, new OpenLayers.Size(kg.w, kg.h));
			map.removeLayer(childLayer);
			curUpdateLayer.id = o.childMapId;
			map.addLayer(curUpdateLayer);
		},
        
        /**
         * 修改当前地图后的的处理事件
         * @param  img	预加载的图片
         * @param  o	保留参
         * @author jq_zhang
         */
        updateCurMapHandle: function(img, o){
            var kg = {
                w: img.width ? img.width : 0,
                h: img.height ? img.height : 0
            }
            var curLayer = map.getLayer(curMapId);
            bounds = new OpenLayers.Bounds(-kg.w / 2, -kg.h / 2, kg.w / 2, kg.h / 2);
            map.restrictedExtent = bounds;
            var curUpdateLayer = new OpenLayers.Layer.Image(curLayer.name, o.layerUrl, bounds, new OpenLayers.Size(kg.w, kg.h));
            map.removeLayer(curLayer);
            var maxRes = curUpdateLayer.size.w / $("#map").width() > curUpdateLayer.size.h / $("#map").height() ? curUpdateLayer.size.w / $("#map").width() : curUpdateLayer.size.h / $("#map").height();
            var curtRes = (maxRes - 0.1) / 9;
            map.resolutions = [maxRes * 1.5, maxRes, maxRes - curtRes, maxRes - 2 * curtRes, maxRes - 3 * curtRes, maxRes - 4 * curtRes, maxRes - 5 * curtRes, maxRes - 6 * curtRes, maxRes - 7 * curtRes, maxRes - 8 * curtRes, 0.1];
            curUpdateLayer.id = curMapId;
            map.addLayer(curUpdateLayer);
            map.setBaseLayer(curUpdateLayer);
            map.zoomToExtent(curUpdateLayer.extent);
            curUpdateLayer.div.style.display = "block";
            var ovmapLayer = new OpenLayers.Layer.Image(curUpdateLayer.name, curUpdateLayer.url, curUpdateLayer.extent, curUpdateLayer.size);
            var wMax = parseFloat(map.div.style.width) / parseFloat(overview.mapDiv.style.width);
            var hMax = parseFloat(map.div.style.height) / parseFloat(overview.mapDiv.style.height);
            var resolutionMax = wMax > hMax ? wMax : hMax;
            overview.ovmap.resolutions = [resolutionMax * map.resolutions[1]];
            overview.ovmap.addLayer(ovmapLayer);
            overview.ovmap.removeLayer(overview.ovmap.baseLayer);
            overview.ovmap.restrictedExtent = curUpdateLayer.extent;
            overview.update();
            $(overview.ovmap.div).find("img").parent().show();
        },
        
        /**
         * 删除子地图
         * @author jq_zhang
         */
        delChildMap: function(){
            var mk = selectedMapMarker;
            if (!mk || !mk.selected) {
                $.dialog({
					drag:false,
                    title: bitmap_lang.js.tip,
                    time: 2,
                    icon: 'warning.png',
                    content: bitmap_lang.js.noAreaTip
                });
                return;
            }
            $.dialog({
				drag:false,
                title: bitmap_lang.js.confirm,
                lock: true,
                icon: 'warning.png',
                content: bitmap_lang.js.confirmDelChildmap,
                ok: function(){
                    main_ctrl.delMapAndDev(mk.id);
                    mapMarkers.removeMarker(mk);
                    selectedMapMarker = null;
                    mapArray = getAllMap();
                    devArray = getAllGisChannels();
                },
                cancel: function(){
                },
                okVal: bitmap_lang.js.yes,
                cancelVal: bitmap_lang.js.no
            });
        },
        
        /**
         * 删除子地图与设备
         * @param  mapId
         * @author jq_zhang
         */
        delMapAndDev: function(mapId){
            var boDelMap = getMapById(mapId);
            delMapByPath(JSON.stringify({
                path: boDelMap.path
            }));
            var mapDelStr = "{\"id\":\"" + mapId + "\"}";
            var curdevs = getDevicesByMapId(mapId);
            deleteMap(mapDelStr);
            if (curdevs && curdevs.length > 0) {
                for (var i = 0; i < curdevs.length; i++) {
                    curdevs[i].mapX = '';
                    curdevs[i].mapY = '';
                }
                batchUpdateDevice(curdevs);
            }
            var subMaps = getChildMaps(mapId);
            if (subMaps && subMaps.length > 0) {
                for (var i = 0; i < subMaps.length; i++) {
                    this.delMapAndDev(subMaps[i].id);
                }
            }
        },
        
        /**
         * 删除设备
         * @author jq_zhang
         */
        delDevice: function(){
            if (selectedDevices.length < 1) {
                $.dialog({
					drag:false,
                    title: bitmap_lang.js.tip,
                    time: 2,
                    icon: 'warning.png',
                    content: bitmap_lang.js.noDevTip
                });
                return;
            }
            var array = new Array();
            for (var i = 0; i < selectedDevices.length; i++) {
                var temp = getCupMapDeviceByMkId(selectedDevices[i].id);
                if(!temp) continue;
                temp.mapX = '';
                temp.mapY = '';
                array.push(deepClone(temp));
                devMarkers.removeMarker(selectedDevices[i]);
                devArray.splice($.inArray(temp, devArray), 1);
            }
            selectedDevices.length = 0;
            try {
                batchUpdateDevice(array);
            } 
            catch (e) {
                $.dialog({
					drag:false,
                    title: bitmap_lang.js.alert,
                    time: 2,
                    icon: 'warning.png',
                    content: bitmap_lang.js.delDevError
                });
            }
        },
        
        /**
         * 添加设备OR地图标记
         * @param  id 		标记唯一标识
         * @param  mapX		标记经度
         * @param  mapY		标记纬度
         * @param  name		标记名
         * @param  type		标记类型
         * @author jq_zhang
         */
        addCustomMarker: function(id, mapX, mapY, name, type){
            var img = (type == 'map') ? images.map : images.dev;
            var size = (type == 'map') ? new OpenLayers.Size(32, 32) : new OpenLayers.Size(30, 30);
            var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
            var icon = new OpenLayers.Icon(img, size, offset);
            var marker = new OpenLayers.DHMarker(id, new OpenLayers.LonLat(mapX, mapY), icon, name, type);
            (type == 'map') ? mapMarkers.addMarker(marker) : devMarkers.addMarker(marker);
            return marker;
        },
        
        /**
         * 根据标记打开视频
         * @param mk
         * @author
         */
        openVideo: function(mk){
            var ev = window.event || e;
            var pos = mouseCoords(ev);
            var chanenlId = (mk.id.split("#"))[0];
            var jsonObj = {
                channelId: chanenlId,
				name: mk.text,
                screenX: pos.x.toString(),
                screenY: pos.y.toString()
            }
            var tempArray = new Array();
            tempArray.push(jsonObj);
            openVedio(JSON.stringify(tempArray));
        },
        
        /**
         * 根据标记关闭指定视频
         * @param  mk
         * @author jq_zhang
         */
        closeVedio: function(mk){
            var chanenlId = (mk.id.split("#"))[0];
            closeVedio("{\"channelId\":\"" + chanenlId + "\"}");
        },
        
        /**
         * 关闭所有视频
         * @author jq_zhang
         */
        closeAllVedio: function(){
            //TODO
        },
        
        /**
         * 根据curpage重置预览编辑
         * @author jq_zhang
         */
        resetPage: function(){
            if (mapMarkers.markers != null) {
                for (var i = 0; i < mapMarkers.markers.length; i++) {
                    unMarker(mapMarkers.markers[i]);
                    onMarker(mapMarkers.markers[i]);
                }
            }
            if (devMarkers.markers != null) {
                for (var j = 0; j < devMarkers.markers.length; j++) {
                    unMarker(devMarkers.markers[j]);
                    onMarker(devMarkers.markers[j]);
                }
            }
            if (main_ctrl.curPage == page.view) {
                $("#editToolBar").hide();
                $("#viewToolBar").show();
            }
            else {
                $("#editToolBar").show();
                $("#viewToolBar").hide();
            }
        },
        
        /**
         * 返回到父地图
         * @author jq_zhang
         */
        goBack: function(){
            var curMapObj = getMapById(curMapId);
            if (curMapObj.pId != null && curMapObj.pId != "") {
                this.gotoSelectedMap(curMapObj.pId);
            }
        },
        
        /**
         * 刷新地图
         * @author jq_zhang
         */
        refreshMap: function(){
            if (map) {
                var zoomLevel = map.zoom;
                map.updateSize();
                var curLayer = map.getLayer(curMapId);
                var curUpdateLayer = new OpenLayers.Layer.Image(curLayer.name, curLayer.url, curLayer.extent, curLayer.size);
                map.removeLayer(curLayer);
                var maxRes = curUpdateLayer.size.w / $("#map").width() > curUpdateLayer.size.h / $("#map").height() ? curUpdateLayer.size.w / $("#map").width() : curUpdateLayer.size.h / $("#map").height();
                var curtRes = (maxRes - 0.1) / 9;
                map.resolutions = [maxRes * 1.5, maxRes, maxRes - curtRes, maxRes - 2 * curtRes, maxRes - 3 * curtRes, maxRes - 4 * curtRes, maxRes - 5 * curtRes, maxRes - 6 * curtRes, maxRes - 7 * curtRes, maxRes - 8 * curtRes, 0.1];
                curUpdateLayer.id = curMapId;
                map.addLayer(curUpdateLayer);
                map.setBaseLayer(curUpdateLayer);
                curUpdateLayer.div.style.display = "block";
                map.zoomTo(zoomLevel);
                var scale = $("#map").height() / $("#map").width();
                var oSize = new OpenLayers.Size(200, parseInt(200 * scale));
                overview.size = oSize;
                overview.mapDiv.style.width = oSize.w + "px";
                overview.mapDiv.style.height = oSize.h + "px";
                overview.ovmap.updateSize();
                var ovmapLayer = new OpenLayers.Layer.Image(curUpdateLayer.name, curUpdateLayer.url, curUpdateLayer.extent, curUpdateLayer.size);
                var wMax = parseFloat(map.div.style.width) / parseFloat(overview.mapDiv.style.width);
                var hMax = parseFloat(map.div.style.height) / parseFloat(overview.mapDiv.style.height);
                var resolutionMax = wMax > hMax ? wMax : hMax;
                overview.ovmap.resolutions = [resolutionMax * map.resolutions[1]];
                overview.ovmap.addLayer(ovmapLayer);
                overview.ovmap.removeLayer(overview.ovmap.baseLayer);
                overview.ovmap.restrictedExtent = curUpdateLayer.extent;
                overview.update();
                $(overview.ovmap.div).find("img").parent().show();
            }
        },
        
        /**
         * 重新获取设备树的数据并刷新树
         * @author jq_zhang
         */
        refreshTree: function(){
            setTreeIcon();
            zTree = $.fn.zTree.init($("#devTree"), setting, treeNodes);
        },
        
        /**
         * 通道报警
         * @param  channelId
         * @author jq_zhang
         */
        devAlert: function(channelId){
            if (this.curPage == page.edit) 
                return;
            var markers = getDevMarkersByChannelId(channelId);
            if (markers && markers.length > 0) {
                for (var i = 0; i < markers.length; i++) {
                    var o = markers[i];
                    (function(o){
                        o.setUrl(images.flashDev);
                        setTimeout(function(){
                            o.selected ? o.setUrl(images.selectedDev) : o.setUrl(images.dev);
                        }, 10000);
                    })(o);
                }
            }
        },
        
        /**
         * 从编辑切换到预览时候取消所有标记的选中状态
         * @param  channelId
         * @author jq_zhang
         */
        viewPageInit: function(){
            if (main_ctrl.curPage == page.edit) {
                if (selectedMapMarker) {
                    selectedMapMarker.selected = false;
                    selectedMapMarker.setUrl(images.map);
                    selectedMapMarker = null;
                }
                if (selectedDevices && selectedDevices.length > 0) {
                    for (var i = 0; i < selectedDevices.length; i++) {
                        selectedDevices[i].selected = false;
                        selectedDevices[i].setUrl(images.dev);
                    }
                    selectedDevices.length = 0;
                }
            }
        },
		
		 /**
         * 添加地图时地图名称超出长度
         * 
         *  @author wang_qing
         */
        alertMapNameOverLength: function(){
		
            $.dialog({
                title: bitmap_lang.js.tip,
				time: 2,
				icon: 'warning.png',
				content: bitmap_lang.js.mapNameOverLength
               
             });
        },
        
        /**
         * 添加地图时地图描述超出长度
         * 
         * @author wang_qing
         */
        alertMapDescribeOverLength: function(){
             $.dialog({
                title: bitmap_lang.js.tip,
				time: 2,
				icon: 'warning.png',
				content: bitmap_lang.js.describeOverLength

             });
        },
		
		/**
		 * 设备树刷新通知
		 */
		devAndTreeRefresh:function(){
			main_ctrl.refreshTree();
			var tempSelectedId = new Array();
			for(var i=0;i<selectedDevices.length;i++){
				tempSelectedId.push(selectedDevices[i].id);
			}
			devArray = getAllGisChannels();
			showMapDevices(curMapId);
			main_ctrl.resetPage();
			for(var j = 0;j<tempSelectedId.length;j++){
				for (var i = 0; i < devMarkers.markers.length; i++) {
					if (devMarkers.markers[i].id == tempSelectedId[j]) {
						devMarkers.markers[i].selected = true;
                        devMarkers.markers[i].setUrl(images.selectedDev);
                        selectedDevices.push(devMarkers.markers[i]);
					}
				}
			}
		}
    }
})($);
