//var map;
var localSearch = new GlocalSearch();

function checkPostCode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  

  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}

function setDirections(fromAddress, toAddress, locale) {
    gdir.load("from: " + fromAddress + " to: " + toAddress,
              { "locale": locale });
}

function createRequest() {
	
	// create an Ajax Request
	
	var ajaxRequest;
	
	try
	{
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}		
		catch (e1)
		{
			try
			{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
				catch (e2)
				{
					ajaxRequest = new XMLHttpRequest();
				}
		}
	
	return ajaxRequest;
}

function usePointFromPostcodeViaCache(postcode, to, locale, callbackFunction) {
	
	map.clearOverlays();
	var ajax_connection = createRequest();
	
	ajax_connection.open('get', "geocode.cfc?method=geocode&postcode=" + postcode);
	
	// setup the function to deal with the reply
	ajax_connection.onreadystatechange = function(){
		
		if (ajax_connection.readyState == 4) {
			var xmlDoc = ajax_connection.responseXML;
			var markers = xmlDoc.documentElement.getElementsByTagName("location");
			
			if (markers.length > 0)
			{
				var resultLat = markers[0].getAttribute('latitude');
				var resultLng = markers[0].getAttribute('longitude');
				var resultDate = markers[0].getAttribute('date_added');
				var from = postcode + '@' + resultLat + ' ' + resultLng ;
				
				document.getElementById("result").innerHTML = "Result for " + postcode + " came from cache. It was last cached on " + resultDate;
				callbackFunction(from,to,locale);
			}else{
				usePointFromPostcode(postcode,to,locale,callbackFunction);
			}
		}
	}	
	
	ajax_connection.send(null);
}

function usePointFromPostcode(postcode, to,locale, callbackFunction) {
	
		localSearch.setSearchCompleteCallback(null, 
			function() {
			
				if (localSearch.results[0])
				{		
					var resultLat = localSearch.results[0].lat;
					var resultLng = localSearch.results[0].lng;
					var from = postcode + '@' + resultLat + ' ' + resultLng ;
					
					document.getElementById("result").innerHTML = "Result for " + postcode + " came from Google.";
					if (checkPostCode (postcode)) {
    					var ajax_connection = createRequest();
						ajax_connection.open('get', "geocode.cfc?method=cache&postcode=" + postcode + "&latitude=" + resultLat + "&longitude=" + resultLng);
						ajax_connection.send(null);
					} 
					callbackFunction(from,to,locale);
				}else{
					alert("Postcode not found!");
				}
			});	
		
		
		 if (checkPostCode (postcode)) {
    		localSearch.execute(postcode + ", UK")
  			} 
  		else {localSearch.execute(postcode)};
		
}


