// This version works with fare_calculator v3.2

var ratePerMile14		// this will be the fare per mile for 1-4 passengers
ratePerMile14 = rate14	// the default value s defined in the ~/javascript/base.js file
						// This will be changed if the journey starts or ends near one of
						// the special places, defined below.

var map;
var gdirfull, gdir;
var gdist = new GDirections(null, null); // in customers it is the other way around

var geocoder = null;
var addressMarker;

var routeArray = new Array(2);
var routeArrayFull = new Array(4);
var distArray = new Array(2);

var traffic;
var miles, duration, outstr;
var custMiles, custDuration, custSeats;

var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));


var g=google.search,s=[new g.LocalSearch,new g.LocalSearch]; 
var fromPoint, toPoint;

// Setup an array of 'special' places. Each element has three parts:
// 1. The place name
// 2. Its location in latitude-longitude
// 3. The fare per mile for 1-4 passengers if the journey starts or ends at this place.
// If neither the start nor en o journey is near a special place then the default fare will be used.
// If one of either the start OR end are near a special place then its special rate will be used.
// If both start and end are near special places the largest value will be used. This enables us to
// 'block' an onine quote by using a rate value >= 100.
// This results in no quote being given - and instead the calculator says "contact us".
var places = [];
places[0] = ["Cambridge", new GLatLng(52.202544,0.131237), 0.50];
places[1] = ["Norwich", new GLatLng(52.628101,1.299349), 0.50];
places[2] = ["Luton Airport", new GLatLng(51.879299, -0.373878), 100.00];



function setRoute(fromAddress, toAddress) {
	// alert("In setRoute\nfromAddress = " + fromAddress + "\ntoAddress = " + toAddress);
	setPointsFromPostcodes(fromAddress, toAddress);
}


function setPointsFromPostcodes(fromAddress, toAddress) { // Here's where searching starts 
  // alert("In setPointsFromPostcodes\nfromAddress = " + fromAddress + "\ntoAddress = " + toAddress);
  var result;
  var x=0,cb=function(){x++;if(x/s.length>=1){allSearchComplete(fromAddress,toAddress);}}; 
  s[0].setSearchCompleteCallback(s[0],cb); 
  s[0].execute(fromAddress + ", UK"); 
  s[1].setSearchCompleteCallback(s[1],cb); 
  s[1].execute(toAddress + ", UK");  
} 


function allSearchComplete(fromAddress,toAddress){ 
 // Now you can go on with your stuff 
	if (s[0].results[0])
	{		
		var fromLat = s[0].results[0].lat;
		var fromLng = s[0].results[0].lng;
		fromPoint = new GLatLng(fromLat,fromLng);
		// alert("From:\nLatitude: " + fromPoint.lat() + "\nLongitude: " + fromPoint.lng());
	}else{
		alert("Starting Address Not found!  Try to give a more descriptive address.");
	};

	if (s[1].results[0])
	{		
		var toLat = s[1].results[0].lat;
		var toLng = s[1].results[0].lng;
		toPoint = new GLatLng(toLat,toLng);
		// alert("To:\nLatitude: " + toPoint.lat() + "\nLongitude: " + toPoint.lng());
	}else{
		alert("Destination Address Not found!  Try to give a more descriptive address.");
	};
	//alert("In allSearchComplete\nFrom point:\nLatitude: " + fromPoint.lat() + "\nLongitude: " + fromPoint.lng() + "\n\nTo Location:\nLatitude: " + toPoint.lat() + "\nLongitude: " + toPoint.lng());
	
	setFare(fromPoint, toPoint);
	
	set3partRoute(fromPoint,toPoint)

}

function setFare(fromCoord, toCoord) {
    var distMiles ;
    var specialRateStart = 0
    
	for (var i = 0; i < places.length; i++) {
	  distMiles = fromCoord.distanceFrom(places[i][1])/1609.344;
	  if (distMiles < 5) {
		// alert("Journey starts close to " + places[i][0] + " (" + distMiles.toFixed(2) + " miles)" );
		specialRateStart = places[i][2]
	  }	   
	};
	
    specialRateEnd = 0
	for (var i = 0; i < places.length; i++) {
	  distMiles = toCoord.distanceFrom(places[i][1])/1609.344;
	  if (distMiles < 5) {
		// alert("Journey ends close to " + places[i][0] + " (" + distMiles.toFixed(2) + " miles)" );
		specialRateEnd = places[i][2]
	  }	   
	};
	
	var specialRate = Math.max(specialRateStart,specialRateEnd)
	// alert("specialRate = " + specialRate);
    if (specialRate == 0) 
    {ratePerMile14 = rate14}
    else
    {ratePerMile14 = specialRate};
	
}


function set3partRoute(fromCoord, toCoord) {
  // alert("In set3partRoute\nfromCoord = " + fromCoord + "\ntoCoord = " + toCoord);
  routeArray[0]=fromCoord;
  routeArray[1]=toCoord;
  gdir.loadFromWaypoints(routeArray);

  // Les' home: var homeCoord = new GLatLng(52.283186,0.328348);
  // Brian's home: var homeCoord = new GLatLng(52.271019,0.494409);
  // Wag's home: var homeCoord = new GLatLng(52.271743,0.328722);
  var homeCoord = new GLatLng(52.271743,0.328722);
  routeArrayFull[0]=homeCoord;
  routeArrayFull[1]=fromCoord;
  routeArrayFull[2]=toCoord;
  routeArrayFull[3]=homeCoord;
  gdirfull.loadFromWaypoints(routeArrayFull);
}


function handleErrors(){
   if (gdirfull.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	 {
	 alert("Could not identify one of these addresses. If you used a postcode make sure that there is a space between the two parts. Try giving more information such as the county, or adding a 'UK' to the end.\nError code: " + gdirfull.getStatus().code);
	 document.getElementById("output").innerHTML = "Sorry. Unable to calculate fare. Please email <A href='mail:contact@wikitaxis.co.uk'>WikiTaxis<\/A> to ask for a quote"
	 }
   else if (gdirfull.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: " + gdirfull.getStatus().code);
	 document.getElementById("output").innerHTML = "Sorry. Unable to calculate fare. Please email <A href='mail:contact@wikitaxis.co.uk'>WikiTaxis<\/A> to ask for a quote"
	 }
   else if (gdirfull.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: " + gdirfull.getStatus().code);
	 document.getElementById("output").innerHTML = "Sorry. Unable to calculate fare. Please email <A href='mail:contact@wikitaxis.co.uk'>WikiTaxis<\/A> to ask for a quote"
	 }
//   else if (gdirfull.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: " + gdirfull.getStatus().code);
	 
   else if (gdirfull.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: " + gdirfull.getStatus().code);
	 document.getElementById("output").innerHTML = "Sorry. Unable to calculate fare. Please email <A href='mail:contact@wikitaxis.co.uk'>WikiTaxis<\/A> to ask for a quote"
	 }
   else if (gdirfull.getStatus().code == G_GEO_BAD_REQUEST)
	 {
	 alert("A directions request could not be successfully parsed.\n Error code: " + gdirfull.getStatus().code);
	 document.getElementById("output").innerHTML = "Sorry. Unable to calculate fare. Please email <A href='mail:contact@wikitaxis.co.uk'>WikiTaxis<\/A> to ask for a quote"
	 }
   else 
	 {
	 alert("Unknown error. \nError code: " + gdirfull.getStatus().code);
	 document.getElementById("output").innerHTML = "Sorry. Unable to calculate fare. Please email <A href='mail:contact@wikitaxis.co.uk'>WikiTaxis<\/A> to ask for a quote"
	 }
}

