// JavaScript Document



	var localSearch = new GlocalSearch(); 

 

    var map;

    var gdir;

    var geocoder = null;

    var addressMarker;

	var disti

	var fare

	var bounds = new GLatLngBounds();

	var rowdata

	var activefield
	var i



function clearbox(name)	

{

	document.getElementById(name).value='';

	

}



function load(field)
   {

	   
	   document.getElementById("bookavail").value='N';
	   var strlen = document.getElementById(field).value;
	   showmiddlediv();
	if(strlen.length >=3){
	   activefield = field;
	   var postc = isValidPostcode(document.getElementById(activefield).value);
	   //alert(document.getElementById(activefield).value);
	   //alert(postc);
	   //lets test and see if the input is a postcode
	   if (postc){
		   usePointFromPostcode(document.getElementById(activefield).value, displayStreet);
	   }
	   else{
 //document.getElementById("middlebar").innerHTML=d;
	   document.getElementById("middlediv").innerHTML='<div id="loader" class="loader"><img class="loaderimage" src="images/activity_indicators/7.gif" /></div>';

      // Create new map object

      //map = new GMap2(document.getElementById("rightbar"));



      // Create new geocoding object

      geocoder = new GClientGeocoder();



      // Retrieve location information, pass it to addToMap()

      geocoder.getLocations(document.getElementById(field).value+',GB', addToMap);
	  document.getElementById(activefield).blur;
	   }
	}
	else {
		document.getElementById(field).focus;
	}
   }

 

 function addToMap(response)

   {

	
	   rowdata='';

	   map.clearOverlays();

	   if (response.Status.code == G_GEO_SUCCESS) {

	   var i = 0;

	   for (i=0;i<=8;i++) {

		  //alert(i);

      // Retrieve the object

	 //alert(response.placemark[i]);

	 



      place = response.Placemark[i];

	  if (place!=null){

		  var p = place.Point.coordinates;

              var lat=p[1];

              var lng=p[0];

              // Display the results in XML format

              var xml = '&nbsp;&nbsp;&lt;marker address="' + place.address + '"&gt;<br>';

              //document.getElementById("middlebar").innerHTML += xml;

			  var pointer = "hand";
	  
if(i<=9){
				rowdata = rowdata + '<tr><td id="rowstd"><div class="yellowicon"><img src="images/icon_yellow' + (i+1) + '.png" border="0px"/></div><div class="suggestedrows" id=row' + i + ' onmouseover="cursorchange()" onmouseout="pointerchange()" onclick="dummyfunction('+i+')">' + place.address + '</div></td></tr>';
} else {
	rowdata = rowdata + '<tr><td><div class="suggestedrows" id=row' + i + ' 			onmouseover="cursorchange()" onmouseout="pointerchange()" onclick="dummyfunction('+i+')">' + place.address + '</div></td></tr>';	
	
}

      // Retrieve the latitude and longitude

     

	 point = new GLatLng(place.Point.coordinates[1],

                          place.Point.coordinates[0]);


rowdata = rowdata + '<tr><td><div class="suggestedrows" style="display:none" id=latlon' + i + ' onmouseover="cursorchange()" onmouseout="pointerchange()" onclick="dummyfunction('+i+')">' + point + '</div></td></tr>';



      // Center the map on this point

	  if (i==0) {

	//document.getElementById("fromAddress").value = place.address;

      map.setCenter(point, 13);

	  }



      // Create a marker
	var Icon = new GIcon();
	Icon.image ='images/icon_yellow' + (i+1) + '.png' ;
	//Icon.shadow = "path to your icon shadow";
	//Icon.iconSize = new GSize(12,20);
	//Icon.shadowSize = new GSize(22, 20);
	Icon.iconAnchor = new GPoint(6, 20);
	Icon.infoWindowAnchor = new GPoint(6, 1);
	//Icon.infoShadowAnchor = new GPoint(13, 13); 

      marker = new GMarker(point,Icon);



      // Add the marker to map

      map.addOverlay(marker);



      // Add address information to marker

      //marker.openInfoWindowHtml(place.address);

		bounds.extend(point);

	  showmapcontrols();

	   }

	   

	   }

	   createlocationstable();

	   }

	   	   else {

                document.getElementById("middlediv").innerHTML = "Sorry but we haven't got any suggestions for that location";

	   }

	   map.setZoom(map.getBoundsZoomLevel(bounds));

	   map.setCenter(bounds.getCenter());

	   

   }

   function clearerror(){
	   
	document.getElementById('disclaimer').innerHTML='<a class="body">Disclaimer : The price quoted above is intended solely to give you a good idea of your likely journey price. The actual fare will be ran on the taximeter in line with the local authorities regulations. </a>';   
   }




    function getDirections(fromAddress, toAddress, toAddress1, toAddress2, toAddress3, toAddress4, locale, settings, address1,address2,address3,address4,address5,address6) {

		var trip
		var btrip
		var msetting
		var headtrip
		
		
		//alert('settings' + settings);
		//document.getElementById('disclaimer').innerHTML="<a style='color:red';> Sorry, There was a problem with one of the addresses you entered, pelase check and try again. remember to select a valid address from the middle column.</a>";
		
		document.getElementById("middlediv").innerHTML='<div id="loader" class="loader"><img class="loaderimage" src="images/activity_indicators/7.gif" /></div>';

		map.clearOverlays();
		//alert(trip);
		document.getElementById("middlediv").innerHTML = '';
		
		trip = fromAddress + ',' + toAddress;
		btrip = address1 + " : " + address2;
		headtrip = "Driving directions to " + address2;
		
		
	
		if (toAddress4 != '') {
			
			if (settings!='A'){
			gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1,toAddress2,toAddress3,toAddress4],{avoidHighways:false}); } else {
				gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1,toAddress2,toAddress3,toAddress4],{avoidHighways:true}) }
		} else if(toAddress3 != '') {
if (settings !='A'){
			gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1,toAddress2,toAddress3],{avoidHighways:false}); } else {
				gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1,toAddress2,toAddress3],{avoidHighways:true});
				
			}
			

		} else	if(toAddress2 != '') {
			if (settings !='A'){
			gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1,toAddress2],{avoidHighways:false});} else {
			gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1,toAddress2],{avoidHighways:true});	
			}
			
		
		} else if(toAddress1 != '') {
			if (settings !='A'){
			gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1],{avoidHighways:false}); } else {
				gdir.loadFromWaypoints([fromAddress,toAddress,toAddress1],{avoidHighways:true});
				
			}
			

		}
		 else {
			
			if (settings !='A'){
			gdir.loadFromWaypoints([fromAddress,toAddress],{avoidHighways:false});} else { 
			gdir.loadFromWaypoints([fromAddress,toAddress],{avoidHighways:true});
			
			}
		}
		
		if (address3 !==''){
			btrip = btrip + " : " + address3;
			headtrip = "Driving directions to " + address3;
		}
		if (address4 !==''){
			btrip = btrip + " : " + address4;
			headtrip = "Driving directions to " + address4;
		}
		if (address5 !==''){
			btrip = btrip + " : " + address5;
			headtrip = "Driving directions to " + address5;
		}
		if (address6 !==''){
			btrip = btrip + " : " + address6;
			headtrip = "Driving directions to " + address6;
		}
		document.getElementById("trip").value = btrip;
		document.getElementById("htrip").value = headtrip;
		
    }



 

function usePointFromPostcode(postcode, callbackFunction) {
  
  localSearch.setSearchCompleteCallback(null,
    function() {
      
      if (localSearch.results[0]) {    
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
		//var city = localSearch.results[0].streetAddress;
		//alert(resultlat);
        var point = new GLatLng(resultLat,resultLng);
        getAddress('map',point,postcode);
      }else{
        alert("Postcode not found!");
      }
    });  
    
  localSearch.execute(postcode + ", UK");
}



function showmapcontrols(){

			map.addControl(new GLargeMapControl());

		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());

}

    function initialize() {

      if (GBrowserIsCompatible()) {  

	  //opacity('route',1,50,1);   
		
        map = new GMap2(document.getElementById("mapdiv"));

        gdir = new GDirections(map, document.getElementById("middlediv"));

        GEvent.addListener(gdir, "load", onGDirectionsLoad);

        GEvent.addListener(gdir, "error", handleErrors);



		//var map = new GMap2(document.getElementById("map_canvas"));

		GEvent.addListener(map, "click", displayAddress);

  		geocoder = new GClientGeocoder();

		map.setCenter(new GLatLng(54.3933, -2.3115), 5); 



      

      //map.setCenter(point,5);

	  

      //marker = new GMarker(point);



      //map.addOverlay(marker);



      //marker.openInfoWindowHtml('Taxi Office');

	  showmapcontrols();


      }

    }



function getAddress(overlay, latlng, postcode) {
  if (latlng != null) {
    address = latlng;
	document.getElementById("postcode").value = postcode;
    geocoder.getLocations(latlng, showAddress);
  }
}

function showAddress(response) {
  map.clearOverlays();
  var postcode = document.getElementById("postcode").value;
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
	map.setCenter(point, 13);
	//alert(point);
	//alert(place.address);
	var numArray = place.address.split('-');

	var numArray1 = numArray[numArray.length-1].replace(/[0-9]/g,'');
	
	document.getElementById(activefield).value = numArray1.trim();
	
	var point1 = "f"+point;

	document.getElementById("hide"+activefield).value = point1.substr(2,point1.length-3);
	//document.getElementById("hide"+activefield).value = numArray1.trim() ;
    marker.openInfoWindowHtml('<b>Address:</b>' + place.address + '<br>')
  }
}

 



    

    function setDirections(fromAddress, toAddress, locale) {

		document.getElementById("middlediv").innerHTML = '';

      gdir.load("from: " + fromAddress + " to: " + toAddress,

                 {avoidHighways:true});

    }

 

    function handleErrors(){

	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)

	     alert("Unfortunately we have been unable to get directions using the addresses provided, please check your spelling and try again.");

	   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.

	  {disti = gdir.getDistance().html}

	  var trimmed = disti.replace(/^\s+|\mi+$/g, '') ;
	  
	  var summary = gdir.getSummaryHtml();
	  
	  var pickup = document.getElementById("htrip").value
	  
	  document.getElementById("middlediv").innerHTML = '<div id="direhead"><p> <b>'+ pickup + '</b></p><b>' + summary + '<b></div>';

	  //alert(trimmed)

	  {fare = trimmed}

	  

 farecalc(fare)

 

 //{ document.getElementById("getDistance").innerHTML = gdir.getDistance().html; }

 //{ document.getElementById("result").innerHTML = 'The calculated fare is �' + fare } 

 //opacity('route',50,100,500) 

      // e.g.

     // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;

	  // and yada yada yada...

	}

	

	    function addrow() {

      	var x=document.getElementById('bkForm').insertRow(0);

		var y=x.insertCell(0);

		var z=x.insertCell(1);

		y.innerHTML="NEW CELL1";

		z.innerHTML="NEW CELL2";



    }

	

	function createlocationstable(){

		

		var newTable,startTag,endTag;



 



//Creating a new table



startTag="<TABLE id='suggestedtable'><TBODY><TR><TD style=\"WIDTH: 100%\" class=\"suggestedheader\">Suggested Addresses</TD></TR>";

endTag="</TBODY></TABLE>";

newTable=startTag + rowdata + endTag;

document.getElementById("middlediv").innerHTML = newTable;

rowdata = '';



	}

	function dummyfunction(rownumber){

		//alert(rownumber);
		
		var divdata = document.getElementById('row' + rownumber).innerHTML;
		var divdata1 = document.getElementById('latlon'+ rownumber).innerHTML;
		divdata1 = divdata1.substr(1,divdata1.length-2);
		document.getElementById(activefield).value=divdata;
		document.getElementById('hide' + activefield).value=divdata1;
		
	}
	

/* tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
	var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
	return postcodeRegEx.test(p);
}

function displayStreet(){
	
  
}

function displayAddress(overlay, latlng) {
  if (latlng != null) {
    address = latlng;
    geocoder.getLocations(latlng, showAddress1);
  }
}

function showAddress1(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
	//document.getElementById(activefield).value = place.address;
    marker.openInfoWindowHtml(

        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
  }
}


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
		
function resizemap() {
	map.checkResize();
}


function showmiddlediv() {
	document.getElementById("middlecell").style.width='25%';
	var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
if(browser=='Microsoft Internet Explorer'){
	document.getElementById("middlecell").style.display='inline';
} else {
document.getElementById("middlecell").style.display='table-cell';
}
document.getElementById("middlediv").style.display='inline';
	document.getElementById("rightdiv").style.width='50%'
document.getElementById("mapdiv").style.width='100%'
resizemap();



	
}

function clearmap(){
	map.clearOverlays();
}

function checkshortcut(field){
	
	xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)

 {

 alert ("Browser does not support HTTP Request")

 return

 }

var url="scripts/checkshortcut.php"

var uid=document.getElementById('uid').value


var fleetid=document.getElementById('fleetid').value

var shortcut=document.getElementById(field).value

url=url+"?fid="+fleetid+"&uid="+uid+"&shortcut="+shortcut+"&field="+field;



//url=url+"&sid="+Math.random()

xmlHttp.onreadystatechange=stateChanged 

xmlHttp.open("GET",url,true)

//alert(url)

xmlHttp.send(null)

}
