// JavaScript Document

function commentInstructionsControl() { }
commentInstructionsControl.prototype = new GControl();

commentInstructionsControl.prototype.initialize = function(map)
{
	var instructions = document.createElement("div");
	instructions.style.width = "360px";
	instructions.style.height = "95px";
	instructions.innerHTML = '<img src = "http://gombeblog.janegoodall.org//IMAGES/cloth.png"/>';
	map.getContainer().appendChild(instructions);
	return instructions;
	
}

commentInstructionsControl.prototype.getDefaultPosition = function()
{
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 15));
}
// Global map variable
var map;

// note that this is incomplete.  The appropriate infoWindowOpen will append dynamic pageID and coordinate values, along with a </form> tag
var formHTML = "<form action = 'comment.asp#Conf' method = 'POST' name = 'commentForm' id = 'commentForm' onsubmit='return validateComment(this)'><td>Subject:<input type = 'text' name = 'subject' id = 'subject' /><br /><textarea name='comment' id='comment' cols='30' rows='3'>Enter your geotagged comment here!</textarea><br /></td><td>Username<input type='text' name = 'name' id = 'name' /><br />Email Address: <input type='text' name = 'email' id = 'email' /><br /><input type='submit' value='Submit Comment' onclick = 'map.closeInfoWindow(); alert('Your comment has been submitted for moderation');' /><input type='button' value = 'Cancel' onclick = 'map.closeInfoWindow()'/></td>";

var points = [];
var arrayIndex = 0;
var line;
var marker;

function copyDataToMap(targetMap)
{
	if (marker)targetMap.removeOverlay(marker);
	if (line) targetMap.removeOverlay(line);
	arrayIndex = 0;
	if (document.getElementById("Latitude") != "" && document.getElementById("Longitude").value != "")
	{
		points[0] = new GLatLng(document.getElementById("Latitude").value, document.getElementById("Longitude").value);
		marker = new GMarker(points[0], {draggable:true});
		GEvent.addListener(marker, "dragend", function()
		{
			document.getElementById("Latitude").value = marker.getPoint().lat();
			document.getElementById("Longitude").value = marker.getPoint().lng();
		});
		targetMap.setCenter(marker.getPoint());
		targetMap.addOverlay(marker);
		arrayIndex = 1;
	}
	
	if (document.getElementById("Coordinates").value != "")
	{
		//clear out all old points.
		var i=0
		while(points[i]!=null)
		{
			points[i]=null;
			i++
		}
		arrayIndex = 0;
		var coordinateString = document.getElementById("Coordinates").value;
		var lng;
		var lat;
		while(coordinateString.search(" ") != -1)
		{
			lng = parseFloat(coordinateString);
			coordinateString = coordinateString.substring(coordinateString.search(",")+1);
			lat = parseFloat(coordinateString);
			points[arrayIndex] = new GLatLng(lat, lng);
			arrayIndex++;
			coordinateString = coordinateString.substring(coordinateString.search(" ")+1);
		} 
		if(arrayIndex != 0)
		{
			lng = parseFloat(coordinateString);
			coordinateString = coordinateString.substring(coordinateString.search(",")+1);
			lat = parseFloat(coordinateString);
			points[arrayIndex] = new GLatLng(lat, lng);
			arrayIndex++
		}
		else
		{
			document.getElementById("Coordinates").value = "";
		}
		line = new GPolyline(points);
		targetMap.addOverlay(line);
	}
}



function removePointFromLine()
{
	if(arrayIndex > 0)
	{
		arrayIndex--;
		points[arrayIndex] = null;
		if (line) map.removeOverlay(line);
		line = new GPolyline(points);
		map.addOverlay(line);
		var coordinateString = document.getElementById("Coordinates").value;
		coordinateString = coordinateString.substring(0, coordinateString.lastIndexOf(" "));
		if(arrayIndex == 1)
		{
			coordinateString = "";
		}
		
		document.getElementById("Coordinates").value = coordinateString;

		if(arrayIndex == 0)
		{
			if (marker) map.removeOverlay(marker);
			document.getElementById("Latitude").value = "";
			document.getElementById("Longitude").value = "";
		}
	}
}
	
function addPointToLine(newPoint)
{
	points[arrayIndex] = newPoint;
	arrayIndex++;
	if (line) map.removeOverlay(line);
	line = new GPolyline(points);
	map.addOverlay(line);
	if(arrayIndex == 1)
	{
		marker = new GMarker(newPoint, {draggable:true});
		GEvent.addListener(marker, "dragend", function()
		{
			document.getElementById("Latitude").value = marker.getPoint().lat();
			document.getElementById("Longitude").value = marker.getPoint().lng();
		});
		map.addOverlay(marker);
		document.getElementById("Latitude").value = marker.getPoint().lat();
		document.getElementById("Longitude").value = marker.getPoint().lng();
	}
	else if(arrayIndex > 1)  // If there's more than one point, we're talking paths.  Note that coordinate pairs are in the format "lng, lat", for KML's sake
	{
		if(arrayIndex == 2)
		{
			document.getElementById("Coordinates").value = points[0].lng()+ "," + points[0].lat();
		}
		document.getElementById("Coordinates").value = document.getElementById("Coordinates").value + " " + newPoint.lng() + "," + newPoint.lat();
	}
}

function validateComment(thisComment)
{
	with (thisComment)
	{
		if (isFieldEmpty(username, "You must provide a username"))
		{
			username.focus();
			return false;
		}
		if (isFieldEmpty(comment, "Blank comments will not be accepted"))
		{
			comment.focus();
			return false;
		}
	}
}

function isFieldEmpty(field, alertTXT)
{
	with (field)
	if (value ==null||value == "")
	{
		alert(alertTXT);
		return true;
	}
	else
	{
		return false;
	}
}

// Icon definition
var binocIcon = new GIcon();
binocIcon.image="http://gombeblog.janegoodall.org/images/binoculars1.png";
binocIcon.iconSize = new GSize(35, 35);
binocIcon.iconAnchor = new GPoint(17,17);
binocIcon.infoWindowAnchor = new GPoint(25, 1);

var commentIconWhite = new GIcon();
commentIconWhite.image = "http://gombeblog.janegoodall.org/images/comments1.png";
commentIconWhite.iconSize = new GSize(32, 32);
commentIconWhite.iconAnchor = new GPoint(8,26);
commentIconWhite.infoWindowAnchor = new GPoint(26, 4);

var commentIconOrange = new GIcon();
commentIconOrange.image = "http://gombeblog.janegoodall.org/images/comments2.png";
commentIconOrange.iconSize = new GSize(32, 32);
commentIconOrange.iconAnchor = new GPoint(8,26);
commentIconOrange.infoWindowAnchor = new GPoint(26, 4);

var parkBoundary = new GGeoXml("http://www.janegoodall.org/news/gombe-blog/assets/Gombe-Stream-National-Park-Boundary.kml");

function showParkBoundary()
{
	map.addOverlay(parkBoundary);
}

function hideParkBoundary()
{
	map.removeOverlay(parkBoundary);
}


var landmarks = new GGeoXml("http://www.janegoodall.org/news/gombe-blog/assets/Gombe-Landmarks.kml");

function showLandmarks()
{
	map.addOverlay(landmarks);
}

function hideLandmarks()
{
	map.removeOverlay(landmarks);
}

function zoomToMeters(zoomLevel)
{
	switch(zoomLevel)
	{
		case 18:
			return "400";
			break
		case 17:
			return "860";
			break
		case 16:
			return "1290";
			break
		case 15:
			return "2790";
			break
		case 14:
			return "5750";
			break
		case 13:
			return "12350";
			break
		case 12:
			return "24150";
			break
		case 11:
			return "48000";
			break
		case 10:
			return "94000";
			break
		case 9:
			return "197000";
			break
		case 8:
			return "393000";
			break
		case 7:
			return "759000";
			break
		case 6:
			return "1530000";
			break
		case 5:
			return "2850000";
			break
		case 4:
			return "6150000";
			break
		case 3:
			return "12000000";
			break
		case 2:
			return "24700000";
			break
		case 1:
			return "54400000";
			break
		default:
			return "2790";
	}
}

function metersToZoom(meters)
{
	var heightInMeters = parseInt(meters);
	if(heightInMeters<=250)
	{
		return (18);
	}
	else if(heightInMeters<=500)
	{
		return (17);
	}
	else if(heightInMeters<=1000)
	{
		return (16);
	}
	else if(heightInMeters<=2000)
	{
		return (15);
	}
	else if(heightInMeters<=3000)
	{
		return (14);
	}
	else if(heightInMeters<=7500)
	{
		return (13);
	}
	else if(heightInMeters<=25000)
	{
		return (12);
	}
	else if(heightInMeters<=1375000)
	{
		return (7);
	}
	else if(heightInMeters<=2500000)
	{
		return (6);
	}
	else if(heightInMeters<=12000000)
	{
		return (3);
	}
	else
	{
		return (2);
	}
}

function parsePoint(coordinateString)
{
	// Getting the longitude from this string is easy; It's just the first floating-point number.
	var longitude = parseFloat(coordinateString);
	// To get the latitude, parse for the number that starts at +1 index from the comma that separate the two values
	var latitudeString = coordinateString.substring(coordinateString.search(",")+1);
	var latitude = parseFloat(latitudeString);
	return (new GLatLng(latitude, longitude));
}

function createMarker(point, name, icon, html)
{
	var placemark = new GMarker(point, {title:name, icon:icon});
	GEvent.addListener(placemark, "click", function()
	{
		placemark.openInfoWindowHtml(html);
	});
	return placemark;
}



function addCommentMarker(ID)
{
	// add a draggable marker to the map
	var commentMarker = new GMarker(map.getCenter(), {draggable:true, title:"Drag this marker to the desired position, then click it to open a comment form!", icon:commentIconOrange});
	map.addOverlay(commentMarker);

	// give the marker the form when clicked
	GEvent.addListener(commentMarker, "click", function()
	{
		commentMarker.openInfoWindowHtml(formHTML + "<input type = 'hidden' name = 'postID' id = 'postID' value = '" + ID + "' /><input type = 'hidden' name = 'latitude' value = '" + commentMarker.getPoint().lat() + "' /><input type = 'hidden' name = 'longitude' value = '" + commentMarker.getPoint().lng() + "' /></form>");
	});
	
	GEvent.addListener(commentMarker, "infowindowclose", function()
	{
		map.removeOverlay(commentMarker);
	});	
	var mapstop = GEvent.addListener(map, "moveend", function()
	{
		var mapPixelCenter = map.fromLatLngToDivPixel(map.getCenter());
		var commentPixel = new GPoint(mapPixelCenter.x+15, mapPixelCenter.y-25);
		commentMarker.setPoint(map.fromDivPixelToLatLng(commentPixel));
	});
	GEvent.addListener(commentMarker, "dragend", function()
	{
		GEvent.removeListener(mapstop);
	});
	map.addControl(new commentInstructionsControl());
}

function addKML(URL, markerIcon)
{
	var request = GXmlHttp.create();
	request.open("GET", URL, true);
	var bounds = new GLatLngBounds();
	bounds.extend(map.getCenter());
	request.onreadystatechange = function()
	{
		if (request.readyState == 4) // When the file has been loaded...
		{

			var kmlDoc = GXml.parse(request.responseText);

			var coordinateElements = kmlDoc.documentElement.getElementsByTagName("coordinates");
			var lookAtElements = kmlDoc.documentElement.getElementsByTagName("LookAt");

			if(navigator.appName == "Microsoft Internet Explorer")
			{
				for(var i=0;i<coordinateElements.length;i++)
				{
					// This if statements checks if the coordinate is a single pair or multiple pairs separated by spaces.
					if(coordinateElements[i].text.search(" ") == -1 && coordinateElements.item(i).text.length != 0) // There are no spaces in coordinate elements which belong to placemarks
					{
						var point = parsePoint(coordinateElements.item(i).text);
						var placemark = createMarker(point, coordinateElements.item(i).parentNode.parentNode.childNodes.item(0).text, markerIcon, coordinateElements.item(i).parentNode.parentNode.childNodes.item(2).text);
						map.addOverlay(placemark);
						bounds.extend(point);
						if(i==0  && lookAtElements.length != 1)
						{
							map.setZoom(metersToZoom(parseInt(lookAtElements.item(1).childNodes.item(3).text)));
							map.setCenter(point);
						}
						else
						{
							map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter());
						}
					}
					else if(coordinateElements.item(i).text.length != 0)
					{
						
						var coordinateString = coordinateElements.item(i).text;
						var pointArray = [];
						var j; // Because we need it later
						for(j=0;coordinateString.search(" ") != -1;j++)
						{
							pointArray[j] = parsePoint(coordinateString);
							coordinateString = coordinateString.substring(coordinateString.search(" ") + 1);
						}
						// When the loop breaks, there should be only one point left,			
						pointArray[j] = parsePoint(coordinateString);
						var thing = new GPolyline(pointArray);
						map.addOverlay(thing);
					} // end of points/path if/else-if
				} // end of element-cycling for
			}
			else
			{
				for(var i=0;i<coordinateElements.length;i++)
				{
					// This if statements checks if the coordinate is a single pair or multiple pairs separated by spaces.
					if(coordinateElements[i].textContent.search(" ") == -1 && coordinateElements.item(i).textContent.length != 0) // There are no spaces in coordinate elements which belong to placemarks
					{
						var point = parsePoint(coordinateElements.item(i).textContent);
						var placemark = createMarker(point, coordinateElements.item(i).parentNode.parentNode.childNodes.item(1).textContent, markerIcon, coordinateElements.item(i).parentNode.parentNode.childNodes.item(5).textContent);
						map.addOverlay(placemark);
						bounds.extend(point);
						if(i==0  && lookAtElements.length != 1)
						{
							map.setZoom(metersToZoom(parseInt(lookAtElements.item(1).childNodes.item(7).textContent)));
							map.setCenter(point);
						}
						else
						{
							map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter());
						}
					}
					else if(coordinateElements.item(i).textContent.length != 0)
					{
						coordinateString = coordinateElements.item(i).textContent;
						var pointArray = [];
						var j; // Because we need it later
						for(j=0;coordinateString.search(" ") != -1;j++)
						{
							pointArray[j] = parsePoint(coordinateString);
							coordinateString = coordinateString.substring(coordinateString.search(" ") + 1);
						}
						// When the loop breaks, there should be only one point left,
						pointArray[j] = parsePoint(coordinateString);
						map.addOverlay(new GPolyline(pointArray));
					} // end of points/path if/else-if
				} // end of element-cycling for
			} // end of IE/Firefox if
		} // end of readystate if
	} // end of request
	request.send(null);	
} // end of function


function addKMLInfo(URL, markerIcon, infoHTML)
{
	var request = GXmlHttp.create();
	request.open("GET", URL, true);
	var bounds = new GLatLngBounds();
	bounds.extend(map.getCenter());
	request.onreadystatechange = function()
	{
		if (request.readyState == 4) // When the file has been loaded...
		{

			var kmlDoc = GXml.parse(request.responseText);
			var coordinateElements = kmlDoc.documentElement.getElementsByTagName("coordinates");
			var lookAtElements = kmlDoc.documentElement.getElementsByTagName("LookAt");
			if(navigator.appName == "Microsoft Internet Explorer")
			{
				for(var i=0;i<coordinateElements.length;i++)
				{
					// This if statements checks if the coordinate is a single pair or multiple pairs separated by spaces.
					if(coordinateElements[i].text.search(" ") == -1 && coordinateElements.item(i).text.length != 0) // There are no spaces in coordinate elements which belong to placemarks
					{
						var point = parsePoint(coordinateElements.item(i).text);
						var placemark = createMarker(point, coordinateElements.item(i).parentNode.parentNode.childNodes.item(0).text, markerIcon, "<h3>" + coordinateElements.item(i).parentNode.parentNode.childNodes.item(0).text + "</h3><br>" + infoHTML);
						map.addOverlay(placemark);
						bounds.extend(point);
						if(i==0  && lookAtElements.length != 1)
						{
							map.setZoom(metersToZoom(parseInt(lookAtElements.item(1).childNodes.item(3).text)));
							map.setCenter(point);
						}
						else
						{
							map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter());
						}
					}
					else if(coordinateElements.item(i).text.length != 0)
					{
						
						var coordinateString = coordinateElements.item(i).text;
						var pointArray = [];
						var j; // Because we need it later
						for(j=0;coordinateString.search(" ") != -1;j++)
						{
							pointArray[j] = parsePoint(coordinateString);
							coordinateString = coordinateString.substring(coordinateString.search(" ") + 1);
						}
						// When the loop breaks, there should be only one point left,	
						pointArray[j] = parsePoint(coordinateString);
						var thing = new GPolyline(pointArray);
						map.addOverlay(thing);
					} // end of points/path if/else-if
				} // end of element-cycling for
			}
			else
			{
				for(var i=0;i<coordinateElements.length;i++)
				{
					// This if statements checks if the coordinate is a single pair or multiple pairs separated by spaces.
					if(coordinateElements[i].textContent.search(" ") == -1 && coordinateElements.item(i).textContent.length != 0) // There are no spaces in coordinate elements which belong to placemarks
					{
						var point = parsePoint(coordinateElements.item(i).textContent);
						var placemark = createMarker(point, coordinateElements.item(i).parentNode.parentNode.childNodes.item(1).textContent, markerIcon, "<h3>" + coordinateElements.item(i).parentNode.parentNode.childNodes.item(1).textContent + "</h3><br>" + infoHTML);
						map.addOverlay(placemark);
						bounds.extend(point);
						if(i==0  && lookAtElements.length != 1)
						{
							map.setZoom(metersToZoom(parseInt(lookAtElements.item(1).childNodes.item(7).textContent)));
							map.setCenter(point);
						}
						else
						{
							map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter());
						}
					}
					else if(coordinateElements.item(i).textContent.length != 0)
					{
						coordinateString = coordinateElements.item(i).textContent;
						var pointArray = [];
						var j; // Because we need it later
						for(j=0;coordinateString.search(" ") != -1;j++)
						{
							pointArray[j] = parsePoint(coordinateString);
							coordinateString = coordinateString.substring(coordinateString.search(" ") + 1);
						}
						// When the loop breaks, there should be only one point left,
						pointArray[j] = parsePoint(coordinateString);
						map.addOverlay(new GPolyline(pointArray));
					} // end of points/path if/else-if
				} // end of element-cycling for
			} // end of IE/Firefox if
		} // end of readystate if
	} // end of request
	request.send(null);	
} // end of function



function mapLoad(ID)
{
	
	if(GBrowserIsCompatible())
	{
		var KMLurl = "http://gombeblog.janegoodall.org/" + ID + ".kml";
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(-4.687901,29.636370), 5, G_SATELLITE_MAP);

		var mt = map.getMapTypes();
		for (var i=0; i<mt.length; i++) 
		{
			mt[i].getMinimumResolution = function() {return 1;}
			mt[i].getMaximumResolution = function() {return 18;}
		}
		addKMLInfo(KMLurl, binocIcon, "<p align='center'><a href ='" + KMLurl + "'><img src = 'http://gombeblog.janegoodall.org/images/earth3.gif' border = '0'></img></a>&nbsp;<a href ='" + KMLurl + "'>Open this entry in Google Earth</a></p>")
	}
}
