<!--

// Parts of this are Copyright © caeus.com Ltd.
// www.caeus.com
// 0800 970 2955
// All Rights Reserved
// These scripts must not be reproduced in any way without permission.
// Please, however, feel free to link to the page from your web site.



// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();

// retrieves the HMLHttpRequest object
function createXmlHttpRequestObject()
{
   // will store the reference to the XMLHttpRequest object
   var xmlHttp;
   
   // if running Internet Explorer
   if(window.ActiveXObject)
   {
      try
	  {
	     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	  }
	  catch (e)
	  {
	     xmlHttp = false;
	  }
   }
   // if running Mozilla or other browsers
   else {
      try
	  {
	     xmlHttp = new XMLHttpRequest();
	  }
	  catch (e)
	  {
	     xmlHttp = false;
	  }
   }
   
   // return the created object or display an error message
   if (!xmlHttp)
      alert("Error creating the XMLHttpRequest object.");
   else
      return xmlHttp;
}

// executed automatically when a message is received from the server
function handleServerResponse(tr)
{
   // move forward only if the transaction has completed
   if (xmlHttp.readyState == 4)
   {
      // status of 200 indicates the transaction completed successfully
	  if (xmlHttp.status == 200)
	  {
	     // extract the XML received from the server
		 xmlResponse = xmlHttp.responseXML;
		 
		 // obtain the document element (the root element) of the XML structure
		 xmlDocumentElement = xmlResponse.documentElement;
		 
		 // get the text message, which is in the first child of the document element
		 resultMessage = xmlDocumentElement.firstChild.data;
		 
		 // ensure a clean canvas to write to
		 document.getElementById("ajaxDiv"+tr).innerHTML = "";
		 
		 // update the client display using the data received from the server
		 document.getElementById("ajaxDiv"+tr).innerHTML = resultMessage;
		 
		 // restart sequence
		 //setTimeout('process()', 250);
	  }
	  // a HTTP status other than 200 signals an error
	  else {
	     alert("There was a problem accessing the server: " + xmlHttp.status + " - " + xmlHttp.StatusText);
	  }
   }
}

function processMileage(tr)
{
// make asynchronous HTTP request using the XMLHttpRequest object

   // proceed only if the xmlHttp object isn't busy
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
   {
      // retrieve the orderID
	  orderID = encodeURIComponent(document.getElementById("orderID_" + tr).value);
	  
      // retrieve the office location
	  office = encodeURIComponent(document.getElementById("office_location_" + tr).value);
	  
	  // retrieve the number of trips
	  trips = encodeURIComponent(document.getElementById("trips" + tr).value);
	  
	  ajaxURL = "../tools/ajax_set_invoice_addresses.php?orderID=" + orderID + "&office=" + office + "&trips=" + trips + "&tr=" + tr;
	  
	  //alert(ajaxURL);
	  
	  // execute the .php page from the server
	  xmlHttp.open("GET", ajaxURL, true);
	  
	  // define the method to handle server responses
	  //xmlHttp.onreadystatechange = handleServerResponse;
	  xmlHttp.onreadystatechange = function() {
	     handleServerResponse(tr); //tr to tell it which element to live update
	  }
	  
	  // make the server request
	  xmlHttp.send(null);
   }
   //else {
      // if the connection is busy, try again after 1 second
	  //setTimeOut('processVendorUsername()', 1000);
   //}
}

function calcMileage(tr, onlyClientPostCode, onlyOfficePostCode)
{
// make asynchronous HTTP request using the XMLHttpRequest object

// Note: currently, this function is missing the functionality to re-call itself with *both* addresses using only a postcode.
// If neither address can be found, it will get stuck in an infinite loop....

   // proceed only if the xmlHttp object isn't busy
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
   {
	  if((onlyClientPostCode===true) && (onlyOfficePostCode===false))
	  {   //alert("client: postcode, office: full");
	     // the client address couldn't be geocoded, but the office one could
		 
		 // retrieve the client's address (postcode only due to earlier geocoding failure)
	     address = document.getElementById("caddresspostcode" + tr).value;
		 address = address.substring(0, address.length - 2);
	  
	     // retrieve the (full) office address
	     office = document.getElementById("coffice" + tr).value;
	  }
	  else if((onlyClientPostCode===false) && (onlyOfficePostCode===true))
	  {   //alert("client: full, office: postcode");
	     // the office address couldn't be geocoded, but the client one could
		 
		 // retrieve the (full) client's address
	     address = document.getElementById("caddress" + tr).value;
	  
	     // retrieve the office address (postcode only due to earlier geocoding failure)
	     office = document.getElementById("cofficepostcode" + tr).value;
		 office = office.substring(0, office.length - 2);
	  }
	  else if((onlyClientPostCode===true) && (onlyOfficePostCode===true))
	  {   //alert("client: postcode, office: postcode");
	     // neither address could be geocoded, so try with just postcodes for both
		 
		 // retrieve the client's address (postcode only due to earlier geocoding failure)
	     address = document.getElementById("caddresspostcode" + tr).value;
		 address = address.substring(0, address.length - 2);
	  
	     // retrieve the office address (postcode only due to earlier geocoding failure)
	     office = document.getElementById("cofficepostcode" + tr).value;
		 office = office.substring(0, office.length - 2);
	  }
	  else 
	  {    //alert("client: full, office: full");
	     // no failings, so get full addresses
		 
		 // retrieve the (full) client's address
	     address = document.getElementById("caddress" + tr).value;
	  
	     // retrieve the (full) office address
	     office = document.getElementById("coffice" + tr).value;
	  }

	  
	  // retrieve the number of trips
	  trips = document.getElementById("ctrips" + tr).value;
	  
	  		geocoder = new GClientGeocoder();
		
		gDir = new GDirections();
		
		GEvent.addListener(gDir, "load", function() {
			var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
			var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
			var miles = drivingDistanceMiles;
			
		miles = encodeURIComponent((miles * (trips * 2)).toFixed(2));
		trips = encodeURIComponent(trips);
	  
	    ajaxURL = "../tools/ajax_set_invoice_mileage.php?orderID=" + orderID + "&miles=" + miles + "&trips=" + trips + "&address=" + address + "&office=" + office;
	  
	      
	  // execute the .php page from the server
	  xmlHttp.open("GET", ajaxURL, true);
	  
	  // define the method to handle server responses
	  //xmlHttp.onreadystatechange = handleServerResponse;
	  xmlHttp.onreadystatechange = function() {
	     handleServerResponse(tr); //tr to tell it which element to live update
	  }
	  
	  // make the server request
	  xmlHttp.send(null);
			
		});

		geocoder.getLocations(office, function (response) {
			if (!response || response.Status.code != 200)
			{
				if(onlyOfficePostCode===true)
				{
				   alert("Sorry, we were unable to geocode the first address:\n\n" + office);
				}
				else {
				   calcMileage(tr, false, true);
				   return;
				}
			}
			else
			{ 
				location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
				
				
						var officeFullPostCode = document.getElementById("cofficepostcode" + tr).value;
						var officeShortPostCode = officeFullPostCode.substring(0, officeFullPostCode.length - 2);
						
						if(location1.address.indexOf(officeShortPostCode) == -1)
						{
						   // Google Maps has changed the postcode (not just shortened it), so go back and use *just* the postcode (which it shouldn't change...)
						   if(onlyOfficePostCode===true)
						   {
  						      alert("Sorry, we were unable to geocode the first address:\n\n" + office);
						   }
						   else {
						      calcMileage(tr, false, true);
						      return;
						   }
						}
				
				
				geocoder.getLocations(address, function (response) {
					if (!response || response.Status.code != 200)
					{
						if(onlyClientPostCode===true)
						{
						   alert("Sorry, we were unable to geocode the second address:\n\n" + address);
						}
						else {
						   calcMileage(tr, true, false);
						   return;
						}
					}
					else
					{
						location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
						
						var addressFullPostCode = document.getElementById("caddresspostcode" + tr).value;
						var addressShortPostCode = addressFullPostCode.substring(0, addressFullPostCode.length - 2);
						
						if(location2.address.indexOf(addressShortPostCode) == -1)
						{
						   // Google Maps has changed the postcode (not just shortened it), so go back and use *just* the postcode (which it shouldn't change...)
						   if(onlyClientPostCode===true)
						   {
  						      alert("Sorry, we were unable to geocode the second address:\n\n" + address);
						   }
						   else {
						      calcMileage(tr, true, false);
						      return;
						   }
						}
						
						gDir.load('from: ' + location1.address + ' to: ' + location2.address);
					}
				});
			}
		});
		

   }
   //else {
      // if the connection is busy, try again after 1 second
	  //setTimeOut('processVendorUsername()', 1000);
   //}
}

function processCheckUsername(admincreate)
{

// make asynchronous HTTP request using the XMLHttpRequest object

   // proceed only if the xmlHttp object isn't busy
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
   {	  
	  // retrieve the username entered
	  username = encodeURIComponent(document.getElementById("username").value);
	  
	  if(admincreate == "0")
	  {
	     relpath = "./";
	  }
	  else {
	     relpath = "../";
	  }

	  // execute the .php page from the server
	  xmlHttp.open("GET", relpath + "tools/ajax_check_username_availability.php?username=" + username + "&admincreate=" + admincreate, true);
	  
	  // define the method to handle server responses
	  xmlHttp.onreadystatechange = function() {
	     handleServerResponse(""); //pass empty string as here there's only one ajaxDiv on the page to be updated 
	  }
	  
	  // make the server request
	  xmlHttp.send(null);
   }
   else {
       // if the connection is busy, try again after 1 second
	  setTimeOut('processCheckUsername()', 1000);
   }
}


//-->