//Load API's
google.load('search', '1');
google.load('maps', '2');

//Define our Globals
var map;			//Map API
var gdir;			//Direction API
var gFirstSearch;	//The From Local Search
var gSecondSearch;	//The To Local Search

var fromAddress;	//From Address The user inputs
var toAddress;		//To Address the user inputs

var first;			//First Set of Results for From Search
var second;			//Second Set of Results for To Search

//Round Function, Much Apreciated
//http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html
//MadCowDzz
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

//Sort the Result Address String
function sortAddress(result){
	var str = "";
	
	if (result.title != "" || result.title != "undefined") 
		{ str = result.title + "</br>"; }
	if (result.streetAddress != "" || result.streetAddress != "undefined" || result.streetAddress != result.title) 
		{ str += result.streetAddress + "</br>"; }
	if (result.city != "" || result.city != "undefined" || result.city != result.streetAdderss) 
		{ str += result.city + "</br>"; }
	if (result.country != "" || result.country != "undefined") 
		{ str += result.country; }
		
	return str;

}

//On Load, Load all the Details Needed
function OnLoad(){
	
	//Set up the Map and the Globals
	//If the Browser Supports its
	if (GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(52.037366,-0.703726), 7);
		map.removeMapType(G_HYBRID_MAP);
		
		var mapControl = new GMapTypeControl();
		map.addControl(mapControl);
		map.addControl(new GLargeMapControl());
		
		gdir = new GDirections(map);
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		
		gFirstSearch = new google.search.LocalSearch();
		gFirstSearch.setCenterPoint(map);
		gFirstSearch.setSearchCompleteCallback(null, FirstSearch);
	
		gSecondSearch = new google.search.LocalSearch();
		gSecondSearch.setCenterPoint(map);
		gSecondSearch.setSearchCompleteCallback(null, SecondSearch);		
	}
}

//Run the From Search
//Runs after the gFirstSearch.execute has finished
//Reference: setSearchCompleteCallback
function FirstSearch(){
	
	if (!gFirstSearch.results.length){ alert("Could Not Find: " + fromAddress + "\n Please Try Refining your 'From' Address Field"); return; }
	//Return the First Result into a Variable
	first = gFirstSearch.results[0];
		
	//Execute the Second
	gSecondSearch.execute(toAddress);
		
}

//Run the To Search
//Runs after the gSecondSearch.execute has finished
//Reference: setSearchCompleteCallback
function SecondSearch(){
	
	
	if (!gSecondSearch.results.length){ alert("Could Not Find: " + toAddress + "\n Please Try Refining your 'To' Address Field"); return; }
	
	//Returns the Second results into a Variable
	second = gSecondSearch.results[0];
	
	//Plot our Graph
	gdir.load("from: " + (first.lat + ", " + first.lng) + " to: " + (second.lat + ", " + second.lng));
	
	
}

//Use to Execite our Form Commands
function setDirections(ifromAddress, itoAddress) {
	if (GBrowserIsCompatible()) { 
	
		//Initiate the inputs into our Global Variables
		fromAddress = ifromAddress; 
		toAddress = itoAddress;
		
		//Execute our Search
		gFirstSearch.execute(fromAddress);	
		
		//Return False so our broweser dosent Refresh
		return false;
	}
}

//Set the Values in our HTML after Direction has loaded
function onGDirectionsLoad(){ 
	
	var miles = gdir.getDistance().meters * 0.000621371192;
	miles = roundNumber(miles, 2);
	document.getElementById("distance").innerHTML = "Distance: " + miles + " ml";
	document.getElementById("price").innerHTML = "Price: &pound;" + roundNumber(((miles * 1.30) + 5), 2);

	
	
	var fromstr = sortAddress(first);
	var tostr = sortAddress(second);
		
	document.getElementById("fromTable").innerHTML = "<b>From:</b> </br>" + fromstr;
	document.getElementById("toTable").innerHTML = "<b>To:</b> </br>" + tostr;
	//document.getElementById("from").value = fromAddString;
  // and yada yada yada...
}

//Error Handling
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.");
   
}

//Load google API on Page Load
//Run the OnLoad Function
google.setOnLoadCallback(OnLoad, true);
