var iSearchTimeout = 0;
var bUpdatingSearch = false;
var iPauseBeforeSearching = 100;		
var sPostcodeAddress = '';
var sPostcodeTown = '';
var objTargetPostcodeTextbox;
		
function postcode_search_keyup(sAddressTextboxID, sTownTextboxID, sPostcodeTextboxID){
	bUpdatingSearch = false;
	
	sPostcodeAddress = document.getElementById(sAddressTextboxID).value;
	sPostcodeTown    = document.getElementById(sTownTextboxID).value;
	
	if (sPostcodeAddress.length>0 && sPostcodeTown.length>0){
	
		objTargetPostcodeTextbox = document.getElementById(sPostcodeTextboxID);
		
		if(bUpdatingSearch==false){
			// set the search to run after a short delay...
			clearTimeout ( iSearchTimeout )
			iSearchTimeout=setTimeout('do_postcode_search()', iPauseBeforeSearching);
		}
		
	}
}

function do_postcode_search(){
	var sWindowLocation = window.location+'';
	if(sWindowLocation.indexOf('efinity')>-1){
		sBaseURL = 'http://www.efinity.co.nz/clients/nziht/';
	} else {
		sBaseURL = 'http://www.nziht.co.nz/';
	}

	if(bUpdatingSearch==false){
		// do the search...
		bUpdatingSearch = true;
		loadXMLPostcodes(sBaseURL + 'ajax_postcode.asp?a=' + sPostcodeAddress + '&t=' + sPostcodeTown);
	}
}
		
var xmlhttppostcodes;
		
function loadXMLPostcodes(url) {
	xmlhttppostcodes=null;

	if (window.XMLHttpRequest) {
		// code for Mozilla, etc.
		xmlhttppostcodes=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// code for IE
		xmlhttppostcodes=new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (xmlhttppostcodes!=null) {
		xmlhttppostcodes.onreadystatechange=postcodes_state_Change;
		xmlhttppostcodes.open("GET",url,true);
		xmlhttppostcodes.send(null);
	} else {
		alert("Your browser does not support XMLHTTP.");
	}
 

}		
		
function postcodes_state_Change() {

	// if xmlhttppostcodes shows "loaded"
	if (xmlhttppostcodes.readyState==4) {
		// if "OK"
		if (xmlhttppostcodes.status==200) {
			// request was ok, update the form...			
			update_postcode( xmlhttppostcodes.responseText );
		} else {
			alert("Problem retrieving postcodes data");
		}
	}

	bUpdatingSearch = false;
}		
		
function update_postcode(sPostcode){
	if (sPostcode.length>0){
		// update the postcode on the selected form field...
		objTargetPostcodeTextbox.value = sPostcode
	}
}