var overlays = [];
var baiduinfoWindows = [];
var newRectangle;
var baiduinfoWindow=null;
var newLeftPointX;
var newLeftPointY;
var newRightPointX;
var newRightPointY;
var leftPointLng;
var leftPointLat;
var rightPointLng;
var rightPointLat;
var pointCenter;
var pointCenterNew;
var baidudrawingManager;
var baiduQueryVechileloading=null;
/*
*初始化百度地图区域查车
*/
function initializeBaiduDraw(){
	//矩形的样式
    var styleOptions = {
        strokeColor:"blue",    //边线颜色。
        fillColor:"blue",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 1,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.1,	   //边线透明度，取值范围0 - 1。
        fillOpacity: 0.3,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid'   //边线的样式，solid或dashed。
    }
    
    //实例化鼠标绘制工具
    baidudrawingManager = new BMapLib.DrawingManager(baidMap, {
        isOpen: false, 							//是否开启绘制模式
        drawingMode: BMAP_DRAWING_RECTANGLE,
        enableDrawingTool: false, 				//是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, 		//位置
            offset: new BMap.Size(5, 5), 		//偏离值
            scale: 0.8, 						//工具栏缩放比例
            drawingModes: [BMAP_DRAWING_RECTANGLE] 
        },
        rectangleOptions: styleOptions 			//矩形的样式
    });
    
    //添加鼠标绘制工具监听事件
	baidudrawingManager.addEventListener('overlaycomplete',function(e){
		overlays.push(e.overlay);
		baidudrawingManager.close();
		newRectangle = e.overlay;
		newRectangle.type = e.type;	
		
		var browser=navigator.appName
		var b_version=navigator.appVersion
		var version=parseFloat(b_version)
		var a = "Microsoft Internet Explorer";
		
		if(version <= 4 && a == browser){
		}else{
			Drag();
		}
	})
    
	//添加清空监听事件，清除当前记录
    baidMap.addEventListener('click', function(e){
    	if(e.point.lng < leftPointLng || e.point.lng > rightPointLng || e.point.lat > rightPointLat || e.point.lat < leftPointLat){
    		clearAll();
    	}
    });

    //添加矩形绘画完成监听事件，用于信息窗的弹出
    baidudrawingManager.addEventListener("rectanglecomplete", function(overlay){
    	pointCenter = overlay.getBounds().getCenter();	
    	

    	
    	leftPointLng = overlay.getBounds().getSouthWest().lng;
    	leftPointLat =  overlay.getBounds().getSouthWest().lat;
		rightPointLng = overlay.getBounds().getNorthEast().lng;		
		rightPointLat =  overlay.getBounds().getNorthEast().lat;
    	
    	openInfo(pointCenter)
    }); 
}
var excelArr =[];
function queryDateExcel(){
	var tbBody="";
	var excelname = Date.parse(new Date());
	$("#excelOutTable").empty();
	if(excelArr.length ==0){
		alert("没有查询结果!");
		return ;
	}
	for ( var i = 0; i < excelArr.length; i++){
		if(i==0)
		tbBody = "<tr><td>车牌号码</td><td>设备编号</td><td>SIM卡号</td></tr>";
		else tbBody="";
		tbBody +="<tr><td>"+excelArr[i][1]+"</td><td><span style='display:none'>'</span>"+excelArr[i][2].toString()+"</td><td><span style='display:none'>'</span>"+excelArr[i][3]+"</td></tr>"
		$("#excelOutTable").append(tbBody);
	}
	
	$("#excelOutTable").table2excel({
		exclude: ".link_style",
		name:"Excel Document Name",
		filename:excelname,
		exclude_img: true,
		exclude_links: false,
		exclude_inputs: true
	});
}
function Drag(){
	var mouseStartX = 0;
	var mouseStartY = 0;
	var mouseEndX = 0;
	var mouseEndY = 0;
	var xChange = 0;
	var yChange = 0;
	var temp1 = false;
	var temp2 = false;
	newRectangle.addEventListener('mousedown',function(e){
		if(e.point.lng > leftPointLng && e.point.lng < rightPointLng && e.point.lat < rightPointLat && e.point.lat > leftPointLat){
			temp1 = true;
			baidMap.disableDragging();
			mouseStartX = e.point.lng;
			mouseStartY = e.point.lat;
			baidMap.removeOverlay(baiduQueryVechileloading);
			newRectangle.addEventListener('mousemove',function(e){
				if(temp1){
					temp2 = true;
					mouseEndX = e.point.lng;
					mouseEndY = e.point.lat;
					xChange = mouseEndX-mouseStartX;
					yChange = mouseEndY-mouseStartY;
					newRightPointX = rightPointLng+xChange;
					newRightPointY = rightPointLat+yChange;
					newLeftPointX = leftPointLng+xChange;
					newLeftPointY = leftPointLat+yChange;					
					drawNewR(newLeftPointX,newLeftPointY,newRightPointX,newRightPointY);
					isquery = false;
		
				}
				newRectangle.addEventListener('mouseup',function(e){
					if(e.point.lng > newLeftPointX && e.point.lng < newRightPointX && e.point.lat < newRightPointY && e.point.lat > newLeftPointY){
						leftPointLng = newLeftPointX;
						rightPointLng = newRightPointX;
						leftPointLat = newLeftPointY;
						rightPointLat = newRightPointY;
						//最终矩形区域的两点经纬度
						/*document.getElementById("showPane1").innerHTML = newRectangle.getPath()[3].lng;
						document.getElementById("showPane2").innerHTML = newRectangle.getPath()[3].lat;
						document.getElementById("showPane3").innerHTML = newRectangle.getPath()[1].lng;
						document.getElementById("showPane4").innerHTML = newRectangle.getPath()[1].lat;*/
						baidMap.enableDragging();
						if(temp2){
							pointCenterNew = newRectangle.getBounds().getCenter();
							
							 
							 curAreaQueryTime = new Date().getTime();
			 
							 isquery = true;
							 
							 setTimeout(function(){if(isquery){openInfo(pointCenterNew);}},500);
							 
							mapMove();		
							temp1 = false;
							temp2 = false;
					}
					}
				})
			})
		}
	})
}	

//设置矩形变动后的点坐标
function drawNewR(leftX,leftY,rightX,rightY){
	newRectangle.setPath([
		new BMap.Point(leftX,rightY),
		new BMap.Point(rightX,rightY),
		new BMap.Point(rightX,leftY),
		new BMap.Point(leftX,leftY)
	])
}

//地图平移
function mapMove(){
	var bs = baidMap.getBounds();
	var mapCenterX = baidMap.getBounds().getCenter().lng;
	var mapCenterY = baidMap.getBounds().getCenter().lat;
	var mapCenterNewX = newRectangle.getBounds().getCenter().lng;
	var mapCenterNewY = newRectangle.getBounds().getCenter().lat;
	var leftDownXover = newLeftPointX - bs.getSouthWest().lng;
	var leftDownYover = newLeftPointY - bs.getSouthWest().lat;
	var rightUpXover = newRightPointX - bs.getNorthEast().lng;
	var rightUpYover = newRightPointY - bs.getNorthEast().lat;
	//左
	if(leftDownXover < 0 && leftDownYover > 0 && rightUpYover < 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//下
	if(leftDownYover < 0 && leftDownXover > 0 && rightUpXover < 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//右
	if(rightUpXover > 0 && leftDownYover > 0 && rightUpYover < 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//上
	if(rightUpYover > 0 && leftDownXover > 0 && rightUpXover < 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//左下
	if(leftDownXover < 0 && leftDownYover < 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//左上
	if(leftDownXover < 0 && rightUpYover > 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//右下
	if(rightUpXover > 0 && leftDownYover < 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
	//右上
	if(rightUpXover > 0 && rightUpYover > 0){
		setTimeout(function(){
			baidMap.panTo(new BMap.Point(mapCenterNewX,mapCenterNewY));
		}, 300);
	}
}
//清空记录
function clearAll() {
	
	if(typeof baidMap !="undefined" && baidMap!=null){
	
	    for(var i = 0; i < overlays.length; i++){
	    	baidMap.removeOverlay(overlays[i]);
	    }
	    
	    overlays.length = 0;
	    
	    if(baiduQueryVechileloading!=null){
	    	baidMap.removeOverlay(baiduQueryVechileloading);
	    }

	    if(baidudrawingManager){
	    	baidudrawingManager.close();
	    }
    }
}

//信息浮窗
function openInfo(point){
	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;
		
	}
	
	var opts = {
				  position : point,    // 指定文本标注所在的地理位置
				  offset   : new BMap.Size(0, -10)    //设置文本偏移量
				 
				}
	baiduQueryVechileloading = new BMap.Label("<img src='"+$("#serverUrl").val()+Url.queryLoading+"'></img>", opts);  // 创建文本标注对象
	
	baiduQueryVechileloading.setStyle({
		  backgroundColor : "",
		  border : "0px",
		 fontSize : "12px",
		 height : "16px",
		 lineHeight : "16px",
		 fontWeight:"bold",
		 fontFamily:""
	});
	
	baidMap.addOverlay(baiduQueryVechileloading); 

	var cars = $("#ids").val();
//	console.info(cars);
	if(typeof(cars)=="undefined"){
		cars = "-1";
	}
	var content="<div class='baiduboxcontent_areaQuery'><p>";
		his_ajax=$.ajax({type:"POST",
		 dataType:"json",
		 async:false,
		 url:"json/vehicleAction_qycc.action",
		 data:{"ids":cars,
		 	   "p.leftLat":leftPointLat,
		 	   "p.leftLng":leftPointLng, 
		 	   "p.rightLat":rightPointLat,
		 	   "p.rightLng":rightPointLng,
		 	   "maptype":mapType,
		 	   "bedate":($("#queryhistoryTime_startTime").val()),
		 	   "endate":($("#queryhistoryTime_endTime").val()),
		 	   "timestamp":0},
	    success:function(json){
//		 	console.info(JSON.stringify(json));
			if (json.flag == true){
				tool.tableobject.addRow(json);
				excelArr = json.data;
				baidMap.removeOverlay(baiduQueryVechileloading);
			}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";
								   }
								}
							}
						}
			}});
}