/* Google Maps API for directions */

//<![CDATA[
	var map = null;
    var gdir = null;
	var geocoder = null;
	var ll = null;
	var marker = null;
	var dirHtml = null;
    var geocoder = null;
	var addressText = null;
	var endingLoc = true;
	var prevText = "";
	
	function load(name, address, city, state_code, zipcode) {
      if (GBrowserIsCompatible() && document.getElementById("locations-branchleaf-directions-map") != null) {
        map = new GMap2(document.getElementById("locations-branchleaf-directions-map"));
		gdir = new GDirections(map, document.getElementById("locations-branchleaf-directions-list"));
        geocoder = new GClientGeocoder();
		addressText = address + ", " + city + ", " + state_code + " " + zipcode;
		geocoder.getLatLng(
			addressText,
			function(point) {
				  if (!point) {
					alert(address + " not found, please contact the website administrator to resolve this issue.");
				  } 
				  else {
				  	ll = new GLatLng(point.lat(), point.lng());
					marker = new GMarker(ll);
					map.setCenter(ll, 15); 
					map.addOverlay(marker);
					GEvent.addListener(gdir, "load", onGDirectionsLoad);
					GEvent.addListener(gdir, "error", handleErrors);
			
					document.getElementById("locations-branchleaf-directions-menu").innerHTML = "Get Directions: <a href='javascript:dirTo();'>To Here</a> - <a href='javascript:dirFrom();'>From Here</a>";
			
					//setDirections("San Francisco", "Mountain View", "en_US");
					GEvent.addListener(marker, "click", function() {
					  map.openInfoWindow(ll, '<span style="font-size:10px;"><strong>Carnegie Library of Pittsburgh<br>' + name + ' Branch</strong><br><br>' + address + ',<br> ' + city + ', ' + state_code + ' ' + zipcode + '</span>');
					});
				  }
			  }
		  );
		}
    }
	
	function startOver() {
		document.getElementById("locations-branchleaf-directions-list").innerHTML = "";
		if(document.getElementById("otherAddress") != null)
		  	prevText = document.getElementById("otherAddress").value;
		GDownloadUrl("/includes/googleapi-directions_inc.cfm?sd=" + Math.floor(Math.random()*99999) + "&address=" + addressText, function(data, responseCode) {
		  setDirHtml(data);
		  document.getElementById("otherLocLabel").innerHTML = endingLoc ? "From:" : "To:";
		  document.getElementById("otherAddress").value = prevText;
		  document.getElementById("otherAddress").focus();
		  document.getElementById("otherAddress").select();
		  document.getElementById("locations-branchleaf-directions-list").style.display = "none";
		  document.getElementById("locations-branchleaf-directions-postlist").style.display = "none";
		  });
		document.getElementById("locations-branchleaf-directions-postlist").innerHTML = "";
		map.clearOverlays();
		map.setCenter(ll, 15);
		map.addOverlay(marker);
	}
	
	function dirTo() {
		endingLoc = true;
		document.getElementById("locations-branchleaf-directions-form").style.display = "inline";
		document.getElementById("locations-branchleaf-directions-menu").innerHTML = "Get Directions: To Here - <a href='javascript:dirFrom();'>From Here</a>";
		startOver();
	}
	
	function dirFrom() {
		endingLoc = false;
		document.getElementById("locations-branchleaf-directions-form").style.display = "inline";
		document.getElementById("locations-branchleaf-directions-menu").innerHTML = "Get Directions: <a href='javascript:dirTo();'>To Here</a> - From Here";
		startOver();
	}
    
	function setDirHtml(data) {
		document.getElementById("locations-branchleaf-directions-form").innerHTML = data;
	}
	
    function setDirections(fromAddress, toAddress, locale) {
      document.getElementById("locations-branchleaf-directions-list").innerHTML = "";
	  prevText = document.getElementById("otherAddress").value;
	  if (document.getElementById("otherAddress").value == "")
	  {
	     errorResult = ("Please enter a valid address.");
		 printError(errorResult);
		 return; 
	  }
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     errorResult = ("The specified address was not found.  Please enter more specific information, such as a zipcode.");
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     errorResult = ("A directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     errorResult = ("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     errorResult = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     errorResult = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
		 
	   else errorResult = ("The specified address was not found, an unknown error occurred.");
	   
	   printError(errorResult);  
	}
	
	function printError(msg) {
		document.getElementById("locations-branchleaf-directions-list").innerHTML = '<span style="color:red; font-weight:bold;">' + msg + '</span>';
	}

	function onGDirectionsLoad() {
		document.getElementById("locations-branchleaf-directions-list").style.display = "inline";
		document.getElementById("locations-branchleaf-directions-postlist").style.display = "inline";
		document.getElementById("locations-branchleaf-directions-form").innerHTML = '<br><a href="javascript:startOver();">Start Over</a>';
		document.getElementById("locations-branchleaf-directions-postlist").innerHTML = '<br><a href="javascript:startOver();">Start Over</a>';
	  // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}

    //]]>