//window.onerror = function(){return true};
var cartIds="";//-1表示没有数据,""表示有数据
var serverip;
var equipmentMap={};
var lineStatus=-1;//设置在线离线选中状态
var groupjson=null;
var groupObject={};
var equipmentObject={};
var udptimer;
//设备状态
var onlines=new Array();
var unonlines=new Array();
var usertype="";

var flagwarmvoice=true;

var warmMsg = null;

$(window).load(function () {

  openMask();
  
  var zMsg =$('#zMsg').val();
 
  if(zMsg=="true"){
	 // showMap();
	
	  //document.getElementById("checkbox2").style.display="none";
	 // document.getElementById("buttonMap").style.display="none";
  }
  serverip=$("#serverip").val();
 
  setuserType();//设置用户类型
  
  startMarker();
 
  getGroup();//添加组
	
  flagwarmvoice=getWarmVoiceStatus();

	try{
		var obj = new ActiveXObject("ScriptAgent.ScriptBridage.1");
		obj.operation ="ok";
	}catch(err){}

  if(cartIds.length != 0){
	  //alert(JSON.stringify(groupjson));
	
	  saveEquipmentMap(groupjson);	

	  initialize(cartIds);//加载车辆详细信息
	  
	  updateGroupTree();
	  
	  warmMsg = setInterval('getwarmMsg()',5000);//每五秒刷新一次报警信息
	  				  
	  getAllComds();//获取命令	 
	   
  }else{
  	  initialize("-1");//没有车辆时加载地图
  	  $("#unlinecount").text(0);
	  $("#onlinecount").text(0);
	  $("#allcount").text(0);
  }
  
  setSystemObject.init();
  
  $("#vhc_name_visable_checkbox").click();
  $("#bzcheckbox").click();
  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();
        
        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;
        }
}

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:false,
	        url: "json/groupAction_groupName.action",
	        data: {dataType:1},
	        success: function(json) {		         
		         if (json.flag==true) {		        	 
					groupjson =	json;
					loadGroupTree();	                     				
                 }else{                      
                       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);
   	     
        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].name=childs[j].vehicleName;
	   	      equipmentObject[childs[j].id].id=childs[j].id;	
	   	      equipmentObject[childs[j].id].simCode = childs[j].simCode;
			  equipmentObject[childs[j].id].vehicleName=childs[j].vehicleName;
			  equipmentObject[childs[j].id].gprsCode = childs[j].gprsCode;  
			  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!=""){
	   	var ab = lastonlineTime.split("T")[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));       
    }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;
   switch(status){
   		case -1:
   				$('#group').find("dd").each(function(){//迭代每一个组
   				    count=0;
   				    $(this).children().each(function(){
   				    	$(this).show();
   				    	count++;  				    
   				    });
   				    $(this).prev().find('span').text(count);
   				});
   		
   		break;
   		case 1:
   				$('#group').find("dd").each(function(){//迭代每一个组
   					count=0;
   				    $(this).children().each(function(){
   				    	if($(this).attr("status")=="1"){
   				    		$(this).show();
   				    		count++;
   				    	}else{
   				    		$(this).hide();
   				    	}				    
   				    });
   				    $(this).prev().find('span').text(count);
   				});

   				
   		break;
   		
   		case 0:
   		
   				$('#group').find("dd").each(function(){//迭代每一个组
   					count=0;
   				    $(this).children().each(function(){
   				    	if($(this).attr("status")=="0"){
   				    		$(this).show();
   				    		count++;
   				    	}else{
   				    		$(this).hide();
   				    	}				    
   				    });
   				    $(this).prev().find('span').text(count);
   				});
   		
   		break;
   		
   }
}

function closeTrackWin_obd(){
	$("#trackContentWin_obd").fadeOut("fast");
	clearTimeout(udptimer);
}

function loadGroupTree(){
	var treeStr="";	
	for(var i=0 ; i< groupjson.totalcount ; i++){
         var childStr="<dd>";
         for(var j=0 ; j< groupjson.data[i].data.length ; j++){
         	var id=groupjson.data[i].data[j].id;
         	childStr+="<div style='overflow:auto;' status='0' id='"+groupjson.data[i].id+"_"+id+"' name='"+groupjson.data[i].data[j].vehicleName+"' onclick=\"showMenu(this,1);\">"+
		                 "<div style='overflow:auto;display:block;'>"+
		                      "<div class='unline'><div style='display:inline-block;float:left; width:145px;'><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+"' style='white-space:nowrap;display:inline-block;width:100px; overflow:hidden;text-overflow: ellipsis;'>"+groupjson.data[i].data[j].vehicleName+"</span>"+
		                      "</div><span id=\"lineStatus_"+groupjson.data[i].id+"_"+id+"\"></span></div>"+
		                 "</div>"+
		              "</div>";
              cartIds+= groupjson.data[i].data[j].id+",";      	
         }
         treeStr+="<dt id='"+groupjson.data[i].id+"'><img src='gpsonline/image/monitor/g_c.gif'/>"+groupjson.data[i].groupName+"(<span>"+j+"</span>)"+childStr+"</dd></dt>";
	}
	document.getElementById("group").innerHTML=treeStr;
	cartIds=cartIds.substring(0,cartIds.length-1);
	$('dl#group').accordion({open:false});     
   $(".list_main").height($(window).height()-$(".idx_top").height()-140);
}


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++){
     		 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;
             equipmentObject[carList.data[i].id].icon=carList.data[i].icon;
              
             if((carList.data[i].positionLast.lat==0&&carList.data[i].positionLast.lng==0) || carList.data[i].positionLast.av == 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;
             
     }
     
    
    

	$('#group').find("dd").each(function(){//迭代每一个组
		var groupId=$(this).prev().attr('id');//获取组id
		$(this).children().each(function(){
			var id=$(this).attr('id').split('_')[1];
	        var curEquipmentDiv=$("#"+groupId+"_"+id);
	        var curEquipmentStatus=$("#lineStatus_"+groupId+"_"+id);
	        var childs=equipmentObject[id];	        
	        
	        if(!childs.isPosition){     
	           			        	
	        	curEquipmentStatus.text("未定位");
	        	
	        	if(childs.online==1){
	        	
	        		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{
	        	
	        		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){
		        	
		        	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=unlineTime(childs.gpstime);
					
		        	if(date!=-1&&date>0){
		        	
		        		if(date>=60){
		        			curEquipmentStatus.text("离线>60天");
		        		}else{
		        			curEquipmentStatus.text("离线"+date+"天");
		        		}
		        		
		        	}else{
		        	
		        		curEquipmentStatus.text("离线");
		        		
		        	}
		        	
		        	curEquipmentStatus.parent().removeClass().addClass("unline");
		        	curEquipmentDiv.attr("status","0");
		        	$("#lineStatusImg_"+groupId+"_"+id).attr("src","gpsonline/image/monitor/u_offline.gif");	        	
		        }
	        }
        });
	});
	
	onlines=onlines.myUnique();
	unonlines=unonlines.myUnique();
	
	$("#unlinecount").text(unonlines.length);
    $("#onlinecount").text(onlines.length);
    $("#allcount").text(onlines.length + unonlines.length); 

}



//三十秒刷新
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(curEquipmentStatus.text()!="未定位"){	       	   		
		        	curEquipmentStatus.text("未定位");
	        	}
	        	
	        	if(childs.online==1){
	        	
	        		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{  
		        
		        	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");		
			        		        	
			        }
			        
		        }
	        	        	
	        	//if($('#elSelected').attr('value')==groupId+"_"+id){//判断某个设备是否已经选中
	        				           
		        		//$("t_menu_"+id).html("<a href='javascript:;' onclick='stopBubble(event);'>&nbsp;</a><a id='playback_"+id+"' onclick=\"getback(event,'"+id+"','"+childs.vehicleName+"','"+childs.icon+"');\" href='javascript:;'>回放</a><a href='javascript:;' onclick='stopBubble(event);'>&nbsp;&nbsp;&nbsp;&nbsp;</a>");
				
				//}
					        	
	        }else{
	        	
	        	
	        	//if($('#elSelected').attr('value')==groupId+"_"+id){//判断某个设备是否已经选中
	        				           
		        		//$("t_menu_"+id).html("<a id='track_"+id+"' onclick='openTrackFrame(this,event)' href='javascript:;'>跟踪</a> | <a id='playback_"+id+"' onclick='openBackFrame(this,event);' href='javascript:;'>回放</a> | <a id='more_"+id+"' href='javascript:;' onclick=\"showSecondMenu(this,event);\">更多</a>");
				
				//}
	        	
	        
	       	    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=unlineTimeT(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{
		        		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(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=500;

function showMenu(element,ptype){
    if(carList==null||carList==""){
    	return;
    }
	clearTimeout(clickRepeat); 
	clickCount++; 
	var id=$(element).attr('id');
	if(clickCount==1) {clickRepeat=setTimeout("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($.inArray(parseInt(id),onlines)>=0){
         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 style="height:20px;float:right;"></div>');
     
     var childdiv ="";	
    // if(equipmentObject[id].isPosition){
		if(alarmType == "Bus_client"){
			
		  	 var voiceCode= "";
		     var dataCode= "";
		     for(var i=0;i<carList.data.length;i++){
		     	if(carList.data[i].id==id){
		     		
		     		voiceCode = carList.data[i].voiceCode;
		     		dataCode = carList.data[i].dataCode;
		     		break;
		     		
		     	}
		     }
			
     		childdiv=$("<div  class='left_tree_caozuo'><a id='track_"+id+"' onclick='openTrackFrame(this,event)' href='javascript:;'>跟踪</a> | <a href=\"javascript:;\" onclick=\"voiceStar('"+$.trim(voiceCode)+"','"+$.trim(dataCode)+"');\">视频</a> | <a id='playback_"+id+"' onclick='openBackFrame(this,event);' href='javascript:;'>回放</a> | <a id='more_"+id+"' href='javascript:;' onclick=\"showSecondMenu(this,event);\">更多</a></div>");  
   		}else{
   			childdiv=$("<div  class='left_tree_caozuo'><a id='track_"+id+"' onclick='openTrackFrame(this,event)' href='javascript:;'>跟踪</a> | <a id='playback_"+id+"' onclick='openBackFrame(this,event);' href='javascript:;'>回放</a> | <a id='more_"+id+"' href='javascript:;' onclick=\"showSecondMenu(this,event);\">更多</a></div>");
   		}
   	 //}else{
   	
   		//childdiv=$("<div  class='left_tree_caozuo'><a id='track_"+id+"' href='javascript:;' onclick='stopBubble(event);'>&nbsp;</a>  <a id='playback_"+id+"' onclick='openBackFrame(this,event);' href='javascript:;'>回放</a>  <a id='more_"+id+"' href='javascript:;' onclick='stopBubble(event);'>&nbsp;&nbsp;&nbsp;&nbsp;</a></div>");   
   	
   	// }	
   
     childdiv.appendTo(mendiv);

     $(parentDiv).append(mendiv);
    if(ptype!=1){
	    var container = $('#leftList'),scrollTo = parentDiv;
	    
	    container.scrollTop(
	      scrollTo.offset().top - container.offset().top-20 + container.scrollTop()
	    );
    }
     
     expelement=$(parentDiv);//保存已选中的菜单
     menuelement=mendiv;
     
      //判断设备是否是未定位若是未定位直接返回
     //if(equipmentObject[id].isPosition){
        centerMap(id,type);
     //}
}
//修改当前选中的菜单信息
function updateCurMenu(data){
	if(data.totalcount==1){
		
		var curEmp=data.data[0];
		var id=expelement.attr("id");
		var groupId = id.split("_")[0];
		var equipmentId = id.split("_")[1];
		
		 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 || data.data[0].positionLast.av == 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());
       
    		if( equipmentObject[equipmentId].online == 1){
 
 				 if(curEquipmentDiv.attr("status") != "1"){//原始状态
 				 
     				onlinecountPan.text(onlineTotal + 1);
     						
				 }
       					
   			}else{
   			
   				 if(curEquipmentDiv.attr("status")!="0"){
   				     unlinecountPan.text(unlineTotal + 1);    					
				 }
   				
   			}
   			
   			if(lineStatus != -1){
   				if( equipmentObject[equipmentId].online == 1){
			 
			 				 if(curEquipmentDiv.attr("status") != "1"){//原始状态
			 				 
        						onlinecountPan.text(onlineTotal + 1);
        						
        					 }
        					
       			}else{
       			
       				 if(curEquipmentDiv.attr("status")!="0"){
       				        unlinecountPan.text(unlineTotal + 1); 					
      				  }
       			}
   			}

		       	
		if(!curEquip.isPosition){			  
	        	
	        	if(curEquipmentStatus.text()!="未定位"){	       	   		
		        	curEquipmentStatus.text("未定位");
	        	}
	        	
	        	if(curEquip.online==1){
	        		
			        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(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')==groupId+"_"+id){//判断某个设备是否已经选中
	        				          
		        		$("t_menu_"+id).html("<a href='javascript:;' onclick='stopBubble(event);'>&nbsp;</a><a id='playback_"+id+"' onclick=\"getback(event,'"+id+"','"+childs.vehicleName+"','"+childs.icon+"');\" href='javascript:;'>回放</a><a href='javascript:;' onclick='stopBubble(event);'>&nbsp;&nbsp;&nbsp;&nbsp;</a>");
				
				}*/
	        		 
		}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=unlineTimeT(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{
		        		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 openTrackFrame(element,event){
	stopBubble(event);
	//alert(1);
	
	$("#mainframe").removeClass().addClass("right_menu_nor_s");
	$("#otherframe2").removeClass().addClass("right_menu_select");	
	$("#closeframe2").removeClass().addClass("right_menu_select_close");
	$("#otherframe").removeClass().addClass("right_menu_select_s");	
	$("#closeframe").removeClass().addClass("right_menu_select_close_s");
	
	var id=$(element).attr("id").split("_")[1];
	$("#indexiframe2").attr("src","");
	
	$("#indexiframe2").attr("src","gpsonline/jsp/TrackMap.jsp?carid="+id+"&type=1&mapType="+mapType);
	$("#main_frame").hide();
	$("#index_iframe").hide();
	$("#index_iframe2").show();
	$("#otherframe2").show();
	$("#otherframe2").text("设备跟踪");
	$("#closeframe2").show();
}

function openBackFrame(element,event){
	stopBubble(event);
	
	$("#mainframe").removeClass().addClass("right_menu_nor_s");
	$("#otherframe2").removeClass().addClass("right_menu_select_s");	
	$("#closeframe2").removeClass().addClass("right_menu_select_close_s");
	$("#otherframe").removeClass().addClass("right_menu_select");	
	$("#closeframe").removeClass().addClass("right_menu_select_close");
	
	var id=$(element).attr("id").split("_")[1];
	var icon="";
	var name="";
    for(var i=0;i<carList.data.length;i++){
     if(carList.data[i].positionLast.vehicleId==id){
        icon=carList.data[i].icon;
        name=carList.data[i].vhcCode;
        break;
     }
    }
    var b = new Base64();
    $("#indexiframe").attr("src","");
	$("#indexiframe").attr("src","gpsonline/jsp/monitor/playBack.jsp?carid="+id+"&carname="+encodeURI(encodeURI(name))+"&icon="+icon+"&type=1&mapType="+mapType);
	$("#main_frame").hide();
	$("#index_iframe2").hide();
	$("#index_iframe").show();
	$("#otherframe").show();
	$("#otherframe").text("轨迹回放");
	$("#closeframe").show();
}

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-30,"top":down_y-33,"width":100});
   //获取二级菜单的所有选项
   $("#secondMenus li").each(function(){
	   $(this).attr('name','secondMenu_id_'+($(element).attr('id').split('_'))[1]);
   });
   //$("#downMenus").show();
   //$("#secondMenus").show();
  
      
}
$(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();
			   if($(this).attr("id")=="order"){	
				   
				   //加载三级菜单
				   loadthridMenus(($(this).attr('name').split('_'))[2]);
				   //显示三级菜单
				   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){
   var mobileId=-1;
   var gprsCode="";
   var name="";
   for(var i=0;i<carList.data.length;i++){
     if(id==carList.data[i].positionLast.vehicleId){
       mobileId=carList.data[i].mobileId;
       gprsCode=carList.data[i].gprsCode;
       name=carList.data[i].vhcCode;
       break;
     }
   }
   
   var thirdMend="";
   
   for(var i=0;i<comds.data.length;i++){
      
       if(mobileId==comds.data[i].mobileId){//$("#test").text($("#test").text()+"/n mobileId:"+comds.data[i].mobileId+",content:"+comds.data[i].meaning);
            thirdMend=thirdMend+"<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+"'>"+comds.data[i].meaning+"</li>";
       }
   }
   $("#thridMenus").find('ul').empty();
    //$("#thridMenus").find('a').remove();
    $("#thridMenusup").hide();
 	$("#thridMenusdown").hide();
    $("#thridMenus").find('ul').append(thirdMend);
    $("#thridMenus ul").css('height','');//ul还原高度
	$("#thridMenus ul").css('overflow','');//ul还原显示方式
   jQuery("#thridMenus").unbind();
}



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

function closeAccordion(){
	$('#group').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().slideUp('fast');
		}
		
		function reset() {
			$(this).next().hide();
		}
	}
})(jQuery);


//轨迹下载开始


function loadtrack(element){
   var id=$(element).attr('name').split('_')[2];
   $('#trackVId').empty();
   //轨迹回放车辆添加列表  
   var carts="<option value='-1'> --选择--</option>";
   for(var i=0;i<carList.data.length;i++){
      if(carList.data[i].id==id){
      	carts=carts+"<option selected='selected' value='"+carList.data[i].id+"'>"+carList.data[i].vhcCode+"</option>";
      }else{
       	carts=carts+"<option value='"+carList.data[i].id+"'>"+carList.data[i].vhcCode+"</option>";
      }
   }
   $('#trackVId').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";
  $("#start").val(start);
  $("#end").val(end);
   
   $("#secondMenus").hide();
   $("#thridMenus").hide();
}

function closeTrackWin(){
	$("#trackContentWin").fadeOut("fast");
}

$(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();
	    
	    $("#mask").css({"height":$(document).height(),"width":$(document).width()});
	    
	    $("#electronicFence_ContentWin").center();	
	    
	    $("#electronicFence_vehicle_binding_ContentWin").center();
	    
	});
});

//命令控制
var comds=null;
function getAllComds() {
         $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/vehiclecmdAction_cmdbyUserId.action",
	        success: function(json) {
		         if (json.flag==true) {
			          comds=json;
		         }
	        },
	        error: function() {
	             //alert('请稍后重试...!');
	        }
	   });
}
//命令弹出框开始
function sendCmd(){
	var flag=true;
	$.each(cmdcheckNumflag, function (k, v) {
		if(v==false){
			flag=false;
			return false;
		}
	});
	
	if(!flag){
		return;
	}
   $("#secondMenus").hide();
   $("#thridMenus").hide();
   var gprsCode=$('#vid').val();
   var mtid=$('#mtid').val();
   var cmdid=$('#cmdid').val();
   var data="vid="+gprsCode+"&mtid="+mtid+"&cmdid="+cmdid;
   
   $('#cpcontent').find('[name=cp]').each(function(){
   		data+="&cp="+$(this).val();
   });
   
  $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/cmdAction_send.action",
	        data: data,
	        success: function(json) {
		         if (json.flag==true) {
			         $("#closecmdWin").click();
			         $('#cmdsgpanel tr').eq(0).after("<tr><td width='100px' style='text-align: left;'>"+$("#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='removemsg(this);'>未处理</a></td></tr>");	          
		         
		         }else{
			          $("#cmd_msg").css("color","red");
			          $("#cmd_msg").text(json.msg);	         	
		         }
	        },
	        error: function() {	             
	             //alert('请稍后重试...!');
	        }
	   });
}
function sendComdWin(element){

	$("#closeGroupWin").click();
   $("#closecmarkerWin").click();
   $("#closeSelectMarkerPhotoWin").click();
   
    $("#closecmdWin").click();
   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]);
   $('#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;
	      default:$("#cpcontent").append("<span>"+cps[i].text+":</span><input name='cp' value='"+cps[i].value+"'/><br/>");	      
	      break;
	  }
   } 
   
   $("#trackContentWin").hide();
   $("#cmdContentWin").fadeIn("fast");
   $("#cmdContentWin").center();
   
   $("#secondMenus").hide();
   $("#thridMenus").hide();
}
var cmdcheckNumflag={};
function checkcpNumber(element){
	var ex = /^\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 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"); 	
			});

});
//命令弹出框结束

//报警信息开始
function getwarmMsg() {
		 if(carList==""||carList==null){
		 	return;
		 }
         $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/vehicleAction_msg.action",
	        data: ((getCurUserAlarmTypeValue() + 1 ) ==0 ) ? {ids:"-1"} : {ids:"-1",alarmType:getCurUserAlarmTypeValue()} ,
	        success: function(json) {
	        	//console.info(JSON.stringify(json));
		         if (json.flag==true) {
		               alarm(json); //检查是否报警
			           updatewarmMsgTable(json);
			           
		         }
	        }/*,
	        error: function() {
	            alert('获取报警信息失败...请联系管理员!');
	        }*/
	   });
}

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 && (alarmType=="" || (alarmType=="PublicVehicle" && datas.data[i].content.indexOf("非法")==0))){
              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){
     for(var i=0;i<datas.data.length;i++){
         for(var j=0;j<carList.data.length;j++){
      		if(carList.data[j].id==datas.data[i].vhcId){
      		     if(datas.data[i].type==1){
      		     	if(alarmType ==""){
        		 		
        		 		$('#warmmsgpanel tr').eq(0).after("<tr><td width='100px' style='text-align: left;'>"+(carList.data[j].vhcCode!=null&&carList.data[j].vhcCode!=""?carList.data[j].vhcCode:"&nbsp;")+"</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='removemsg(this);'>未处理</a></td></tr>");     
                 	
                 	}else{
                 	
                 		if(alarmType == "PublicVehicle"){
                 			
                 			if(datas.data[i].content.indexOf("非法")==0){
                 			
                 				$('#warmmsgpanel tr').eq(0).after("<tr><td width='100px' style='text-align: left;'>"+(carList.data[j].vhcCode!=null&&carList.data[j].vhcCode!=""?carList.data[j].vhcCode:"&nbsp;")+"</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='removemsg(this);'>未处理</a></td></tr>");     
                 	
                 			}
                 			
                 		}else{
                 		
                 			$('#warmmsgpanel tr').eq(0).after("<tr><td width='100px' style='text-align: left;'>"+(carList.data[j].vhcCode!=null&&carList.data[j].vhcCode!=""?carList.data[j].vhcCode:"&nbsp;")+"</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='removemsg(this);'>未处理</a></td></tr>");     
                 	
                 		}
                 	}
                 }else{
                 	
                 	if(alarmType == "PublicVehicle" && datas.data[i].content.indexOf("透传数") > -1){
                 		
                 	}else{
                 		$('#cmdsgpanel tr').eq(0).after("<tr><td width='100px' style='text-align: left;'>"+(carList.data[j].vhcCode!=null&&carList.data[j].vhcCode!=""?carList.data[j].vhcCode:"&nbsp;")+"</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='removemsg(this);'>未处理</a></td></tr>");
                 	}
                 }
                 break;
            }
         }
     }

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

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 outSys() {
         $.ajax({
	        type: "POST",
	        dataType: "json",
	        url: "json/loginAction_out.action",
	        success: function(json) {
		         if (json.flag==true) {
			           if($.browser.msie) { 
                          location.href = "../login.jsp";
					   }else{
					      location.href = "./gpsonline/jsp/login.jsp";
					   }
		         }else {
		            alert(json.msg);
		         }
	        },
	        error: function() {
	             //alert('获取账号信息失败...请联系管理员!');
	        }
	   });
}

var managerDictionary=null;

function loadDictionary(data){	
		managerDictionary=data;
}

//数组去除重复项
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;
} 


var alarmType = "";

function setAlarmType(type){
	//alert(type);
	alarmType = type; 

}

function closeAlramMsg(){
	if(warmMsg != null){
		window.clearInterval(warmMsg);
	}
}

function openAlramMsg(){
	if(warmMsg != null){
		window.clearInterval(warmMsg);
	}
	 warmMsg = setInterval('getwarmMsg()',5000);//每五秒刷新一次报警信息
}




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($("#msg_title"));
		    		$("#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><td width='100px' style='text-align: left;padding-left:30px;'>"+($.trim(equipmentObject[cartIdsArr[i]].vehicleName))+"</td><td width='100px' style='text-align: center;'>"+(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></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;\">[<input id='showOverTimeCheckInput' onclick='cancleOverTimeVehicleShow(this)' type='checkbox' style='vertical-align:middle;'></input><span id=\"showOverTimeCheckInputtitle\" >下次不再提示过期设备</span>]</label>";
	}
	
	return "";
}

function cancleOverTimeVehicleShow(){
	
	if($("#showOverTimeCheckInput").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 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
}

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


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