//window.onerror = function(){return true};
var cartIds="";//-1表示没有数据,""表示有数据
var tempcarIds="";//-1表示没有数据,""表示有数据
var cartIdsArr = new Array();//-1表示没有数据,""表示有数据
var serverip;
var equipmentMap={};
var lineStatus=-1;//设置在线离线选中状态
var groupjson=null;
var groupObject={};
var equipmentObject={};
var qonun = -1;//-1:全部   0 :离线  1:在线
var isShowTTs = false;//(气泡框)是否显示TTS文本播读
var isShowInstill = false;//(气泡框)是否显示安装时间
var isShowVideo = false;//气泡框是否显示视频按钮(尖峰时刻)
//设备状态
var onlines=new Array();
var unonlines=new Array();

var usertype="";
var flagwarmvoice=true;

var isLargeData = false;

var largeDataThresholds = 500;
var isF = false;

var pagingRefreshObject = {
	isPaging : true,
	total : 0,
	pageSize : 500
}
$(window).load(function () {
  if( $('#usertypeId').val() != '-1000' && $('#usertypeId').val() != '-100'){
  	 loginManager();//用于获取后台管理权限
  }
 mapType = getUserStatus()?getUserStatus().mapType:1;
  if(mapType == 2){
	  loadGoogleMapJs();//加载地图js
	  $("#eqname").hide();
	  $("#markerNamePermissionsPanelBtn").hide();
	  $("#mapsearch").hide();
  }else if(mapType == 1){
	  $("#gd_mapsearch").hide();
  }else{
	  $("#mapsearch").hide();
	  $("#thisAreaQuery").hide();
	  $("#historyAreaQuery").hide();
  }
  openMask();
  
  setSystemObject.init();
  
  var zMsg =$('#zMsg').val();
  
  if(zMsg=="true"){
	  showMap();
	  document.getElementById("checkbox2").style.display="none";
	  document.getElementById("buttonMap").style.display="none";
  }
  serverip=$("#serverip").val();
  
  setuserType();//设置用户类型 
  loadTreeNodeCss();
  if(isIncludeClientNode()){
  		loadClientData();
  }
  getGroup();//添加组 
  
  flagwarmvoice=getWarmVoiceStatus();
  
  if(mapType == 2){
  	if(usertype=="-1000"||usertype=="-100"){
  	
  	}else{
  		$("#fencePermissionsPanelBtn").show();
  		electronicFence.tree.init();
  	}
  }
   startMarker();
   ExliveMap.setMap(mapType);//设置地图类型
   initTool();//切换地图时初始化工具*/
});

function time2stamp(){
    var d = new Date();
    return Date.parse(d)+d.getMilliseconds();
}
//设置用户类型
function setuserType(){
  usertype=$('#usertypeId').val();
  if(usertype!=null){
      switch($.trim(usertype)){
         case '0': $('#userType').text("系统管理员"); break;
         case '1': $('#userType').text("一级管理员"); break;
         case '2': $('#userType').text("二级管理员"); break;
         case '-1': $('#userType').text("普通监控员"); break;
         case '10': $('#userType').text("演示账号"); break;
         case '-100': $('#userType').text("个人用户"); break; 
         case '-1000': $('#userType').text("体验账号"); break; 
      }
  }
}

//设备组
function Group(){
        var id=null;
        var name=null;
        var childs={};      
        var childsIds = new Array();
        var clientId = 0;
        
        this.getId = function(){
            return id;
        }
        this.setId = function(_id){
            id = _id;
        }
        this.getName = function(){
            return name;
        }
        this.setName = function(_name){
            name = _name;
        }
        this.getChilds = function(){
            return childs;
        }
        this.setChilds = function(_childs){
            childs = _childs;
        }
        this.getChildsIds = function(){
            return childsIds;
        }
        this.setChildsIds = function(_childsIds){
            childsIds = _childsIds;
        }
        this.getClientId = function(){
            return clientId;
        }
        this.setClientId = function(_clientId){
            clientId = _clientId;
        }
}

function Equipment(){
        var id=null;
        var name=null;
        var speed=0;//速度
        var gpstime=null;
        var online=0;

        this.getId = function(){
            return id;
        }
        this.setId = function(_id){
            id = _id;
        }
        this.getName = function(){
            return name;
        }
        this.setName = function(_name){
            name = _name;
        }
        this.getSpeed = function(){
            return speed;
        }
        this.setSpeed = function(_speed){
            speed = _speed;
        }
        this.getGpstime = function(){
            return gpstime;
        }
        this.setGpstime = function(_gpstime){
            gpstime = _gpstime;
        }
        this.getOnline = function(){
            return online;
        }
        this.setOnline = function(_online){
            online = _online;
        }
}

function openMask(){

	$("#mask").css({"height":$(document).height(),"width":$(document).width()}).show();		
	$("#content").show();
	$('#content').center();
	
}
function closeMask(){

    $("#mask").hide();
    $("#content").hide();
    
}      

//获取组以及设备信息
function getGroup(){
	$.ajax({
	        type: "POST",
	        dataType: "json",
	        async:true,
	        url: "json/groupAction_groupName.action",
	        data: {dataType:1, haveClient : curUserIncludeClientFlag()},
	        success: function(json){
//	        	 console.info(JSON.stringify(json));
		         if(json.flag==true){
		        	//$.cookie('vehicledatestr',"123456",{path:'/',expires:1});
		        	sessionStorage.setItem("vehicledatestr",JSON.stringify(json)); //存数据
					groupjson =	json;
					loadGroupTree();
					if(cartIds.length != 0){
						  
						 saveEquipmentMap(groupjson);
 
						 if(!isLargeData){
						  	initialize(cartIds);//加载车辆详细信息	  	
						  }else{
							   initialize("-2");
						  	 //initialize("thresholds");//加载车辆详细信息
						  	 //initialize("-1");//没有车辆时加载谷歌地图
						  }
						  getAllComds();//获取命令
						  //getUnDispoesAlarmMsg();
						  setInterval('getwarmMsg()',5000);//每五秒刷新一次报警信息
						  setInterval('getNotice()',30000);//每30秒刷新一次报警信息
						  setInterval('getDriverMov()',5000);//每5秒刷新一次驾驶行为数据
					 }else{
					  	    //initialize("-1");//没有车辆时加载谷歌地图
					  	    initialize("thresholds");
					  	    $("#unlinecount").text(0);
						    $("#onlinecount").text(0);
						    $("#allcount").text(0);
					 }	
                 }else{
                 	groupjson =	json;                
                    //alert(json.msg);
								  		
					if(json.statecode){
						if(json.statecode==10000){
							if($.browser.msie) { 
			                  location.href = "../login.jsp";
						   }else{
						      location.href = "./gpsonline/jsp/login.jsp";
						   }
						}
					}
                 }
	        },
	        error: function() {
	             //alert('获取组信息失败...请联系管理员!');
	        }
	   });			
}
//使用设备json构建设备组map
function saveEquipmentMap(data){

    var count=data.totalcount;
    
    var groups=data.data;
    
    var groupMap={};//设备组map
    
    for(var i=0;i<count;i++){
    
         var groupObject=new Group();
         
         groupObject.setId(groups[i].id);
   	     groupObject.setName(groups[i].groupName);
   	     groupObject.setClientId(groups[i].clientid);
   	     
        var childs=groups[i].data;
    	   
   	   	var childMap={};//设备map
   	    var childsIds = new Array();
   	    
   	    for(var j=0;j<childs.length;j++){
	   	      
	          var child = new Equipment();  	      
	   	      child.setId(childs[j].id);
	   	      child.setName(childs[j].vehicleName);
	   	      
	   	      childMap[childs[j].id]=child;	
	   	      
	   	      childsIds.push(childs[j].id);
	   	     
	   	      equipmentObject[childs[j].id]={};
	   	      equipmentObject[childs[j].id].vehicleName=childs[j].vehicleName;
	   	      equipmentObject[childs[j].id].id=childs[j].id;	   	      
			  equipmentObject[childs[j].id].icon = childs[j].icon;
			  
			  equipmentObject[childs[j].id].name=childs[j].vehicleName;
			  
			  equipmentObject[childs[j].id].simCode = childs[j].simCode;
			  
			  equipmentObject[childs[j].id].gprsCode = childs[j].gprsCode;
			  
			  equipmentObject[childs[j].id].mobileId = childs[j].mobileId;
			  
			  equipmentObject[childs[j].id].isPosition=true;//是否是未定位
			  
			  equipmentObject[childs[j].id].overduetime = childs[j].overduetime; 
			  			  	      
   	    }
   	    
        groupObject.setChilds(childMap);
        groupObject.setChildsIds(childsIds);
        groupMap[groups[i].id]=groupObject;
        
    }   
    
    equipmentMap=groupMap;
    
     addOverTimeVehicleTableRecoders();//显示将要或已过期设备信息
}

/*
var map = {}; // Map map = new HashMap();
map[key] = value; // map.put(key, value);
var value = map[key]; // Object value = map.get(key);搜索
var has = key in map; // boolean has = map.containsKey(key);
delete map[key]; // map.remove(key);
*/

//指定时间与当前时间间隔天数
function unlineTime(lastonlineTime){
   if(lastonlineTime!=null&&lastonlineTime!=""){
	    var ab = lastonlineTime.split(" ")[0].split("-");    
        var from = new Date();
        var now = new Date();      
        //alert(lastonlineTime+","+ab[0]+"-"+ab[1]+"-"+ab[2]);
        from.setUTCFullYear(ab[0], ab[1]-1, ab[2]); 
        return Math.floor((now.getTime()-from.getTime())/(24*60*60*1000));       
    }else{
      return -1;
    }
}
function unlineTimeT(lastonlineTime){
   if(lastonlineTime!=null&&lastonlineTime!=""){
	   	lastonlineTime=lastonlineTime.replace("T"," ");
	   	var ab = lastonlineTime.split(" ")[0].split("-");    
        var from = new Date();
        var now = new Date();
        from.setUTCFullYear(ab[0], ab[1]-1, ab[2]);
        //return Math.floor((now.getTime()-from.getTime())/(24*60*60*1000))-1;   
        return Math.floor((now.getTime()-from.getTime())/(24*60*60*1000));
    }else{
      return -1;
    }
}
//计算间隔，单位天
function unlineTimeT2(lastonlineTime){
	   if(lastonlineTime!=null&&lastonlineTime!=""){
		   	lastonlineTime = lastonlineTime.replace("T"," ");
		   	
    		var timearr = lastonlineTime.split(" ");
    		var year = timearr[0].split("-")[0];
    		var moth = timearr[0].split("-")[1];
    		var day = timearr[0].split("-")[2];
    		
    		var hour = timearr[1].split(":")[0];
    		var minu = timearr[1].split(":")[1];
    		var secsond = timearr[1].split(":")[2];
	        var from = new Date(year,moth-1,day,hour,minu,secsond);
	        var now = new Date();
	        return parseInt((now.getTime()-from.getTime())/(24*60*60*1000));
	    }else{
	      return -1;
	    }
	}
//计算间隔，单位  小时
function unlineTimeT3(lastonlineTime){
	   if(lastonlineTime!=null&&lastonlineTime!=""){
		   	lastonlineTime=lastonlineTime.replace("T"," ");
		   	
		   	var timearr = lastonlineTime.split(" ");
    		var year = timearr[0].split("-")[0];
    		var moth = timearr[0].split("-")[1];
    		var day = timearr[0].split("-")[2];
    		
    		var hour = timearr[1].split(":")[0];
    		var minu = timearr[1].split(":")[1];
    		var secsond = timearr[1].split(":")[2];
	        var from = new Date(year,moth-1,day,hour,minu,secsond);
	       // var from = new Date(lastonlineTime);
	        var now = new Date();
	        return parseInt((now.getTime()-from.getTime())/(60*60*1000));
	    }else{
	      return -1;
	    }
	}
//显示所有设备信息
function allEquipment(element){
   $("#myNavigate").find("li").each(function(){
       $(this).attr("class","navigate_item");
   });
   $(element).attr("class","navigate_item navigate_item_over");
   showstatusThree(-1);
  // $('dl#group').accordion({open:false});
  closeAccordion();
   lineStatus=-1;//更改当前显示树状态标识
}
//显示离线设备信息
function unlineEquipment(element){
   $("#myNavigate").find("li").each(function(){
       $(this).attr("class","navigate_item");
   });
    $(element).attr("class","navigate_item navigate_item_over");
    showstatusThree(0);
   // $('dl#group').accordion({open:false});
   closeAccordion();
    lineStatus=0;//更改当前显示树状态标识
}
//显示在线设备信息
function onlineEquipment(element){
   $("#myNavigate").find("li").each(function(){
       $(this).attr("class","navigate_item");
   });
   $(element).attr("class","navigate_item navigate_item_over");
   showstatusThree(1);
   //$('dl#group').accordion({open:false});
   closeAccordion();
   lineStatus=1;//更改当前显示树状态标识
}
function showstatusThree(status){
   var count = 0, onLineCount = 0;
   switch(status){
   		case -1:
   			    qonun = -1;
   				$('#leftList').find("dd").each(function(){//迭代每一个组
   				    count =0, onLineCount = 0;
   				    $(this).prev().show();
   				    $(this).children().each(function(){
   				    	$(this).show();
   				    	count++;
   				    	if($(this).attr("status")=="1"){
   				    		onLineCount++;
   				    	} 				    
   				    });
   				    $(this).prev().find('span').text(onLineCount + "/" + count);
   				});
   		
   		break;
   		case 1:
   			qonun = 1;
   				$('#leftList').find("dd").each(function(){//迭代每一个组
   					count=0;
   				    $(this).children().each(function(){
   				    	if($(this).attr("status")=="1"){
   				    		$(this).show();
   				    		count++;
   				    	}else{
   				    		$(this).hide();
   				    	}
   				    });
   				    if(count==0){
   				    	$(this).prev().hide();
   				    }else{
   				    	$(this).prev().show();
   				    }
   				    $(this).prev().find('span').text(count);
   				});
   				
   		break;
   		
   		case 0:
   			   qonun = 0;
   				$('#leftList').find("dd").each(function(){//迭代每一个组
   					count=0;
   					$(this).prev().show();
   				    $(this).children().each(function(){
   				    	if($(this).attr("status")=="0"){
   				    		$(this).show();
   				    		count++;
   				    	}else{
   				    		$(this).hide();
   				    	}				    
   				    });
   				    if(count==0){
				    	$(this).prev().hide();
				    }else{
				    	$(this).prev().show();
				    }
   				    $(this).prev().find('span').text(count);
   				});
   		break;
   }
}
var fristId = "";
//加载左侧树形菜单
function loadGroupTree(){

	var treeStr="", childStr="", id, treeBuffer = new StringBuffer(), childBuffer = null, clientGroupCountLabel = null, clientGroupCount = 0;
	
	for(var i=0 ; i< groupjson.totalcount ; i++){
		
		 childBuffer = new StringBuffer();
		 childBuffer.append("<dd style='display:none;'>");
         
         for(var j=0 ; j< groupjson.data[i].data.length ; j++){
         
         	  id=groupjson.data[i].data[j].id;
         	  if(i==0 && j==0){
         		fristId = id;
         	  }
		              
		      childBuffer.append("<div style='overflow:auto;' status='0' id='"+groupjson.data[i].id+"_"+id+"' name='"+groupjson.data[i].data[j].vehicleName+"' onclick=\"showMenu(this,1);\">"+
					                 "<div class='vehicle_div_content'>"+
					                      "<div class='unline'><span class='idx_list_right' id=\"lineStatus_"+groupjson.data[i].id+"_"+id+"\">离线</span><div class='idx_list_left' ><img id=\"lineStatusImg_"+groupjson.data[i].id+"_"+id+"\" src='gpsonline/image/monitor/u_offline.gif'/>&nbsp;&nbsp;"+"<span title='"+groupjson.data[i].data[j].vehicleName+"'  id='eqname_"+groupjson.data[i].id+"_"+id+"' class='vehicle_div_Name'>"+groupjson.data[i].data[j].vehicleName+"</span>"+//style='display:inline-block;float:left; width:260px;'
					                      "</div></div>"+
					                 "</div>"+
					              "</div>");  
              cartIdsArr.push(id);
         }
         
        treeBuffer.append("<dt id='"+groupjson.data[i].id+"' clientId='" + groupjson.data[i].clientid + "'><img src='gpsonline/image/monitor/g_c.gif'/>"+groupjson.data[i].groupName+"(<span>0/"+j+"</span>)"+childBuffer.toString()+"</dd></dt>");
		childBuffer = null;
		
		if(isIncludeClientNode()){
			$("#client_group_content_" + groupjson.data[i].clientid).append(treeBuffer.toString());	
			clientGroupCountLabel = $("#client_group_count_" + groupjson.data[i].clientid);	
			clientGroupCount = parseInt(clientGroupCountLabel.attr("count")) + 1;
			clientGroupCountLabel.html("(" + clientGroupCount + ")");
			clientGroupCountLabel.attr("count", clientGroupCount);
		}else{
			$("#group").append(treeBuffer.toString());
		}
		treeBuffer = new StringBuffer();
	}
	cartIdsArr=cartIdsArr.myUnique();
	pagingRefreshObject.total = cartIdsArr.length;
	
	if(pagingRefreshObject.total>largeDataThresholds){
		if( $.cookie("isLargeData") != null && $.cookie("isLargeData")== "false" ){
			isLargeData = false;
			$("#largeDateShowVehicle").attr("checked","checked");
		}else{
			isLargeData = true;
			$("#largeDateShowVehicle").attr("checked","");
		}		
	}

	cartIds = cartIdsArr.toString();
	
	if(isIncludeClientNode()){
		$("dl[name='client_group_content']").each(function(){
			$(this).accordion({open:false});
		});
	}else{
		$('dl#group').accordion({open:false});   		
	}
	$("#unlinecount").text(cartIdsArr.length);
    $("#onlinecount").text(0);
    $("#allcount").text(cartIdsArr.length);   
}

function settive(){
	if(markers.length==0){
		setTimeout("settive()",1000);
		return;
	}
	centerMap(fristId,"0");
}

function updateGroupTree(){
	if(carList==null||carList==""){
   			setTimeout("updateGroupTree()",50);
   			return;	    
   	} 	
   	
   	//onlines=carList.onlines;//更新在线数组
    //unonlines=carList.unonlines;//更新离线数组
    
     for(var i=0;i<carList.data.length;i++){
     		 if(carList.data[i].positionLast == null) continue;
     		 equipmentObject[carList.data[i].id].speed=carList.data[i].positionLast.speed;
			 equipmentObject[carList.data[i].id].gpstime=carList.data[i].positionLast.recvtime;
			 equipmentObject[carList.data[i].id].online=carList.data[i].positionLast.online;
            
             //是否是未定位
             if(carList.data[i].positionLast.lat == 0 || carList.data[i].positionLast.lng == 0){
             	equipmentObject[carList.data[i].id].isPosition=false;
             }else{
             	equipmentObject[carList.data[i].id].isPosition=true;
             }	  		 
             
             equipmentObject[carList.data[i].id].overduetime = carList.data[i].overduetime;
             
             equipmentObject[carList.data[i].id].driverId = carList.data[i].driverId; 
             
             equipmentObject[carList.data[i].id].number = carList.data[i].dataCode;
             equipmentObject[carList.data[i].id].voice = carList.data[i].voiceCode; 
     }
    
    
    var allCount=0,unCount=0,onCount=0;
    
    var groupId,groupCountPanel,groupVhcTotal,groupOnlineVhcTotal;

	$('#leftList').find("dd").each(function(){//迭代每一个组
	
		groupId=$(this).prev().attr('id');//获取组id
		groupCountPanel = $("#" + groupId).find("span");
		groupVhcTotal = 0;
		groupOnlineVhcTotal = 0;
		
		$(this).children().each(function(){
			
			groupVhcTotal++;
			
			var id=$(this).attr('id').split('_')[1];
	        var curEquipmentDiv=$("#"+groupId+"_"+id);
	        var curEquipmentStatus=$("#lineStatus_"+groupId+"_"+id);
	        var childs=equipmentObject[id];	        
	        
	        if(!childs.isPosition){     	           			        		        	
	        	
	        	if(childs.online==1){
	        	
	        		curEquipmentStatus.text("静止");
	        		
	        		groupOnlineVhcTotal++;
	        	
	        		onlines.push(id);
	        		
		        	curEquipmentStatus.parent().removeClass().addClass("speed_0");
			        
			        curEquipmentDiv.attr("status","1");
			        
			        $("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/o_offline.gif");
			        
	        	}else{
	        		
	        		curEquipmentStatus.text("未定位");
	        		
	        		unonlines.push(id);
	        		
	        		curEquipmentStatus.parent().removeClass().addClass("unline");
	        		
		        	curEquipmentDiv.attr("status","0");
		        	
		        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");
		        	
	        	}	        	
	        }else{
		        if(childs.online==1){
		        
		        	groupOnlineVhcTotal++;
		        	
		        	onlines.push(id);
		        	
		        	var speed=childs.speed;
		        	
		        	if(speed==0){
		        	
		        		curEquipmentStatus.text("静止");
		        		curEquipmentStatus.parent().removeClass().addClass("speed_0");
		        		
			        }else{
			        
			        	curEquipmentStatus.text(speed+" km/h");
			        	curEquipmentStatus.parent().removeClass().addClass("speed_n");
			        	
			        }
			        
			        curEquipmentDiv.attr("status","1");
			        $("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/o_offline.gif");
			        
		        }else{
		            
		            unonlines.push(id);
		               	
		        	var date=unlineTimeT2(childs.gpstime);
					
		        	if(date!=-1&&date>0){
		        	
		        		if(date>=60){
		        			curEquipmentStatus.text("离线>60天");
		        		}else{
		        			curEquipmentStatus.text("离线"+date+"天");
		        		}
		        		
		        	}else{
		        		var hour=unlineTimeT3(childs.gpstime);
		        		if(hour!=-1 && hour >0){
		        			if(curEquipmentStatus.text()!="离线"+hour+"小时"){
		        				curEquipmentStatus.text("离线"+hour+"小时");
		        			}
		        		}else{
		        			if(curEquipmentStatus.text()!="离线"){
		        				curEquipmentStatus.text("离线");
		        			}
		        		}
		        		//curEquipmentStatus.text("离线");
		        	}
		        	
		        	curEquipmentStatus.parent().removeClass().addClass("unline");
		        	curEquipmentDiv.attr("status","0");
		        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");	        	
		        }
	        }
        });
        
        if(lineStatus == -1) groupCountPanel.text(groupOnlineVhcTotal + "/" + groupVhcTotal );
        
	});
	
	onlines=onlines.myUnique();
	unonlines=unonlines.myUnique();
	
	$("#unlinecount").text(unonlines.length);
    $("#onlinecount").text(onlines.length);
    $("#allcount").text(onlines.length + unonlines.length); 
      
}

var isrefersh=true;

//定时刷新
function reEquipmentStatus(datas){

	/*if(!isrefersh){		
		return ;
	}
	
	isrefersh = false;*/
	//var t1 = time2stamp();
	//var startTime=time2stamp();
    onlines=new Array();//更新在线设备id数组
    unonlines=new Array();//更新离线设备id数组

	for(var i=0;i<datas.st.length;i++){	        
        
        if(datas.st[i].online){
        
        	equipmentObject[datas.st[i].id].online=1;        	       	
        	
        }else{
        
        	equipmentObject[datas.st[i].id].online=0;
        	
        }
        
        equipmentObject[datas.st[i].id].speed=datas.st[i].v;
		equipmentObject[datas.st[i].id].gpstime=datas.st[i].t;
		
		//equipmentObject[datas.st[i].id].icon=datas.st[i].icon;
		
		if(datas.st[i].p){
        	equipmentObject[datas.st[i].id].isPosition=true;
        }else{
        	equipmentObject[datas.st[i].id].isPosition=false;
        }

                 
	} 
	
	
	
	
	
	var allcount=0;uncount=0;oncount=0;
	
	
	var i=0;id=-1,groupId = -1,curEquipmentDiv = null,curEquipmentStatus = null,childs = null,curGroupChildsIds = null,curGroupChildsIdsLength =0;
	
    $.each(equipmentMap, function (k, v) {//迭代每一个组
    		
		groupId=k;//获取组id
		curGroupChildsIds = v.getChildsIds();
		curGroupChildsIdsLength = curGroupChildsIds.length;
		
		for(i=0;i<curGroupChildsIdsLength;i++) {
			
			allcount ++;
			
			id=curGroupChildsIds[i];
	        curEquipmentDiv=$("#"+groupId+"_"+id);
	        curEquipmentStatus=$("#lineStatus_"+groupId+"_"+id);
	        childs=equipmentObject[id];	              
       	    
	        
       	    if(!childs.isPosition){		        	
       	   		
	        	
	        	if(childs.online==1){
	        	
	        		if(curEquipmentStatus.text()!="静止"){	       	   		
			        	curEquipmentStatus.text("静止");
		        	}
	        	
	        		oncount++;
	        		onlines.push(id);
			        if(curEquipmentDiv.attr("status")!="1"){
			        			        
			        	curEquipmentDiv.attr("status","1");
			        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/o_offline.gif");
			        	curEquipmentStatus.parent().removeClass().addClass("speed_0");	
			        			        	
			        }	
			        
			        	        
		        }else{  
					
					
	       	   		if(curEquipmentStatus.text()!="未定位"){	       	   		
			        	curEquipmentStatus.text("未定位");
		        	}
							        
		        	uncount++;
		        	unonlines.push(id);     	
		        	if(curEquipmentDiv.attr("status")!="0"){	
		        		        	
			        	curEquipmentDiv.attr("status","0");
			        	curEquipmentStatus.parent().removeClass().addClass("unline");
			        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");		
			        		        	
			        }
			        
		        }
					        	
	        }else{
	        	
	       	    if(childs.online==1){
	       	    	oncount++;
	       	    	onlines.push(id);
		        	var speed=childs.speed;
		        	if(speed==0){
		        		if(curEquipmentStatus.text()!="静止"){
			        		curEquipmentStatus.text("静止");
			        		curEquipmentStatus.parent().removeClass().addClass("speed_0");
			            }
			        }else{
			        	if(curEquipmentStatus.text()!=speed+" km/h"){
				        	curEquipmentStatus.text(speed+" km/h");
				        	curEquipmentStatus.parent().removeClass().addClass("speed_n");
			        	}
			        }
			        if(curEquipmentDiv.attr("status")!="1"){
			        	curEquipmentDiv.attr("status","1");
			        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/o_offline.gif");
			        }		        
		            if($('#elSelected').attr('value')==groupId+"_"+id){//判断某个设备是否已经选中			          
		        		curEquipmentStatus.parent().removeClass().addClass("onlineclick");
		        		curEquipmentDiv.addClass("onlineselectedstyle");
				    }
				    
				    if(lineStatus == 0){
		            	curEquipmentDiv.hide();
		            }else{
		            	curEquipmentDiv.show();
		            }
				    
		        }else{
		        	
		        	uncount++;
		        	unonlines.push(id);
		        	    	
		        	var date=unlineTimeT2(childs.gpstime);
		        	
		        	if(date!=-1&&date>0){
		        	
		        		if(date>=60){
		        			if(curEquipmentStatus.text()!="离线>60天"){
		        				curEquipmentStatus.text("离线>60天");
		        			}
		        		}else{
		        			if(curEquipmentStatus.text()!="离线"+date+"天"){
		        				curEquipmentStatus.text("离线"+date+"天");
		        			}
		        		}
		        		
		        	}else{
		        		var hour=unlineTimeT3(childs.gpstime);
		        		if(hour!=-1 && hour >0){
		        			if(curEquipmentStatus.text()!="离线"+hour+"小时"){
		        				curEquipmentStatus.text("离线"+hour+"小时");
		        			}
		        		}else{
		        			if(curEquipmentStatus.text()!="离线"){
		        				curEquipmentStatus.text("离线");
		        			}
		        		}
		        	}
		        	if(curEquipmentDiv.attr("status")!="0"){
		        	
			        	curEquipmentDiv.attr("status","0");
			        	curEquipmentStatus.parent().removeClass().addClass("unline");
			        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");
			        	
			        }
			        
		        	if($('#elSelected').attr('value')==groupId+"_"+id){//判断某个设备是否已经选中									          	  
			           curEquipmentStatus.parent().removeClass().addClass("unlineclick");
			           curEquipmentDiv.addClass("unlineselectedstyle");
		            }
		            
		            if(lineStatus == 1){
		            	curEquipmentDiv.hide();
		            }	else{
		            	curEquipmentDiv.show();
		            }
		        }
	        }
	    }
	    
	  switch(lineStatus){//判断在那个面板中显示（-1全部，1在线，0离线）
			 case -1: $("#"+groupId).find('span').text( oncount + "/" + allcount); break;
			 case 1:  $("#"+groupId).find('span').text(oncount); break;
			 case 0: $("#"+groupId).find('span').text(uncount); break; 
	  } 
	   
	   allcount = 0; 
	   oncount = 0; 
	   uncount = 0; 
	   
    });
   
    
  
	onlines=onlines.myUnique();//更新在线设备id数组
    unonlines=unonlines.myUnique();//更新离线设备id数组

    
    $("#unlinecount").text(unonlines.length);
    $("#onlinecount").text(onlines.length);
    $("#allcount").text(unonlines.length+onlines.length);

    
}


var expelement;
var menuelement;

//用于但双击事件处理
var clickRepeat; 
var clickCount=0; 
var clickDelay=300;

function showMenu(element,ptype){
	
	if(cartIds==null||cartIds==""){
    	return;
    }
	if(clickRepeat != null) window.clearTimeout(clickRepeat); 
	
	clickCount++; 
	var id=$(element).attr('id');//组ID  和 设备ID
	if(clickCount==1){
		clickRepeat = window.setTimeout(function(){
									createMenu(id,0,ptype);
									clickCount=0;
								},clickDelay);
	}else{
		createMenu(id,1,ptype);
		clickCount=0;
	}
}
function createMenu(parentDivId,type,ptype){
     parentDiv=$("#"+parentDivId);
     cancleMenu();

     var name=$(parentDiv).attr('name');
     var id=$(parentDiv).attr('id');
     $('#elSelected').attr('value',id);
     id=id.substring(id.indexOf("_")+1);//获取车辆id
     
    
     if(equipmentObject[id].online){
         parentDiv.find('span').parent().removeClass().addClass("onlineclick");
         parentDiv.removeClass().addClass("onlineselectedstyle");
     }else{
         parentDiv.find('span').parent().removeClass().addClass("unlineclick");
         parentDiv.removeClass().addClass("unlineselectedstyle");
     }
     var mendiv=$('<div></div>');  
          
     var icon=equipmentObject[id].icon;

	 var childdiv ="";
   	 childdiv=$("<div id='t_menu_"+id+"' class='left_tree_caozuo'>"+getEqEditMenuItem(id)+"<a id='track_"+id+"' href='javascript:;' onclick='getVechiletrack(event,"+id+");'><i class='idx_list_caozuo_ico_2'></i>跟踪</a>" + getPlayBackMenuItem(id) + "<a id='more_"+id+"' href='javascript:;' onclick=\"showSecondMenu(this,event);\"><i class='idx_list_caozuo_ico_4'></i>更多</a></div>");  
     childdiv.appendTo(mendiv);
     $(parentDiv).append(mendiv);
     
    if(ptype!=1){
	    treeNodePosition(parentDivId);//将选中设备调整到醒目位置
    }
     expelement=$(parentDiv);//保存已选中的菜单
     menuelement=mendiv;
     fristId = id;
     centerMap(id,type);
     if(mapType==1){
    	 baidMap.setZoom(13);
     }
     initVisualPower();//装载属性可见性
}
//获取树形轨迹回放菜单
function getPlayBackMenuItem(id){

	var item = "<a id='playback_" + id + "' onclick=\"getback(event,'" + id + "');\" href='javascript:;'><i class='idx_list_caozuo_ico_3'></i>回放</a> ";
	
	return isHasPBackAut() ? item : "";
}

function getEqEditMenuItem(vechileId){
	
	var item = "";
	initUpdateEqPowerState();
	if( eqEditPower.isEdit ){
		item = "<a href=\"javascript:openPopuWin('"+$("#serverUrl").val()+"gpsonline/jsp/monitor/updateEqInfoWin.jsp?p_eqName="+eqEditPower.eqName+"&sim_power="+eqEditPower.sim+"&gprs_power="+eqEditPower.gprs+"&number_power="+eqEditPower.number+"&voice_power="+eqEditPower.voice+"&vehicleId="+vechileId+"&remark="+eqEditPower.remark+"');\"><i class='idx_list_caozuo_ico_1'></i>编辑</a>";
	}
	return item;
}

//修改车辆权限
var eqEditPower = {
	isInited : false,
	isEdit : false,
	eqName : false,
	sim : false,
	gprs : false,
	number : false,
	voice : false,
	remark : false,
	UPDATE_EQ_NAME_POWER : 992010,
	UPDATE_EQ_SIM_POWER : 992020,
	UPDATE_EQ_GPRS_POWER : 992030,
	UPDATE_EQ_NUMBER_POWER : 992014,
	UPDATE_EQ_VOICE_POWER : 992015,
	UPDATE_EQ_REMARK_POWER : 992040,
	UPDATE_EQ_Full : 10103020,
};
//车辆属性可见
var eqVisualPower = {
	init : false,
	sim : false,
	gprs : false,
	remark : false,
	state : false,
	play : false,
	simchit:false,
	VISUAL_EQ_SIM_POWER : 991030,
	VISUAL_EQ_GPRS_POWER : 991020,
	VISUAL_EQ_REMARK_POWER : 991040,
	VISUAL_EQ_STATE_POWER : 991050,
	VISUAL_EQ_PLAY_POWER : 991025,
	VISUAL_EQ_SIMCHIT_POWER : 991010
};

var isvisble = true;//是否正常
//装载设备属性可见性
function initVisualPower(){
	if(!eqVisualPower.init && modelJson){
		for(var i=0; i<modelJson.length; i++){
			if(isvisble)isvisble=false;
			if(modelJson[i].id == eqVisualPower.VISUAL_EQ_SIM_POWER){
				eqVisualPower.sim = true;
			}else if(modelJson[i].id == eqVisualPower.VISUAL_EQ_GPRS_POWER){
				eqVisualPower.gprs = true;
			}else if(modelJson[i].id == eqVisualPower.VISUAL_EQ_REMARK_POWER){
				eqVisualPower.remark = true;
			}else if(modelJson[i].id == eqVisualPower.VISUAL_EQ_STATE_POWER){
				eqVisualPower.state = true;
			}else if(modelJson[i].id == eqVisualPower.VISUAL_EQ_PLAY_POWER){
				eqVisualPower.play = true;
			}else if(modelJson[i].id == eqVisualPower.VISUAL_EQ_SIMCHIT_POWER){
				eqVisualPower.simchit = true;
			}
			if(eqVisualPower.sim&&eqVisualPower.gprs&&eqVisualPower.remark&&eqVisualPower.state&&eqVisualPower.play&&eqVisualPower.simchit)  {
				break;
			}
		}
		eqVisualPower.init = true;
		if(isvisble)eqVisualPower.play=eqVisualPower.state=eqVisualPower.remark=eqVisualPower.gprs=eqVisualPower.sim=true;
	}
}

function initUpdateEqPowerState(){
	
	if(!eqEditPower.isInited && modelJson){
//		console.info(JSON.stringify(modelJson));
		for(var i=0; i<modelJson.length; i++){
			if(modelJson[i].id == eqEditPower.UPDATE_EQ_NAME_POWER){
				eqEditPower.eqName = true;
				eqEditPower.isEdit = true;
			}else if(modelJson[i].id == eqEditPower.UPDATE_EQ_SIM_POWER){
				eqEditPower.sim = true;
				eqEditPower.isEdit = true;
			}else if(modelJson[i].id == eqEditPower.UPDATE_EQ_GPRS_POWER){
				eqEditPower.gprs = true;
				eqEditPower.isEdit = true;
			}else if(modelJson[i].id == eqEditPower.UPDATE_EQ_NUMBER_POWER){
				eqEditPower.number = true;
				eqEditPower.isEdit = true;
			}else if(modelJson[i].id == eqEditPower.UPDATE_EQ_VOICE_POWER){
				eqEditPower.voice = true;
				eqEditPower.isEdit = true;
			}else if(modelJson[i].id == eqEditPower.UPDATE_EQ_REMARK_POWER){
				eqEditPower.remark = true;
				eqEditPower.isEdit = true;
			}else if(modelJson[i].id == eqEditPower.UPDATE_EQ_Full){
				eqEditPower.eqName = true;
				eqEditPower.sim = true;
				eqEditPower.gprs = true;
				eqEditPower.number = true;
				eqEditPower.voice = true;
				eqEditPower.remark = true;
				eqEditPower.isEdit = true;
			}
			
			if(eqEditPower.eqName && eqEditPower.sim && eqEditPower.gprs && eqEditPower.number && eqEditPower.voice && eqEditPower.remark)  {
				break;
			}
		}
	}
	eqEditPower.isInited = true;
}


function getVechiletrack(event,carid){
	stopBubble(event);
	window.open($("#serverUrl").val()+"gpsonline/jsp/TrackMap.jsp?mapType="+mapType+"&carid="+carid);
}

	 
	 
function getback(event,id){
	
	stopBubble(event);
	//var b = new Base64();
	window.open($("#serverUrl").val()+"gpsonline/jsp/monitor/playBack.jsp?mapType="+mapType+"&carid="+id+"&carname="+encodeURI(encodeURI(equipmentObject[id].vehicleName))+"&icon="+equipmentObject[id].icon);
}

//修改当前选中的菜单信息
function updateCurMenu(data){
	if(data.totalcount==1){
		
		if(!expelement){
			return;
		}
		
		var curEmp=data.data[0];
		
		var id=expelement.attr("id");
		
		var equipmentId = id.split("_")[1];
		
		var groupId = id.split("_")[0];
		
		if(data.data[0].positionLast != null){
		
			 equipmentObject[equipmentId].speed=data.data[0].positionLast.speed;
			 equipmentObject[equipmentId].gpstime=data.data[0].positionLast.recvtime;
			 equipmentObject[equipmentId].online=data.data[0].positionLast.online;
	         
	         if(data.data[0].positionLast.lat==0 || data.data[0].positionLast.lng==0){        	
	         	equipmentObject[equipmentId].isPosition=false;
	         }else{        	
	         	equipmentObject[equipmentId].isPosition=true;       
	         }  	
		}
		
        var curEquipmentDiv=$("#"+id);
        var curEquipmentStatus=$("#lineStatus_"+id);
        var curEquip=equipmentObject[equipmentId];
        
        var curGroupTotalDiv = $("#"+id.split("_")[0]).find('span'),
        	curGroupTotal = parseInt(curGroupTotalDiv.text());
        	
        var unlinecountPan = $("#unlinecount"),
        	unlineTotal = parseInt(unlinecountPan.text()),
        	onlinecountPan = $("#onlinecount"),
        	onlineTotal = parseInt(onlinecountPan.text()),
        	groupCountPanel = $("#" + groupId ).find("span"),
        	grouptotalStr = groupCountPanel.text().split("/"),
 			groupallTotal = parseInt(grouptotalStr[1]),
 			grouponlineTotal = parseInt(grouptotalStr[0]);
       
    		if( equipmentObject[equipmentId].online == 1){
 
 				 if(curEquipmentDiv.attr("status") != "1"){//原始状态
 				 
     				onlinecountPan.text(onlineTotal + 1);
     				if(lineStatus == -1) groupCountPanel.text( (++grouponlineTotal) + "/" + groupallTotal);		
				 }
       					
   			}else{
   			
   				 if(curEquipmentDiv.attr("status")!="0"){
   				     unlinecountPan.text(unlineTotal + 1);  
   				     if(lineStatus == -1) groupCountPanel.text( (--grouponlineTotal) + "/" + groupallTotal);	  					
				 }
   				
   			}
   			
		if(!curEquip.isPosition){
	        	
	        	
	        	if(curEquip.online==1){
	        		
	        		if(curEquipmentStatus.text()!="静止"){	       	   		
			        	curEquipmentStatus.text("静止");
		        	}
	        		
			        if(curEquipmentDiv.attr("status")!="1"){
			        			        
			        	curEquipmentDiv.attr("status","1");
			        	$("#lineStatusImg_"+id).attr("src","gpsonline/image/monitor/o_offline.gif");
			        	curEquipmentStatus.parent().removeClass().addClass("speed_0");		
			        		        	
			        }		        
		        }else{
		        	
		        	if(curEquipmentStatus.text()!="未定位"){	       	   		
			        	curEquipmentStatus.text("未定位");
		        	}
		        	
		        	     	
		        	if(curEquipmentDiv.attr("status")!="0"){		        	
			        	curEquipmentDiv.attr("status","0");
			        	curEquipmentStatus.parent().removeClass().addClass("unline");
			        	$("#lineStatusImg_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");			        	
			        }
		        }       	
	        		 
		}else{
			if(curEquip.online==1){
				
		        	var speed=curEquip.speed;
		        	if(speed==0){
		        		if(curEquipmentStatus.text()!="静止"){
			        		curEquipmentStatus.text("静止");
			        		curEquipmentStatus.parent().removeClass().addClass("speed_0");
			            }
			        }else{
			        	if(curEquipmentStatus.text()!=speed+" km/h"){
				        	curEquipmentStatus.text(speed+" km/h");
				        	curEquipmentStatus.parent().removeClass().addClass("speed_n");
			        	}
			        }
			        if(curEquipmentDiv.attr("status")!="1"){
			        	curEquipmentDiv.attr("status","1");
			        	$("#lineStatusImg_"+id).attr("src","gpsonline/image/monitor/o_offline.gif");
			        }		        
		            if($('#elSelected').attr('value')==id){//判断某个设备是否已经选中			          
		        		curEquipmentStatus.parent().removeClass().addClass("onlineclick");
		        		curEquipmentDiv.addClass("onlineselectedstyle");
				    }
		        }else{
		        	    	
		        	var date=unlineTimeT2(curEquip.gpstime);
		        	
		        	if(date!=-1&&date>0){
		        		if(date>=60){
		        			if(curEquipmentStatus.text()!="离线>60天"){
		        				curEquipmentStatus.text("离线>60天");
		        			}
		        		}else{
		        			if(curEquipmentStatus.text()!="离线"+date+"天"){
		        				curEquipmentStatus.text("离线"+date+"天");
		        			}
		        		}
		        	}else{
		        		var hour=unlineTimeT3(curEquip.gpstime);
		        		if(hour!=-1&&hour>0){
		        			if(curEquipmentStatus.text()!="离线"+hour+"小时"){
			        			curEquipmentStatus.text("离线"+hour+"小时");
			        		}
		        		}else{
			        		if(curEquipmentStatus.text()!="离线"){
			        			curEquipmentStatus.text("离线");
			        		}
		        		}
		        	}
		        	if(curEquipmentDiv.attr("status")!="0"){
			        	curEquipmentDiv.attr("status","0");
			        	curEquipmentStatus.parent().removeClass().addClass("unline");
			        	$("#lineStatusImg_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");
			        }
		        	if($('#elSelected').attr('value')==id){//判断某个设备是否已经选中									          	  
			           curEquipmentStatus.parent().removeClass().addClass("unlineclick");
			           curEquipmentDiv.addClass("unlineselectedstyle");
		            }	
		        }
		}
	}
}

function cancleMenu(){
    if(expelement!=null&&menuelement!=null){
        $('#elSelected').attr('value',''); 	
        menuelement.remove();//删除菜单选项

	    //var height=expelement.height();
	    //expelement.css({width: height-20});//恢复高度
	    expelement.removeClass();//恢复样式
	    var id=$(expelement).attr('id').split('_')[1];
	    if(!equipmentObject[id].isPosition){
        	expelement.find('span').parent().removeClass().addClass('unline');
        }else{
        	 if(equipmentObject[id].online==1){
	            if(equipmentObject[id].speed==0){
	               expelement.find('span').parent().removeClass().addClass('speed_0');
	            }else{
	               expelement.find('span').parent().removeClass().addClass('speed_n');
	            }
	         }else{	
	            expelement.find('span').parent().removeClass().addClass('unline');    
	         }
        }	    
    }
}


function stopBubble(e){  
        // 如果传入了事件对象，那么就是非ie浏览器  
        if(e&&e.stopPropagation){  
            //因此它支持W3C的stopPropagation()方法  
            e.stopPropagation();
        }else{  
            //否则我们使用ie的方法来取消事件冒泡  
            window.event.cancelBubble = true;  
        }  
}  


	
//弹出菜单开始
function showSecondMenu(element,event){
   //event.stopPropagation();
   stopBubble(event)
   $("#downMenus").show();
   $("#secondMenus").show();
   // 取得元素的左下角坐标
   var offset = $(element).offset();
   var left_x = offset.left;
   var down_y = offset.top+$(element).height();
   //var mw=$(window).width();
   var mh=$(window).height();
   
   //var w=$("#secondMenus").width();
   var h=$("#secondMenus").height();
   if(mh<h+down_y){//超 高
   	 down_y=down_y-h+15;
   }
   //if(mw<w+left_x){
   //	 left_x=mw-w;
   //}//超 宽
   

   //更改二级菜单样式并显示
   $("#secondMenus").css({"left":left_x,"top":down_y-33,"width":100});
   //获取二级菜单的所有选项
   $("#secondMenus li").each(function(){
	   $(this).attr('name','secondMenu_id_'+($(element).attr('id').split('_'))[1]);
   });
   //$("#downMenus").show();
   //$("#secondMenus").show();
  if(!isHasPBackAut()) $("#down_back_item").hide();
      
}
$(function() {
	 $("#secondMenus").hide();
	 $("#thridMenus").hide();

	 $("#downMenus").bind({
		mouseleave:function(){
		   $("#secondMenus").hide();
		   $("#thridMenus").hide();
	   }
	 });
	 $("#thridMenus").bind({
		mouseleave:function(){
		   $("#thridMenus").hide();
	   }
	 });

	 // 鼠标点击二级菜单效果
	 $("#secondMenus li").bind({
		  mouseenter:function(){
			   $("#thridMenus").hide();
			   var type = $(this).attr("id");
			   if(type == "order" || type == "fortification"){	
				   
				   //加载三级菜单(***)
				   loadthridMenus(($(this).attr('name').split('_'))[2], type);
				   //显示三级菜单
				   if($("#thridMenus").find('ul li').length!=0){
				   	  $("#thridMenus").attr("style","z-index: 99999; display: none;");
				   	  $("#thridMenus").show();
				   	  
				   }else{
				   	  return;
				   }
				   
				   
				   // 取得元素的右上角坐标
				   var offset = $(this).offset();
				   var right_x = offset.left+$(this).width()+21;
				   var top_y = offset.top;
				  
				   var h=$("#thridMenus").height();
				   
   				   var mh=$(window).height();
   					
   					
   					
   				   if(mh<h+top_y){ //超 高
   				   	   if(top_y-h<=0){
				   	   		$("#thridMenus").css('height',top_y+15);//三级菜单置顶高度
				   	   		$("#thridMenusup").show();//显示向上按钮
				   	   		$("#thridMenusdown").show();//显示向下按钮				   	   		
				   	   		$("#thridMenus ul").css('height',$("#thridMenus").height()-(2*$("#thridMenusup").height()));//ul指定高度
				   	   		$("#thridMenus ul").css('overflow','hidden');//隐藏ul超指定顶高度的部分
				   	   		
				   	   		//$("#thridMenus ul").css('height',top_y-2);
				     		//$("#thridMenus").css('overflow','auto');
				     		//$("#thridMenus").append("<a align='center' href='javascript:showbutton();'>V</a>");
				     		top_y=10;
				     		jQuery("#thridMenus").mousewheel(function(e, delta) {
								if(delta>0){
									thridMenusup();
								}else{
									thridMenusdown();
								}
							});
				   	   }else{
				   	   		top_y=top_y-h+30;
				   	   }
				   	   
				   }
				   
				   // 设置三级菜单左上角坐标
				   $("#thridMenus").css({"left":right_x-20,"top":top_y});
					
			   }
			   $(this).addClass("lihover");
		  },
		  mouseleave:function(){
			$(this).removeClass("lihover");
		  }
	});
	$("#thridMenusup").click(function(){thridMenusup()});
	$("#thridMenusdown").click(function(){thridMenusdown()});

});
function thridMenusdown(){
	var last=$("#thridMenus ul li:last").clone();
	last.attr("class",'');
	last.prependTo($("#thridMenus ul")).slideDown('fast');	
	$("#thridMenus ul li:last").remove();
}
function thridMenusup(){
	var first=$("#thridMenus ul li:first").clone();
	$("#thridMenus ul li:first").remove();
	first.attr("class",'');
	first.appendTo($("#thridMenus ul")).slideDown('fast');	
	
}

function loadthridMenus(id, type){
   $("#thridMenus").find('ul').empty();
    $("#thridMenusup").hide();
 	$("#thridMenusdown").hide();
    $("#thridMenus").find('ul').append(getThirdMenuContent(id, type));
    $("#thridMenus ul").css('height','');//ul还原高度
	$("#thridMenus ul").css('overflow','');//ul还原显示方式
   jQuery("#thridMenus").unbind();
}

function getThirdMenuContent(id,type){
	
	var content = "";
	if(type == "order"){
		content = getThirdMenuContentOfCmd(id);
	}else{
		content = getThirdMenuContentOfFortification(id);
	}
	
	return content;
}

function getThirdMenuContentOfCmd(id){
   var mobileId = equipmentObject[id].mobileId;
   var gprsCode = equipmentObject[id].gprsCode;
   var name = equipmentObject[id].vehicleName;
   
   var content = [];
   for(var i=0;i<comds.data.length;i++){
       if(mobileId==comds.data[i].mobileId){
            content.push("<li  onmouseover='thirdMenumouseenter(this)'  onmouseout='thirdMenumouseleave(this)' onclick='sendComdWin(this)' name='mtId="+comds.data[i].mobileId+",comdId="+comds.data[i].mask+",vidId="+gprsCode+",name="+name+",mask="+comds.data[i].mask+",eqId="+id+"'>"+comds.data[i].meaning+"</li>");
       }
   }
   return content.join("");
}

function getThirdMenuContentOfFortification(id){//获取原地设防菜单内容
   
   var content = [];
   
   content.push("<li style=\"min-width:100px;\" onmouseover='thirdMenumouseenter(this)'  onmouseout='thirdMenumouseleave(this)' onclick='SheFang.openSheFangWin(" + id + ")'>设防</li>");
   content.push("<li style=\"min-width:100px;\" onmouseover='thirdMenumouseenter(this)'  onmouseout='thirdMenumouseleave(this)' onclick='SheFang.cancleSheFang(" + id + ")'>撤销</li>"); 
   return content.join("");
}

function thirdMenumouseenter(element){
   $(element).addClass("lihover");
}
function thirdMenumouseleave(element){
  $(element).removeClass("lihover");
}

function closeAccordion(){
	$('#leftList').find("dt").each(function(){//迭代每一个组
	     if($(this).attr("status")=="open"){
	        $(this).click();
	     }
	});
}
/*
 *树形 
 */
(function($) {
	$.fn.accordion = function(options) {
		
		var settings = $.extend({}, {open: false}, options);
		
        this.each(function() {
			var dts = $(this).children('dt');
			dts.click(onClick);
			dts.each(reset);
			if(settings.open) 
			   $(this).children('dt:first-child').next().show();
		});
		
		function onClick() {
			//$(this).siblings('dt').each(hide);//其余的折叠
			if($(this).next().is(":hidden")){
			  //判断是否隐藏改变组样式
			  $(this).find("img").attr("src","gpsonline/image/monitor/g_o.gif");
			  $(this).attr("status","open");
			  $(this).next().show();		
			}else{
			  $(this).find("img").attr("src","gpsonline/image/monitor/g_c.gif");
			  $(this).attr("status","close");
			  $(this).next().hide();
			  cancleMenu();
			}
			return false;
		}
		
		function hide() {
			$(this).next().hide();
		}
		
		function reset() {
			$(this).next().hide();
		}
	}
})(jQuery);

//定位树形节点到醒目的位置
function treeNodePosition(id){
	var container = $('#leftList'),
		scrollTo = $("#" + id);	 
	container.scrollTop( scrollTo.offset().top - container.offset().top-20 + container.scrollTop());
}

//打开该设备的统计报表页面
var curVehicleOfReport = null;//选中要显示报表的设备Id
function openReport(element){
	var id=$(element).attr('name').split('_')[2];
	curVehicleOfReport = id;
	$("#menu_report").click();
}

//违章下载

function trafficViolation(element){
	var id=$(element).attr('name').split('_')[2];
 	openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/monitor/trafficViolation.jsp?vid=" + id);
}

//车主信息
function showCarOwiner(element){
	var carwinid = $(element).attr('name').split('_')[2];
	openCarOwnerInfo(carwinid);
}
//查询sim卡
function  openSim(sim){
	openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/sim_search.jsp?simCode="+sim);
}

// 车辆基本信息
function showCarBaseinfo(element){
	var carwinid = $(element).attr('name').split('_')[2];
	var obj = JSON.stringify(equipmentObject[carwinid]);
	openPopuWin($("#serverUrl").val() +"/gpsonline/jsp/monitor/vhcBaseInfo.jsp?obj="+encodeURI(obj));
}
//车辆基本信息
function tempsetting(element){
	var carwinid = $(element).attr('name').split('_')[2];
	var obj = JSON.stringify(equipmentObject[carwinid]);
	openPopuWin($("#serverUrl").val() +"/gpsonline/jsp/monitor/vhcBaseInfo.jsp?obj="+encodeURI(obj));
}
//TTS 发送命令
function ttsCmd(terCode){
	openPopuWin($("#serverUrl").val() +"/gpsonline/jsp/monitor/ttscmd.jsp?terCode="+terCode);
}
//视频界面
function videoShow(terCode){
	terCode = 86201450343;
	openPopuWin($("#serverUrl").val() +"/gpsonline/jsp/monitor/video.jsp?terCode="+terCode);
}
//轨迹下载开始
function loadtrack(element){
   var id=$(element).attr('name').split('_')[2];
   $('#trackVId').empty();
   //轨迹回放车辆添加列表  
   var carts="<option value='-1'> --选择--</option>";
   var cartIdsArr =cartIds.split(","),cutObject = null;
   for(var i=0;i<cartIdsArr.length;i++){
   	  cutObject = equipmentObject[cartIdsArr[i]];
      if(cutObject.id==id){
      	carts=carts+"<option selected='selected' value='"+cutObject.id+"'>"+cutObject.vehicleName+"</option>";
      }else{
       	carts=carts+"<option value='"+cutObject.id+"'>"+cutObject.vehicleName+"</option>";
      }
   }
   $('#trackVId_0').append(carts);
   $('#trackVId_1').append(carts);
   $("#closecmdWin").click();
   $("#closeGroupWin").click();
   $("#closecmarkerWin").click();
   $("#closeSelectMarkerPhotoWin").click();
   $("#trackContentWin").fadeIn("fast");
   $("#trackContentWin").center();
   
  var d = new Date();
  var vYear = d.getFullYear();
  var vMon = d.getMonth() + 1;
  var vDay = d.getDate();
  var start=vYear + "-" + (vMon < 10 ? "0" + vMon : vMon) + "-" + (vDay < 10 ? "0" + vDay : vDay) + " 00:00:00";
  var end=vYear + "-" + (vMon < 10 ? "0" + vMon : vMon) + "-" + (vDay < 10 ? "0" + vDay : vDay) + " 23:59:59";
  $("#kml_start").val(start);
  $("#kml_end").val(end);
  $("#excel_start").val(start);
  $("#excel_end").val(end);
   
   $("#secondMenus").hide();
   $("#thridMenus").hide();
}

function closeTrackWin(){
	$("#trackContentWin").fadeOut("fast");
}
function closeTrackWin_obd(){
	$("#trackContentWin_obd").fadeOut("fast");
}
function closeTrackWin_addmarker(){
	$("#trackContentWin_addmarker").fadeOut("fast");
}
function showaddmarker(){
	
	$("#addmarker_nonull").show();
	//$("#addmarker_null").hide();
	$("#addmarkerinfo").html("");
	$("#trackContentWin_addmarker").fadeIn("fast");
	$("#trackContentWin_addmarker").center();
	
	$(window.parent.document).contents().find("#iframe_map")[0].contentWindow.chushihua();
	
	
}
$(function(){
$("#movetrackWin").mousedown(function(dom){
			     var top1=$("#trackContentWin").css("top");
				 var left1=$("#trackContentWin").css("left");
				 var x=dom.clientX;
				 var y=dom.clientY;
				 var x1=Math.abs(x-parseInt(left1));
				 var y1=Math.abs(y-parseInt(top1));
				 $("body").mousemove(function(dom){
				 	  var x=dom.clientX;
				      var y=dom.clientY;  
				      $("#trackContentWin").css({"top":y-y1,"left":x-x1}) 
				 	});
			}).mouseup(function(){
			    $("body").unbind("mousemove"); 	
			});

});
//轨迹下载结束

$(function(){
	$(window).resize(function() {
	    $("#trackContentWin").center();
	    $("#cmdContentWin").center();
	    $('#content').center();
	    $(".list_main").height($(window).height()-($(".main_top").height()+$(".idx_top").height())-20);
	    $("#markerContentWin").center();
	    $("#selectMarkerPhotoWin").center();
	    $("#addGroupContentWin").center();
	    $("#updatePasswordContentWin").center();
	    $("#updatePasswordContentWin").center();
	    $("#setSystemContentWin").center();
	    
	    $("#mask").css({"height":$(document).height(),"width":$(document).width()});
	    
	    $("#electronicFence_ContentWin").center();	
	    
	    $("#electronicFence_vehicle_binding_ContentWin").center();
	    
	    $("#marker_vehicle_binding_ContentWin").center();
	    
	    $("#popuWin").center();
	    
	    $("#managerWin").center();
	    
	});
});

//命令控制
var comds=null;
//获取所有命令
function getAllComds() {
         $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/vehiclecmdAction_cmdbyUserId.action",//json/vehiclecmdAction_cmdbyUserId.action
	        success: function(json){
		         if(json.flag==true){
			          comds=json;
		         }
	        },
	        error:function(){
	             //alert('请稍后重试...!');
	        }
	   });
}
var PZCmdPrevSendVHc = null;

//命令弹出框开始
function sendCmd(){
	var flag=true;
	$.each(cmdcheckNumflag, function (k, v) {
		if(!v){
			flag=false;
			return false;
		}
	});
	if(!flag){
		return;
	}
   $("#secondMenus").hide();
   $("#thridMenus").hide();
   var gprsCode=$('#vid').val();
   var mtid=$('#mtid').val();
   var cmdid=$('#cmdid').val();
  
   if(!checkCusotmForm(mtid, cmdid)) return;
   /*if(cmdid=='7000'){
	   var dur = $("#cmd_0").val();
	   if(dur<20 || dur>60){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("回报间隔超出范围，范围20-60");
		   return;
	   }
   }
//   console.info();
   if(cmdid=='7004' && mtid!=0){
	   var durday = $("#cmd_1").val();
	   if(durday<0 || durday>15){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("休眠天数超出范围，范围0-15");
		   return;
	   }
	   var duronline = $("#cmd_3").val();
	   if(duronline<3 || duronline>240){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("上线时长超出范围，范围3-240");
		   return;
	   }
   }
   if(cmdid=='7023'){
	   var zwCode = $("#cmd_1").val();
	   var tdCode = $("#cmd_2").val();
	   if(zwCode==''){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("组网号不能为空");
		   return;
	   }else if(zwCode<1){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("组网号大于0");
		   return;
	   }
	   if(tdCode==''){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("通道号不能为空");
		   return;
	   }else if(tdCode<0 || tdCode>20){
		   $("#cmd_msg").css("color","red");
		   $("#cmd_msg").text("通道号超出范围，范围0-20");
		   return;
	   }
   }*/
   var data="vid="+gprsCode+"&mtid="+mtid+"&cmdid="+cmdid;  
   $('#cpcontent').find('[name=cp]').each(function(){
   		data+="&cp="+$(this).val().replace(/\+/g,"%2B");
   });
//   console.info("mtid:" + mtid + ",cmdid" + cmdid);
//   console.info("data:" + data);
   
   if(mtid == 248 && cmdid == 7018){
	   data+="&cp="+$("select[name='cp']").find("option:selected").text();
   }
   $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/cmdAction_send.action",
	        data: data,
	        success: function(json){
		         if (json.flag) {
			         $("#closecmdWin").click();
			         
			         $('#cmdsgpanel tr').eq(0).after("<tr class='alarmrow" + ( getCmdTableSize() % 2) + "'><td width='100px' style='text-align: left;padding-left:30px;'>"+$("#equipmentName").text()+"</td><td width='200px' style='text-align: center;'>"+getNowFormatDate()+"</td><td tyle='text-align: left;'>发送了"+$.trim($("#cmdName").text())+"命令</td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='openCarOwnerInfo(" + curSendCmdEq.eqId + ");'>" + language.chezhuxiangqing + "</a></td></tr>");	     //<td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='removemsg(this);'>未处理</a></td>     
		         	 
		         	 if(cmdid == 7020 || cmdid == 7024 || cmdid == 7029 || cmdid == 7013){		        
		         	 	 try {
					        if (typeof(eval("setAlarmDispose")) == "function"){
					           setAlarmDispose(curSendCmdEq.eqId, cmdid);
					        }
					     } catch(e) {}
		         	 }
		         	 
		         	 if(cmdid == 7024){
		         	 	PZCmdPrevSendVHc = curSendCmdEq;
		         	 }
		         	 
		         }else{
			          $("#cmd_msg").css("color","red");
			          $("#cmd_msg").text(json.msg);	         	
		         }
	        },
	        error: function() {	             
	             //alert('请稍后重试...!');
	        }
	   });
}

function checkCusotmForm(mtid, cmdid){
	
	if( mtid == 185 && cmdid == 7022 ){//校验特殊输入
         	
         	var TimeTrackInput = $("#cmd_0");
         		TimeTrackVal = TimeTrackInput.val();
         		TimeTrackInputMsg = TimeTrackInput.next();
         	
         	if(TimeTrackVal.length > 0  && TimeTrackVal >= 300 && TimeTrackVal <= 1800){
         	
         		 TimeTrackInputMsg.css("color","rgb(153, 153, 153)");
         		 TimeTrackInputMsg.html("*只能输入整数!");
         	}else{
         	
         		 TimeTrackInputMsg.css("color","red");
         		 TimeTrackInputMsg.html("*300～1800!");
             	 return false;            	 
         	}
         	
         	var IntervalInput = $("#cmd_1");
         		IntervalVal = IntervalInput.val();
         		IntervalInputMsg = IntervalInput.next();
         	
         	if(IntervalVal.length > 0  && IntervalVal >= 30 && IntervalVal <= 900){
         	
         		 IntervalInputMsg.css("color","rgb(153, 153, 153)");
         		 IntervalInputMsg.html("*只能输入整数!");
         	}else{
         	
         		 IntervalInputMsg.css("color","red");
         		 IntervalInputMsg.html("*30～900!");
             	 return false;               	 
         	}
         
         return true;
     }
     
     return true;

}

var curSendCmdEq = {};

function sendComdWin(element){
   //mtId=74,comdId=7000,vidId=0868120103026701,name=gt06,mask=7000
   $("#closeGroupWin").click();
   $("#closecmarkerWin").click();
   $("#closeSelectMarkerPhotoWin").click();  
   $("#closecmdWin").click();
   $("#closePopuWin").click();
   $("#trackContentWin").hide();
   $("#secondMenus").hide();
   $("#thridMenus").hide();
   
   var ids=$(element).attr('name').split(',');
   
   
   var gprsCode=ids[2].split('=')[1];
   var mtid=ids[0].split('=')[1];
   var cmdid=ids[1].split('=')[1];
   var name=ids[3].split('=')[1];
   var mask=parseInt(ids[4].split('=')[1]);
   var eqId = parseInt(ids[5].split('=')[1]);
   
   curSendCmdEq.gprsCode = gprsCode;
   curSendCmdEq.mtid = mtid;
   curSendCmdEq.cmdid = cmdid;
   curSendCmdEq.mask = mask;
   curSendCmdEq.name = name;
   curSendCmdEq.simCode = equipmentObject[eqId].simCode;
   curSendCmdEq.eqId = eqId;
   
//   console.info(mtid + "----" + cmdid); 
    if((mtid == 252 && cmdid == 7018) || (mtid == 243 && cmdid == 7536)){
//    	console.info("----->" + $("#serverUrl").val());
    	openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/cmd/sdms.jsp?name="+encodeURI(encodeURI(name))+"&gprsCode="+gprsCode+"&mask="+mask+"&mtid="+mtid+"&cmdid="+cmdid);
   		return;
    }
   
   if(mtid == 185 && cmdid == 7000 ){
   		openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/cmd/TerminalReport.jsp");
   		return;
   }
   
   if(mtid == 174 && cmdid == 7524 ){
   		//for(var i = 0; i < 2; i++){//解决第一次加载timespinner不能渲染问题
   			openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/cmd/ShangBaoCmd.jsp");
   		//}
   		return;
   }
   if(mtid == 191 && cmdid == 7011 ){

   		openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/cmd/DianZiSuoCmd.jsp");
   		
   		return;
   }
   
   $('#vid').val(gprsCode);
   $('#mtid').val(mtid);
   $('#cmdid').val(cmdid);
   $('#description').text($(element).text());
   $('#cmdName').text($(element).text());
   $('#equipmentName').text($.trim(name));
   
   
   var cps = new Array();
   for(var i=0;i<comds.data.length;i++){
      if(comds.data[i].mobileId==mtid&&mask==comds.data[i].mask){
   		 cps=comds.data[i].cp;
         $('#equipmentdesc').text(comds.data[i].description);
         break;
      }
   }
   
   $("#cpcontent").empty();
   for(var i=0;i<cps.length;i++){
	  switch(cps[i].type){
	      case "int":
	             var cpNumber=$("<input id='cmd_"+i+"' name='cp' value='"+cps[i].value+"'/>");
	             var text=$("<span>"+cps[i].text+":</span>");
	             var msg=$("<span style='color:rgb(153, 153, 153);'>*只能输入整数!</span><br/>");
	             text.appendTo("#cpcontent");
	             cpNumber.appendTo("#cpcontent");
	             msg.appendTo("#cpcontent");

             	 checkcpNumber(cpNumber);
	      break;
	      case "flaot":
	             var cpNumber=$("<input id='cmd_"+i+"' name='cp' value='"+cps[i].value+"'/>");
	             var text=$("<span>"+cps[i].text+":</span>");
	             var msg=$("<span style='color:rgb(153, 153, 153);'>*只能输入数字!</span><br/>");
	             text.appendTo("#cpcontent");
	             cpNumber.appendTo("#cpcontent");
	             msg.appendTo("#cpcontent");
	             checkcpFloatNumber(cpNumber);
	      break;
	      case "password":
	      		 $("#cpcontent").append("<span>"+cps[i].text+":</span><input type='password' name='cp' value='"+cps[i].value+"'/><br/>");
	      break;
	      case "select":
	             var options=new Array();
	             var optionStr="";
	             var selectStr="<span>"+cps[i].text+":</span><select name='cp'>";
	             if(cps[i].value!=""&&cps[i].value!=null){
	             	options=cps[i].value.split(",");
	             }
	             for(var j=0;j<options.length;j++){
	             	optionStr+="<option value='"+j+"'>"+options[j]+"</option>";
	             }
	             selectStr=selectStr+optionStr+"</select><br/>";
      			 $("#cpcontent").append(selectStr);
	      break;
	      case "time":
	      		 $("#cpcontent").append("<span>"+cps[i].text+":</span><input id=\"cp_time_" + i + "\" type=\"text\"  name=\"cp\" style=\"width:141px;height:17px;\"/><br/>");	
	      		 addCSS($("#serverUrl").val() + "/gpsonline/css/extends/easyui.css");
	      		 getScriptSync($("#serverUrl").val() + "/gpsonline/js/extends/jquery.easyui.min.js",function(){      		 	 	
	      		 	$("#cp_time_" + i).timespinner({
					    min: '00:00:00',
					    required: false,
					    showSeconds: true
					});   	    
	      		 });
	           	break;
	      default:$("#cpcontent").append("<span>"+cps[i].text+":</span><input name='cp' value='"+cps[i].value+"'/><br/>");	      
	      break;
	  }
   } 
   $("#cmdContentWin").fadeIn("fast");
   $("#cmdContentWin").center();

}
var cmdcheckNumflag={};
function checkcpNumber(element){
	var ex = /^\d+$/;
	$(element).keyup(function(){  //keyup事件处理 
		 var val = $(this).val();
         if(val=="" || !ex.test(val)){
             $(this).next().css("color","red");
             $(this).next().html("*只能输入整数!");
             var id=$(this).attr('id');
             cmdcheckNumflag[id]=false;
        
         }else{
         	$(this).next().css("color","rgb(153, 153, 153)");
         	$(this).next().html("*只能输入整数!");
         	var id=$(this).attr('id');
         	cmdcheckNumflag[id]=true;
         }
    }).bind("paste",function(){  //CTR+V事件处理 
    	  var val = $(this).val();
          if(val=="" || !ex.test(val)){
             $(this).next().css("color","red");
             $(this).next().html("*只能输入整数!");
             var id=$(this).attr('id');
             cmdcheckNumflag[id]=false;
         }else{
       		 $(this).next().css("color","rgb(153, 153, 153)");
       		 $(this).next().html("*只能输入整数!");
       		 var id=$(this).attr('id');
       		 cmdcheckNumflag[id]=true;
         }
    });
}
function checkcpFloatNumber(element){
	var ex = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/;
	$(element).keyup(function(){  //keyup事件处理 
         if(!$(this).val()==""&&!ex.test($(this).val())){
             $(this).next().css("color","red");
             var id=$(this).attr('id');
             cmdcheckNumflag[id]=false;
         }else{
         	$(this).next().css("color","rgb(153, 153, 153)");
         	var id=$(this).attr('id');
         	cmdcheckNumflag[id]=true;
         }
    }).bind("paste",function(){  //CTR+V事件处理 
          if(!$(this).val()==""&&!ex.test($(this).val())){
             $(this).next().css("color","red");
             var id=$(this).attr('id');
             cmdcheckNumflag[id]=false;
         }else{
       		 $(this).next().css("color","rgb(153, 153, 153)");
       		 var id=$(this).attr('id');
       		 cmdcheckNumflag[id]=true;
         }
    });
}

//拖动命令窗口
$(function(){

$("#closecmdWin").click(function(event){
	
	//event.stopPropagation();
	stopBubble(event);
   $("#cmdContentWin").fadeOut("fast");
   
    $("#cmd_msg").css("color","rgb(153, 153, 153)");
    $("#cmd_msg").text("");
   
});

$("#cancelCmd").click(function(event){
	//event.stopPropagation();
	stopBubble(event);
   $("#cmdContentWin").fadeOut("fast");

    $("#cmd_msg").css("color","rgb(153, 153, 153)");
    $("#cmd_msg").text("");
   
});

$("#movecmdWin").mousedown(function(dom){
			     var top1=$("#cmdContentWin").css("top");
				 var left1=$("#cmdContentWin").css("left");
				 var x=dom.clientX;
				 var y=dom.clientY;
				 var x1=Math.abs(x-parseInt(left1));
				 var y1=Math.abs(y-parseInt(top1));
				 $("body").mousemove(function(dom){
				 	  var x=dom.clientX;
				      var y=dom.clientY;  
				      $("#cmdContentWin").css({"top":y-y1,"left":x-x1}) 
				 	});
			}).mouseup(function(){
			    $("body").unbind("mousemove"); 	
			});

});
//命令弹出框结束
var isgetMsg = true;
//报警信息开始
var maxAlarmMsgTotal = 100;
function getwarmMsg() {
		 if(cartIds==null||cartIds==""){
		 	return;
		 }
		 
		 if(isgetMsg){
		 	 isgetMsg = false;
	         $.ajax({
		        type: "POST",
		        dataType: "json",
		        url: "json/vehicleAction_msg.action",
		        data: ((getCurUserAlarmTypeValue() + 1 ) ==0 ) ? {ids:"-1"} : {ids:"-1",alarmType:getCurUserAlarmTypeValue()} ,
		        success: function(json){
		        	 //json = {"alarmType":null,"begin_time":null,"data":[{"content":"车机命令发送失败","createtime":"2017-05-17 13:35:08","disposeContent":null,"disposeDate":null,"disposeResult":null,"disposeWay":null,"id":null,"isAlarm":0,"type":0,"vhcId":9359424}],"datatype":null,"end_time":null,"flag":true,"intermin":null,"key":null,"ltype":null,"msg":"","onlines":[],"st":null,"timeorder":null,"timestamp":null,"totalcount":1,"unonlines":[],"vhcid":null,"w":null}
		        	 isgetMsg = true;
			         if (json.flag==true){
			               alarm(json); //检查是否报警
				           updatewarmMsgTable(json);
			         }
		        },
		        error: function() {
		            isgetMsg = true;
		        }
		   });
	   }	   
}

var isgetDriverMov = true;
var alarmid = "0";
function getDriverMov(){
	 if(isgetDriverMov){
		 isgetDriverMov = false;
         $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/vehicleAction_driverMov.action",
	        data: ((getCurUserAlarmTypeValue() + 1 ) ==0 ) ? {ids:"-1",gids:alarmid} : {ids:"-1",alarmType:getCurUserAlarmTypeValue(),gids:alarmid} ,
	        success: function(json){
	        	isgetDriverMov = true;
		         if(json.flag == true){
		        	 jiexiDriverDate(json);
		         }
	        },
	        error:function(){
	            isgetMsg = true;
	        }
	   });
   }
}
var adsalarm = [];
function jiexiDriverDate(json){
	var html = "";
	if(json.id != 0)alarmid = json.id;
	for ( var i = 0; i < json.data.length;i++){
		adsalarm.push(json.data[i]);
		var adstr = $("#" + "ads_" + json.data[i].vhcCode);
		html = "<tr align='center' id = 'ads_" + json.data[i].vhcCode+"'><td scope='col' width='100px'>"+json.data[i].vhcCode +"</td>" +
				"<td scope='col' width='150px'>" + json.data[i].recvtime + "</td>" +
				"<td scope='col' width='70px'>" + json.data[i].duration + "</td>" +
				"<td>" + json.data[i].alarmdesc+ "</td>" +
				"<td scope='col' width='60px'> <a href='javascrapt:void(0);' onclick='lookForPicture("+json.data[i].image_urls+");' >查看图片</a></td>" +
				"<td scope='col' width='60px'> <a href='javascrapt:void(0);' onclick='lookForVedio("+json.data[i].video_urls+");'>查看视频</a></td></tr>";
		$("#warmDriverGpanel2").prepend(html);
	}
	warmtitle();//窗口提示信息闪动
}
function showAllImg(){
	$("#tuce_div_content").empty();
	for (var i = 0; i < adsalarm.length; i++){
		var cpat = " 时间："+adsalarm[i].recvtime+",&nbsp&nbsp车牌："+adsalarm[i].vhcCode+",&nbsp&nbsp报警类型："+adsalarm[i].alarmdesc;
		var html = "<div class='imgshowall'><a href='"+eval(adsalarm[i].image_urls)[0]+"' data-caption='"+cpat+"'>" +
				"<div class='imgrap_new'><img src='"+eval(adsalarm[i].image_urls)[0]+"'></div><div class='bgtext'>" +
				"<div class='textmsgwrap'><span '"+adsalarm[i].recvtime+"'>时间："+ adsalarm[i].recvtime+"</span> " +
				"<span title='"+adsalarm[i].vhcCode+"'>车牌号码："+adsalarm[i].vhcCode+"</span>" +
				"<span title='"+adsalarm[i].alarmdesc+"'>报警类型："+ adsalarm[i].alarmdesc +"</span>" +
				"</div></div></a><div class='videolink' title='查看视频' onclick='lookForVedio("+adsalarm[i].video_urls+")'></div></div>";
		$("#tuce_div_content").append(html);
	}
	baguetteBox.run('.baguetteBoxOne',{});
	$("#adspicshowall—well").show();
}
 function lookForPicture(date){
	 $("#adsshowType").html("图片");
	 $("#adspicshow").empty();
	 for ( var i = 0; i < 1; i++){
		var html = "<li><div class='srcwrap'><img src='"+date[i]+"'></div></li>";
		$("#adspicshow").append(html);
	}
	 $("#adspicshowall").show();
 }
 var ob1 = {
	        source: "",
	        type: "video",
	        streamtype: "file",
	        server: "",//Used for rtmp streams
	        duration: "52",
	        poster: "",
	        autostart:"true",
	        logo: "",
	        logoposition: "top left",
	        logoalpha: "30",
	        logowidth: "130",
	        logolink: "http://jaris.sourceforge.net",
	        hardwarescaling: "false",
	        darkcolor: "000000",
	        brightcolor: "4c4c4c",
	        controlcolor: "FFFFFF",
	        hovercolor: "67A8C1",
			controltype: 1 // 控制类型：0 - 老版本样式，播放控制在右边，1-新版本样式，播放控制在下边  
	    };
	var params = {
	        menu: "false",
	        scale: "noScale",
	        allowFullscreen: "true",
	        allowScriptAccess: "always",
	        bgcolor: "#000000",
	        quality: "high",
	        wmode: "opaque"
	    };
	var attributes = {
	        id:"JarisFLVPlayer"
	    };
function lookForVedio(date){
	$("#adsshowType").html("视频");
	 $("#adspicshow").empty();
	 for ( var i = 0; i < 1; i++){
		 var html = "<li><div class='srcwrap' id='id_"+i+"'></div></li>";
		 $("#adspicshow").append(html);
		 var html2 = "<p><a href='http://www.adobe.com/go/getflashplayer'><img src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player'/></a></p>";
		 $("#id_"+i).append(html2);
		 ob1.source = date[i];
		 swfobject.embedSWF("JarisFLVPlayer.swf","id_"+i,"100%","100%","10.0.0","expressInstall.swf",ob1,params,attributes);
	}
	 $("#adspicshowall").show();
 }

//获取公告
var isgetNotice = true;
function getNotice(){
	
	var userid = $("#userId").val();
	if(userid==null||userid==""){
		return;
	}
	$.ajax({
        type: "POST",
        dataType: "json",
        url: "json/vehicleAction_notice.action",
        data:{ids:userid},
        success:function(json){
	         if(json.flag==true && json.totalcount>0){
	        	 var html="";
	              for( var i = 0; i < json.totalcount; i++){
	            	  html ="<tr><td scope='col' width='100px' style='text-align:center;'>"+
	            	  json.data[i].userName+"</td><td scope='col' width='200px' style='text-align:center;'>"+
	            	  json.data[i].createtime+"</td><td scope='col' style='text-align:left;'>"+
	            	  json.data[i].content+"</td></tr>";
	            	  //$("#broadcastMsggpanel tr:gt(0):eq(0)").after(html);
	            	  $("#broadcastMsggpanel tr:first").after(html);
	              }
	        	// $("#broadcastMsggpanel").append(html);
	         }
        },
        error: function() {
            isgetMsg = true;
        }
   });
}	   

function getUnDispoesAlarmMsg() {
	 $.ajax({
		        type: "POST",
		        dataType: "json",
		        url: "json/alarmAction_query.action?dataSize=" + maxAlarmMsgTotal + "&alarmType=" + getCurUserAlarmTypeValue(),
		        success: function(json) {
			         if (json.flag) {
			                 alarm(json); //检查是否报警
				             updatewarmMsgTable(json);
			         }
		        }
	   });

}

function clearAllMsg(msgtablePane){
	$("#"+msgtablePane+" tr").eq(0).nextAll().remove();
}
//检查是否报警
function alarm(datas){
 	  if(datas.data.length>0){
	       var flag=false;
	       for(var i=0;i<datas.data.length;i++){
	           if(datas.data[i].type==1){
	              flag=true;
	              break;
	           }
    	   }
	       if(flagwarmvoice && flag){
		       $('#msg_main').find('object').remove();
		     var voice="<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'"+
							 "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0'"+
							 "width='1' height='1'>"+
							 "<param name='loop' value='true'>"+
							 "<param name='volume' value='10'>"+
							 "<param name='AutoStart' value='false' />"+
							 "<param name='Play' value='false'>"+
							 "<param name='movie' value='gpsonline/voice/warm/sound.swf' />"+
							"<param name='quality' value='high' />"+
							"<embed src='gpsonline/voice/warm/sound.swf' loop='true' volume='10' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='1' height='1'>"+
							"</embed>"+
						"</object>";
		      $('#msg_main').append(voice);
	      }
      warmtitle();//窗口提示信息闪动
   }
}
//停止报警
function stopWarnSound(){
	if($('#msg_main').find('object').length>0){
		$('#msg_main').find('object').remove();
	} 
}

var msgstatus;
//开始闪动报警信息窗口提示信息
function warmtitle(){
  if($('#warmtitle').length>0){
    clearInterval(msgstatus);
    msgstatus = setInterval(function(){$('#warmtitle').css('color','red');$('#warmtitle').toggle();},300);
  }
}

//取消闪动
function canclewarmtitle(){

   if($('#warmtitle').length>0){
		clearInterval(msgstatus);
		$('#warmtitle').css('color','');
   		$('#warmtitle').show();
   }
}

function updatewarmMsgTable(datas){
	  
	  var curObject = null;
	  var warmmsg = [], comdmsg = [];
	  var alarmTime = "";
	  
	  var oldAlarmMsgTableSize = getAlarmTableSize();
	  var oldCmdMsgTableSize = getCmdTableSize();
	  
      for(var i=0;i<datas.data.length;i++){
      
      	 curObject = equipmentObject[datas.data[i].vhcId];
      	 
         if(curObject){
		     if(datas.data[i].type==1){
		     	if(isAlarmExist(datas.data[i].vhcId)){//该设备是否存在报警信息
		     		updateVhcAlarm(datas.data[i]);
		     	}else{
		     		 warmmsg.push("<tr class='alarmrow" + ((warmmsg.length + oldAlarmMsgTableSize - 1) % 2) + "'><td width='100px' style='text-align: left;padding-left:30px;'>"+(curObject.vehicleName)+"</td><td width='150px' style='text-align: center;' id=\"vhc_alarm_time_panel_" + datas.data[i].vhcId + "\">"+(datas.data[i].createtime!=null&&datas.data[i].createtime!=""?(datas.data[i].createtime).replace("T"," "):"&nbsp;")+"</td><td tyle='text-align: left;' id=\"vhc_alarm_content_panel_" + datas.data[i].vhcId + "\">"+(datas.data[i].content!=null&&datas.data[i].content!=""?datas.data[i].content:"&nbsp;")+"</td><td width='50px' style='text-align: center;' id='vhc_alarm_count_panel_" + datas.data[i].vhcId + "'>1</td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='openCarOwnerInfo(" + curObject.id + ");'>" + language.chezhuxiangqing + "</a></td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href=\"javascript:disposeAlarm('" + datas.data[i].createtime + "','" + datas.data[i].vhcId + "');\" id=\"alarm_dispose_state_" + datas.data[i].vhcId + "\">未处理</a></td></tr>"); 
		     	}
		     	
		     	setvhcAlarm(datas.data[i].vhcId, datas.data[i].content, datas.data[i].createtime.replace("T"," "));
		     	
	         }else{
	         	if(datas.data[i].type==2){
	          		comdmsg.push("<tr class='alarmrow" + ((comdmsg.length + oldCmdMsgTableSize - 1) % 2) + "'><td width='100px' style='text-align: left;padding-left:30px;'>"+(curObject.vehicleName)+"</td><td width='200px' style='text-align: center;'>"+(datas.data[i].createtime!=null&&datas.data[i].createtime!=""?(datas.data[i].createtime).replace("T"," "):"&nbsp;")+"</td><td tyle='text-align: left;'>"+(datas.data[i].content!=null&&datas.data[i].content!=""?datas.data[i].content:"&nbsp;")+"</td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='openCarOwnerInfo(" + curObject.id + ");'>" + language.chezhuxiangqing + "</a></td></tr>");	  //<td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='removemsg(this);'>未处理</a></td>        
	         	}else if(datas.data[i].type==0){
	         		comdmsg.push("<tr class='alarmrow" + ((comdmsg.length + oldCmdMsgTableSize - 1) % 2) + "'><td width='100px' style='text-align: left;padding-left:30px;'>"+(curObject.vehicleName)+"</td><td width='200px' style='text-align: center;'>"+(datas.data[i].createtime!=null&&datas.data[i].createtime!=""?(datas.data[i].createtime).replace("T"," "):"&nbsp;")+"</td><td tyle='text-align: left;'>"+(datas.data[i].content!=null&&datas.data[i].content!=""?datas.data[i].content:"&nbsp;")+"</td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='openCarOwnerInfo(" + curObject.id + ");'>" + language.chezhuxiangqing + "</a></td></tr>");
	         	}else{
	         		if(PZCmdPrevSendVHc != null && PZCmdPrevSendVHc.eqId == curObject.id) {
	         			VhcImg.openWin(curObject.id);
	         			PZCmdPrevSendVHc = {};
         			}
	         		comdmsg.push("<tr class='alarmrow" + ((comdmsg.length + oldCmdMsgTableSize - 1) % 2) + "'><td width='100px' style='text-align: left;padding-left:30px;'>"+(curObject.vehicleName)+"</td><td width='200px' style='text-align: center;'>"+(datas.data[i].createtime!=null&&datas.data[i].createtime!=""?(datas.data[i].createtime).replace("T"," "):"&nbsp;")+"</td><td tyle='text-align: left;'>拍照成功,立即<a style='cursor:pointer;color:#069;' href='javascript:VhcImg.openWin(" + curObject.id + ");'>查看</a>照片</td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='openCarOwnerInfo(" + curObject.id + ");'>" + language.chezhuxiangqing + "</a></td></tr>");
	         	}
	         }
          }
     }
     
     if(warmmsg.length != 0){
     	//clearAlarmMsg(warmmsg.length);
     	$('#warmmsgpanel tr').eq(0).after(warmmsg.join(""));     
     }
     if(comdmsg.length != 0){
     	$('#cmdsgpanel tr').eq(0).after(comdmsg.join(""));	 
     }
}

function formatAlarmTime(alarmTime){
	return alarmTime.replace(" ","_").replace(/\:/g,"_");
}

var vhcAlarm = [];//存放报警信息标识，用于过滤重复报警信息
//var vhcAlarmRepeatIntervalTime = 10;//单位 分钟
function isRepeatAlarm(data){//是否重复
	
	var flag = false,
		prevAlarm = vhcAlarm[data.vhcId];
	
	if(prevAlarm && getAlarmType(data.content) == prevAlarm.type /*&& dateConvertLong(data.createtime) - dateConvertLong(prevAlarm.time)  < vhcAlarmRepeatIntervalTime * 60 * 1000*/ ){
		flag = true;
	}
	
	return flag;
}

function isAlarmExist(vhcId){
	var prevAlarm = vhcAlarm[vhcId];
	return prevAlarm ? true : false;
}

function setvhcAlarm(vid, content, time){
	var prevAlarm = vhcAlarm[vid];
	var type = getAlarmType(content);
	if(prevAlarm){
		prevAlarm.type = type;
	}else{
		vhcAlarm[vid] = {type : type, dospose : 0 };
	}
}

function updateVhcAlarm(data){
	
	var prevAlarm = vhcAlarm[data.vhcId];
	    
	$("#vhc_alarm_time_panel_" + data.vhcId).html(data.createtime.replace("T"," "));
	$("#vhc_alarm_content_panel_" + data.vhcId).html(data.content);
	
	var countPanel = $("#vhc_alarm_count_panel_" + data.vhcId);
	if(isRepeatAlarm(data) && prevAlarm.dospose != 1){//dospose 0未处理、1已处理
		 var count = parseInt(countPanel.html());  
		 countPanel.html(++count); 			
	}else{
		  
		 if(isRepeatAlarm(data) && prevAlarm.dospose == 1){
		 	setAlarmDispose(data.vhcId, prevAlarm.dosposeType);
		 	return;
		 }
		 
		 countPanel.html("1");
		 var disposePanel =$("#alarm_dispose_state_" + data.vhcId); 
		 disposePanel.css("color","#069");	
		 disposePanel.attr("href","javascript:disposeAlarm('" + data.createtime + "','" + data.vhcId + "');");	
		 
		 prevAlarm.dospose = 0; 
	}
	
}

 var ALARM_OVERSPEED = 1,    //超速报警
	 ALARM_LOWSPEED	= 2, 		//低速报警
	 ALARM_SOS = 4,           //防劫报警
 	 ALARM_POWEROFF = 8,      //断电报警/电瓶拆除
	 ALARM_OUTREGION = 16,     //出区域报警/驶出行政区域
	 ALARM_INREGION	= 32,    //进区域报警/入区域报警/进入行政区域
	 ALARM_TIREDDRIVE =	64,     //疲劳驾驶
     ALARM_LINEAWAY	= 128,       // 偏离路线报警
	 ALARM_LINEOFF = 256,        // 天线开路报警
	 ALARM_TEMPERATURE = 512,   // 温度报警
 	 ALARM_UNLAWOPENDOOR = 1024,  // 非法开门
 	 ALARM_UNLAWFIRE = 2048,       //非法点火报警
	 ALARM_STOPDEF = 4096,          // 原地设防报警
     ALARM_TINGCHECHAOSHI =	8192,   // 停车超时报警
 	 ALARM_LOUYOU_VAL =	16384,          // 漏油报警
 	 ALARM_LOWPOWER_ORDER = 32768,       // 低电压报警
 	 ALARM_TURNOFF_ORDER = 65536,        // 关机报警
 	 ALARM_FANZHUAN_ORDER = 131072,       // 反转报警
 	 ALARM_VHCONLINE = 262144,            // 车辆上线报警
 	 ALARM_VHCOFFLINE = 524288,           // 车辆掉线报警
 	 ALARM_ZHENDONGBJ = 1048576;           // 震动报警

function getAlarmType(cstate){

		 if(cstate.indexOf("超速报警")>-1) return ALARM_OVERSPEED;
		 if(cstate.indexOf("低速报警")>-1) return ALARM_LOWSPEED;
		 if(cstate.indexOf("防劫报警")>-1) return ALARM_SOS;
		 if(cstate.indexOf("断电报警")>-1||cstate.indexOf("电瓶拆除")>-1) return ALARM_POWEROFF;
		 if(cstate.indexOf("出区域报警")>-1||cstate.indexOf("驶出行政区域")>-1) return ALARM_OUTREGION;
		 if(cstate.indexOf("进区域报警")>-1||cstate.indexOf("入区域报警")>-1 || cstate.indexOf("进入行政区域")>-1) return ALARM_INREGION;
		 if(cstate.indexOf("疲劳驾驶")>-1) return ALARM_TIREDDRIVE;
		 if(cstate.indexOf("偏离路线报警")>-1) return ALARM_LINEAWAY;
		 if(cstate.indexOf("天线开路报警")>-1) return ALARM_LINEOFF;
		 if(cstate.indexOf("温度报警")>-1) return ALARM_TEMPERATURE;
		 if(cstate.indexOf("非法开门")>-1) return ALARM_UNLAWOPENDOOR;
		 if(cstate.indexOf("非法点火报警")>-1) return ALARM_UNLAWFIRE;
		 if(cstate.indexOf("原地设防报警")>-1) return ALARM_STOPDEF;
		 if(cstate.indexOf("停车超时报警")>-1) return ALARM_TINGCHECHAOSHI;
		 if(cstate.indexOf("漏油报警")>-1) return ALARM_LOUYOU_VAL;
		 if(cstate.indexOf("低电压报警")>-1) return ALARM_LOWPOWER_ORDER;
		 if(cstate.indexOf("关机报警")>-1) return ALARM_TURNOFF_ORDER;
		 if(cstate.indexOf("反转报警")>-1) return ALARM_FANZHUAN_ORDER;
		 if(cstate.indexOf("车辆上线报警")>-1) return ALARM_VHCONLINE;
		 if(cstate.indexOf("车辆掉线报警")>-1) return ALARM_VHCOFFLINE;
		 if(cstate.indexOf("震动报警")>-1) return ALARM_ZHENDONGBJ;		 		 		 	 
}

//删除指定航
function removemsg(element){
    $(element).parent().parent().remove();
}

function clearAlarmMsg(addTotal){

	var resRecoderTotal = $("#warmmsgpanel tr").length;
	
	if(resRecoderTotal.size + addTotal > maxAlarmMsgTotal){
	
		var clearRowCount = addTotal - (maxAlarmMsgTotal - resRecoderTotal.size);

		for(var i = resRecoderTotal.size - clearRowCount; i < resRecoderTotal; i++){
			$("#warmmsgpanel").find("tr").eq(i).remove();
		}
		
	}
}

function getAlarmTableSize(){
	return $("#warmmsgpanel tr").length;
}

function getCmdTableSize(){
	return $("#cmdsgpanel tr").length;
}

function　disposeAlarm(createTime, vid){
	openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/monitor/alarmDispose.jsp?createTime=" + createTime + "&vid=" + vid);
}


function direction(t){
	if(t>27 && t<=72){							  		
		return "东北";
	}else if(t>72 && t<=117){									
		return "东";
	}
	else if(t>117 && t<=162){									
		return "东南";
	}
	else if(t>162 && t<=207){									
		return "南";
	}
	else if(t>207 && t<=252){									
		return "西南";
	}
	else if(t>252 && t<=297){									
		return "西";
	}
	else if(t>297 && t<=342){									
		return "西北";
	}
	else {									
		return "北";
	}
}

function setAlarmDispose(vid, type){
						
		var disposeWay = "";
		if(type == 7020){
			disposeWay = "下发文本";
		}else if(type == 7024){
			disposeWay = "下发拍照";
		}else if(type == 7029){
			disposeWay = "车辆监听";
		}else{
			disposeWay = "解除报警";
		}
		
		var params = {
			disposeWay : disposeWay,
			createTime : equipmentObject[vid].gpstime,
			vid : vid
		};
					
		$.ajax({
                  type: "POST",
                  dataType: "json",
                  url: $("#serverUrl").val() + "/json/alarmAction_dispose.action",
                  data: params,
                  success: function (json) {
                  		try{
                   		var statusDom = $("#alarm_dispose_state_" + vid );	
                    	vhcAlarm[vid].dospose = 1;//设置该条记录为已处理	
                    	vhcAlarm[vid].dosposeType = type;	    
                    	statusDom.html("已处理");
                    	statusDom.attr("href", "javascript:;");
                    	statusDom.css("color","red");
                   	}catch(e){}
                  }		
              });    				
}
//报警信息结束

//退出
function outSys() {
         $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/loginAction_out.action",
	        success: function(json) {
	           memoryStatus(false);
	           if($.browser.msie) { 
                  location.href = $("#serverUrl").val() + "gpsonline/jsp/login.jsp";
			   }else{
			      location.href = $("#serverUrl").val() + "/gpsonline/jsp/login.jsp";
			   }
	        },
	        error: function() {
	            // alert('获取账号信息失败...请联系管理员!');
	        }
	   });
}

function closeAllWin(){
		$("#closecmarkerWin").click();
		$("#closeSelectMarkerPhotoWin").click();
		$("#closeGroupWin").click();
		$("#closecmdWin").click();
		closeTrackWin();
		$("#closePasswordWin").click();
		$("#closeSetSystemWin").click();
		
		$("#close_electronicFence_Win").click();
		
		$("#close_electronicFence_vehicle_binding_Win").click();
		
		$("#close_marker_vehicle_binding_Win").click();
		
		$("#secondMenus").hide();
		$("#thridMenus").hide();
}

function largeDataShowAllVechileonMap(element){
		
		if($(element).attr("checked")){
					
			$.cookie("isLargeData", 'false', {expires:7});
			
		}else{
		
			$.cookie("isLargeData", 'true', {expires:7});			
			
		}
		
		if(confirm("重新打开页面后有效，是否立刻刷新当前页面?")){
			 memoryStatus(false);
			 location.replace(location.href);
		}
	   
}

//数组去除重复项
Array.prototype.myUnique = function(){

	var res = [];
	var json = {};
	
	for(var i = 0; i < this.length; i++){
		if(!json[this[i]]){
			res.push(this[i]);
			json[this[i]] = 1;
		}
	}
	
	return res;
}

function StringBuffer(){

    this._strings=new Array();

}

StringBuffer.prototype.append=function(str){

    this._strings.push(str)

}

StringBuffer.prototype.toString=function(){

    return this._strings.join("");

}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + (month<10?('0'+parseInt(month)):month) + seperator1 + (strDate<10?('0'+strDate):strDate)
            + " " + (date.getHours()<10?('0'+date.getHours()):date.getHours()) + seperator2 + (date.getMinutes()<10?('0'+date.getMinutes()):date.getMinutes())
            + seperator2 + (date.getSeconds()<10?('0'+date.getSeconds()):date.getSeconds());
    return currentdate;
} 

function addOverTimeVehicleTableRecoders(){
	
		if(cartIds.length != 0){
			
			var content = getOverTimeVehicleTableContent(cartIds.split(","));	
			
			if(content.length > 0){
				$('#vehiclePanel tr').eq(0).after(content);
									
				if(isShowOverTimeVehicleWin($("#userId").val())){			
		    		setToggle($("#icon_open_expand"));
		    		$("#overTime_vehicle").click();
	    		}
	    		
	    	}
	    }
}

var overTimeVehicleCount = 0;

function overTimeVehicleItemTitle(){
	if(overTimeVehicleCount == 0){
		return "设备信息";
	}
	
	return "设备信息(<span style=\"color:red;\">" + overTimeVehicleCount + "</span>)";
}

function getOverTimeVehicleTableContent(cartIdsArr){
	
	var content = "";
	cartIdsArr = cartIdsArr.myUnique();
	for(var i=0;i<cartIdsArr.length;i++){
		  if(getOverTimeDayCount(equipmentObject[cartIdsArr[i]].overduetime) < 10){
		  		content += "<tr class='alarmrow" + (overTimeVehicleCount % 2) + "'><td width='100px' style='text-align: left;padding-left:30px;'>"+($.trim(equipmentObject[cartIdsArr[i]].vehicleName))+"</td><td width='100px' style='text-align: center;'>"+
		  		(eqVisualPower.sim==true?equipmentObject[cartIdsArr[i]].simCode:"")+
		  		"</td><td style='text-align: center;width:150px;'>"+equipmentObject[cartIdsArr[i]].overduetime.replace("T"," ")+"</td><td style='width:150px;text-align: left;padding-left:60px;'>"+getoverTimeDesc(getOverTimeDayCount(equipmentObject[cartIdsArr[i]].overduetime))+"</td><td width='80px' style='text-align: center;'><a style='cursor:pointer;color:#069;' href='javascript:;' onclick='openCarOwnerInfo(" + equipmentObject[cartIdsArr[i]].id + ");'>" + language.chezhuxiangqing + "</a></td></tr>";	          
		  		overTimeVehicleCount ++ ;
		  }
	}
	return content;
}

function getOverTimeDayCount(overTime){
	return  parseInt((new Date(overTime.split(" ")[0].replace(/-/g, "/")).getTime() - new Date().getTime())/ (1000 * 60 * 60 * 24));
}

function getoverTimeDesc(overTimeDayCount){
	 if(overTimeDayCount == 0){
	  		return 1 + "天后过期";
	 }else if(overTimeDayCount > 0 && overTimeDayCount < 10){
	  		return overTimeDayCount + "天后过期";
	 }else if(overTimeDayCount < 0){
	 		
	 		overTimeDayCount = Math.abs(overTimeDayCount);
	 		
	 		if (overTimeDayCount > 0 && overTimeDayCount < 30 ){
	 			return "已过期" + overTimeDayCount + "天";
	 		}else if(overTimeDayCount >= 30 && overTimeDayCount <= 365 ){
	 			return "已过期" + parseInt( overTimeDayCount / 30 ) + "个月";
	 		}else{
	 			
	 			if(overTimeDayCount % 365 >= 30){
	 				return "已过期" + parseInt( overTimeDayCount / 365 ) + "年" + parseInt( parseInt(overTimeDayCount % 365) / 30 ) + "个月";
	 			}else{
	 				return "已过期" + parseInt( overTimeDayCount / 365 ) + "年";
	 			}
	 					
	 		}		
	 }
	 
} 

function overTimeVehicleShowSetCheckInput(userId){
	
	if(isShowOverTimeVehicleWin(userId)){
		return "&nbsp;&nbsp;<label id='promptOvertimeEqCheckBox' onclick=\"cancelPropagation(event);\" style=\"line-height:20px;display:none;\">[<input id='showOverTimeCheckInput' onclick='cancleOverTimeVehicleShow(this)' type='checkbox' style='vertical-align:middle;'></input><span id=\"showOverTimeCheckInputtitle\" >下次不再提示过期设备</span>]</label>";
	}
	
	return "";
}

function cancleOverTimeVehicleShow(el){
	
	if($(el).attr("checked")){
		setOverTimeVehicleWinSetStatusCookie($("#userId").val(),1);
	}else{
		setOverTimeVehicleWinSetStatusCookie($("#userId").val(),0);
	}
	
}

function isShowOverTimeVehicleWin(userId){
	
	if(getOverTimeVehicleWinSetStatusByUserIdCookie(userId) == userId){		
		return false;	
	}	
	return true;
	
}


function getOverTimeVehicleWinSetStatusCookie(){
	return getmyCookie("overTimeVehicleWinSetStatus");
}	

function getOverTimeVehicleWinSetStatusByUserIdCookie(userId){

	var overTimeVehicleWin_set_statusCookie = getOverTimeVehicleWinSetStatusCookie();
	
	if(overTimeVehicleWin_set_statusCookie && overTimeVehicleWin_set_statusCookie.length > 0){
		
		overTimeVehicleWin_set_statusCookie = overTimeVehicleWin_set_statusCookie.split(",");
		
		for(var i=0; i < overTimeVehicleWin_set_statusCookie.length; i++){
			
			if(overTimeVehicleWin_set_statusCookie[i] == userId ){
				return overTimeVehicleWin_set_statusCookie[i];
				break;
			}
			
		}
		
		return "";
	}
	
	return "";
	
}

function cancleOverTimeVehicleWinSetShowStatusByUserIdCookie(userId){
			
	if(getOverTimeVehicleWinSetStatusByUserIdCookie(userId).length > 0 ){
			
			var overTimeVehicleWin_set_statusCookie = "";
			
			overTimeVehicleWin_set_statusCookie = getOverTimeVehicleWinSetStatusCookie();
	
			if(overTimeVehicleWin_set_statusCookie && overTimeVehicleWin_set_statusCookie.length > 0){
				
				overTimeVehicleWin_set_statusCookie = overTimeVehicleWin_set_statusCookie.split(",");
				
				for(var i=0; i < overTimeVehicleWin_set_statusCookie.length; i++){
					
					if(overTimeVehicleWin_set_statusCookie[i] == userId ){
						overTimeVehicleWin_set_statusCookie.remove(i);
						break;
					}
					
				}
			}
			
			return overTimeVehicleWin_set_statusCookie = overTimeVehicleWin_set_statusCookie.join(",");
			
	}else{
		return getOverTimeVehicleWinSetStatusCookie() ? getOverTimeVehicleWinSetStatusCookie() : "" ;
	}
	
}

function addOverTimeVehicleWinSetNotShowStatusByUserIdCookie(userId){
	
	
	
	if( getOverTimeVehicleWinSetStatusByUserIdCookie(userId).length <= 0 ){
			
		return ((getOverTimeVehicleWinSetStatusCookie() && getOverTimeVehicleWinSetStatusCookie().length > 0) ? (getOverTimeVehicleWinSetStatusCookie() + ",") : "") + userId;
			
	}else{
		return getOverTimeVehicleWinSetStatusCookie() ? getOverTimeVehicleWinSetStatusCookie() : "" ;
	}
	
}

function setOverTimeVehicleWinSetStatusCookie(userId,state){//state 0 下次打开显示,1不显示

	var content = "";
	
	if(state - 1 == 0){//不显示
	
		content = addOverTimeVehicleWinSetNotShowStatusByUserIdCookie(userId);
		
	}else{//显示
		
		content = cancleOverTimeVehicleWinSetShowStatusByUserIdCookie(userId);
		
	}
		
	setmyCookie("overTimeVehicleWinSetStatus", content, 365);

}

function openCarOwnerInfo(vid){
	var driverid =0;
	if(equipmentObject[vid].driverId!=null && equipmentObject[vid].driverId!='undefined'){
		driverid = equipmentObject[vid].driverId;
	}
	openPopuWin($("#serverUrl").val() + "/gpsonline/jsp/monitor/carOwner.jsp?driverId=" + driverid+"&vhcid="+vid);
}
var so = "true";
function openDriverInfo(vid){
		$("#managerWin").html("");
		openPopuWin($("#serverUrl").val() + "manager/vechileAction_driverInfoWin.action?isSee=true&driver.id="+vid+"&so="+so);
		frame("popuWin","dragDriverPanel","closeDriverWin");
		$("#driverTop").remove();
		$("#diverBot").remove();
}

/**
*设置系统参数
*/

function initOverTimeVehicleSetBtn(){
	
	var obj = $("a[name='overTimeVehicleRemind']");
	
	if(isShowOverTimeVehicleWin($("#userId").val())){
		obj.find("img").attr("src","gpsonline/image/monitor/tool/yes.gif");
		obj.attr("flag","false");
	}else{
		obj.find("img").attr("src","gpsonline/image/monitor/tool/no.gif");
		obj.attr("flag","true");
	}
	
}





Array.prototype.remove=function(dx)
  {
    if(isNaN(dx)||dx>this.length){return false;}
    for(var i=0,n=0;i<this.length;i++)
    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
}


function updateVehicle(vehicleId,icon){
	
	if(carList != null && equipmentObject[vehicleId])
	{   
		equipmentObject[vehicleId].icon = icon;
		
		for(var i = 0; i< carList.data.length ; i++ )
		{
			if(carList.data[i].id == vehicleId)
			{
				carList.data[i].icon = icon;

				updateVehicleIcon(vehicleId,icon);
			
				break;
			
			}

		}
	}
}

function updateVehicleIcon(vehicleId,icon){
	if(2 - (getUserStatus()?getUserStatus().mapType:1) == 0){
					
		updateGoogleVehicleIcon(vehicleId,icon);
	
	}else{
	
		updateBaiDuVehicleIcon(vehicleId,icon);

	}
}

function updateGoogleVehicleIcon(vehicleId,icon){
	
	if(vehicles != null){
	
		for(var i = 0 ; i < vehicles.length ; i++)
		{
			if(vehicles[i].id == vehicleId)
			{
				if(vehicles[i].marker)
				{   	
						vehicles[i].icon = icon;
						var markerIcon = vehicles[i].marker.getIcon().url.split("/");
						
						markerIcon[markerIcon.length-2] = icon;
						
						vehicles[i].marker.setIcon(new google.maps.MarkerImage(markerIcon.join("/"), new google.maps.Size(40, 40),new google.maps.Point(0,0),new google.maps.Point(10, 10)));
				}								
				break;
			}
		}
	}
}
//修改百度地图的
function updateBaiDuVehicleIcon(vehicleId,icon){
	if(markers != null){
		for(var i = 0 ; i < markers.length ; i++)
		{
			if(markers[i].id == vehicleId)
			{
				if(markers[i].marker)
				{
						markers[i].icon = icon;
						var markerIcon = markers[i].marker.getIcon().imageUrl.split("/");
						markerIcon[markerIcon.length-2] = icon;
						
						markers[i].marker.setIcon(new BMap.Icon(markerIcon.join("/"), new BMap.Size(40,40)));
				}
				
				break;
			}
		}

	}
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//报警类型过滤


var curUserAlarmTypeValue = 0;
var isInitedAlarmTypeValu = false;

function getCurUserAlarmTypeValue(){

	if(isInitedAlarmTypeValu)  return curUserAlarmTypeValue;
	
	var userId = $("#userId").val();
	
	var alarmType = getAlarmTypeCookie();
	for(var i = 0; i < alarmType.length; i++){
		if(alarmType[i].userId == userId){
			curUserAlarmTypeValue = alarmType[i].value;
			break;
		}
	}
	
	isInitedAlarmTypeValu = true;
	
	return curUserAlarmTypeValue;
	
}

function getAlarmTypeCookie(){
	
	var sysCookie = getSysCookie();
	
	if(sysCookie && sysCookie.alarmType){
		return sysCookie.alarmType;
	}else{
		return [ {userId : $("#userId").val(), value : -1 } ];
	}	
	
}

function setCurUserAlarmTypeCookie(value){

	curUserAlarmTypeValue = value;
	isInitedAlarmTypeValu = true;
	
	var userId = $("#userId").val();
	var curUserAlarmTypeCookieisExist = false;
	
	var alarmType = getAlarmTypeCookie();
	for(var i = 0; i < alarmType.length; i++){
		if(alarmType[i].userId == userId){
		    alarmType[i].value = value;
		    curUserAlarmTypeCookieisExist = true;
			break;
		}
	}
	
	if(!curUserAlarmTypeCookieisExist){
	   alarmType.push({userId:$("#userId").val(),value:value});
	}
	
	setAlarmTypeCookie(alarmType);
	
}

function setAlarmTypeCookie(value){
	
	var sysCookie = getSysCookie();
	
	if(sysCookie){
		sysCookie.alarmType = value;
	}else{
		sysCookie = {alarmType:value};
	}
	setSysCookie(sysCookie);
}

function showTtsDiv(){
	
	//alert("-----------");
}

function dateConvertLong(time){
	time = time.replace(new RegExp("-","gm"),"/");
	return (new Date(time)).getTime(); //得到毫秒数
}


//openPopuWin("gpsonline/jsp/cmd/ShangBaoCmd.jsp");