var map;
var jmarkers = new Array();
var jmarkers_map = {}
var init_flag;
var nav_index = -1;
var points = []
var pmarkers;
var startn;
var endn;
var startMarker;
var endMarker;

// JPMarker
function JPMarker(markersSrc, markerWidth, markerHeight, points, photos, photos_desc, activity_id) {
	this.points = points;
	this.photos = photos;
	this.photos_desc = photos_desc;
	this.srcPhotos = markersSrc;
	this.markerW = markerWidth;
	this.markerH = markerHeight;
	this.activity_id = activity_id;
	this.None = -1;	
}
JPMarker.prototype = new GOverlay();

JPMarker.prototype.initialize = function(map) {
	var pane = map.getPane(G_MAP_MARKER_PANE);
	var events = ["mouseover", "mouseout", "click"];
	this.mDivs = [];
	this.map = map;
	this.infodiv;	
	this.infoindex = -1;
	this.selectIndex = this.None;
	var self = this;	
	
	var img = new Image();

	img.onload = function() {
		setTimeout(function() {
			for (var i = 0; i < self.mDivs.length; i++)
				self.mDivs[i].style.backgroundImage = "url(" + self.srcPhotos + ")";
		}, 200);
	};

	img.src = this.srcPhotos;
		
	this.infodiv = document.createElement("div");
	var s = this.infodiv.style;
	s.position = "absolute";
	s.cursor = "pointer";	
		
	for (var i = 0; i < this.points.length; i++)
	{		
		var div = document.createElement("div");
		var s = div.style;				
		s.border = "1px solid #F0F0F0";
		s.width = (this.markerW - 2) + "px";
		s.height = (this.markerH - 2) + "px";
		s.backgroundPosition = "-1px " + (-i * this.markerH - 1) + "px";
		s.position = "absolute";
		s.cursor = "pointer";
		s.zIndex = GOverlay.getZIndex(this.points[i].lat());		
		pane.appendChild(div);
		this.mDivs.push(div);
				
		for (var j = 0; j < events.length; j++)
		{
			(function(){
			var idx = i;
			var tevent = events[j];
			GEvent.addDomListener(div, tevent, function() { GEvent.trigger(self, tevent, idx);});})();
		}			
	}
};

JPMarker.prototype.remove = function(map) {
	for (var i = 0; i < this.mDivs.length; i++)
	{
		this.mDivs[i].parentNode.removeChild(this.mDivs[i]);
		GEvent.clearInstanceListeners(this.mDivs[i]);
	}
};

JPMarker.prototype.copy = function() {
	return new JPMarker(this.srcPhotos, this.markerW, this.markerH, this.points);
};

JPMarker.prototype.redraw = function(force) {
	if (!force) return;

	for (var i = 0; i < this.points.length; i++)
	{		
		var c = this.map.fromLatLngToDivPixel(this.points[i]);
		var s = this.mDivs[i].style;
		s.left = (c.x - this.markerW / 2 - 1) + "px";
		s.top = (c.y - this.markerH / 2 - 1) + "px";
	}	
	if(this.infoindex >= 0)
		this.openInfoWindowHtml(this.infoindex, true);		
};

JPMarker.prototype.unselect = function() {	
	if(this.selectIndex >= 0 && this.selectIndex < this.mDivs.length) {
		var s = this.mDivs[this.selectIndex].style;		
		s.border = "1px solid #F0F0F0";
		s.left = (parseInt(s.left) + 1) + "px";
		s.top = (parseInt(s.top) + 1) + "px";
		s.zIndex = GOverlay.getZIndex(this.points[this.selectIndex].lat());	
		this.selectIndex = this.None;
	}
}

JPMarker.prototype.select = function(i) {		
	if (this.selectIndex != this.None)
		this.unselect();

	if (i == this.None || (i >= 0 && i < this.mDivs.length))
	{
		this.selectIndex = i;
		if (i != this.None)
		{
			var s = this.mDivs[i].style;
			s.border = "2px solid #FF7800";
			s.left = (parseInt(s.left) - 1) + "px";
			s.top = (parseInt(s.top) - 1) + "px";			
			s.zIndex = GOverlay.getZIndex(-100000);
		}
	}
};

JPMarker.prototype.closeInfoWindowHtml = function() {		
	try {
		this.map.getPane(G_MAP_MARKER_PANE).removeChild(this.infodiv);
	} catch(err) {}		
	this.infoindex = this.None;						
}			

JPMarker.prototype.openInfoWindowHtml = function(i, redraw) {
	if (i == this.None || (i >= 0 && i < this.mDivs.length))
	{		
		this.select(i);
		this.selectIndex = i;
		if (i != this.None)
		{
			if(this.infoindex == i && redraw!=true) { //already opened
				this.map.getPane(G_MAP_MARKER_PANE).removeChild(this.infodiv);
				this.infoindex = this.None;				
				return;
			}
									
			//this.map.panTo(this.points[i]);
			var c = this.map.fromLatLngToDivPixel(this.points[i]); 
			var c2 = this.map.fromDivPixelToLatLng(new GPoint(c.x + 200, c.y + 200));			
			this.map.panTo(c2);
			
			this.infoindex = i;			
			var winClass = "markerInfo";
			var c = this.map.fromLatLngToDivPixel(this.points[this.infoindex]);
			var s = this.infodiv.style;
			s.left = (c.x + this.markerW / 2 + 3) + "px";
			s.top = (c.y - this.markerH / 2) + "px";
			s.display = "block";			
			s.zIndex = GOverlay.getZIndex(-901.0);		
			
			var html; 						
			//html = "<table><tr><td><center><img src=\"" + this.photos[i] + "\"></center></td></tr><tr><td><center>" + this.photos_desc[i] + "</center></td></tr></table>";
			html = "<table><tr><td><center><a target=\"new\" href=\"http://www.jmap.cc/activity/" + activity_id + "/\"><img src=\"" + this.photos[i] + "\"></a></center></td></tr></table>";
						
			this.infodiv.innerHTML = "<div class='" + winClass + "'>" + html + "</div>";
			this.map.getPane(G_MAP_MARKER_PANE).appendChild(this.infodiv);
						
			GEvent.addListener(this.infodiv, "click", function(i) {									
				this.closeInfoWindowHtml();
			});					
		}
	}
};

////////////////////////////////////////////////////////////////////////////////////////////
function JLogoControl() {}
JLogoControl.prototype = new GControl();

JLogoControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	var logoDiv = document.createElement("div");
	//logoDiv.title="LOGO";
	this.setButtonStyle_(logoDiv);
	container.appendChild(logoDiv);      
	logoDiv.innerHTML = "<img src=\"/img/base/logo_s.gif\"/>";

	GEvent.addDomListener(logoDiv, "click", function() {
		window.open('http://www.jmap.cc/','_blank');
	});

	map.getContainer().appendChild(container);
	return container;
}

JLogoControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 15));
}

JLogoControl.prototype.setButtonStyle_ = function(button) {
	//button.style.border = "1px solid black";
	button.style.width = "auto";
	button.style.height = "auto";
	button.style.cursor = "pointer";
}


function TMarker(a, b) {
	this.inheritFrom = GMarker;
	this.inheritFrom(a,b);
	this.removed = false;
	this.ty = 0;
	this.index = 0;
	this.lv = 0;
	this.oPoint = 0;
	this.photo_src = null;
}
TMarker.prototype = new GMarker(new GLatLng(1, 1));

TMarker.prototype.initialize = function(a) {
	GMarker.prototype.initialize.call(this, a);
}

TMarker.prototype.setRemoved = function(a) {
	this.removed = a;
}
TMarker.prototype.isRemoved = function() {
	return this.removed;
}

function onMapPanelLoad() {
	if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(25.12, 121.46), 10);
	map.addControl(new GSmallMapControl());
	map.addControl(new JLogoControl());
	map.addControl(new GMenuMapTypeControl());
	//map.getMapTypes().length = 0;  
	map.removeMapType( G_HYBRID_MAP );  
	map.addMapType( G_NORMAL_MAP );  
	map.addMapType( G_SATELLITE_MAP );  
	map.addMapType( G_PHYSICAL_MAP ); 
	map.disableDoubleClickZoom();

	startn = new GIcon();
	startn.image = "/img/marker/start.png";
	startn.shadow = "/img/marker/shadow.png";
	startn.iconSize = new GSize(22, 30);
	startn.shadowSize = new GSize(39, 30);
	startn.iconAnchor = new GPoint(11, 30);
	startn.infoWindowAnchor = new GPoint(5, 1);

	endn = new GIcon(startn);
	endn.image = "/img/marker/end.png";
	marker_init_get();
	}
}


function marker_init_get() {		
	var AjaxObject = {
		handleSuccess:function(o){			
			this.processResult(o);
		},
		handleFailure:function(o){},		
		processResult:function(o){			
			onMarkerInitComplete(o);
		},
		startRequest:function() {
		YAHOO.util.Connect.asyncRequest('POST', '/activity/mashupdata/' + activity_id + '/', callback, "type=mashup");		
		}
	};

	var callback =
	{
		success:AjaxObject.handleSuccess,
		failure:AjaxObject.handleFailure,
		timeout: 60000,
		scope: AjaxObject
	};
	AjaxObject.startRequest();
}

var onMarkerInitComplete = function onMarkerInitComplete(res)
{	
	var ret = eval( "(" + res.responseText + ")" );	
	
	if(ret.type=="satellite") map.setMapType(G_SATELLITE_MAP);
	else if(ret.type=="terrain") map.setMapType(G_PHYSICAL_MAP);	

	var line = ret.line
	var rets = ret.points
	var map_bound=new GLatLngBounds();	
	var photos = []
	var photos_desc = []

	function importanceOrder (marker, b) {
		return GOverlay.getZIndex(marker.getPoint().lat() - 2);
	}

	point = new GLatLng( Number(ret.start[0]),	Number(ret.start[1]));
	if(!init_flag) {
		map_bound.extend(point);
		map_bound.extend(new GLatLng( Number(ret.maxp[0]),	Number(ret.maxp[1])))
		map_bound.extend(new GLatLng( Number(ret.minp[0]),	Number(ret.minp[1])))
	}
	startMarker = new TMarker(point, {icon: startn, draggable: false, title:i, zIndexProcess:importanceOrder});
	map.addOverlay(startMarker);
	GEvent.addListener(startMarker, "mouseover", function(i) {		
	});

	point = new GLatLng( Number(ret.end[0]),  Number(ret.end[1]));
	if(!init_flag) map_bound.extend(point);
	endMarker = new TMarker(point, {icon: endn, draggable: false, title:i, zIndexProcess:importanceOrder});
	map.addOverlay(endMarker);
	GEvent.addListener(endMarker, "mouseover", function(i) {		
	});


	for(var i = 0 ;i<rets.length; i++) {
		point = new GLatLng( Number(rets[i][0]),  Number(rets[i][1]));
		if(!init_flag) map_bound.extend(point);
		points.push(point);
		photos.push(rets[i][2]);
		photos_desc.push(rets[i][4]);				
	}
	
	if(photos.length > 0) {
		pmarkers = new JPMarker("/activity/" + activity_id + "/photoconcat/?w=32&h=32", 32, 32, points, photos, photos_desc, ret.activity_id);
		map.addOverlay(pmarkers);

		GEvent.addListener(pmarkers, "mouseover", function(i) {
			pmarkers.select(i);		
		});
		GEvent.addListener(pmarkers, "mouseout", function(i) {
			pmarkers.select(jmarkers.None);		
		});
		GEvent.addListener(pmarkers, "click", function(i) {
			pmarkers.openInfoWindowHtml(i, false);
			this.nav_index = i;
		});
	}

	track = new GPolyline.fromEncoded({
	color: "#f00000",
	weight: 2,
	opacity: 0.8,
	points: line[0],
	levels: line[1],
	zoomFactor: 16,
	numLevels: 4
	})
	map.addOverlay(track);


	if(!init_flag) map.setCenter(map_bound.getCenter(), map.getBoundsZoomLevel(map_bound));
	init_flag = true;
}

var goToStart = function goToStart()
{	
	photoPaneUnSelect(nav_index);		
	nav_index = -1;
	map.panTo(startMarker.getPoint());	
	if(pmarkers) {	
		pmarkers.unselect();	
		pmarkers.closeInfoWindowHtml();	
	}
}

var goToEnd = function goToEnd()
{	
	map.panTo(endMarker.getPoint());
	nav_index = points.length;
	if(pmarkers) {	
		pmarkers.unselect();
		pmarkers.closeInfoWindowHtml();
	}
}

var nextPOI = function()
{	
	photoPaneUnSelect(nav_index);
	nav_index ++;

	if (nav_index>=points.length) goToEnd();
	else gotoPOI(nav_index);		
}

var previousPOI = function()
{	
	photoPaneUnSelect(nav_index);
	nav_index --;

	if(nav_index <= 0 ) goToStart();
	else gotoPOI(nav_index);			
}

var gotoPOI = function(i)
{	
	photoPaneUnSelect(nav_index);
	nav_index=i;
	map.panTo(points[nav_index]);
	if(pmarkers){
		pmarkers.select(i);
		pmarkers.openInfoWindowHtml(nav_index, false);
	}
	photoPaneSelect(nav_index);
}

var photoPaneSelect = function(i)
{	
	if (i >= 0&& i < this.points.length) {				
		d = YAHOO.util.Dom.get("photo_" + i)
		if(d!=null) d.style.background = "#FF7800";
	}
}
var photoPaneUnSelect = function(i)
{	
	if (i >= 0 && i < this.points.length) {		
		d = YAHOO.util.Dom.get("photo_" + i)		
		if(d!=null) d.style.background = "#ffffff";
	}
}

YAHOO.util.Event.onContentReady("map", function () {
	onMapPanelLoad();
});


window.onunload = GUnload;
