
 
var map;
var gdir;
var geocoder = null;
var addressMarker;
var mpg;
var cost;
var route;
//var trafficInfo = new GTrafficOverlay();;
    	
    
function initialize(bMap, from, to, mpg, gascost) {

  var x;
  var y;
    	
  x = 40.757;
  y = -73.957;
    	
  // document.getElementById("debug").innerHTML = "here: initialize";

  if (GBrowserIsCompatible()) {  
    if (bMap == '1'){
      map = new GMap2(document.getElementById("map_canvas"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      //map.setCenter(new GLatLng(42.361989,-71.080732),13);
      map.setCenter(new GLatLng(x,y),13);
      //map.addOverlay(trafficInfo);
	        
      //Message
      //map.openInfoWindow(map.getCenter(), document.createTextNode("Welcome to MuzzleYourGuzzle.com!"));
      map.openInfoWindowHtml(new GLatLng(x-0.01,y), "<div class='maptitle'>Welcome to MuzzleYourGuzzle.com!</div><P>Estimate Your Gas Usage!"
			     + "<P>Select POI ('Points of Interest') for a quick search. ");
		
	                
      gdir = new GDirections(map, document.getElementById("directions"));
	        
    }else{
      gdir = new GDirections();
    }
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    //setDirections("Boston", "Mountain View", "en_US");
  }
      
  // corners
  Nifty("div#wrapper","big");
  Nifty("div#introtext","");
  Nifty("div#tool","");
  Nifty("div#tips","");
  Nifty("div#links","");
  Nifty("#navbar li","small transparent top");

  // Load directions if parameters were passed in
  if (from && to && mpg && gascost) {
    document.forms['dirform'].fromAddress.value = from;
    document.forms['dirform'].toAddress.value = to;
    document.forms['dirform'].gascost.value = gascost;
    document.forms['dirform'].mpg.value = mpg;

    var vehicles = new Array();
    setDirections(from, to, mpg, gascost, vehicles);
  }
}
    
function setDirections(fromAddress, toAddress, specifiedMPG, gasCost, vehiclesArr) {

  // document.getElementById("debug").innerHTML = "here: setDirections";

  gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": "en_US" });
  
      
  mpg = specifiedMPG;
  gas = gasCost;
  vehicles = "";
  
  for (var i = 0; i < vehiclesArr.length; i++) {
    if (vehiclesArr[i].checked) {
      vehicles = vehicles + vehiclesArr[i].value + "|";
    }
  }
}

function handleErrors(){
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or 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)
    alert("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)
    alert("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)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
  else alert("An unknown error occurred.");
	   
}

function onGDirectionsLoad(){ 
  // Use this function to access information about the latest load()
  // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...

  if (mpg <= 0) {
    alert("Invalid miles per gallon entry");
    return;
  }
  if (gas <= 0) {
    alert("Invalid gas price entry");
    return;
  }

  var distanceURL = gdir.getDistance().meters;
  var durationURL = gdir.getDuration().seconds;
  
  var dataURL = "/calculatefare.php?distance="+distanceURL+"&duration="+durationURL+"&specifiedMPG=" + mpg + "&gasCost=" + gas + "&vehicles=" + vehicles;

  //document.getElementById("debug").innerHTML = "here" + vehicles;

  GDownloadUrl(dataURL, function(data) {
		 var xml = GXml.parse(data);

		 var datablocks = xml.documentElement.getElementsByTagName("datablock");
		 var datablockStr = "";
		 for (var i = 0; i < datablocks.length; i++) {
		   datablockStr = datablockStr + "<div class='datablock'>" + datablocks[i].getAttribute("data") + "</div>";
		 }		   
		 
		 document.getElementById("datablocks").innerHTML = datablockStr;
	       });
	       
}
