/*
 *调度页面使用的百度地图标注
 **/
(function(){
	
	var markerBDArr = [];
	
	var tempPolygon = null;
	
	var infoWin = null;
	
	var tempMarker = null;
	
	function open(id, isCenter){
		var curMarkerObj = markerObject.markerArr[id];
		markerBDArr[id] = {};	
			
		var point = googleToBaidu(curMarkerObj.lng, curMarkerObj.lat);
		
		var marker = new BMap.Marker(point, {icon: new BMap.Icon(curMarkerObj.icon, new BMap.Size(35,35))});
		marker.setTitle(id);		
		baidMap.addOverlay(marker);		
		
		if(isCenter != false) baidMap.centerAndZoom(point, 15);
		
		if($("#bzcheckbox").is(":checked")){
			
			var opts = {  position : point,    // 指定文本标注所在的地理位置
						  offset   : new BMap.Size(15, -10)   //设置文本偏移量
					   };
			
			var lable = new BMap.Label(curMarkerObj.title, opts);  // 创建文本标注对象
			lable.setStyle({
				 color : "#000000",
				 backgroundColor : "#f5fcb8",
				 borderColor : "#000000",
				 fontSize : "12px",
				 height : "16px",
				 lineHeight : "16px",
				 fontWeight:"bold",
				 fontFamily:""
			});
			
			baidMap.addOverlay(lable); 
			
			markerBDArr[id].lable = lable;
		}
		
		var pStart;
		var pEnd;
		if(curMarkerObj.area == null){
			pStart = new BMap.Point(0,0);
			pEnd = new BMap.Point(0,0);
		}else{		
			pStart = getAreaNELatLngBaidu(curMarkerObj.lat, curMarkerObj.lng, curMarkerObj.areaRadius);
			pEnd = getAreaSWLatlngBaidu(curMarkerObj.lat, curMarkerObj.lng, curMarkerObj.areaRadius);			
		}
		
		var polygon = new BMap.Polygon([googleToBaidu(pStart.lng,pStart.lat),
							              googleToBaidu(pEnd.lng,pStart.lat),
							              googleToBaidu(pEnd.lng,pEnd.lat),
							              googleToBaidu(pStart.lng,pEnd.lat)
							          ], {strokeColor:"blue",fillColor:"blue", strokeWeight:2, strokeOpacity:0.5});
		
		baidMap.addOverlay(polygon);
		
		
		
		marker.addEventListener("click", function(e){
			var markerId = e.target.getTitle();
			var curMarkerObj =markerObject.markerArr[markerId];
			
			var html = "<div style='font-weight:normal;'><b>名称：</b>"+curMarkerObj.title+"</br>"
					+"<b>描述：</b>"+curMarkerObj.text+"</br>"
					+"<b>经度：</b>"+curMarkerObj.lat.toFixed(6)+"</br>"
					+"<b>纬度：</b>"+curMarkerObj.lng.toFixed(6)+"</br>";
	
			var htm="<a href='javascript:openUpdateMarkerWin("+markerId+");'><font color='#0000FF'>修改</font></a></div>"; 
			if(curMarkerObj.competence==1){
				html=html+htm;
			}else{
				html=html+"</div>";
			}
			
			infoWin = new BMap.InfoWindow(html);
			
			this.openInfoWindow(infoWin);		
		});
		
		marker.enableDragging();
		marker.addEventListener("dragging",function(e){
			
			var markerId = e.target.getTitle();
			
			if(tempMarker && tempMarker.id != markerId) {
				hide(tempMarker.id);
				open(tempMarker.id, false);
				tempMarker = null;
			}
			
			tempMarker = markerObject.markerArr[id];//保存google,百度地图公用对象
			
			var curMarkerObj = markerBDArr[markerId];
			var point = e.point;
			
			if(curMarkerObj.lable) curMarkerObj.lable.setPosition(point);
			
			if(curMarkerObj.polygon){
				
				var pStart;
				var pEnd;
				
				if(tempMarker.area == null){
					pStart = new BMap.Point(0,0);
					pEnd = new BMap.Point(0,0);
				}else{		
					pStart = getAreaNELatLngBaidu(point.lat, point.lng, tempMarker.areaRadius);
					pEnd = getAreaSWLatlngBaidu(point.lat, point.lng, tempMarker.areaRadius);			
				}
				
				curMarkerObj.polygon.setPath([new BMap.Point(pStart.lng,pStart.lat),
								              new BMap.Point(pEnd.lng,pStart.lat),
								              new BMap.Point(pEnd.lng,pEnd.lat),
								              new BMap.Point(pStart.lng,pEnd.lat)]);
			}
			
			var html= "<div style='font-weight:normal;'><b>名称：</b>"+tempMarker.title+"</br>"
					+"<b>描述：</b>"+tempMarker.text+"</br>"
					+"<b>经度：</b>"+point.lat+"</br>"
					+"<b>纬度：</b>"+point.lng+"</br>";
				
			var htm="<a href='javascript:openUpdateMarkerWin("+id+");' style=\"display:none;\"><font color='#0000FF'>修改 |</font></a><a id=\"marcker_move_position_save_btn\" href='javascript:MarkerBD.savePosition("+e.target.getTitle()+");'><font color='#0000FF'>保存 | </font></a><a id=\"marcker_move_position_cancle_btn\" href='javascript:MarkerBD.cancleMove("+e.target.getTitle()+");'><font color='#0000FF'>取消</font></a></div>";// | <a href='javascript:deleteMarker("+markersJson.data[i].id+");' ><font color='#0000FF'>删除</font></a> 
			if(tempMarker.competence==1){
				html=html+htm;
			}else{
				html=html+"<a id=\"marcker_move_position_save_btn\" href='javascript:MarkerBD.savePosition("+e.target.getTitle()+");'><font color='#0000FF'>保存 | </font></a><a id=\"marcker_move_position_cancle_btn\"  href='javascript:MarkerBD.cancleMove("+e.target.getTitle()+");'><font color='#0000FF'>取消</font></a></div>";
			}
			
			//if(infoWin == null){
				infoWin = new BMap.InfoWindow(html);
				this.openInfoWindow(infoWin);	
				infoWin.addEventListener("clickclose",function(e){
					hide(markerId);
					open(markerId, false);
				});
				 	
			//}else{			
			//	infoWin.setContent(html);	
			//}
			
			$("#rigthlat").val(pStart.lat);
			$("#rigthlng").val(pStart.lng);
			$("#leftlat").val(pEnd.lat);
			$("#leftlng").val(pEnd.lng);
			
			$("#markerlat").val(point.lat);							
	    	$("#markerlng").val(point.lng);
				
		});
		
		markerBDArr[id].marker = marker;
		markerBDArr[id].polygon = polygon;
	}
	
	function hide(id){
		var curMarkerObj = markerBDArr[id];
		if(curMarkerObj){
			if(curMarkerObj.marker) baidMap.removeOverlay(curMarkerObj.marker);
			if(curMarkerObj.polygon) baidMap.removeOverlay(curMarkerObj.polygon);
			if(curMarkerObj.lable) baidMap.removeOverlay(curMarkerObj.lable);
			
			curMarkerObj = null;
		}
	}
	
	function showName(){
		var curMarkerObj = null;
		for(var i in markerBDArr){
			if(i == "myUnique") break;
			curMarkerObj = markerBDArr[i];			
			if(treeObj.getNodeByParam("id", i).checked){
				if(curMarkerObj.lable) baidMap.removeOverlay(curMarkerObj.lable);
				var point = googleToBaidu(markerObject.markerArr[i].lng, markerObject.markerArr[i].lat);
				var opts = {  position : point,    // 指定文本标注所在的地理位置
						      offset   : new BMap.Size(15, -10)  //设置文本偏移量
				};
			
				var lable = new BMap.Label(markerObject.markerArr[i].title, opts);  // markerObject.markerArr google标注的标注集合对象
				lable.setStyle({
					 color : "#000000",
					 backgroundColor : "#f5fcb8",
					 borderColor : "#000000",
					 fontSize : "12px",
					 height : "16px",
					 lineHeight : "16px",
					 fontWeight:"bold",
					 fontFamily:""
				});
				
				baidMap.addOverlay(lable); 
				
				markerBDArr[i].lable = lable;
			}
		}
	}
	
	function hideName(){
		var curMarkerObj = null;
		for(var i in markerBDArr){
			if(i == "myUnique") break;
			curMarkerObj = markerBDArr[i];
			if(curMarkerObj.lable) baidMap.removeOverlay(curMarkerObj.lable);				
		}
	}
	
	function removePolygon(){
	
		if(tempPolygon != null) baidMap.removeOverlay(tempPolygon);
	}
	
	function updatePolygon(pStart,pEnd){
	
		removePolygon();
		
		var polygon = new BMap.Polygon([googleToBaidu(pStart.lng(),pStart.lat()),googleToBaidu(pEnd.lng(),pStart.lat()), googleToBaidu(pEnd.lng(),pEnd.lat()),googleToBaidu(pStart.lng(),pEnd.lat())], {strokeColor:"blue",fillColor:"blue", strokeWeight:2, strokeOpacity:0.5});
		
		baidMap.addOverlay(polygon);
		
		tempPolygon = polygon;
	}
	
	function updatePolygonById(pStart, pEnd, id){
	
		var curMarkerObj = markerBDArr[id];
		if(curMarkerObj.polygon) baidMap.removeOverlay(curMarkerObj.polygon);
		
		var polygon = new BMap.Polygon([googleToBaidu(pStart.lng(),pStart.lat()),googleToBaidu(pEnd.lng(),pStart.lat()), googleToBaidu(pEnd.lng(),pEnd.lat()),googleToBaidu(pStart.lng(),pEnd.lat())], {strokeColor:"blue",fillColor:"blue", strokeWeight:2, strokeOpacity:0.5});
		
		baidMap.addOverlay(polygon);
		
		curMarkerObj.polygon = polygon;
	}
	
	function savePosition(id){
	
		var curMarkerObj = markerBDArr[id];
		
		var latlng= baiduToGoogle(curMarkerObj.marker.getPosition().lng, curMarkerObj.marker.getPosition().lat);
		
		var pStart = getAreaNELatLng(latlng.lat,latlng.lng,tempMarker.areaRadius);
	
		var pEnd = getAreaSWLatlng(latlng.lat,latlng.lng,tempMarker.areaRadius);
		
		$.ajax({
	        type: "POST",
	        dataType: "json",
	        async:true,
	        url: "json/markerAction_addOrUpdateUserMarker.action",
	        data:{"id":id,"lng":latlng.lat,"lat":latlng.lng,"leftLat":pEnd.lat(),"leftLon":pEnd.lng(),"rightLat":pStart.lat(),"rightLon":pStart.lng(),"title":tempMarker.title,"text":tempMarker.text,"icon":tempMarker.icon,"groupid":tempMarker.groupid,"radius":tempMarker.areaRadius,"bzType":tempMarker.bzType,"customerNum":tempMarker.markcode,"mapType":2},	        
	        success: function(json) {		         
		         if (json.flag==true) {
		         
					tempMarker.lat=json.data[0].lng2;
			  		tempMarker.lng=json.data[0].lat2;

				  	tempMarker.areaRadius=json.data[0].userMarkerArea.markerRadius;
				  	
				  	for(var i=0;i<markerObject.markerJson.data.length;i++){
	                	  if(json.data[0].id==markerObject.markerJson.data[i].id){
								markerObject.markerJson.data.remove(i);
								break;
						  }
	                }					  	 
				    markerObject.markerJson.data.push(json.data[0]);
				    
				  	hide(id);
				  	open(id,false);
				  	
	             }else{
	             	$("#updatePositionMsg").val("*"+json.msg);
	             	
	             }
	        },
	        error: function() {}
	   });	
	}
	
	function cancleMove(id){
	
		hide(id);
		open(id, false);
	}
	
	function showCheckedMarkers(){
		
		var nodes = treeObj.getCheckedNodes(true);
	
		for(var i=0;i<nodes.length;i++){
			if(!nodes[i].isParent){
				MarkerBD.hide(nodes[i].id);
				MarkerBD.open(nodes[i].id, false);									
			}
		}
	}
	
	/*util*/
	function googleToBaidu(glng,glat) {
	
		var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		
		var x = glng, y = glat;
		var z =Math.sqrt(x * x + y * y) + 0.00002 *Math.sin(y * x_pi);
		var theta =Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		var lng = z *  Math.cos(theta) + 0.0065;
		var lat = z *  Math.sin(theta) + 0.006;
		var myLatlng = new BMap.Point(lng,lat);
		
		return myLatlng;
		
	}
	function baiduToGoogle(blng,blat) {
	
		var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		var lng=blng;
		var lat=blat;
		var x = lng - 0.0065, y = lat - 0.006;
		var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		lng = z * Math.cos(theta);
		lat = z * Math.sin(theta);
		var obj=new Object();
		obj.lng=lng;
		obj.lat=lat;
		return obj;
	}
	
	function getAreaNELatLngBaidu(lat_,lng_,len_){
		var dlat = len_/111.0/1000.0;
		var dlng = len_/85.567/1000.0;
		return new BMap.Point(lng_+dlng,lat_-dlat);
	}
	
	function getAreaSWLatlngBaidu(lat_,lng_,len_){
		var dlat = len_/111.0/1000.0;
		var dlng = len_/85.567/1000.0;
		return new BMap.Point(lng_-dlng,lat_+dlat);
	}
	/*util/*/
	
	window.MarkerBD = {
		open : open,
		hide : hide,
		showName : showName,
		hideName : hideName,
		removePolygon : removePolygon,
		updatePolygon : updatePolygon,
		updatePolygonById : updatePolygonById,
		savePosition : savePosition,
		cancleMove : cancleMove,
		showCheckedMarkers : showCheckedMarkers
	};
	
})();