// path to the postcode finder
var strPostcodePath = '/includes/php/postcode.php';
var strFind = 'Search';
var strWait = 'Busy';

var objForm,
	objAddressBox1,
	objAddress1,
	objAddress2,
	objAddress3,
	objTownCity,
	objCounty,
	objPostCode,
	objCountry,
	strOrganisation,
	strAddress1,
	strAddress2,
	strAddress3,
	strTownCity,
	strCounty,
	strPostCode,
	objFind,
	objList,
	objListLabel,
	objLabel,
	objResultXML,
	arrResults,
	intResults;

function getAddress()
{
	if (objList.options[objList.selectedIndex].value == '') return;

	var objGetAddress = new Request
	({
		url : strPostcodePath,

		onSuccess : function(reponseText, reponseXML)
		{
			// the XML
			objResultXML = reponseXML.getElementsByTagName('Item')[0];

			// fill the main fields
			strOrganisation = objResultXML.getAttribute('organisation_name');
			strAddress1 = objResultXML.getAttribute('line1');
			strAddress2 = objResultXML.getAttribute('line2');
			strAddress3 = objResultXML.getAttribute('line3');
			strTownCity = objResultXML.getAttribute('post_town');
			strCounty = objResultXML.getAttribute('county');
			strPostCode = objResultXML.getAttribute('postcode');

			// update the fields with their new values
			objAddress1.value = (typeof(strAddress1) != 'string')? '' : strAddress1;
			objAddress2.value = (typeof(strAddress2) != 'string')? '' : strAddress2;
			objAddress3.value = (typeof(strAddress3) != 'string')? '' : strAddress3;
			objTownCity.value = (typeof(strTownCity) != 'string')? '' : strTownCity;
			objCounty.value = (typeof(strCounty) != 'string')? '' : strCounty;
			objPostCode.value = (typeof(strPostCode) != 'string')? '' : strPostCode;

			// check for organisation name
			if (strOrganisation)
			{
				// if all fields are fully packed
				if (strAddress3) objAddress1.value = strOrganisation + ', ' + strAddress1;
				
				// if line3 is free
				else
				{
					objAddress1.value = strOrganisation;
					objAddress2.value = strAddress1;
					objAddress3.value = strAddress2;
				}
			}
			
			// get rid of the post code finder elements
			objFind.dispose();
			objLabel.dispose();
			objList.dispose();

			// reset the notification area
			RegisterForm.message.setStyle('display', 'none');
			RegisterForm.message.setAttribute('text', '');

			// show the address fields
			hideAddress(false);
		},

		onFailure : catchError

	}).send('address=' + objList.options[objList.selectedIndex].value);

	// disable the button
	objFind.setAttribute('text', strWait);
	objFind.disabled = true;
}

function catchError()
{
	// get rid of the post code finder elements
	if (objFind) objFind.dispose();
	if (objLabel) objLabel.dispose();
	if (objList) objList.dispose();

	RegisterForm.notify('Sorry, an error occurred. Please enter your address manually', true);
	hideAddress(false);
	
	objAddress1.focus();
}

function getAddresses()
{
	if (objPostCode.value == '')
	{
		RegisterForm.notify('Please enter a valid postcode.', true);
		return;
	}

	var objGetAddresses = new Request
	({
		url : strPostcodePath,

		onSuccess : function(reponseText, reponseXML)
		{
			arrResults = reponseXML.getElementsByTagName('Item');

			// reset the notification area
			RegisterForm.message.setStyle('display', 'none');
			RegisterForm.message.set('text', '');
			
			// if there's an error message
			if (arrResults[0].getAttribute('message'))
			{
				catchError();
				return;
			}
			
			// if we've got more than zero results
			else if (arrResults.length > 0)
			{
				// reset the button
				objFind.disabled = false;
				objFind.set('text', strFind);

				if (!objList)
				{
					// add a select box and a label
					objLabel = new Element('label', { 'for' : 'postcode-select', 'html' : 'Select Address' }).inject(objAddressBox2);
					objList = new Element('select',
					{
						'id' : 'postcode-select',
						
						'events' :
						{
							'change' : getAddress
						}
				
					}).inject(objAddressBox2);
				}
				else
				{
					objList.set('text', '');
				}
				
				// insert the first select box item
				objListLabel = new Element('option', { 'html' : 'Please Select', 'value' : '' }).inject(objList);

				// loop each address item and add to the select box
				for (i = 0; i < arrResults.length; i++)
				{
					new Element('option', { 'html' : arrResults[i].getAttribute('description'), 'value' : arrResults[i].getAttribute('id') }).inject(objList);
				}

				// write a notification
				RegisterForm.notify('Please select one of ' + arrResults.length + ' address(es) in the list.', true);
			}
			else
			{
				// write a notification
				RegisterForm.notify('Sorry, no addresses could be found.', true);
			}
		},

		onFailure : catchError

	}).send('postcode=' + objPostCode.value);
	
	// send notification
	RegisterForm.notify('Please wait, looking up address matches.', true);

	// disable the button
	objFind.set('text', strWait);
	objFind.disabled = true;
}

function postcodeFinder()
{
	objForm = $('register');

	objAddress1 = $('address1');
	objAddress2 = $('address2');
	objAddress3 = $('address3');
	objTownCity = $('town_or_city');
	objCounty = $('county');
	objPostCode = $('post_code');
	objCountry = $('country');

	objAddressBox1 = $('addresses1');
	objAddressBox2 = ($('addresses2'))? $('addresses2') : objPostCode.parentNode;

	if (objAddress1.value == '')
	{
		// onsubmit functions
		objPostCode.onkeypress = function(event)
		{
			var intKeyCode = (window.event)? window.event.keyCode : event.keyCode;
		
			if (intKeyCode == 3 || intKeyCode == 13)
			{
				getAddresses();
				return false;
			}
		}
	
		// hide the address fields
		hideAddress(true);
	
		// create the find button
		objFind = new Element('button',
		{
			'id' : 'postcode-button',
			'html' : strFind,
			'class' : 'left button',
			'type' : 'button',
	
			'events' :
			{
				'click' : getAddresses
			}
	
		}).inject(objAddressBox2);
	}
}

function hideAddress(blnHide)
{
	// determine whether to hide or show
	strHide = (blnHide)? 'none' : '';
	
	// remove the postcode button if it exists
	if (blnHide == false)
	{
		objPostCode.erase('class');
	}

	// hide the left fieldset
	if (objAddressBox1) objAddressBox1.setStyle('display', strHide);

	// hide the fields
	objAddress1.setStyle('display', strHide);
	objAddress2.setStyle('display', strHide);
	objAddress3.setStyle('display', strHide);
	objTownCity.setStyle('display', strHide);
	objCounty.setStyle('display', strHide);
	objCountry.setStyle('display', strHide);

	// and hide their labels
	getLabel(objAddress1).setStyle('display', strHide);
	getLabel(objAddress2).setStyle('display', strHide);
	getLabel(objAddress3).setStyle('display', strHide);
	getLabel(objTownCity).setStyle('display', strHide);
	getLabel(objCounty).setStyle('display', strHide);
	getLabel(objCountry).setStyle('display', strHide);
}

function getLabel(objField)
{
	return $$('label[for=' + objField.name + ']')[0];
}