/*******************************************************************************
 *	Equator Prize Winners Map Project **no reload map version**
 *	31 December 2008
 *	By Chengguang Zhao
 ******************************************************************************/ 
var markerSize = 10;					//size of marker in pixels
var containerId = "menuImage";		//id of container element to place map in
var markerIconURL = "/ep_map/EP_red_icon.png";//URL of marker icon, must be png file
var selectedMarkerIconURL = "/ep_map/EP_blue_icon.png";//URL of selected marker icon, must be png file
var xmlFileURL = "/ep_map/EI_Winners.xml";	//URL of xml data file
var	zoomThreshhold = 3;				//zoom in further or load url? depends...

var xmlhttp;
var markers = new Array();
var map = null;
var container = null;
var hoverText = null;
var resetButton = null;
var selectedMarker = -1;

/*******************************************************************************
 *	newMarker function takes three parameters:
 *		latlng: latitude and longitude coordinate in the form of a string, 
 *				e.g. "21.112,-123.54"
 *		info: html text to be displayed when mouse hovers over marker
 *				e.g. "<b>ABC Inc.</b><br><em>2002</em> Winner"
 *		url: the url to be loaded if marker is clicked
 *				e.g. "http://www.equatorinitiative.org"
 *
 *	newMarker function creates a new marker using the image file in
 *	markerIconURL and anchors the new marker to the coordinate in latlng.
 *	When mouse moves over a marker, info will be displayed in a hovering box.
 *	When mouse moves out of a marker, the hovering box would be turned off.
 *	When a marker is clicked, if current zoom is too far out, map would zoom
 *	int that marker. Otherwise, load the provided url in the current page.
 ******************************************************************************/
function newMarker(latlng, info, url)
{
	var temp = new Array();
	var lat = 0;
	var lng = 0;
	temp = latlng.split(',');
	lat = temp[0] * 1;	//converts string to number
	lng = temp[1] * 1;
	var iconR = new GIcon();
	if (selectedMarker==markers.length) {
		iconR.image = selectedMarkerIconURL;
		iconR.iconAnchor = new GPoint(markerSize / 2 , markerSize / 2);
		iconR.iconSize = new GSize(markerSize*2, markerSize*2);
		map.setCenter(new GLatLng(lat, lng), 4, GMapType.G_NORMAL_MAP);
	} else {
		iconR.image = markerIconURL;
		iconR.iconAnchor = new GPoint(markerSize / 2, markerSize / 2);
		iconR.iconSize = new GSize(markerSize, markerSize);
	}
	var marker = new GMarker(new GLatLng(lat, lng), 
							 {icon: iconR});
	GEvent.addListener(marker, "click", function(latlng) {
												 if (map.getZoom() < zoomThreshhold) {
													 map.setCenter(new GLatLng(lat, lng), map.getZoom()+3, GMapType.G_NORMAL_MAP);
													 } else if (url != "") {
														 window.location.assign(url+"&idx="+this.idx);
													 }
													 });
	GEvent.addListener(marker, "mouseover", function() {
													 if (map.getZoom() < zoomThreshhold) {
														 //hoverText.innerHTML=info+"<br>Click to zoom in.";
														 hoverText.innerHTML=info;
													 } else if (url!="") {
														 hoverText.innerHTML=info+"<br>Click to see more.";
													 } else {
														 hoverText.innerHTML=info;
													 }
													 hoverText.style.visibility="visible";
													 });
	GEvent.addListener(marker, "mouseout", function() {
		  hoverText.style.visibility="hidden";
	});	
	marker.idx=markers.length;
	return marker;
}

/*******************************************************************************
 *	loadXMLDoc function takes one parameter:
 *		url: the url of the xml file
 *
 *	loadXMLDoc sends out a request to load the xml file specified by url.
 *	After the request is complete, onResponse function will be called.
 ******************************************************************************/
function loadXMLDoc(url)
{
	xmlhttp=null;
	if (window.XMLHttpRequest)
	{// code for IE7, Firefox, Mozilla, etc.
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{// code for IE5, IE6
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp!=null)
	{
		xmlhttp.onreadystatechange=onResponse;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
  	}
	else
	{
		alert("Your browser does not support XMLHTTP.");
	}
}

/*******************************************************************************
 *	onResponse function processes the data loaded from the xml file.
 *	It creates markers for all winners, and forms hover text.
 ******************************************************************************/
function onResponse()
{
	var x=null;
	var xx="";
	var txt="";
	var url = "";
	
	if(xmlhttp.readyState!=4) return;
	if(xmlhttp.status!=200)
	{
		alert("Problem retrieving XML data "+xmlhttp.status);
		return;
	}
	x=xmlhttp.responseXML.documentElement.getElementsByTagName("winner");

	for (i=0;i<x.length;i++)
	{
		txt="";

		xx=x[i].getElementsByTagName("name");
		{
			try
			{
				txt=txt + "<b>" + xx[0].firstChild.nodeValue + "</b><br>";
			}
			catch (er)
			{
				txt=txt + "failed to get winner name\n";
			}
		}
		xx=x[i].getAttribute("id");
		{
			try
			{				
				txt=txt + "<em>" + xx.substr(0,4) + "</em> "+(xx.substr(7)=="1"?"Winner":"Finalist");
			}
			catch (er)
			{
			}
		}
		/*xx=x[i].getElementsByTagName("desc");
		{
			try
			{
				txt=txt + "<br>"+xx[0].firstChild.nodeValue;
			}
			catch (er)
			{
			}
		}*/
		xx=x[i].getElementsByTagName("url");
		{
			try
			{
				url = ""+xx[0].firstChild.nodeValue;
				//if (url != "") {
				//txt=txt + "<br>Click to see more. "+url;}
			}
			catch (er)
			{
				//txt=txt + "<br>No profile available.";
				url = "";
			}
		}
		xx=x[i].getElementsByTagName("loc");
		{
			try
			{
				//markers[i]=newMarker(xx[0].firstChild.nodeValue, txt, url);
				markers.push(newMarker(xx[0].firstChild.nodeValue, txt, url));
				map.addOverlay(markers[markers.length-1]);
				url="";
			}
			catch (er)
			{
			}
		}
	}
}

/*******************************************************************************
 *	shadowNonTropics function places two rectangular transparent overlays 
 *	on the map to cover up non-eligible regions for the Equator Prize
 ******************************************************************************/
function shadowNonTropics()
{
	var polygon1 = new GPolygon([
				new GLatLng(23.5, -180),
				new GLatLng(23.5, -90),
				new GLatLng(23.5, 0),
				new GLatLng(23.5, 90),
				new GLatLng(23.5, 180),
				new GLatLng(85, 180),
				new GLatLng(85, 90),
				new GLatLng(85, 0),
				new GLatLng(85, -90),
				new GLatLng(85, -180),
				new GLatLng(23.5, -180)
			  ], "#00cc00", 0, 0.2, "#00cc00", 0.2);
			  map.addOverlay(polygon1);
			  var polygon2 = new GPolygon([
				new GLatLng(-23.5, -180),
				new GLatLng(-23.5, -90),
				new GLatLng(-23.5, 0),
				new GLatLng(-23.5, 90),
				new GLatLng(-23.5, 180),
				new GLatLng(-85, 180),
				new GLatLng(-85, 90),
				new GLatLng(-85, 0),
				new GLatLng(-85, -90),
				new GLatLng(-85, -180),
				new GLatLng(-23.5, -180)
			  ], "#00cc00", 0, 0.2, "#00cc00", 0.2);
			  map.addOverlay(polygon2);
}

/*******************************************************************************
 *	addHoverBox function creates a floating text box near the cursor.
 *	This floating text is initially set to hidden or invisible.
 *
 *  This floating text is turned visible when cursor moves over a marker, and
 *	turned invisible again when cursor moves out.
 *		(implemented in the newMarker function)
 ******************************************************************************/
function addHoverBox()
{
	hoverText = document.createElement("div");
	hoverText.innerHTML="";
	hoverText.style.position = "absolute";
	hoverText.style.zIndex = 1000;
	hoverText.style.width = "200px";
	hoverText.style.left = "100px";
	hoverText.style.top = "100px";
	hoverText.style.backgroundColor ="white";
	hoverText.style.border = "1px solid black";
	hoverText.style.padding = "2px";
	hoverText.style.visibility = "hidden";
	container.appendChild(hoverText);
	GEvent.addListener(map, "mousemove", function (latlng) {
													   hoverText.style.top = (map.fromLatLngToContainerPixel(latlng).y-30)+"px";
													   hoverText.style.left = (map.fromLatLngToContainerPixel(latlng).x+10)+"px";
													   });
}

function addResetButton()
{
	resetButton = document.createElement("input");
	resetButton.type = "button";
	resetButton.value = "Return to World View";
	resetButton.style.position = "absolute";
	resetButton.style.zIndex = "1000";
	resetButton.style.width = "135px";
	resetButton.style.height = "23px";
	resetButton.style.left = "450px";
	resetButton.style.top = "10px";
	resetButton.style.visibility = "hidden";
	resetButton.onclick = function() {
		map.setCenter(new GLatLng(0, 15), 1);
		resetButton.style.visibility="hidden";
	};
	container.appendChild(resetButton);
}

function initialize() 
{
	if (GBrowserIsCompatible()) {
		//Placed the new map in the specified container
		if( document.location.href.lastIndexOf("idx=")!=-1){
			selectedMarker=1*document.location.href.substr(document.location.href.lastIndexOf("idx=")+4, 
							document.location.href.length-document.location.href.lastIndexOf("idx=")-4);
		}
		container = document.getElementById(containerId);
		container.style.zIndex=1000;
		while (container.firstChild) container.removeChild(container.firstChild);
		map = new GMap2(container); 
		map.setCenter(new GLatLng(0, 15), 1);
		map.addControl(new GSmallMapControl());
		//load Equator Prize winners data from the specified file
		loadXMLDoc(xmlFileURL);
		addHoverBox();					   
		shadowNonTropics();
		addResetButton();
		GEvent.addListener(map,"zoomend", function(oldz,newz) {
												   resetButton.style.visibility = "visible";
												   });
	}
}
