/**
* 封装 GOOGLE 地图 API
*/
//;;;var iterate = function (obj){	s="遍历对象"+obj+"的属性：\n";	for(i in obj)	s+=i+":"+obj[i]+"\n";	return s;};
var MapApi = function(){
	var arg = arguments;
	var cont = 'mapObj';
	var lat = 39.917;
	var lng = 116.397;
	var zoom = 14;
	for(var i=0; i<arg.length; i++)
	{
		if(0 == i) cont = arg[0];
		else if(1 == i) lat = arg[1];
		else if(2 == i) lng = arg[2];
		else if(3 == i) zoom = arg[3];
	}

	this.isClick = 0;
	this.viewAuto = false;

	this._map = new GMap2(document.getElementById(cont));
	this.citycenter = new GLatLng(lat,lng);
	this._map.setCenter(this.citycenter, zoom);

	var customUI = this._map.getDefaultUI();
	customUI.maptypes.hybrid = false;
	customUI.maptypes.physical = false;
	customUI.maptypes.satellite = false;
	G_NORMAL_MAP.getMinimumResolution = function(){return 10;};
	G_NORMAL_MAP.getMaximumResolution = function(){return 18;};
	G_SATELLITE_MAP.getMinimumResolution = function(){return 10;};
	G_SATELLITE_MAP.getMaximumResolution = function(){return 18;};
	this._map.setUI(customUI);
	this._map.enableScrollWheelZoom();
	this._map.addControl(new GOverviewMapControl());
	this._map.addControl(new GScaleControl());
	//this._map.addControl(new GMapTypeControl(true));
	//this._map.removeMapType(G_HYBRID_MAP);

	this._markerManager = new MarkerManager(this._map);
};

//MapApi.ZOOM_MAX = 19;
MapApi.ZOOM_MIN = 10;

MapApi.prototype.addEvent = function(obj, eve, motion)
{
	if(obj === this) obj = this._map;
	return GEvent.addListener(obj, eve, motion);
};
MapApi.prototype.removeEvent = function(handler)
{
	GEvent.removeListener(handler);
};
MapApi.prototype.enableScrollWheel = function()
{
	var map = this._map;
	map.enableScrollWheelZoom();
};
MapApi.prototype.gethdBounds = function()
{
	var map = this._map;
	var bounds = map.getBounds();
	var sw0 = bounds.getSouthWest();
	var ne0 = bounds.getNorthEast();
	var pointSw = map.fromLatLngToContainerPixel(sw0);
	var sw = map.fromContainerPixelToLatLng(new GPoint(pointSw.x+8, pointSw.y-8));
	var pointNe = map.fromLatLngToContainerPixel(ne0);
	var ne = map.fromContainerPixelToLatLng(new GPoint(pointNe.x-8, pointNe.y+8));
	return {'hdx1':sw.lng(),'hdx2':ne.lng(),'hdy1':sw.lat(),'hdy2':ne.lat()};
};
MapApi.prototype.setTipId = function(newCode)
{
	this.isClick = newCode;
};
MapApi.prototype.drawMarkers = function(metaMarkers)
{
	var me = this;
	var map = me._map;
	var mm = me._markerManager;
	var bounds = new GLatLngBounds();
	var counter = 0;
	//
	for(var i=0; i<metaMarkers.length; i++)
	{
		var info = metaMarkers[i];
		if(!info.y || !info.x || Math.abs(info.y*1)>90 || Math.abs(info.x*1)>180) continue;
		bounds.extend(new GLatLng(info.y, info.x));
		
		
		
		var marker = me.createMarker(info);
		marker.provalue = info;
		map.addOverlay(marker);
		counter ++;
	}
	//alert(bounds.getSouthWest().toString()+';'+bounds.getNorthEast().toString());
	//mm.refresh();
	if(counter > 0) me.panMap(bounds);
};
MapApi.prototype.setMapType = function(mType)
{
	this._map.setMapType(mType);
};
MapApi.prototype.clearMarkers = function()
{
	this._markerManager.clearMarkers();
};
MapApi.prototype.clearOverlays = function()
{
	this._map.clearOverlays();
	this.closeTip();
};
//注意对地图进行移动操作时，如果不想重新搜索，应该先把SFMap中的isDragend置成false
//重新设置地图中心点
MapApi.prototype.setCenter = function(y,x,zoom)
{
	if(!y || !x) return;
	var zoom = zoom || this._map.getZoom();
	this._map.setCenter(new GLatLng(y,x),zoom);
};
MapApi.prototype.panTo = function(y,x)
{
	if(!y || !x) return;
	this._map.panTo(new GLatLng(y,x));
};
MapApi.prototype.createMarker = function(info)
{
	var me = this;
	var map = me._map;
	var mm = me._markerManager;
	var latLng = new GLatLng(info.y,info.x);
	if ('undefined' != typeof(info.isAD) && info.isAD == 1)
	{
		var lclass = "mapFinddingCanvasLabelStyle8";
		var ltext = '<table id="tip'+info.newCode+'" cellspacing="0" cellpadding="0" border="0" id="tip"><tbody><tr><td class="s1">&nbsp;</td><td class="s2"><strong>'+info.title+'</strong><br><span>'+info.tel400+'</span></td><td class="s3">&nbsp;</td></tr><tr><td class="s5" colspan="3"></td></tr></tbody></table>';	
		var offset_new = new GSize(0,-53);
	}
	else
	{
		var lclass = "mapFinddingCanvasLabelStyle3";
		var sTc = {'0':'0', '1':'1', '2':'2'};
		if('undefined' != typeof(info.saling) && 'undefined' != typeof(sTc[info.saling]))
		{
			lclass = 'mapFinddingCanvasLabelStyle' + sTc[info.saling];
		}
		var ltext = '<table  cellpadding=0 cellspacing=0 border=0><tr><td class="s1">&nbsp;</td><td class="s2">'+info.title+'</td><td class="s3">&nbsp;</td></tr><tr><td colspan="3" class="s5">&nbsp;</td></tr></table>';
		//var ltext = '<div class="s1"></div><div class="s2" id="tip'+info.newCode+'">'+info.title+'</div><div class="s3"></div><div class="s4"></div><div class="s5"></div>';
		var offset_new = new GSize(0,-40);
	}
	
	var marker = new ComplexCustomOverlay(latLng,this,info,{/*icon:icon,*/labelText:ltext,labelClass:lclass,labelOffset:offset_new,pointer:new BMap.Point(info.y,info.x)});//原-25,-40
	//marker.disableDragging();
	//var newCode = info.newCode;
	
	return marker;
};
//隐藏标点的 DIV 元素
//newCode 楼盘 ID
MapApi.prototype.hideMarker = function(newCode)
{
	var nodeId = 'tip'+newCode;
	var mNode = $id(nodeId);
	if(mNode)
	{
		var domMark = mNode.parentNode;
		domMark.style.display='none';
	}
};
MapApi.prototype.hoverMarker = function(obj,provalue, flg)
{
	var me = this;
	var map = me._map;
	var mm = me._markerManager;
	if(!obj.div_) return;
	if(flg){
		if(me.isClick == provalue.newCode)
		{
			obj.div_.style.zIndex=500;
		}
		else
		{
			obj.div_.style.zIndex=501;
		}
		if (obj.div_.className != "mapFinddingCanvasLabelStyle8")
		{
			obj.div_.className="mapFinddingCanvasLabelStyle5";
		}
		
	}
	else
	{
		if(me.isClick != provalue.newCode)
		{
			var mIndex = GOverlay.getZIndex(obj.pointer_.lat);
			obj.div_.style.zIndex = mIndex;
			if (obj.div_.className != "mapFinddingCanvasLabelStyle8")
			{
				var lclass = "mapFinddingCanvasLabelStyle3";
				var sTc = {'0':'0', '1':'1', '2':'2'};
				if('undefined' != typeof(provalue.saling) && 'undefined' != typeof(sTc[provalue.saling]))
				{
					lclass = 'mapFinddingCanvasLabelStyle' + sTc[provalue.saling];
				}
				obj.div_.className = lclass;
			}
			map.enableDragging();
		}
	}
};
MapApi.prototype.openTip = function(obj,provalue)
{
	var me = this;
	var map = me._map;
	var mm = me._markerManager;
	var node = $id('maptip');
	if('undefined' == typeof provalue.newCode) return; 
	//alert(iterate(marker.div_.offsetParent));
	//me.getMarkerById(marker.provalue.newCode);
	if(0 != me.isClick && provalue.newCode != me.isClick)
	{
		me.closeTip();
	}
	if(provalue.newCode == me.isClick)
	{
		return;
	}
	var mapBounds = map.getBounds();
	var point = new GLatLng(provalue.y, provalue.x);
	if(!mapBounds.containsLatLng(point))
	{
		if('undefined' != typeof(SFMap.isDragend))
		{
			var isDragendSave = SFMap.isDragend;
			SFMap.isDragend = false;
		}
		//setCenter的执行速度要比panTo快很多
		map.setCenter(point);
		if('undefined' != typeof(SFMap.isDragend))
		{
			SFMap.isDragend = isDragendSave;
		}
	}
	me.isClick = provalue.newCode;
	//alert(iterate(marker.provalue));
	var content = SFUI.templateFetch($id('template_maptip').value, provalue);
	//alert(content);
	node.innerHTML = content;
	node.style.display = 'block';
	var mapNode = $id('map_canvas');
	var mapHeight = mapNode.offsetHeight;
	var topPx = 0;
	var leftPx = 0;
	var nodeWidth = node.offsetWidth;
	var nodeHeight = node.offsetHeight;
	var atLeft = true;
	var pixel = me._map.fromLatLngToContainerPixel(point);
	if(pixel.y > nodeHeight - 27)
	{
		topPx = pixel.y - nodeHeight + 27;
		if(topPx+nodeHeight > mapHeight) topPx = mapHeight - nodeHeight;
	}
	else
	{
		topPx = 3;
	}
	if(pixel.x > nodeWidth + 12)
	{
		leftPx = pixel.x - nodeWidth - 12;
	}
	else
	{
		leftPx = pixel.x + 12;
		atLeft = false;
	}
	node.style.top = topPx+'px';
	node.style.left = leftPx+'px';
	var qipaojt = document.getElementById('qipaojt');
	if(qipaojt)
	{
		qipaojt.className = atLeft ? 'qipaojt2' : 'qipaojt1';
		var jtTop = pixel.y - topPx - 8;
		if(jtTop > 7)
		{
			if(jtTop > nodeHeight-27) jtTop = nodeHeight - 27;
		}
		else
		{
			jtTop = 7;
		}
		qipaojt.style.top = jtTop+'px';
	}
	me.hoverMarker(obj,provalue,true);
	var newCode = provalue.newCode;
	if(newCode && SFMap.markerList[newCode])
	{
		SFMap.markerList[newCode].onCloseTip = function(){me.hoverMarker(obj,provalue,false);};
	}
};
MapApi.prototype.closeTip = function()
{
	var me = this;
	var node = $id('maptip');
	var newCode = me.isClick;
	me.isClick = 0;
	if(node)
	{
		node.style.display = 'none';
		node.innerHTML = '';
	}
	if(newCode && SFMap.markerList[newCode])
	{
		SFMap.markerList[newCode].onCloseTip();
	}
};
MapApi.prototype.panMap = function(markerBounds)
{
	var me = this;
	var map = me._map;
	var mm = me._markerManager;
	var center = markerBounds.getCenter();
	if(me.viewAuto)
	{
		var zoom = map.getBoundsZoomLevel(markerBounds);
		me.viewAuto = false;
	}
	else
	{
		var mapBounds = map.getBounds();
		//alert(mapBounds.getSouthWest().toString()+';'+mapBounds.getNorthEast().toString());
		if(mapBounds.containsBounds(markerBounds))
		{
			//alert('not pan');
			return;
		}
		//alert('pan');
		var zoomt = map.getBoundsZoomLevel(markerBounds);
		//alert(zoomt);
		var zoomn = map.getZoom();
		var zoom = (zoomt < zoomn) ? zoomt : zoomn;
	}
	//if(zoom > MapApi.ZOOM_MAX) zoom = MapApi.ZOOM_MAX;
	if(zoom < MapApi.ZOOM_MIN)
	{
		//如果缩放的太小，就把比例设成最小的，中心点设为城市的中心点
		zoom = MapApi.ZOOM_MIN;
		center = this.citycenter;
	}
	map.setCenter(center,zoom);
};
MapApi.prototype.addKeyMarker = function(info)
{
	
};
MapApi.prototype.setViewAuto = function(flg)
{
	this.viewAuto = flg;
};
MapApi.prototype.setZoom = function(zoom)
{
	var zoom = parseInt(zoom);
	this._map.setZoom(zoom);
};
MapApi.prototype.drawLine = function(linexy, pan)
{
	var pan = pan ? true : false;
	var me = this;
	var map = me._map;
	var linexys = linexy;

	var lineNodes = linexys.split(';');
	var polyline = [];
	var counter = 0;
	for(var ln=0;ln<lineNodes.length;ln=ln+2)
	{
		if(!lineNodes[ln] || !lineNodes[ln+1]) continue;
		var vertex =  new GLatLng(lineNodes[ln+1],lineNodes[ln]);
		polyline.push(vertex);
		counter ++;
	}

	var polylines = new GPolyline(polyline, '#ff0000' , 6, 1);
	var bounds = polylines.getBounds();
	map.addOverlay(polylines);

	//pan为true并且有线路时，移动地图
	if(pan && counter > 0)
	{
		me.viewAuto = true;
		me.panMap(bounds);
	}
};
MapApi.prototype.createSubwayMarker = function(subwayTemp)
{
	var me = this;
	var gSmallIcon = new GIcon();
	var dotphoto = imgPath+'site.png';
	gSmallIcon.image = dotphoto;
	gSmallIcon.shadow = dotphoto;
	gSmallIcon.iconSize = new GSize(12, 12);
	gSmallIcon.shadowSize = new GSize(12, 12);
	gSmallIcon.iconAnchor = new GPoint(12, 12);
	gSmallIcon.infoWindowAnchor = new GPoint(5, 1);

	//var subwayTempArr = subwayTemp.split(',');
	var latlng = new GLatLng(parseFloat(subwayTemp[2]),parseFloat(subwayTemp[1]));
	var marker = new GMarker(latlng, gSmallIcon);
	var sContent = '<div class="subwayneme">'+subwayTemp[0]+'</div>';
	var station = document.getElementById('subway_station_tip');
	var container = me._map.getContainer();
	var point = me._map.fromLatLngToContainerPixel(latlng);
	if(!station)
	{
		station = document.createElement('div');
		station.id = 'subway_station_tip';
		container.appendChild(station);
	}

	GEvent.bind(marker, 'mouseover', this, function() {
		var newpoint = me._map.fromLatLngToContainerPixel(latlng);
		station.innerHTML = sContent;
		station.style.display = 'block';
		station.style.top = (newpoint.y-station.offsetHeight-12)+'px';
		station.style.left = (newpoint.x-6)+'px';
		//station.onclick = function(){this.style.display = 'none';};
		//marker.openInfoWindow(sContent);
	});
	GEvent.bind(marker, 'mouseout', this, function() {
		if(station) station.style.display = 'none';
	});
	if('undefined' != typeof subwayTemp.center)
	{
		station.innerHTML = sContent;
		station.style.display = 'block';
		station.style.top = (point.y-station.offsetHeight-12)+'px';
		station.style.left = (point.x-6)+'px';
	}
	return marker;
};
MapApi.prototype.drawSubwayStation = function(subwayLineSites)
{
	var me = this;
	var map = me._map;
	for(var p=0; p<subwayLineSites.length; p++)
	{
		var subwaymarker = me.createSubwayMarker(subwayLineSites[p]);
		map.addOverlay(subwaymarker);
	}
};
MapApi.prototype.addOverlay = function(o)
{
	this._map.addOverlay(o);
};
MapApi.prototype.removeOverlay = function(o)
{
	this._map.removeOverlay(o);
};
function MarkerManager(map)
{
	this._markers = [];
	this._map = map;
}
MarkerManager.prototype.addMarker = function(marker)
{
	this._markers.push(marker);
	this._map.addOverlay(marker);
};
MarkerManager.prototype.clearMarkers = function(marker)
{
	while(this._markers.length > 0)
	{
		this._map.removeOverlay(this._markers.shift());
	}
};
