// JavaScript Document

function byPostCode() {

	var request = '/actions/postcodeanywhere_result.asp?action=bypostcode&postcode=' + $('CD_PostCode').getValue();

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport) {

			var response = transport.responseText.evalJSON();

			$('liSearchPostCode').show();

			if (response.error != null)
			{
				// Show the message SPAN element and display the error messaage
				$('spaMessage').update(response.error);
				$('spaMessage').show();

				// Hide the address selection form elements
				$('SelectAddress').hide();
				$('cmdSelectAddress').hide();
			}
			else
			{
				// Clear the SelectAddress dropdown's current options
				for(iLoopA = $('SelectAddress').options.length - 1; iLoopA >= 0 ; iLoopA--)
					$('SelectAddress').options[iLoopA] = null;

				// Populate the SelectAddress dropdown with the new address list
				for (iLoopA = 0; iLoopA < response.result.address.length; iLoopA++)
				{
					var optAddressItem = document.createElement("option");

					optAddressItem.value = response.result.address[iLoopA].id;
					optAddressItem.text = response.result.address[iLoopA].description;

					$('SelectAddress').options.add(optAddressItem);
				}
				
				// Show the SelectAddress dropdown and hide the message SPAN element
				$('SelectAddress').show();
				$('spaMessage').hide();
			}

		},

	  	onFailure: function(transport){ alert('There was an error returning the data : byPostCode') }

	});

	return false;
}

function fetchAddress() {

	var request = '/actions/postcodeanywhere_result.asp?action=fetchaddress&addressid=' + $('SelectAddress').getValue();

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport) {

			var response = transport.responseText.evalJSON();

			if (response.error != null)
			{
				// Display the error to the user
				alert(response.error);
			}
			else
			{
				// Update the address fields...
				$('CD_StreetAddress1').value = response.result.address[0].line1;
				$('CD_StreetAddress2').value = response.result.address[0].line2;
				$('CD_StreetAddress3').value = response.result.address[0].line3;
				$('CD_TownCity').value = response.result.address[0].post_town;
				$('CD_County').value = response.result.address[0].county;
				$('CD_PostCode').value = response.result.address[0].postcode;
			}

		},
		
	  	onFailure: function(transport){ alert('There was an error returning the data : fetchAddress') }

	});

	return false;

}
