/***********************************************************************************************
*	Title:				projectmap.js
*	Version:			1.0.1
*
*	Date Created:	10/24/2006
*	Updated On:		06/19/2007
*	
*	Create By: 		Brian Bal
*	Company: 			Washtenaw County Road Commission
*
*	Description:	builds, displays, and controls the project map
*	Requires:			parse-roadwork.js v0.9.x
*
*	Changes:		
*								+ 1.0.1 fixed bug with not displaying Media Advisories in IE
*								+ 1.0.0.0 Multiple Tweaks and added detour map output to bubble
*								+ 0.9.6.1 load(path to xml file) instead of load()
*								+ 0.9.6.1 Cleaner, Better, Prettier code
*								+ 0.9.6.1 Alpha sort places completed projects before ongoing work
*								+ 0.9.6.1 Changed innerHTML of infowindow
*								+ 0.9.6.0 Changed the way markers, info are added to arrays
*								+ 0.9.5.0 GMarkerManger Class used to improve preformance
*								+ 0.9.4.0 Added DotMover (should be commented out when not needed)
*								+ 0.9.4.0 Zoom in when township is selected
*								+ 0.9.3.0 Added Twp Borders as Polylines
*								+ 0.9.3.0 Display Green Markers for completed Projects
*								+ 0.9.2.0 Various Bug Fixes
***********************************************************************************************/
    
    var map = null;
    var mgr = null;
    var xmlDoc;
    var req;
    var projectsA = new Array();
    var roadmarkers = new Array();
    var infohtml = new Array();
    
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/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 load(path){
			$('twp_select').options[0].selected = true;
			xmlDoc = getXMLDocument();
			sendRequest(path);
		}
    
    
	function getXMLDocument()
	{
		var xDoc=null;
		if (document.implementation && document.implementation.createDocument)
		{
			xDoc=document.implementation.createDocument("","",null);
		}else if (typeof ActiveXObject != "undefined"){
			var msXmlAx=null;
			try{
				msXmlAx=new ActiveXObject("Msxml2.DOMDocument");
			}catch (e){
				msXmlAx=new ActiveXObject("Msxml.DOMDocument");
			}
			xDoc=msXmlAx;
		}
		if(xDoc=null || typeof xDoc.load=="undefined"){
			xDoc=null;
		}
		return xDoc;
	}
	
	
	function getXMLHTTPRequest()
	{
		var xRequest=null;
		if(window.XMLHttpRequest)
		{
			xRequest=new XMLHttpRequest();
		}else if (typeof ActiveXObject != "undefined"){
			xRequest=new ActiveXObject("Microsoft.XMLHTTP");
		}
		return xRequest;
	}
	
	
	function sendRequest(url,params,HttpMethod)
	{
		req=getXMLHTTPRequest();
		if(req){
			req.onreadystatechange=onReadyStateChange;
			req.open("GET", url, true);
			req.send("");
		}
	}
	
	
	function onReadyStateChange()
	{
		var ready=req.readyState;
	
		if(ready==4)
		{
			if (req.status == 200) {
				var data=null;
				data=req.responseXML;
				loadPage(data);
			}else{
				alert("There was a problem retrieving the XML data:\n" +
				req.statusText + " " + req.status);	
			}
		}
	}
	
	
	//this function will load the page and all of its elements
	function loadPage(data)
	{
		xmlDoc = data;
		var pa = parseXML();
		pa.sort(sortByTitle);
		projectsA = pa;
		buildMap(pa, "Any");
	}
	
	//this function will update the markers on the map and the mc list
	function updateProjectMap(twpName)
	{
		var mc = document.getElementById("mc")
		mc.innerHTML = "";
		roadmarkers = new Array();
		infohtml = new Array();
		buildMap(projectsA, twpName);
	}
			
	// this function takes two strings as a,b
	// returns: -1, 1 or 0 depending on sort
	function sortByTitle(a,b)
	{
		ret = 0;
		if(a['title'] < b['title']){
			ret = -1;
		}else if(a['title'] < b['title']){
			ret = 1;
		}else{
			ret = 0;
		}
		
		if(a['complete'] == "yes" && b['complete'] == "no"){
			ret = -1;
		}
		if(a['complete'] == "no" && b['complete'] == "yes"){
			ret = 1;
		}
		if(a['complete'] == "pre" && b['complete'] != "pre"){
			ret = 1;
		}
		if(a['complete'] != "pre" && b['complete'] == "pre"){
			ret = -1;
		}
		return ret;
	}
    
    function buildMap(pa, twpname) 
    {
		if (GBrowserIsCompatible()) 
		{
			
			// Setup the Map
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			
			// Zoom in on the map if township is selected
			if(twpname == "Lyndon"){map.setCenter(new GLatLng(42.37921, -84.08008), 12);}
			else if(twpname == "Dexter"){map.setCenter(new GLatLng(42.37909, -83.95889), 12);}
			else if(twpname == "Webster"){map.setCenter(new GLatLng(42.38492, -83.84113), 12);}
			else if(twpname == "Northfield"){map.setCenter(new GLatLng(42.3849, -83.72131), 12);}
			else if(twpname == "Salem"){map.setCenter(new GLatLng(42.38822, -83.60595), 12);}
			else if(twpname == "Sylvan"){map.setCenter(new GLatLng(42.29178, -84.07012), 12);}
			else if(twpname == "Lima"){map.setCenter(new GLatLng(42.29331, -83.95614), 12);}
			else if(twpname == "Scio"){map.setCenter(new GLatLng(42.29788, -83.83975), 12);}
			else if(twpname == "Ann Arbor"){map.setCenter(new GLatLng(42.30118, -83.71307), 12);}
			else if(twpname == "Superior"){map.setCenter(new GLatLng(42.30397, -83.60287), 12);}
			else if(twpname == "Sharon"){map.setCenter(new GLatLng(42.2090, -84.0660), 12);}
			else if(twpname == "Freedom"){map.setCenter(new GLatLng(42.2071, -83.9561), 12);}
			else if(twpname == "Lodi"){map.setCenter(new GLatLng(42.20919, -83.83667), 12);}
			else if(twpname == "Pittsfield"){map.setCenter(new GLatLng(42.2152, -83.71307), 12);}
			else if(twpname == "Ypsilanti"){map.setCenter(new GLatLng(42.2173, -83.6018), 12);}
			else if(twpname == "Manchester"){map.setCenter(new GLatLng(42.1156, -84.0660), 12);}
			else if(twpname == "Bridgewater"){map.setCenter(new GLatLng(42.1175, -83.9520), 12);}
			else if(twpname == "Saline"){map.setCenter(new GLatLng(42.1216, -83.8325), 12);}
			else if(twpname == "York"){map.setCenter(new GLatLng(42.1277, -83.7034), 12);}
			else if(twpname == "Augusta"){map.setCenter(new GLatLng(42.1287, -83.5963), 12);}
			else {map.setCenter(new GLatLng(42.2547, -83.8375), 10);}
			
			// set the map type
			map.setMapType(G_NORMAL_MAP);
			
			// Add an ecoded polylines
			addPolies();
			
			// Add DotMover
			//addDoteMover();
			
			// Add markers to the map at locations from xml file
			// also add the li with zoom to ballon link
			var mcList = "<div id=\"mc-list\">\n";
			
			// create letter counter varibale
			var letterCount = 0;
			
			// create the variable for testing
			var trubar = false;
			var matchStr = "";
			
			// Cycle through all projects then add them to the map if
			//  they are in the right township
			for (var i = 0; i < pa.length; i++) 
			{
				trubar = false
				matchStr = pa[i]['township'];
				
				if(( matchStr.match(twpname) || twpname == "Any") && pa[i]['onmap'] == "yes")
				{
					//create the point
					var point = new GLatLng(parseFloat(pa[i]['lat']), parseFloat(pa[i]['lng']));
					
					
					//create html for info window
					info = "<h4>" + pa[i]['title'] + "</h4>";
					
					info = info +  "<dl class=\"small\">";
					
					if (pa[i]['status'] != "Not Available")
					{
						info = info +  "<dt>Impact to traffic:</dt>";
						info = info +  "<dd>" + pa[i]['status'] + "</dd>";
					}
					
					info = info +  "<dt>Schedule:</dt>";
					info = info +  "<dd>" + pa[i]['schedule'] + "</dd>";
					
					info = info +  "<dt>Work being done:</dt>";
					info = info +  "<dd>" + pa[i]['desc'] + "</dd>";
					
					if (pa[i]['contact'] != "Not Available")
					{
						info = info +  "<dt>Contact Info:</dt>";
						info = info + "<dd><div class=\"vcard\">" +
						"<span class=\"fn\">" + pa[i]['contact'] + "</span><br />\n" +
						"<a class=\"email\" href=\"mailto:" + pa[i]['email'] + "\">" + 
						pa[i]['email'] + "</a><br />" + 
						"<span class=\"tel\"><span class=\"type\" style=\"display: none;\">Work</span>" + 
						"<span class=\"value\">" + pa[i]['phone'] + "</span></span></div></dd>";
					}
					
					info = info +  "</dl>";
					
					// add link to projectpage.htm
					info = info + "<a href=\"../roadwork/projectpage.htm?year=2010&project=" + pa[i]['id'] + "\">More Info</a>";
					
					if (pa[i]['detours'] != "Not Available")
					{
						info = info + " | <a href=\"projects/detours/" + pa[i]['detours'] + "\">Detour Map</a>";
					}
					
					if (pa[i]['advisory'] != "Not Available")
					{
						info = info + " | <a href=\"../news/media/" + pa[i]['advisory'] + "\">Media Advisory</a>";
					}
					
					
					infohtml.push(info);
					
					
					// create the marker
					if(pa[i]['complete'] == "yes"){
						roadmarkers.push(createGreenMarker(point, letterCount, info));
					}
					if(pa[i]['complete'] == "pre"){
						roadmarkers.push(createYellowMarker(point, letterCount, info));
					}
					if(pa[i]['complete'] == "no"){
						roadmarkers.push(createRedMarker(point, letterCount, info));
					}
					
					
					//create the mc zoom links
					//get the letter of the marker and then the url of the marker
					letter = String.fromCharCode("A".charCodeAt(0) + letterCount);
					
					
					imageURL = "#";
					letter = String.fromCharCode("A".charCodeAt(0) + letterCount);
					if(pa[i]['complete'] == "yes"){
						imageURL = "http://wcroads.org/images/mapfiles/marker-green-" + letter + ".png";
					}
					if(pa[i]['complete'] == "pre"){
						imageURL = "http://wcroads.org/images/mapfiles/yellow-marker-" + letter + ".png";
					}
					if(pa[i]['complete'] == "no"){
						imageURL = "http://www.google.com/mapfiles/marker" + letter + ".png";
					}
					
					
					//add the image to the list
					mcList = mcList + "\t<div style=\"background: url('" + imageURL + "') no-repeat top left;\">";
					
					//add the roadwork title to the li
					mcList = mcList + "<span><a href=\"javascript:panToRoad(" + pa[i]['lat'] + "," + pa[i]['lng'] + ",15," + letterCount + ")\">" + pa[i]['title'] + "</a></span>";
					
					mcList = mcList + "<p>" + pa[i]['location'] + "<br />";
					
					mcList = mcList + pa[i]['desc'] + "</p>";
					
					// close the project div tag
					mcList = mcList + "</div>\n";
					
					//increment to the next letter
					letterCount ++;
					
				}// and of twpname if
			}// end of pa for loop
			
			// add the markers to the map with the marker manager
			mgr = new GMarkerManager(map);
			mgr.addMarkers(roadmarkers, 8, 17);
			mgr.refresh();
               
			//add the end of the mclist and then put it on the page
			mcList = mcList + "</div>\n";
			var mc = document.getElementById("mc")
			mc.innerHTML = mcList;
			
		}//end of if supported browser
	}//end of onload()
	
	// Creates a red marker at the given point with the given number label
	function createRedMarker(point, index ,info) 
	{
		// Create a lettered icon for this point using our icon class
		var letter = String.fromCharCode("A".charCodeAt(0) + index);
		var icon = new GIcon(baseIcon);
		icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
		var marker = new GMarker(point, icon);
		
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(info);
		});
		return marker;
	}
	
	// Creates a green marker at the given point with the given number label
	function createGreenMarker(point, index ,info) 
	{
		// Create a lettered icon for this point using our icon class
		var letter = String.fromCharCode("A".charCodeAt(0) + index);
		var icon = new GIcon(baseIcon);
		icon.image = "http://wcroads.org/images/mapfiles/marker-green-" + letter + ".png";
		var marker = new GMarker(point, icon);
		
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(info);
		});
		return marker;
	}
	
		// Creates a yellow marker at the given point with the given number label
	function createYellowMarker(point, index ,info) 
	{
		// Create a lettered icon for this point using our icon class
		var letter = String.fromCharCode("A".charCodeAt(0) + index);
		var icon = new GIcon(baseIcon);
		icon.image = "http://wcroads.org/images/mapfiles/yellow-marker-" + letter + ".png";
		var marker = new GMarker(point, icon);
		
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(info);
		});
		return marker;
	}
	
	function panToRoad(longCord, latCord, zoomAmt, pos)
	{
		// zoom to marker
		map.setCenter(new GLatLng(longCord, latCord), zoomAmt);
		
		//open the info window
		if( pos >= 0 )
		{
			roadmarkers[pos].openInfoWindowHtml(infohtml[pos]);
		}else{
			map.closeInfoWindow();
			$('twp_select').options[0].selected = true;
			updateProjectMap("Any")
		}
	}
	
	function addPolies()
	{
			var cbPoints = "sb}aGlfo`Og^}gqBjibA{u@vaB`kqB{ldAvr@";
			var cdLevels = "BBBBB";
 
			var countyBorder = new GPolyline.fromEncoded({
				color: "#333333",
				weight: 3,
				points: cbPoints,
				levels: cdLevels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(countyBorder);
			
			var twp1points = "einaGxq||NjyAdfqB";
			var twp1levels = "BB";
 
			var twp1line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp1points,
				levels: twp1levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp1line);
			
			var twp2points = "kk}`Gbc||NjkAxhqB";
			var twp2levels = "BB";
 
			var twp2line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp2points,
				levels: twp2levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp2line);
			
			var twp3points = "gaj`Gf`n`OobAgjqB";
			var twp3levels = "BB";
 
			var twp3line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp3points,
				levels: twp3levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp3line);
			
			var twp4points = "k{}aGzvs}NfvbAmbA";
			var twp4levels = "BB";
 
			var twp4line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp4points,
				levels: twp4levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp4line);
			
			var twp5points = "{t}aGnuk~NzccAmsA";
			var twp5levels = "BB";
 
			var twp5line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp5points,
				levels: twp5levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp5line);
			
			var twp6points = "sn}aGlla_OrqcA?";
			var twp6levels = "BB";
 
			var twp6line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp6points,
				levels: twp6levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp6line);
			
			var twp7points = "qh}aGfox_O`_dA{t@";
			var twp7levels = "BB";
 
			var twp7line = new GPolyline.fromEncoded({
				color: "#00cc00",
				weight: 1,
				points: twp7points,
				levels: twp7levels,
				zoomFactor: 32,
				numLevels: 4
			});
			
			map.addOverlay(twp7line);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function addDotMover()
	{
		var center = new GLatLng(42.2547, -83.8375);
		var marker = new GMarker(center, {draggable: true});
		
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		
		GEvent.addListener(marker, "dragend", function() {
			point = marker.getPoint();
			lat = point.lat();
			lng = point.lng();
			marker.openInfoWindowHtml("<br /><p>" + lat + ", " + lng + "<p>");
		});
		map.addOverlay(marker);
	}
