 var mapType="1";
 var baidMap = null;
 var Vechieljson = null;
 var cuuCity = "";
 $(window).load(function(){
 		mapType=$("#mapType").val();

 		if(typeof(google)=="undefined" && mapType==2){
 			loadGoogleMapJs();
		}
 		setTimeout('mapObject.init()',1000);
 		$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function(_result) {
 			 if (remote_ip_info.ret == '1'){
 				cuuCity = remote_ip_info.city;
 			 }
 		});
 		
});

var mapObject = {
	init : function(){
		
		$("#map").html("");
		
		if(mapType != "1"){
			googleMap.init();
		}else{
			baiduMap.init();
		}
 		tool.init();	
	}
}

var tool = {
	isInitTime : true,
	init : function(){
		  var d = new Date();
		  var vYear = d.getFullYear();
		  var vMon = d.getMonth() + 1;
		  var vDay = d.getDate();
		  var vHour = d.getHours();
		  var vMinutes = d.getMinutes();
		  var vSeconds = d.getSeconds();
		  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) + " "+vHour+":"+vMinutes+":"+vSeconds;
		  if(this.isInitTime){
			  $("#queryhistoryTime_startTime").val(start);
			  $("#queryhistoryTime_endTime").val(end);
			  this.isInitTime=false;
		  }
		  $("#vehicle_table_history_content_div").css("height",$(window).height()-98);
		  
		  initializeDraw(); 
		  $("#queryBtn").click(function(){
			  
			  addRectangShape();
			  
		  });
		  
		  $(window).resize(function() {
	     	 $("#vehicle_table_history_content_div").css("height",$(window).height()-98);
		  });
		  
		  
		  (function($){
		    $.fn.getDistanceDay = function(dateBegin,dateEnd){
		    	var sDateArr = dateBegin.split(" ")[0].split("-");  
		    	var eDateArr = dateEnd.split(" ")[0].split("-");  
		        var sDate = new Date(dateBegin);
		        var eDate = new Date(dateEnd);
		        sDate.setUTCFullYear(sDateArr[0], sDateArr[1]-1, sDateArr[2]); 
		        eDate.setUTCFullYear(eDateArr[0], eDateArr[1]-1, eDateArr[2]);
		        if(sDate.getTime()>eDate.getTime()){
		        	return Math.floor((sDate.getTime()-eDate.getTime())/(24*60*60*1000));
		        }else{
		        	return Math.floor((eDate.getTime()-sDate.getTime())/(24*60*60*1000));
		        }	    
		    };
		})(jQuery);	
		
		
	},
	tableobject :{
		addRow : function(data){
					
					var rows="";
					this.clearRow();
					Vechieljson = data;
					if(data.data.length>0){
						for(var i=0;i<data.data.length;i++){						
								 rows += "<tr name='"+data.data[i][0]+"' onclick='tool.tableobject.clearCurSelect(this)'>" +
									    "<td align='center' style='width:10%;'>"+(i+1)+"</td>"+
									    "<td align='center' style='width:20%;'><span title='"+$.trim(data.data[i][1])+"' style='white-space:nowrap;display:inline-block;width:100px; overflow:hidden;text-overflow: ellipsis;'>"+$.trim(data.data[i][1])+"</span></td>"+
									    "<td align='center' style='width:10%;'>"+"<a href=\"javascript:queryVehciletoPlayBack("+data.data[i][0]+",'"+$.trim(data.data[i][1])+"',"+data.data[i][4]+")\" class='link_style'>"+areaquery.huifang+"</a>"+"</td>"+
									 "</tr>"					 							
								if(i%100 == 0){
									$("#vehicle_table_history_content tbody").append(rows);
									rows="";
								}
								
								
						}
					}else{
						rows="<tr><td>&nbsp;</td><td>"+areaquery.wlsjl+"</td>"+
                                      "<td>&nbsp;</td></tr>";
					}	
					
					$("#vehicle_table_history_content tbody").append(rows);
					rows="";			
		},
		clearRow : function(){
			$("#vehicle_table_history_content tbody").empty();
			Vechieljson = null;
		},
		clearCurSelect : function(element){
			if(curTr != null){
				curTr.css("background","");
				curTr.css("color","#676767");
			}
			curTr=$(element);
			curTr.css("background","#d9e1ee");
		},
		loadding : function(){
			$("#vehicle_table_history_content tbody").empty();
			$("#vehicle_table_history_content tbody").append("<tr><td>&nbsp;</td><td>loading...</td>"+
                                      "<td>&nbsp;</td></tr>");
		}
		
	}
}
var times = 0;
try{
	queryVechileLoading.prototype = new google.maps.OverlayView();
}catch (e) {
	// TODO: handle exception
}
var googleMap ={
	map : null,
	init : function(){
	
	if(typeof(google)=="undefined"){
		//console.info(times);
		if(times > 10){
			alert("加载谷歌api失败,请稍后再试!");
			return;
		}
		setTimeout('googleMap.init()',1000);
		times++;
		return;
	}
		
	// 继承自  google.maps.OverlayView
	        if($("#center_lat").val() != "null" && $("#center_lat").val().length!=0 && $("#center_lng").val() != "null" &&  $("#center_lng").val().length!=0 && $("#zoom").val() != "null" &&  $("#zoom").val().length!=0){    
				var mapOptions = {
			          center: new google.maps.LatLng(parseFloat($("#center_lat").val()),parseFloat($("#center_lng").val())),
			          zoom: parseInt($("#zoom").val()),
			          //poistion: cuuCity,
			          mapTypeId: google.maps.MapTypeId.ROADMAP,
				      mapTypeControlOptions: {
		                    mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, "MAPabc"]
		              }
	        	};
	       		 
	       		 this.map = new google.maps.Map(document.getElementById("map"),
	            	mapOptions);
	            	
	        }else{
	        
	        	var mapOptions = {
			          zoom: 2,
			          center : new google.maps.LatLng(47.60316025877417,151.73735755822483),
			          mapTypeId: google.maps.MapTypeId.ROADMAP,
				      mapTypeControlOptions: {
		                    mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, "MAPabc"]
		              }
	       		 };
	       		 
	       		 this.map = new google.maps.Map(document.getElementById("map"),
	            	mapOptions);
	        } 
            this.addMAPabc(this.map);
	},
	destroy : function(){
	
	},
    addMAPabc : function(map){//添加MAPabc的瓦片 参数为地图对象 
      
	    var _tileSize = new google.maps.Size(256,256);
	    
	    var getTileUrl = function(tile,zoom){
	        return "http://emap" + ((tile.x + tile.y) % 4) + ".mapabc.com/mapabc/maptile?v=w2.99&x=" + tile.x + "&y=" + tile.y + "&zoom=" + (17-zoom);  
	    }; 
	    
	    var imageMapType = new google.maps.ImageMapType({alt:"MAPabc",isPng:true,maxZoom:18,minZoom:1,name:"MAPabc",tileSize: new google.maps.Size(256, 256),opacity:1.0,getTileUrl:getTileUrl});  
	    
	    map.mapTypes.set('MAPabc',imageMapType);  
	}
}

var baiduMap ={
	init : function(){		

			baidMap = new BMap.Map("map");            // 创建Map实例
			
			 if($("#center_lat").val() != "null" && $("#center_lat").val().length!=0 && $("#center_lng").val() != "null" &&  $("#center_lng").val().length!=0 && $("#zoom").val() != "null" &&  $("#zoom").val().length!=0){    
			   
				var point = new BMap.Point(parseFloat($("#center_lng").val()),parseFloat($("#center_lat").val()));    // 创建点坐标
			
				baidMap.centerAndZoom(point,parseInt($("#zoom").val()));      // 初始化地图,设置中心点坐标和地图级别。
				
			}else{
			
				var point = new BMap.Point(104.01078,34.329978);    // 创建点坐标
			
				baidMap.centerAndZoom(5);      // 初始化地图,设置中心点坐标和地图级别。
			}
			
			
			baidMap.enableScrollWheelZoom();
			
			// 初始化地图，设置中心点坐标和地图级别
			baidMap.addControl(new BMap.NavigationControl());  //缩放轴
			baidMap.addControl(new BMap.OverviewMapControl());    //缩略图
			baidMap.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_SATELLITE_MAP ]})); //地图类型
			baidMap.enableScrollWheelZoom(); //启用滚轮放大缩小
			baidMap.addControl(new BMap.ScaleControl());   // 添加默认比例尺控件
	},
	destroy : function(){
	
	}
}

var queryToolObject={
	open : function(){
	
	},
	close : function(){
	
	},
	
	mapChange : function(){
		closeRectangShape();
		
		if($("#mapTypeSel").val()=="1"){
			mapType="1";
		}else{
			mapType="2";
		}
		
		if(mapType !="1"){
			if(typeof(google)=="undefined"){
	 			loadGoogleMapJs();
			}
			$("#center_lat").val(baidMap.getCenter().lat);
		    $("#center_lng").val(baidMap.getCenter().lng);
		    $("#zoom").val(baidMap.getZoom()-2);
		}else{
			$("#center_lat").val(googleMap.map.getCenter().lat());
		    $("#center_lng").val(googleMap.map.getCenter().lng());
		    $("#zoom").val(googleMap.map.getZoom()+2);
		}
		
		baidMap = null;
		googleMap.map = null;
		
		mapObject.init();
	}
}



var drawingManager=null;
var selectedShape;
var infowindow;
var loadingmarker=null;

var isOpenQuery =true;

var isQuery = false ;

function clearSelection() {

    drawingManager.setMap(null);

	if (selectedShape) {
		//selectedShape.setMap(null);
	}
	if (infowindow) {
		infowindow.close();
	}
	
	isOpenQuery=true;
}

function setSelection(shape) {
	//clearSelection();
	selectedShape = shape;
	//shape.setEditable(true);
}

function addRectangShape() {
	closeRectangShape();
	if($("#queryhistoryTime_startTime").val().length ==0){
		alert(areaquery.kssjbnwk);
		return;
	}
	
	if($("#queryhistoryTime_endTime").val().length ==0){
		alert(areaquery.jssjbnwk);
		return;
	}

	var days=$.fn.getDistanceDay($("#queryhistoryTime_startTime").val(),$("#queryhistoryTime_endTime").val());
	if(days>60){
	
		alert(areaquery.sjxz);
		
		return;
		
	}
	
	$("#queryBtn").val(areaquery.qxcx);
	
	$("#queryBtn").unbind( "click" );
	
	$("#queryBtn").click(function(){closeRectangShape();});
	
	
	if(mapType=="2"){
		initializeDraw();
		if(isOpenQuery){
		    
		    isQuery = true;
		    
			isOpenQuery=false;
			
			drawingManager.setMap(googleMap.map);
		}else{
			closeRectangShape();		
		}
	}else{
		initializeBaiduDraw();
		baidudrawingManager.open();
	}
	
}

function closeRectangShape(){
	isOpenQuery=true;
	isQuery = false ;
	//console.info("取消");
	if(mapType=="2"){
		//googleMap.init();
	}
	clearAll();
	stopAjaxRequest();
	if(loadingmarker){
		//loadingmarker.setMap(null);
	}
	
	$("#queryBtn").val(areaquery.dkcx);
	$("#queryBtn").click(function(){
		addRectangShape();
	});
	tool.tableobject.clearRow();
	
    if (selectedShape) {
		selectedShape.setMap(null);
	}
	if(drawingManager!=null){
		drawingManager.setMap(null);
	}
}

var curAreaQueryTime = null;
var isquery = false;

/**
	   加载地图初始化绘图控件
	  */
function initializeDraw() {
	if (typeof googleMap.map == "undefined" || googleMap.map == null) {
		setTimeout("initializeDraw()", 500);
		return;
	}
    
	drawingManager = new google.maps.drawing.DrawingManager({
		drawingControl: false, 
		drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
		polylineOptions: {
				 //editable:true, 
				 //draggable:true
				 }, 
		rectangleOptions : {
				strokeWeight:0, 
				fillOpacity:0.3, 
				fillColor:"blue",
				 //editable:true, 
				 draggable:true,
				 zIndex : 999
				 }
	});
		
	google.maps.event.addListener(drawingManager, "overlaycomplete", function (e) {
		var newShape = e.overlay;
		newShape.type = e.type;
		google.maps.event.addListener(newShape,'dragstart', function() {

				 if(infowindow!=null){
				 	infowindow.close();
				 	infowindow=null;
				 }
				if(loadingmarker!=null){	
					 loadingmarker.setMap(null);
				}
				isquery = false; 
        });
        google.maps.event.addListener(newShape, 'dragend', function() {
        	
			 if(loadingmarker!=null){
					 //loadingmarker.setMap(null);
			 }
			 curAreaQueryTime = new Date().getTime();
			 isquery = true;
			 setTimeout(function(){if(isquery){openInfowin(newShape);}},500);
        });
		
		setSelection(newShape);

		openInfowin(newShape);
		


		
		drawingManager.setMap(null);
		
	});
	
	google.maps.event.addListener(map, "mousedown", clearSelection);//去除选择
   
}


function closeAreaQuery() {
	 closeRectangShape();
}

function openInfowin(newShape) {
	
	if($("#queryhistoryTime_startTime").val().length ==0){
		alert(areaquery.kssjbnwk);
		return;
	}
	
	if($("#queryhistoryTime_endTime").val().length ==0){
		alert(areaquery.jssjbnwk);
		return;
	}

	var days=$.fn.getDistanceDay($("#queryhistoryTime_startTime").val(),$("#queryhistoryTime_endTime").val());
	
	if(days>60){
	
		alert(areaquery.sjxz);
		
		return;
		
	}
	
	loadingmarker = new queryVechileLoading(googleMap.map,"<div ><img src='"+$("#serverUrl").val()+Url.queryLoading+"'></img></div>",newShape.getBounds().getCenter());
	stopAjaxRequest();
	tool.tableobject.loadding();
	his_ajax=$.ajax({type:"POST",
	 dataType:"json", 
	 url:"json/vehicleAction_qycc.action", 
	 data:{"ids":"-1", 
	 	   "p.leftLat":newShape.getBounds().getSouthWest().lat(),
	 	   "p.leftLng":newShape.getBounds().getNorthEast().lng(),
	 	   "p.rightLat":newShape.getBounds().getNorthEast().lat(),
	 	   "p.rightLng":newShape.getBounds().getSouthWest().lng(),
	 	   "maptype":mapType,
	 	   "bedate":($("#queryhistoryTime_startTime").val()),
	 	   "endate":($("#queryhistoryTime_endTime").val())}, 
	 success:function (json) {
		if (json.flag == true) {
			tool.tableobject.addRow(json);
			excelArr = json.data;
		}else{
							alert(json.msg);
							if(json.statecode){
								if(json.statecode==10000){
									if($.browser.msie) { 
					                  location.href = "../login.jsp";
								   }else{
								      location.href = "./gpsonline/jsp/login.jsp";
								   }
								}
							}
						}
	
	}});
	
}

function queryVehciletoPlayBack(id,name,icon){
	
	if($("#queryhistoryTime_startTime").val().length ==0){
		alert(areaquery.kssjbnwk);
		return;
	}
	
	if($("#queryhistoryTime_endTime").val().length ==0){
		alert(areaquery.jssjbnwk);
		return;
	}

	var days=$.fn.getDistanceDay($("#queryhistoryTime_startTime").val(),$("#queryhistoryTime_endTime").val());
	
	if(days>60){
	
		alert(areaquery.sjxz);
		
		return;
		
	}	
	window.open($("#serverUrl").val()+"gpsonline/jsp/monitor/playBack.jsp?carid="+id+"&carname="+encodeURI(encodeURI(name))+"&icon="+icon+"&startTime="+$("#queryhistoryTime_startTime").val()+"&endTime="+$("#queryhistoryTime_endTime").val()+"&mapType="+mapType);
}
var his_ajax = null;
function stopAjaxRequest(){
	if(his_ajax){
		his_ajax.abort();
		his_ajax = null;
	}
}
function queryVechileLoading(map, text, latLng){
		 this.map_ = map;
		 this.text_ = text;
		 this.latLng_ = latLng;
		 this.div_ = null;
		 //this.setMap(map);
}
// 当准备将 悬浮层 添加到地图上时 调用
queryVechileLoading.prototype.onAdd = function(){
	 var div = document.createElement('DIV');
	 div.style.border = 'none';
	 div.style.position='absolute';   
	 div.innerHTML = this.text_;
	 this.div_ = div;	    
	 var panes = this.getPanes();
	 panes.overlayLayer.appendChild(div);
};
  
// 当第一次在地图上显示时 调用
queryVechileLoading.prototype.draw = function(){
	 var overlayProjection = this.getProjection();
	 var latLng = overlayProjection.fromLatLngToDivPixel(this.latLng_);
	 // 设置层的大小 和 位置
	 var div = this.div_;
	 var size = new google.maps.Size(17, -10); // 修正坐标的值;Size(width:number, height:number, widthUnit?:string, heightUnit?:string)
	 div.style.left = (latLng.x) + 'px';
	 div.style.top = (latLng.y) + 'px';
	 div.style.zIndex=9999;
};

// 当设置 悬浮层的 setMap(null) 会自动调用 
queryVechileLoading.prototype.onRemove = function(){
	 this.div_.parentNode.removeChild(this.div_);
	 this.div_ = null;
};
