var points = [];
var mapPolyLine;
var entryImages = [];
var markers = [];
var locationInfoObjects = [];
var bounds = new GLatLngBounds();
var markerCount = 0;
var iWidth = 0;
var iHeight = 0;

var map;

function load(xmlPath, clearCache)
{
    if (GBrowserIsCompatible()) 
    {    
		if (clearCache)
		{
			var geocoder = new GClientGeocoder();
			geocoder.setCache(null);
		}

		map = new GMap2(document.getElementById("map1"));
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		
		var point = new GLatLng(10,10);
		
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(0,0),0);
		
		var myEStyle;
		if (IsIE())
			myEStyle = new EStyle("images/maps/stem7.png", new GSize(24,24),  "estyle2", new GPoint(-10,23));
		else
			myEStyle = new EStyle("images/maps/stem7.png", new GSize(24,24),  "estyle2", new GPoint(-10,18));
		
		ew = new EWindow(map, myEStyle);      
		map.addOverlay(ew);

		var baseIcon = new GIcon();
		baseIcon.shadow = "images/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
      
		function importanceOrder (marker,b)
		{
			return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
		}
		
		function createMarker(point, locationInfo, index)
		{			
			var icon = new GIcon();
			icon.image = "images/maps/organica_36156225_255_255_255_25_" + index + ".png";
			icon.shadow = "images/shadow50.png";
			icon.iconSize = new GSize(25, 25);
			icon.shadowSize = new GSize(37, 34);
			icon.iconAnchor = new GPoint(13, 26);
			icon.infoWindowAnchor = new GPoint(5, 1);
		
			var marker = new GMarker(point, {zIndexProcess:importanceOrder, icon:icon});
			marker.importance = -index;
			GEvent.addListener(marker, "click", function() {
			ew.openOnMap(point, locationInfo.createWindowHtml(), new GPoint(10, 30));
			});
			return marker;
		}
		
		var request = GXmlHttp.create();
		request.open("GET", xmlPath, true);
		
		request.onreadystatechange = function()
		{		
			if (request.readyState == 4)
  			{
  				var xmlDoc = request.responseXML;
  				var routes = xmlDoc.getElementsByTagName("route");
		  	
  				for (var i = 0; i < routes.length; i++)
  				{
  					var currentRoute = routes[i];
		  			
  					var floatLatitude = 0;
  					var floatLongitude = 0;  				
  					var name = null;
  					var note = null;
  					var url = null;
  					var image = null;
		  			
  					for (var j = 0; j < currentRoute.childNodes.length; j++)
  					{
  						if (currentRoute.childNodes[j].tagName == "latitude")
  						{
  							var strLat = currentRoute.childNodes[j].childNodes[0].nodeValue;
  							var latitude = strLat.substring(0, strLat.length - 1);
  							var lastChar = strLat.substring(strLat.length - 1, strLat.length);
		  					
  							if (lastChar == "N")
  							{
  								// greater than zero
  								floatLatitude = parseFloat(latitude);
  							}
  							else if (lastChar == "S")
  							{
  								// less than zero
  								floatLatitude = parseFloat(latitude);
  								floatLatitude = floatLatitude - (floatLatitude * 2);
  							}
  						}
		  				
  						if (currentRoute.childNodes[j].tagName == "longitude")
  						{
  							var strLon = currentRoute.childNodes[j].childNodes[0].nodeValue;
  							var longitude = strLon.substring(0, strLon.length - 1);
  							var lastChar = strLon.substring(strLon.length - 1, strLon.length);
		  					
  							if (lastChar == "E")
  							{
  								// if there is E on the end its a positive number
  								floatLongitude = parseFloat(longitude);
  							}
  							else if (lastChar == "W")
  							{
  								// if there is W on the end it needs to be converted to a negative number
  								floatLongitude = parseFloat(longitude);
  								floatLongitude = floatLongitude - (floatLongitude * 2);
  							}
  						}
		  				
  						if (currentRoute.childNodes[j].tagName == "locations")
  						{
  							var locationsNode = currentRoute.childNodes[j];

  							var locationNode = null;

							for (var k = 0; k < locationsNode.childNodes.length; k++)
							{
								if (locationsNode.childNodes[k].tagName == "location")
								{
									locationNode = locationsNode.childNodes[k];
									break;
								}
							}

							if (locationNode != null)
							{
  								for (var l = 0; l < locationNode.childNodes.length; l++)
  								{
  									if (locationNode.childNodes[l].tagName == "name")
  										name = locationNode.childNodes[l].childNodes[0].nodeValue;
		  								
  									if (locationNode.childNodes[l].tagName == "note")
  										note = locationNode.childNodes[l].childNodes[0].nodeValue;
		  							
  									if (locationNode.childNodes[l].tagName == "url")
  										url = locationNode.childNodes[l].childNodes[0].nodeValue;
	  									
  									if (locationNode.childNodes[l].tagName == "image" && locationNode.childNodes[l].childNodes.length != 0)
  									{
  										image = locationNode.childNodes[l].childNodes[0].nodeValue;
	  									
  										if (locationNode.childNodes[l].attributes['width'] != null && locationNode.childNodes[l].attributes['height'] != null)
  										{
  											iWidth = locationNode.childNodes[l].attributes['width'].value;
  											iHeight = locationNode.childNodes[l].attributes['height'].value;
  										}
	  									
  										var imgPreLoadObj = new Image();
  										imgPreLoadObj.src = image;
  										entryImages.push(imgPreLoadObj);
  									}
  								}
							}
  						}
  					}
	  				
		  			
  					if (floatLatitude != 0 && floatLongitude != 0)
  					{					
						var point = new GLatLng(floatLatitude, floatLongitude);
						var locationInfo = new MapLocationInfo(name, note, url, image, iWidth, iHeight);
						var marker = createMarker(point, locationInfo, markerCount);
						
						locationInfoObjects.push(locationInfo);
						map.addOverlay(marker);
						markers.push(marker);
						points.push(point);
						bounds.extend(point);
						markerCount++;
  					}
    			}
  			}
	  		
  			if (points != null && points.length > 0 && bounds != null)
  			{
  				mapPolyLine = new GPolyline(points);
  				map.addOverlay(mapPolyLine);
  				map.setCenter(bounds.getCenter());
	  			
  				if (points.length > 1)
  					map.setZoom(map.getBoundsZoomLevel(bounds));
  				else
  					map.setZoom(8);
  			}
		}
		
		request.send(null);
	}	
}

var animationIcon = new GIcon();
animationIcon.image="images/maps/personicon.png"
animationIcon.iconSize=new GSize(16,16);
animationIcon.iconAnchor=new GPoint(10,15);

var animationMarker;

var endOfLine;
var k=0;
var metresToMoveby = 0;
var isExplorer;
var vertCount = 0;
var locationIndex = 0;

function startAnimation()
{
	if (document.getElementById("playAnimationButton") != null)
		document.getElementById("playAnimationButton").disabled = true;
	
	if (IsIE())
		isExplorer = true;
	else
		isExplorer = false;

	if (animationMarker == null)
	{
		animationMarker = new GMarker(mapPolyLine.getVertex(0),{icon:animationIcon});
		map.addOverlay(animationMarker);
	}
	
	endOfLine=mapPolyLine.Distance();
	vertCount = mapPolyLine.getVertexCount();
	
	setTimeout("moveAnimatedMarker(0)", 2000);
}

function moveAnimatedMarker(distance)
{	
	try
	{
		if (distance > endOfLine)
		{
			if (document.getElementById("playAnimationButton") != null)
				document.getElementById("playAnimationButton").disabled = false;
			return;
		}
		
		var currentPoint = mapPolyLine.GetPointAtDistance(distance);
		
		if (locationIndex < (markerCount))
		{
			var nextPlottedLocation = mapPolyLine.getVertex(locationIndex);
			
			var currentLat = Math.round(currentPoint.lat()*10)/10;
			var lat = Math.round(nextPlottedLocation.lat()*10)/10;
			
			if (currentLat >= (lat-0.1) && currentLat <= (lat+0.1))
			{			
				ew.openOnMarker(markers[locationIndex], locationInfoObjects[locationIndex].createWindowHtml());
				
				if (locationIndex <= vertCount)
					locationIndex++;
			}
		}
		
		if (k++>=180/metresToMoveby)
		{
			map.panTo(currentPoint);
			k=0;
		}
	    
		metresToMoveby = calculateMetresToMoveby(map.getZoom(), endOfLine);
		
		animationMarker.setPoint(currentPoint);
		
		var callInterval = 1;		
		setTimeout("moveAnimatedMarker("+(distance+metresToMoveby)+")", callInterval);
	}
	catch(err)
	{
	}
}

function calculateMetresToMoveby(zoomLevel, distance)
{
	if (isExplorer)
	{
		if (zoomLevel > 0 && zoomLevel < 4)
			return 5000
		else if (zoomLevel > 3 && zoomLevel < 6)
			return 3000;
		else if (zoomLevel > 5 && zoomLevel < 8)
			return 1000;
		else if (zoomLevel > 7 && zoomLevel < 10)
			return 500;
		else if (zoomLevel > 9 && zoomLevel < 12)
			return 100;
		else if (zoomLevel > 11 && zoomLevel < 14)
			return 50;
		else if (zoomLevel > 13 && zoomLevel < 16)
			return 20;
		else if (zoomLevel > 15)
			return 10;
	}
	else
	{
		if (zoomLevel > 0 && zoomLevel < 4)
			return 20000
		else if (zoomLevel > 3 && zoomLevel < 6)
			return 10000;
		else if (zoomLevel > 5 && zoomLevel < 8)
			return 2000;
		else if (zoomLevel > 7 && zoomLevel < 10)
			return 1000;
		else if (zoomLevel > 9 && zoomLevel < 12)
			return 500;
		else if (zoomLevel > 11 && zoomLevel < 14)
			return 200;
		else if (zoomLevel > 13 && zoomLevel < 16)
			return 100;
		else if (zoomLevel > 15)
			return 50;
	}
	
	return 0;
}

function IsIE()
{
	var agent = navigator.userAgent.toLowerCase();
	return (agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1);
}

function MapLocationInfo(name, note, url, image, imageWidth, imageHeight) 
{
	this.name = name;
	this.note = note;
	this.url = url;
	this.image = image;
	this.imageWidth = imageWidth;
	this.imageHeight = imageHeight;	
	
	MapLocationInfo.prototype.createWindowHtml = function()
	{
		var html = "<table cellpadding=\"5\" cellspacing=\"0\" class=\"mapPopupTable\">";
		
		html += "<tr><th width=\"100%\" colspan=2 nowrap>";
		html += this.name;
		html += "<a href=\"javascript:ew.hide()\"><img width=\"14\" height=\"13\" title=\"Close the EWindow\" src=\"images/maps/eclose.gif\" border=\"0\" style=\"position:absolute;right:4px;top:4px\"></a>";
		html += "</th></tr>";
		
		html += "<tr>";
		
		if (this.image != null)
		{
			html += "<td>";
			if (this.imageWidth > 0 && this.imageHeight > 0)
				html += "<a href=\"" + this.url + "\"><img src=\"" + this.image + "\" width=\"" + this.imageWidth + "\" height=\"" + this.imageHeight + "\" /></a>";		
			else
				html += "<a href=\"" + this.url + "\"><img src=\"" + this.image + "\" /></a>";		
			html += "</td>";
		}
		
		html += "<td valign=\"top\" width=\"250px;\" nowrap>";
		html += "<b>" + this.note + "</b>";
		html += "<br/><span style=\"font-size: 12px;font-weight:normal;color:#cc0000;\">" + this.name + "</span><br/>";
		html += "<br/><a href=\"" + this.url + "\">View</a>";
		html += "</td>";
		html += "</tr>";
		html += "</table>";
		
		return html;
	}
}

function resetGlobalVars()
{
	points = [];
	mapPolyLine;
	entryImages = [];
	markers = [];
	locationInfoObjects = [];
	bounds = new GLatLngBounds();
	markerCount = 0;
	iWidth = 0;
	iHeight = 0;

	map;
	
	animationIcon = new GIcon();
	animationIcon.image="images/maps/personicon.png"
	animationIcon.iconSize=new GSize(16,16);
	animationIcon.iconAnchor=new GPoint(10,15);

	animationMarker = null;

	endOfLine = 0;
	k = 0;
	metresToMoveby = 0;
	isExplorer = false;
	vertCount = 0;
	locationIndex = 0;
}