// holds an instance of XMLHttpRequest
var SPLxmlHttp = SPLcreateXmlHttpRequestObject();
var LastArea = 1;
var LastSearchAreaID = 'SPLSearchArea';
var TraderArea = 'normal';

var AddressFields = (function ()
{
	var instance = null;

	function AddressFields()
	{
		this.txtDeliveryCompanyName = null;
		this.txtDeliveryPostcode = null;
		this.txtDeliveryBuildingNumber = null;
		this.txtDeliveryBuildingName = null;
		this.txtDeliveryStreet = null;
		this.txtDeliveryStreet2 = null;
		this.txtDeliveryCity = null;
		this.txtDeliveryCounty = null;
		this.ddlDeliveryCountry = null;
		this.txtBillingCompanyName = null;
		this.txtBillingPostcode = null;
		this.txtBillingBuildingNumber = null;
		this.txtBillingBuildingName = null;
		this.txtBillingStreet = null;
		this.txtBillingStreet2 = null;
		this.txtBillingCity = null;
		this.txtBillingCounty = null;
		this.ddlBillingCountry = null;

		this.txtTraderDeliveryCompanyName = null;
		this.txtTraderDeliveryPostcode = null;
		this.txtTraderDeliveryBuildingNumber = null;
		this.txtTraderDeliveryBuildingName = null;
		this.txtTraderDeliveryStreet = null;
		this.txtTraderDeliveryStreet2 = null;
		this.txtTraderDeliveryCity = null;
		this.txtTraderDeliveryCounty = null;
		this.ddlTraderDeliveryCountry = null;
		this.txtTraderBillingCompanyName = null;
		this.txtTraderBillingPostcode = null;
		this.txtTraderBillingBuildingNumber = null;
		this.txtTraderBillingBuildingName = null;
		this.txtTraderBillingStreet = null;
		this.txtTraderBillingStreet2 = null;
		this.txtTraderBillingCity = null;
		this.txtTraderBillingCounty = null;
		this.ddlTraderBillingCountry = null;
	}

	return new function ()
	{
		this.getInstance = function ()
		{
			if (instance == null)
			{
				instance = new AddressFields();
				instance.constructor = null;
			}
			return instance;
		}
	};
})();

// creates an XMLHttpRequest instance
function SPLcreateXmlHttpRequestObject()
{
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// assume IE6 or older
		var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
									'MSXML2.XMLHTTP.5.0',
									'MSXML2.XMLHTTP.4.0',
									'MSXML2.XMLHTTP.3.0',
									'MSXML2.XMLHTTP',
									'Microsoft.XMLHTTP');
		// try every prog id until one works
		for (var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++)
		{
			try
			{
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e) { }
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
		alert("Error creating the XMLHttpRequest object.");
	else
		return xmlHttp;
}


// function called when the state of the HTTP request changes
function SPLhandleRequestStateChange()
{
	try
	{
		// when readyState is 4, we are ready to read the server response
		if (SPLxmlHttp.readyState == 4)
		{
			// continue only if HTTP status is "OK"
			if (SPLxmlHttp.status == 200)
			{
				try
				{
					// do something with the response from the server
					SPLhandleServerResponse();
				}
				catch (e)
				{
					// display error message
					//alert("Error reading the response: " + e.toString());
				}
			}
			else
			{
				// display status message
				alert("There was a problem retrieving the data:\n" +
			SPLxmlHttp.statusText);
			}
		}
	}
	catch (e)
	{
		// ignore
	}
}

// #################### Get Address to Combo ############################ 

// read a file from the server (area is for multiple address sections on same page)
function SPLGetAddressData(postcode, area, searchAreaID)
{
	if (undefined == searchAreaID)
	{
		searchAreaID = 'SPLSearchArea';
	}
	// only continue if xmlHttp isn't void
	if (SPLxmlHttp)
	{
		LastArea = area;
		LastSearchAreaID = searchAreaID;
		var varText = searchAreaID;
		var varNum = 0;
		varNum = varText.indexOf("Trader");
		if (varNum != -1) { TraderArea = 'trader' }

		// try to connect to the server
		try
		{
			// initiate reading a file from the server
			SPLxmlHttp.open("GET", "SPLGetFullAddress1.aspx?postcode=" + escape(postcode), true);
			SPLxmlHttp.onreadystatechange = SPLhandleRequestStateChange;
			SPLxmlHttp.send(null);
		}
		// display the error in case of failure
		catch (e)
		{
			//alert("Can't connect to server:\n" + e.toString());
			//Suppress error, since can be cause by two calls at once
		}
	}
}


// gets word

function getWord(str, pos)
{
	var SplitString = str.split(" ");
	return SplitString[parseInt(pos) - 1];

}


// #################### On Click on Combo ############################ 

// handles click on combo
function SPLAddressChange(AddressCombo)
{
	// only continue if xmlHttp isn't void
	if (SPLxmlHttp)
	{
		// try to connect to the server
		try
		{
			// initiate reading a file from the server
			SPLxmlHttp.open("GET", "SPLGetFullAddress2.aspx?AddressID=" + AddressCombo.options[AddressCombo.selectedIndex].value, true);
			SPLxmlHttp.onreadystatechange = SPLhandleRequestStateChange;
			SPLxmlHttp.send(null);
		}
		// display the error in case of failure
		catch (e)
		{
			//alert("Can't connect to server:\n" + e.toString());
			//Suppress error, since can be cause by two calls at once
		}
	}

	document.getElementById(LastSearchAreaID + LastArea).innerHTML = "";
}


// #################### Handle returned data ############################ 
function SPLhandleServerResponse()
{
	//##########################################################
	//### Delete this line on production server              ###
	//### This can be used for debuging to show XML returned ###
	//alert(SPLxmlHttp.responseText);
	//##########################################################

	// Test that XML contains valid Address, test for <line1>
	var Credits = "", COMP = "", LINE1 = "", LINE2 = "", LINE3 = "", TOWN = "", COUNTY = "", POSTCODE = "", COUNTRY = "", MultiLineAddress = ""
	var XMLresponse = SPLxmlHttp.responseText;

	if (XMLresponse.indexOf("</select>") > 0)
	{
		//if contains a </select> then must be combo box
		document.getElementById(LastSearchAreaID + LastArea).innerHTML = XMLresponse;
	}
	else
	{
		if (XMLresponse.indexOf("<line1>") == -1)
		// error or no data so show message
			document.getElementById(LastSearchAreaID + LastArea).innerHTML = XMLresponse;
		else
		{
			//contains address information so write to fields
			// read the message from the server
			var xmlResponse = SPLxmlHttp.responseXML;

			// obtain the XML's document element
			xmlRoot = xmlResponse.documentElement;

			if (xmlRoot.getElementsByTagName("credits_display_text").item(0).firstChild)
			{ Credits = xmlRoot.getElementsByTagName("credits_display_text").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("organisation").item(0).firstChild)
			{ COMP = xmlRoot.getElementsByTagName("organisation").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("line1").item(0).firstChild)
			{ LINE1 = xmlRoot.getElementsByTagName("line1").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("line2").item(0).firstChild)
			{ LINE2 = xmlRoot.getElementsByTagName("line2").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("line3").item(0).firstChild)
			{ LINE3 = xmlRoot.getElementsByTagName("line3").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("town").item(0).firstChild)
			{ TOWN = xmlRoot.getElementsByTagName("town").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("county").item(0).firstChild)
			{ COUNTY = xmlRoot.getElementsByTagName("county").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("postcode").item(0).firstChild)
			{ POSTCODE = xmlRoot.getElementsByTagName("postcode").item(0).firstChild.data; }
			if (xmlRoot.getElementsByTagName("country").item(0).firstChild)
			{ COUNTRY = xmlRoot.getElementsByTagName("country").item(0).firstChild.data; }

			// Massage the data
			var HOUSENUM = '';
			var HOUSENAME = '';
			var FIRSTWORD = '';
			var FIRSTWORD = getWord(LINE1, 1);
			var houseNumber = FIRSTWORD;

			if (!isNaN(houseNumber))
			{
				HOUSENUM = houseNumber + '';
				// Line 1 starts with a number, so split it into "{house number} {street 1}"
				try
				{
					LINE1 = LINE1.substring(LINE1.indexOf(' ') + 1);
				}
				catch (e)
				{
				}
			}
			else
			{
				// Line 1 doesn't start with a number, assume it's a house name
				var NUMBERCHECK = parseInt(FIRSTWORD);
				if (isNaN(NUMBERCHECK))
				{
					HOUSENAME = LINE1;
					LINE1 = LINE2
					LINE2 = LINE3
				}
				else
				{
					HOUSENAME = FIRSTWORD;
					LINE1 = LINE1.replace(FIRSTWORD, '');
				}
			}
						
			var addressFields = AddressFields.getInstance();
			
			if (TraderArea == 'trader')
			{
				if (LastArea == 1)
				{
					addressFields.txtTraderDeliveryCompanyName.value = COMP;
					addressFields.txtTraderDeliveryPostcode.value = POSTCODE;
					addressFields.txtTraderDeliveryBuildingNumber.value = HOUSENUM;
					addressFields.txtTraderDeliveryBuildingName.value = HOUSENAME;
					addressFields.txtTraderDeliveryStreet.value = LINE1;
					addressFields.txtTraderDeliveryStreet2.value = LINE2;
					addressFields.txtTraderDeliveryCity.value = TOWN;
					addressFields.txtTraderDeliveryCounty.value = COUNTY;
					addressFields.ddlTraderDeliveryCountry.value = 'GB';
				}
				else
				{
					addressFields.txtTraderBillingCompanyName.value = COMP;
					addressFields.txtTraderBillingPostcode.value = POSTCODE;
					addressFields.txtTraderBillingBuildingNumber.value = HOUSENUM;
					addressFields.txtTraderBillingBuildingName.value = HOUSENAME;
					addressFields.txtTraderBillingStreet.value = LINE1;
					addressFields.txtTraderBillingStreet2.value = LINE2;
					addressFields.txtTraderBillingCity.value = TOWN;
					addressFields.txtTraderBillingCounty.value = COUNTY;
					addressFields.ddlTraderBillingCountry.value = 'GB';
				}
			}

			if (TraderArea != 'trader')
			{
				if (LastArea == 1)
				{
					addressFields.txtDeliveryCompanyName.value = COMP;
					addressFields.txtDeliveryPostcode.value = POSTCODE;
					addressFields.txtDeliveryBuildingNumber.value = HOUSENUM;
					addressFields.txtDeliveryBuildingName.value = HOUSENAME;
					addressFields.txtDeliveryStreet.value = LINE1;
					addressFields.txtDeliveryStreet2.value = LINE2;
					addressFields.txtDeliveryCity.value = TOWN;
					addressFields.txtDeliveryCounty.value = COUNTY;
					addressFields.ddlDeliveryCountry.value = 'GB';
				}
				else
				{
					addressFields.txtBillingCompanyName.value = COMP;
					addressFields.txtBillingPostcode.value = POSTCODE;
					addressFields.txtBillingBuildingNumber.value = HOUSENUM;
					addressFields.txtBillingBuildingName.value = HOUSENAME;
					addressFields.txtBillingStreet.value = LINE1;
					addressFields.txtBillingStreet2.value = LINE2;
					addressFields.txtBillingCity.value = TOWN;
					addressFields.txtBillingCounty.value = COUNTY;
					addressFields.ddlBillingCountry.value = 'GB';
				}
			}
		}
	}
}

 

