// JavaScript Document

if (GBrowserIsCompatible()) {
	
	var map = null;
	var om = null;
	
	//initializes and creates the map
	//also retrieves the project data based on the variable mapType, which is set on the page
	function initialize(mapType) {
		//loading message	
		om = new OverlayMessage(document.getElementById('map'),"#FFFFFF","#2891da");
		om.Set('Loading...');
		
		map = new GMap2(document.getElementById("map")); 
		map.addControl(new GSmallMapControl()); 
		map.addControl(new GScaleControl()); 
		map.setCenter(new GLatLng(40.001935,-75.125157), 11, G_PHYSICAL_MAP);
		
		G_PHYSICAL_MAP.getMinimumResolution = function () { return 11 }; 
		G_PHYSICAL_MAP.getMaximumResolution = function () { return 15 };
		
		var city_line = new GGeoXml("http://www.phillywatersheds.org/kml/City_Line.kml");
		map.addOverlay(city_line); 
		
		GDownloadUrl("/php/getProjectMap.php?projectType=" + mapType, mapProjects);
		
		// Add a move listener to restrict the bounds range
		GEvent.addListener(map, "move", function() {
			checkBounds();
		});

	}

	//function to clear loading message
	function clearOverlay(){ om.Clear() }
	
	//base icon
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.phillywatersheds.org/img/marker/shadow-projectIcon.png";
	baseIcon.iconSize=new GSize(32,32);
	baseIcon.shadowSize=new GSize(41,32);
	baseIcon.iconAnchor=new GPoint(12,16);
	baseIcon.infoWindowAnchor = new GPoint(12,2)
	
	//green stormwater infrastructure
	var greenIcon = new GIcon(baseIcon);
	greenIcon.image = "http://www.phillywatersheds.org/img/marker/greenIcon.png";
	
	//traditional infrastructure icon
	var grayIcon = new GIcon(baseIcon);
	grayIcon.image = "http://www.phillywatersheds.org/img/marker/grayIcon.png";

	//waterways restoration icon
	var waterwaysIcon = new GIcon(baseIcon);
	waterwaysIcon.image = "http://www.phillywatersheds.org/img/marker/waterwaysIcon.png";

	//community partnership icon
	var communityIcon = new GIcon(baseIcon);
	communityIcon.image = "http://www.phillywatersheds.org/img/marker/communityIcon.png";
	
    function createMarker(point,html,icon) {
        var marker = new GMarker(point,icon);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
	}
	
	//holds project info for projects with no lat/lon
	var noCoordsList = "";
	
	//parses through xml project data and maps projects
	function mapProjects(data){
		
		var xml = GXml.parse(data)
		var projects = xml.documentElement.getElementsByTagName("project");
		
		projectCount = projects.length;
		
		for (var i=0; i<projects.length; i++) {
			
			var title = projects[i].getAttribute("title");
			var intro = projects[i].getAttribute("intro");
			var latLon = projects[i].getAttribute("latLon");
			
			var coords = latLon.split(",");
			var lat = parseFloat(coords[0]);
			var lng = parseFloat(coords[1]);
			
			var url = projects[i].getAttribute("url");
						
			//if the project has a location
			if (isNaN(lat) == false) {
				var point = new GLatLng(lat,lng);
							
				var html = "<h2>" + title + "</h2>" +
				           "<div class='txttwocolleft'>" + intro + "<br><br>" +
						   "<a href='" + url + "'>View Project Details</a></div>";
						   					
				var icon = '';
				switch (mapType) {
					case 'green':
						var marker = createMarker(point,html,greenIcon);
						map.addOverlay(marker);
						
						//uncompleted green projects KML
						var GI_projects = new GGeoXml("http://www.phillywatersheds.org/kml/GI_project_status.kml");
						map.addOverlay(GI_projects); 
		
						break;
					case 'gray':
						var marker = createMarker(point,html,grayIcon);
						map.addOverlay(marker);
						break;
					case 'waterways':
						var marker = createMarker(point,html,waterwaysIcon);
						map.addOverlay(marker);
						break;
					case 'community':
						var marker = createMarker(point,html,communityIcon);
						map.addOverlay(marker);
						break;
				}
				
			} else { //otherwise, just add it to the list of projects that have no location, which will be listed out on the webpage
				noCoordsList = noCoordsList + "<h2><a href=" + url + ">" + title + "</a></h2>";					
			}
		}

		document.getElementById('noCoordsList').innerHTML = noCoordsList;
		
		//remove loading msg
		window.setTimeout(clearOverlay, 3000);
	}
		
	//bounding box for searches and panning
	var allowedBounds = new GLatLngBounds(new GLatLng(39.8480851,-75.395736), new GLatLng(40.15211,-74.863586));	
	
	/*Thank you Mike Williams
	http://econym.googlepages.com/range.htm
	If map is moved outside of a bounding box initialized on the map page, the map is
	moved back within the box.*/
 	// If the map position is out of range, move it back
  	function checkBounds() {
		// Perform the check and return if OK
		if (allowedBounds.contains(map.getCenter())) {
			return;
		}
		// It`s not OK, so find the nearest allowed point and move there
		var C = map.getCenter();
		var X = C.lng();
		var Y = C.lat();
	
		var AmaxX = allowedBounds.getNorthEast().lng();
		var AmaxY = allowedBounds.getNorthEast().lat();
		var AminX = allowedBounds.getSouthWest().lng();
		var AminY = allowedBounds.getSouthWest().lat();
	
		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
	
		map.setCenter(new GLatLng(Y,X));
	}

} else {
  alert("Sorry, Google Maps is not compatible with this browser");
}
