/*------------------------------------------------------------------------*\
| File: FindAddress.js         

	FindAddress expects to find a text file cotaining llpg terms and conditions
	at the location:                 \WestBerks\utilities\Data\                            |
\*------------------------------------------------------------------------*/

var intervalID;
var addressSelected = false;
var globalAddress;


//required global for Address class to funtion.
//this.winSelectAddress always returns null after method scope even when assigned to an existing object????? 
//so global it is - this behavour seems unique to the window object
var winSelectAddress;

//class declaration - Address object (constructor)
function Address(qualifier, articleId, path)
{
	this.qualifier = new String(qualifier);
	this.formId = new String();
	this.userAddress = new AddressFields();
	this.userAddress.validate = UserAddressValidate;
	this.winSelectAddress = null;
	this.articleId = articleId;
	this.pluginfolder = new String(path);
	
	//we need to set up an event that will close the address select window if the user
	//navigates away from this page or closes this window.
	window.onunload = this.CloseWindow;
	this.GetArticleId();
}

//function designed to be used as member method for userAddress.validate
function UserAddressValidate()
{
	//uk
	if(this.country == "United Kingdom" || this.country == "")
	{
		if (!/^([A-Za-z]{1,2}[0-9]{1,2}|[A-Za-z]{1,2}[0-9][A-Za-z]|[A-Za-z]{3,3}) ?[0-9][A-Za-z]{2,2}$/.test(this.postcode))
		{
			this.valid = false;
			return false;
		}
		this.valid = true;
	}//add additonal country postcode handling here
	else	//all others
	{
		if(this.postcode.length < 2)
		{
			this.valid = false
			return false;
		}
		this.valid = true;	
	}
	return true;
}

//Class declaration - object used for holding address fields
function AddressFields()
{
	this.address1 = new String();
	this.address2 = new String();
	this.address3 = new String();
	this.uprnnonllpgid = new String();
	this.city = new String();
	this.region = new String();
	this.postcode = new String();
	this.country = new String();
	this.valid = new Boolean(false);
}

//loads the address fields of the Address.userAddress object using the qualifier reference
//and the document reference
Address.prototype.GetUserAddress = function()
{
	//obtain each of the required address fields using the id qualifier(qualifier)	
	try
	{
		this.userAddress.address1 = document.getElementById(this.qualifier + '_ADDRESS1').value;
	}
	catch(e)
	{
		this.userAddress.address1 = "";
	}
	try
	{
		this.userAddress.address2 = document.getElementById(this.qualifier + '_ADDRESS2').value;
	}
	catch(e)
	{
		this.userAddress.address2 = "";
	}
	try
	{
		this.userAddress.address3 = document.getElementById(this.qualifier + '_ADDRESS3').value;
	}
	catch(e)
	{
		this.userAddress.address3 = "";
	}
	try
	{
		this.userAddress.city = document.getElementById(this.qualifier + '_CITY').value;
	}
	catch(e)
	{
		this.userAddress.city = "";
	}
	try
	{
		this.userAddress.region = document.getElementById(this.qualifier + '_REGION').value;
	}
	catch(e)
	{
		this.userAddress.region = "";
	}
	try
	{
		this.userAddress.postcode = document.getElementById(this.qualifier + '_POSTCODE').value;
	}
	catch(e)
	{
		this.userAddress.postcode = "";
	}
	try
	{		
		this.userAddress.country = document.getElementById(this.qualifier + '_COUNTRY').value;
	}
	catch(e)
	{
		this.userAddress.country = "";
	}
	try
	{		
		this.userAddress.uprnnonllpgid = document.getElementById(this.qualifier + '_UPRNNONLLPGID').value;
	}
	catch(e)
	{
		this.userAddress.uprnnonllpgid = "";
	}	
	//validate the details
	this.userAddress.validate();
}

//gets the article id from the query string
Address.prototype.GetArticleId = function()
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) 
	{
		var pair = vars[i].split("=");
		if (pair[0] == "articleid") 
		{
			this.articleId = pair[1];
		}
	}
}

//displays the select address window if the current post code is valid
Address.prototype.LookUpSystemAddress = function(strAddress)
{
	if(this.IsWindowOpen())
	{//the window is already open - just focus it
		winSelectAddress.focus();	//ensure that the window becomes the top most
	}
	else	//no windows exists so lets create it
	{
		if(this.userAddress.valid)	//check the validity of the user address
		{//all good open a window loaded from PickAddress.aspx
		
			winSelectAddress = window.open(this.pluginfolder + "?postcode="+this.userAddress.postcode+"&qualifier="+this.qualifier,"seladdr","width=600,height=500,scrollbars=yes,resizable=yes");
			winSelectAddress.focus();	//ensure that the window becomes the top most
		}
		else
		{
			alert("The postcode is invalid - Please supply a valid postcode.");
		}
	}
}

//closes the select address window if it open
Address.prototype.CloseWindow = function()
{	
	if(winSelectAddress != null && !winSelectAddress.closed && winSelectAddress.location)	//if the window is not already closed
	{
		winSelectAddress.close();
	}
}

//checks if the window is open by resolving if the location property exists and the window.closed property
Address.prototype.IsWindowOpen = function()
{	
	if(winSelectAddress == null) 	return false;	//if null window has never been opened
		//we check location object also as !closed will be true for a null object also
	if (!winSelectAddress.closed && winSelectAddress.location)
	{
		return true;
	}
	else return false;
}

//returns the raw html for a form to obtain an address
//sets default values of those provided by the user profile
//the action of the form is set to 

Address.prototype.GetAddressForm = function()
{
	var form = [
		{ field: '_ADDRESS1', label: 'Address line 1:' }, { field: '_ADDRESS2', label: 'Address line 2:' }, 
		{ field: '_ADDRESS3', label: 'Address line 3:' }, { field: '_CITY', label: 'City:' }, 
		{ field: '_REGION', label: 'Region:' }/*, { field: '_UPRNNONLLPGID', label: 'UPRN:' }*/
	];
	var strHTML = "<div id=\"userAddress\" style=\"padding:30px;\"><table cellpadding=\"3\" cellspacing=\"0\" summary=\"form display\" border=\"0\"><form style=\"padding : 0; margin : 0;\" name=\"getAddress\" action=\"pickAddress.aspx?update=true&postcode=" + this.userAddress.postcode +"\" method=\"post\" enctype=\"multipart/form-data\" onSubmit=\"window.opener.globalAddress.UpdateSystemAddress();\" id=\"addressForm\">";
	for (var fld = 0; fld < form.length; fld++) {
		var defn = form[fld];
		var item = document.getElementById(this.qualifier + defn.field);
		
		if (item) {
			var fieldHtml;
			if (navigator.appName == 'Microsoft Internet Explorer')
			{
				fieldHtml = item.parentNode.innerHTML.replace("readOnly","");
			}
			else
			{
				fieldHtml = item.parentNode.innerHTML.replace('readOnly="readonly"', "");
			}
			var completeHtml = "<label for=\"" + this.qualifier + defn.field + "\">" + defn.label + "</label></th></tr><br/>" +
				fieldHtml + "<br/>";
			strHTML += completeHtml;
		}
	}
	
	//note that the post code is rendered as an input box instead of copying the html from the original form as we dont want the find button
	//to be displayed
	strHTML += "<label for=\"" + this.qualifier + "_POSTCODE" +"\">Postcode:</label><br/>" +"<input name=\"" + this.qualifier + "_POSTCODE" + "\" type=\"text\" size=\"40\" maxlength=\"40\" id=\"" + this.qualifier + "_POSTCODE"+ "\"><br/>";
	
	//we also need to add a hidden field to put the qualifier in as the aspx will need this information to
	//rebuild the names of the form keys
	strHTML += "<input name=\"Qualifier\" value=\"" + this.qualifier + "\" type=\"hidden\" id=\"qualifier\" />";
	
	//add the article id or formid as we need this for checking default field values
	//if formid is non zero (ie has been supplied) then we are working from within iCM else this is from the website
	//iCM does not use articles  so cannot provide an article id with which to get the form id (which is not a form anyway)
	// so the form or section must be explicitly defined in the function call. ie GetAddressPrivate()
	strHTML +="<input type=\"hidden\" name=\"formId\" value =\"" + this.formId + "\" id=\"formId\"/>";
	strHTML +="<input type=\"hidden\" name=\"callingArticle\" value=\"" + this.articleId + "\" id=\"callingArticle\"/>";
	
	//cancel and continue buttons
	strHTML += "<br/><br/>";
	strHTML += "<input type=\"submit\" class=\"btntext\" name=\"continue\" value=\"Continue\" id=\"submit\"/> ";
	strHTML += "<input name=\"Cancel\" class=\"btntext\" type=\"button\" id=\"Cancel\"value=\"Cancel\" onClick=\"javascript:window.close();\"/>";
	strHTML += "</form></table></div>";
	
	//firefox and opera and safari (not ie) mince the above code as they read the .value of each outerHTML element read
	//as the original when the page was renderd - not a value added or edited by the user ie. the dom is not refreshed
	//we can update the values using a .fixNonIEBug() method which should be called immediatley after this method	
	return strHTML;
}

// ----------- only to be called after GetAdressForm has been rendered on the html page!!
// Adds the user address values to the form fields as non (ie) browsers failed to pick up modfied values
//through the dom (only grabs values provided in the original rendered document).
Address.prototype.FixNonIEBug = function()
{
	if(this.IsWindowOpen())
	{
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_ADDRESS1').value = this.userAddress.address1;
		}
		catch(e)
		{
		
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_ADDRESS2').value = this.userAddress.address2;
		}
		catch(e)
		{
			
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_ADDRESS3').value = this.userAddress.address3;
		}
		catch(e)
		{
		
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_CITY').value = this.userAddress.city;
		}
		catch(e)
		{
		
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_REGION').value = this.userAddress.region;
		}
		catch(e)
		{
		
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_POSTCODE').value = this.userAddress.postcode;
		}
		catch(e)
		{
		
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_COUNTRY').value = this.userAddress.country;	
		}
		catch(e)
		{
		
		}
		try
		{
			winSelectAddress.document.getElementById(this.qualifier + '_UPRNNONLLPGID').value = this.userAddress.country;	
		}
		catch(e)
		{
		
		}
	}
}

/*
	Return form field's value
*/
function GetFormValue(fieldId)
{
	var f = document.getElementById(fieldId);
	if (f != null)
	{
		return f.value;
	}
	else return null;
}

/*
	Find Address
	
	A standardised approach to launching the Address finder popup window, regardless of whether the user
	is using the front end web-site or iCM. In both cases this function will have been called from
	within a form, and we expect that form to contain a hidden form field (Local_ArticleID for iCM,
	articleid for front-end) that contains the Article ID we will need later on to ascertain the default
	form field values in order to filter them out.
*/
function FindAddress(qualifier, path)
{
	//Locate Article ID
	var icmArticleId	= GetFormValue('Local_ArticleID');
	var frontArticleId	= GetFormValue('articleid');
	var useArticleId	= 0;
	if (icmArticleId != null)
	{
		useArticleId	= icmArticleId;
	}
	else
	{
		useArticleId	= frontArticleId;
	}
	
	//Sanitise the path to exclude anything that iCM might have added
	var strpath	 = new String(path);
	var first	 = true;
	var newpath	 = "";
	var sections = strpath.split('/');
	for (i = 0; i < sections.length; i++)
	{
		var s = sections[i].toLowerCase();
		if (s == 'icm' || s == 'enterprise')
		{
			break;
		}
		else
		{
			if ( (sections[i].indexOf('.aspx') >= 0) || (sections[i].indexOf('.cfm') >= 0) )
			{
				break;
			}
			else 
			{
				if (!first) newpath = newpath + "/";
				newpath = newpath + s;
				first	= false;
			}
		}
	}
	
	//Launch popup
	globalAddress = new Address(qualifier, useArticleId, newpath + '/pGossCustom/PickAddress.aspx');
	globalAddress.GetUserAddress();
	globalAddress.LookUpSystemAddress();
}

