function lookupAddressPostCode(postCode) {
	postCode = trim(postCode);
	if (postCode != "") {
		lookupAddressParams = getRandomParam() + "&post_code=" + escape(postCode);
		jQuery.ajax({   
		  type: "POST",
		  url: "postAddressLookupV2.php",
		  cache: false,
		  data: lookupAddressParams,
		  beforeSend: function(){ },   
		  complete: function(){ },
		  error: function() { alert('There was an error looking up your address, please try again.') }, 
		  success: function(response){ alert("lookupAddressPostCode after failure: " + response); }   
		}); //close jQuery.ajax(   
	}
}

// This lookupAddress call is not used because its asynchronous - it cannot return the responseArray so it needs to do something inside of success
function lookupAddress(houseName, flatNo, postCode) {
	postCode = trim(postCode);
	if (postCode != "") {
		lookupAddressParams = getRandomParam() + "&house_name=" + escape(houseName) + "&flat=" + escape(flatNo) + "&post_code=" + escape(postCode);
		jQuery.ajax({   
		  type: "POST",
		  url: "postAddressLookupV2.php",
		  cache: false,
		  // dataType: "xml",
		  data: lookupAddressParams,
		  beforeSend: function(){ },   
		  complete: function(){ },
		  error: function() { lookupAddressPostCode(postCode); }, // if there is an error attempt to get the address from the post code only 
		  success: function(response){ alert("success"); responseArray = parseAddressResponse(response); /* do something with responseArray here */}   
		}); //close jQuery.ajax(   
	}
}

var ADDRESS_DELIMITER = '%';
function parseAddressResponse(response) {
	var responseArray = [];
	
	jQuery("address",response).each(function(id) {
		var addressVar = jQuery("address",response).get(id); 
		var addressObj = new Object();
//		addressObj.id = jQuery("id", addressVar).text();
		addressObj.address_string = jQuery("address_string", addressVar).text();
		
		var displayStr = jQuery("address_house_name", addressVar).text() + ADDRESS_DELIMITER;
		displayStr += jQuery("address_house_num", addressVar).text() + ADDRESS_DELIMITER;
		displayStr += jQuery("address_unit", addressVar).text() + ADDRESS_DELIMITER;
		displayStr += jQuery("address_street", addressVar).text() + ADDRESS_DELIMITER;
		displayStr += jQuery("address_city", addressVar).text();
		//+ '%';
		//displayStr += jQuery("id", addressVar).text();
		addressObj.id = displayStr;
		
		responseArray[responseArray.length] = addressObj;
	}); 
	
	return responseArray;
}

function fillAddressDropDown(responseArray, dropDownElement, selectedValue, pageConstant) {
	fillAddressDropDown2(responseArray, dropDownElement, selectedValue, pageConstant, "Please enter your home address postcode and then click 'Find Address'");
}

function fillAddressDropDown2(responseArray, dropDownElement, selectedValue, pageConstant, badPostCodeAlert) {
	dropDownElement.options.length = 0;
/*	if (responseArray.length == 0) {
		alert(badPostCodeAlert);
		dropDownElement.options.length = 0;	
		googleEventButton('Find Address Button', 'Invalid Postcode', pageConstant);
		return false;
	}*/
	dropDownElement.options.length = responseArray.length + 2;
	dropDownElement.options[0].text = "Please choose an address..."; 
//	dropDownElement.options[0].value = -1;
	dropDownElement.options[0].value = '';
	dropDownElement.options[0].selected = (selectedValue == -1 || selectedValue == "");
	for (var i=0; i<responseArray.length; i++) {
		var index = i + 1;
		dropDownElement.options[index].text = responseArray[i].address_string; 
		dropDownElement.options[index].value = responseArray[i].id;
		dropDownElement.options[index].selected = (selectedValue == responseArray[i].id);
	}	
	var index  = responseArray.length + 1;
	dropDownElement.options[index].text = "My address is not in the list"; 
	dropDownElement.options[index].value = -2; 
//	dropDownElement.options[index].selected = (selectedValue == -2);
	dropDownElement.options.length = responseArray.length + 2;
	googleEventButton('Find Address Button', 'Valid Postcode', pageConstant);
}

function lookupAddress_fillDropdown(houseName, flatNo, postCode, dropDownElement, selectedValue, showElementWhileLoading, hideElementWhileLoading, pageConstant) {
	return lookupAddress_fillDropdown2(houseName, flatNo, postCode, dropDownElement, selectedValue, showElementWhileLoading, hideElementWhileLoading, pageConstant, "Please enter your home address postcode and then click 'Find Address'");
}

function lookupAddress_fillDropdown2(houseName, flatNo, postCode, dropDownElement, selectedValue, showElementWhileLoading, hideElementWhileLoading, pageConstant, badPostCodeAlert) {
	var responseArray = [];
	postCode = trim(postCode);
	if (postCode != "") {
		if ((hideElementWhileLoading != null) && (showElementWhileLoading != null)) {
			hideElementWhileLoading.style.display = "none";
			showElementWhileLoading.style.display = "";
		}
		lookupAddressParams = getRandomParam() + "&house_name=" + escape(houseName) + "&flat=" + escape(flatNo) + "&post_code=" + escape(postCode);
		jQuery.ajax({   
		  type: "POST",
		  url: "postAddressLookupV2.php",
		  cache: false,
		  data: lookupAddressParams,
          timeout: 10000,
		  beforeSend: function(){ },   
		  complete: function(){ },
		  error: function() {
			  // try to post again - ie 6 sometimes fails on every other request so this will fix them
				jQuery.ajax({   
					  type: "POST",
					  url: "postAddressLookupV2.php",
					  cache: false,
					  data: lookupAddressParams,
			          timeout: 5000,
					  beforeSend: function(){ },   
					  complete: function(){ },
					  error: function() {
						  alert("There was an error loading your address.  Please try again.");
			              if ((hideElementWhileLoading != null) && (showElementWhileLoading != null)) {
			              	showElementWhileLoading.style.display = "none";
			              	hideElementWhileLoading.style.display = "";
			              }
			          },
					  success: function(response) {
						  responseArray = parseAddressResponse(response); 
						  if ((hideElementWhileLoading != null) && (showElementWhileLoading != null)) {
							  showElementWhileLoading.style.display = "none";
							  hideElementWhileLoading.style.display = "";
						  }
						  fillAddressDropDown2(responseArray, dropDownElement, selectedValue, pageConstant, badPostCodeAlert); 
					  }   
				}); //close jQuery.ajax(   
          },
//		  error:function (xhr, ajaxOptions, thrownError){
//              alert(xhr.status);
//              alert(thrownError);
//		  },
		  success: function(response) {
			  responseArray = parseAddressResponse(response); 
			  if ((hideElementWhileLoading != null) && (showElementWhileLoading != null)) {
				  showElementWhileLoading.style.display = "none";
				  hideElementWhileLoading.style.display = "";
			  }
			  fillAddressDropDown2(responseArray, dropDownElement, selectedValue, pageConstant, badPostCodeAlert); 
		  }   
		}); //close jQuery.ajax(   
	}
}

function showLookup(id, formName) {
	if (document[formName].ap && document[formName].ap.value == '') {
		return false;
	}
	
	var div = document.getElementById(id);
	div.style.display = 'block';
	
	var select = div.getElementsByTagName('select');
	select[0].setAttribute('size', '10');
}

function popFields(field, formName) {
	field.style.display = "";
	
	var value = field.value.split(ADDRESS_DELIMITER);
	var myForm = document[formName];
	var addressTypein = (value[0] == -2) ? true : false;
	
	if (value.length < 5) {
		var i = 0;
		while (i < 5) {
			if (!value[i] || value[i] < 0) {
				value[i] = '';
			}
			i++;
		}
	}
	
	var addressFields = ['house_num_and_name', 'house_name', 'an', 'au', 'as', 'ac'];
	for (var i = 0; i < addressFields.length; i++) {
		var key = addressFields[i];
		if (addressTypein && myForm[key]) {
			myForm[key].style.backgroundColor = '#FFFFFF';
		}
	}
	
	if ((myForm.house_num_and_name) && ((value[0] != '') || (value[1] != ''))) {
		myForm.house_num_and_name.value = jQuery.trim(value[0] + ' ' + value[1]);
	} else {
		if ((myForm.house_name && !myForm.an) && ((value[0] != '') || (value[1] != ''))) {
			myForm.house_name.value = jQuery.trim(value[0] + ' ' + value[1]);
		} else {
			if ((myForm.house_name) && (value[0] != '')) {
				myForm.house_name.value = value[0];
			}
			if ((myForm.an) && (value[1] != '')) {
				myForm.house_num.value = value[1];
			}
		}
	}
	
	if ((myForm.au) && (value[2] != '')) {
		myForm.au.value = value[2];
	}
	if ((myForm.as) && (value[3] != '')) {
		myForm.as.value = value[3];
	}
	if ((myForm.ac) && (value[4] != '')) {
		myForm.ac.value = value[4];
	}
}
