/*
*
*  Author: Malcolm Elsworth (electricputty.co.uk)
*  Date: 09-02-09
*  Version: 0.9
*  Dependacies:
*     jquery-1.3.2.min.js
*
*/







// Create closed namespace for jQuery code.
(function($) {


	var $theForm;
	var $thePostcode;
	var $errorMsg = "";
	var localSearch = new GlocalSearch();


	writeError = function()
	{
		alert($errorMsg);
		return false;
	}


	checkPostCode = function(toCheck)
	{
		var alpha1 = "[abcdefghijklmnoprstuwyz]";
		var alpha2 = "[abcdefghklmnopqrstuvwxy]";
		var alpha3 = "[abcdefghjkstuw]";
		var alpha4 = "[abehmnprvwxy]";
		var alpha5 = "[abdefghjlnpqrstuwxyz]";
		var pcexp = new Array ();
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		pcexp.push (/^(GIR)(\s*)(0AA)$/i);
		pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
		pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
		var postCode = toCheck;
		var valid = false;
		for ( var i=0; i<pcexp.length; i++)
		{
		if (pcexp[i].test(postCode))
		{
			pcexp[i].exec(postCode);
			postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
			postCode = postCode.replace (/C\/O\s*/,"c/o ");
			valid = true;
			break;
		}
		}
		if (valid) {return true;} else return false;
	}


	usePointFromPostcode = function(postcode, callbackFunction)
	{
		localSearch.setSearchCompleteCallback(null,
		function()
		{
			if (localSearch.results[0])
			{
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
			} else {
				alert("Postcode not found!");
			}
		});
		localSearch.execute(postcode + ", UK");
	}


	submitSearchForm = function(point)
	{
		$("#inpTheLong").val(point.lng());
		$("#inpTheLat").val(point.lat());

		$thePageID = $("#inpPageID").val();
		$theForm.attr("action", websiteURL + "memberAJAXSearch.asp?page_id=" + $thePageID + "&inpPostcode=" + $thePostcode + "&ajax=true");
		$theForm.submit();

		return false;
	}


	$(document).ready(function() {

		$("form#frmPostcode .subbut").click(
			function(){

				$self = $(this);
				$theForm = $self.parents("form");
				$thePostcode = $("#inpPostcode").val();

				if ($thePostcode.length < 1)
				{
					$errorMsg = "Please enter a postcode";
					return writeError();
				}

				// Remove full postcode checking
				//if(!checkPostCode($thePostcode))
				//{
				//	$errorMsg = "Please enter a valid postcode";
				//	return writeError();
				//}

				usePointFromPostcode($thePostcode,submitSearchForm);

				return false;
			}
		)

	});
})(jQuery);




