d = document;

function setCookie2(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

function setCookie(name, value, days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
	{
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ')
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function delCookie(name)
{
	setCookie(name, "", -1);
}

function cookieTest()
{
	setCookie('cookietest', '1');
	if (getCookie('cookietest') == '1')
	{
		delCookie('cookietest');
		return true;
	}
	else
	{
		delCookie('cookietest');
		return false;
	}
}

function parseQueryString()
{
	var result = {};
	var qs = location.search.substring(1, location.search.length)
	qs = qs.replace(/\+/g, ' ');

	var params = qs.split('&');
	for(var i=0; i<params.length; ++i)
	{
		var key = params[i].split('=')[0];
		var value = params[i].split('=')[1];
		result[key] = value;
	}
	return result;
}

function toggle(blockname, obj)
{
	var blocks = new Array('features', 'specs', 'faq');
	for (var i=0; i<blocks.length; i++)
	{
		document.getElementById(blocks[i]).style.display = (blocks[i] == blockname) ? 'block' : 'none';
		document.getElementById('tab'+(i+1)).className = 'tab_'+blocks[i]+((blocks[i] == blockname) ? '' : ' tab_unselected');
	}
	obj.blur();
	return false;
}

function toggleTabPage()
{
	var page;
	var tab;

	if (toggleTabPage.arguments.length == 3)
	{
		var tabPrefix = toggleTabPage.arguments[1];
		var tabpagePrefix = toggleTabPage.arguments[2];
	}
	else
	{
		var tabPrefix = 'tab';
		var tabpagePrefix = 'tabpage';
	}

	// if it can't find the first element, start from the second one
	// var i = (d.getElementById(tabPrefix+'1')) ? 1 : 2

	// find first tab
	var i = 1;
	for(var j=1; j<5; j++)
		if (d.getElementById(tabPrefix+j))
		{
			i = j;
			break;
		}

	while(tab = d.getElementById(tabPrefix+i))
	{
		if (page = d.getElementById(tabpagePrefix+i))
		{
			if (i == toggleTabPage.arguments[0])
			{
				addClass(tab, 'tab_selected');
				removeClass(tab, 'tab_unselected');
				removeClass(page, 'nodisplay');
			}
			else
			{
				addClass(tab, 'tab_unselected');
				removeClass(tab, 'tab_selected');
				addClass(page, 'nodisplay');
			}
		}
		i++;
	}

	return false;
}

function addClass(e,theClass)
{
	if (e.className == theClass)
		return;

	removeClass(e,theClass);

	var c = e.className.split(' ');
	c[c.length] = theClass;
	e.className = c.join(' ');
}

function removeClass(e,theClass)
{
	var newClass = [];
	var currClass = e.className.split(' ');

	for(var i=0; i<currClass.length; i++)
		if(currClass[i] != theClass)
			newClass[newClass.length] = currClass[i];

	e.className = newClass.join(' ');
}

function hasClass(e,theClass)
{
	var c = e.className;
	if(c)
	{
		c = c.split(' ');
		for(var i=0; i<c.length; i++)
			if(c[i] == theClass)
				return true;
	}
	return false;
}

function toggleDiv(id)
{
	if (d.getElementById(id).style.display == 'none')
		d.getElementById(id).style.display = 'block';
	else
		d.getElementById(id).style.display = 'none';

	return false;
}

/* Direct Debit Layer */



function showddform()
{
	d.getElementById("dd_form").style.display = 'block';
}


function hideddform()
{
	d.getElementById("dd_form").style.display = 'none';
}

function stripChars2(str, chars) {

/*	var newStr = '';
	var char = '';

	if (chars) {
		for (var i=0; i<str.length; i++) {
			char = str.charAt(i);
			if (chars.indexOf(tmp) == -1) {
				newStr += char;
			}
		}
	}

	return newStr;
*/
	return str;

}


/* -----------------------------------------  Domain Checker Form  --------------------------------------------  */

// Validate Transfer In Domain Form
function IsValidDomain(thisForm)
{
	var errorMsg = "The following errors were encountered:\n\n- Domain name is invalid \n";
	var errorFlag = false;

	if(!IsAlphaNumeric(thisForm.domain.value) || !CheckFilled(thisForm.domain))
	{
		alert(errorMsg);
		return false;
	}

	return true;
}

/* -----------------------------------------  ADSL Install Form  --------------------------------------------  */

function ClearADSLInstall()
{
	if (d.getElementById('ADSL_INST_ADDR1'))
	{
		d.getElementById('ADSL_INST_ADDR1').value = '';
		d.getElementById('ADSL_INST_ADDR2').value = '';
		d.getElementById('ADSL_INST_ADDR3').value = '';
		d.getElementById('ADSL_INST_ADDR4').value = '';
		d.getElementById('ADSL_INST_POST_CODE').value = '';
	}
}

function PopulateADSLInstall()
{
	if (d.getElementById('adsl_install_same') && d.getElementById('adsl_install_same').checked)
	{
		d.getElementById('ADSL_INST_ADDR1').value = d.getElementById('Address1').value;
		d.getElementById('ADSL_INST_ADDR2').value = d.getElementById('Address2').value;
		d.getElementById('ADSL_INST_ADDR3').value = d.getElementById('City').value;
		d.getElementById('ADSL_INST_ADDR4').value = d.getElementById('County').value;
		d.getElementById('ADSL_INST_POST_CODE').value = d.getElementById('Postcode').value;
	}
}

function showOtherAddress()
{
	var i = 1;
	var cb;
	while(cb = d.getElementById('otheraddr'+i))
	{
		if (cb.checked) {
			d.getElementById('otheraddress').style.display = 'block';
			return true;
		}
		i++;
	}
	d.getElementById('otheraddress').style.display = 'none';
	return false;
}

/ * ----------------------------------------- Reusable Functions ----------------------------------------- */



/*
 * checkEmail
 *
 * @param emailStr [String] The entire email address to check
 *
 */

function checkEmail(emailStr)
{
	// The following variable tells the rest of the function whether or not to verify that the address ends in a two-letter country or well-known TLD.  1 means check it, 0 means don't.
	var checkTLD=1;

	// The following is the list of known TLDs that an e-mail address must end with.
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	// The following pattern is used to check if the entered e-mail address fits the user@domain format.  It also is used to separate the username from the domain.
	var emailPat=/^(.+)@(.+)$/;

	// The following string represents the pattern for matching all special characters. We don't want to allow special characters in the address.  These characters include ( ) < > @ , ; : \ " . [ ]
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	// The following string represents the range of characters allowed in a username or domainname.  It really states which chars aren't allowed.
	var validChars="\[^\\s" + specialChars + "\]";

	// The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes).
	//E.g. "jiminy cricket"@disney.com is a legal e-mail address.
	var quotedUser="(\"[^\"]*\")";

	// The following pattern applies for domains that are IP addresses, rather than symbolic names.
	// E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required.
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	// The following string represents an atom (basically a series of non-special characters.)
	var atom=validChars + '+';

	// The following string represents one word in the typical username.
	// For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string.
	var word="(" + atom + "|" + quotedUser + ")";

	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	// The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above.
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	// Finally, let's start trying to figure out if the supplied address is valid.

	// Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null)
	{
		// Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address.
		alert("Email Address Check: Email address seems incorrect (check @ and .'s)");
		return false;
	}

	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).

	for (i=0; i<user.length; i++)
	{
		if (user.charCodeAt(i)>127)
		{
			alert("Email Address Check: This username contains invalid characters.");
			return false;
		}
	}

	for (i=0; i<domain.length; i++)
	{
		if (domain.charCodeAt(i)>127)
		{
			alert("Email Address Check: This domain name contains invalid characters.");
			return false;
		}
	}

	// See if "user" is valid

	if (user.match(userPat)==null)
	{
		// user is not valid
		alert("Email Address Check: The username doesn't seem to be valid.");
		return false;
	}


	// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid.
	var IPArray=domain.match(ipDomainPat);

	if (IPArray!=null)
	{
		// this is an IP address
		for (var i=1;i<=4;i++)
		{
			if (IPArray[i]>255)
			{
				alert("Email Address Check: Destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}

	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;

	for (i=0;i<len;i++)
	{
		if (domArr[i].search(atomPat)==-1)
		{
			alert("Email Address Check: The domain name does not seem to be valid.");
			return false;
		}
	}

	// domain name seems valid, but now make sure that it ends in a known top-level domain (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country.

	if (checkTLD && domArr[domArr.length-1].length!=2 &&
		domArr[domArr.length-1].search(knownDomsPat)==-1)
	{
		alert("Email Address Check: The address must end in a well-known domain or two letter " + "country.");
		return false;
	}


	// Make sure there's a host name preceding the domain.
	if (len<2)
	{
		alert("Email Address Check: This address is missing a hostname!");
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}


function checkValidChars(str, strValidChars)
{
	for (var i=0; i<str.length; i++)
		if (strValidChars.indexOf( str.charAt(i) ) == -1)
			return false;

	return true;
}

function checkInvalidChars(str, strInvalidChars)
{
	for (var i=0; i<str.length; i++)
		if (strInvalidChars.indexOf( str.charAt(i) ) != -1)
			return true;

	return false;
}


function IsAlphaNumeric(theField)
{
	// Function to Check if a form field value contains alphanumeric input
	if (checkInvalidChars(theField, "@¬!\"£$%^*()_+=}{[]|\\<>?/,"))
		return false;

	return true;
}


function CheckFilled(theElement)
{
	if(theElement.value == "")
		return false;

	return true;
}


function IsNumeric(theField)
{
	// Function to Check if a form field value is numeric
	if (checkValidChars(theField, "0123456789 "))
		return true;

	return false;
}

function IsAlpha(theField)
{
	//Function to Check if a form field value contains alphanumeric input
	if (checkInvalidChars(theField, "@¬!\"£$%^*()_+=}{[]|\\<>?/,123456789"))
		return false;

	return true;
}

function IsAlphaSpecial(theField)
{
	//Function to Check Alpha Special
	if (checkInvalidChars(theField, "@¬!\"£$%^*_+=}{[]|\\<>?/,"))
		return false;

	return true;
}

function IsAddress(theField)
{
	//Function to Check Addresses
	if (checkInvalidChars(theField, "@¬!\"£$%^*_+=}{[]|\\<>?/"))
		return false;

	return true;
}

function IsCompanyName(theField)
{
	//Function to Check Addresses
	if (checkInvalidChars(theField, "@¬!\"£$%^*_+=}{[]|\\<>?/"))
		return false;

	return true;
}

/* ----------------------------------------- ADSL Tel No New Connection ----------------------------------------- */
function CheckCli()
{
	var x = document.frm_cli;

	if (CheckFilled(x.cli) && IsNumeric(x.cli.value)) {
		x.cli.value = stripChars2(x.cli.value, ' ');
		return true;
	}

	alert( "- Phone Number is invalid\n");
	return false;
}





/* ----------------------------------------- New Customer ADSL ----------------------------------------- */
function new_customer()
{
	var x = document.frm_newcustomer;

	if(!IsCompanyName(x.Company_Name.value))
	{
		alert("Company Name contains invalid characters.");
		x.Company_Name.focus();
		return false;
	}

	if(!CheckFilled(x.Firstname) || !IsAlpha(x.Firstname.value))
	{
		alert("First Name is invalid\n");
		x.Firstname.focus();
		return false;
	}

	if(!CheckFilled(x.Surname) || !IsAlpha(x.Surname.value))
	{
		alert("Surname is invalid\n");
		x.Surname.focus();
		return false;
	}

	if(!CheckFilled(x.Address1) || !IsAddress(x.Address1.value))
	{
		alert("Address is invalid\n");
		x.Address1.focus();
		return false;
	}

	if(!IsAddress(x.Address2.value))
	{
		alert("Address Line2 is invalid\n");
		x.Address2.focus();
		return false;
	}

	if(!CheckFilled(x.City) || !IsAlpha(x.City.value))
	{
		alert("City is invalid\n");
		x.City.focus();
		return false;
	}

	if(!CheckFilled(x.County) || !IsAlpha(x.County.value))
	{
		alert("County is invalid\n");
		x.County.focus();
		return false;
	}

	if(!CheckFilled(x.Postcode) || !IsAlphaNumeric(x.Postcode.value))
	{
		alert("Postcode is invalid\n");
		x.Postcode.focus();
		return false;
	}

	if(!CheckFilled(x.Tel_1) || !IsNumeric(x.Tel_1.value))
	{
		alert("Please provide a valid telephone number\n");
		x.Tel_1.focus();
		return false;
	}

	if(!CheckFilled(x.Email))
	{
		alert("Please provide a valid email address\n");
		x.Email.focus();
		return false;
	}

	if(!checkEmail(x.Email.value))
	{
		alert("Please provide a valid email address\n");
		x.Email.focus();
		return false;
	}

	if(!x.tandcs.checked)
	{
		alert("Please indicate that you have read and agreed to the Terms and Conditions by ticking the box");
		return false;
	}

	return true;
}


/* ---------------------------------   ADSL Details page --------------------------------------- */

function validate_adsl_details_old()
{
	var x = document.frm_existing_customer || document.frm_newcustomer;
	if (d.getElementById('end_user_tel'))
	{
		if (d.getElementById('end_user_tel').value != d.getElementById('confirm_end_user_tel').value)
		{
			alert('Please confirm your telephone number');
			d.getElementById('confirm_end_user_tel').focus();
			return false;
		}

		if (!d.getElementById('bt_phone_line').checked)
		{
			alert('Please confirm you have a BT phone line');
			return false;
		}

		if (!d.getElementById('confirmrequirements').checked)
		{
			alert('Please confirm you meet the minimum requirements');
			return false;
		}

		if (!IsNumeric(d.getElementById('ADSL_NO_OF_LAN').value))
		{
			alert('Number of IP addresses is not a numeric field');
			return false;
		}

		if (d.getElementById('bbinfo').style.display == 'block')
		{
			if (!CheckFilled(d.getElementById('ADSL_INST_ADDR1'))|| !IsAddress(d.getElementById('ADSL_INST_ADDR1').value))
			{
				alert('Please complete your ADSL installation address');
				d.getElementById('ADSL_INST_ADDR1').focus();
				return false;
			}

			if (!IsAddress(d.getElementById('ADSL_INST_ADDR2').value))
			{
				alert('ADSL installation address contains invalid characters');
				d.getElementById('ADSL_INST_ADDR2').focus();
				return false;
			}

			if (!CheckFilled(d.getElementById('ADSL_INST_ADDR3'))|| !IsAlphaNumeric(d.getElementById('ADSL_INST_ADDR3').value))
			{
				alert('Please enter the town/city for your ADSL installation');
				d.getElementById('ADSL_INST_ADDR3').focus();
				return false;
			}

			if (!CheckFilled(d.getElementById('ADSL_INST_ADDR4'))|| !IsAlphaNumeric(d.getElementById('ADSL_INST_ADDR4').value))
			{
				alert('Please enter the county for your ADSL installation');
				d.getElementById('ADSL_INST_ADDR4').focus();
				return false;
			}

			if (!CheckFilled(d.getElementById('ADSL_INST_POST_CODE'))|| !IsAlphaNumeric(d.getElementById('ADSL_INST_POST_CODE').value))
			{
				d.getElementById('ADSL_INST_POST_CODE').focus();
				alert('Please enter the postcode for your ADSL installation');
				return false;
			}
		}
	}

	if (d.getElementById('otheraddress').style.display == 'block')
	{
		if (!CheckFilled(d.getElementById('Other_Address1'))|| !IsAddress(d.getElementById('Other_Address1')))
		{
			alert('Please complete your other delivery address');
			return false;
		}

		if (!IsAddress(d.getElementById('Other_Address2').value))
		{
			alert('Please complete your other delivery address');
			return false;
		}

		if (!CheckFilled(d.getElementById('Other_City'))|| !IsAlphaNumeric(d.getElementById('Other_City').value))
		{
			alert('Please enter the town/city for your other delivery address');
			return false;
		}

		if (!CheckFilled(d.getElementById('Other_County'))|| !IsAlphaNumeric(d.getElementById('Other_County').value))
		{
			alert('Please enter the county for your other delivery address');
			return false;
		}

		if (!CheckFilled(d.getElementById('Other_Postcode'))|| !IsAlphaNumeric(d.getElementById('Other_Postcode').value))
		{
			alert('Please enter the postcode for your other delivery address');
			return false;
		}
	}

	return true;
}

function validate_adsl_details2()
{
	return validate_adsl_details();
}

function validate_adsl_details()
{
	var frm = document.frm_existing_customer || document.frm_newcustomer;
	var el_name = '';
	var parent_id;

	for (var i=0; i<frm.elements.length; i++)
	{
		el_name = frm.elements[i].name;

		/* end user telephone number */
		if(el_name.indexOf('[endusertel]') > -1)
		{
			parent_id = el_name.substring(18, el_name.length - 13);
			if (validate_adsl_details_byid(parent_id) == false)
				return false;
		}
	}
	return true;
}

function validate_adsl_details_byid(parent_id)
{
	var prefix = 'basket_product_id['+parent_id+']';
	var frm = d.frm_existing_customer || d.frm_newcustomer;
	if (frm[prefix+'[endusertel]'])
	{
		if (!IsNumeric(frm[prefix+'[endusertel]'].value))
		{
			alert('Invalid telephone number');
			frm[prefix+'[endusertel]'].focus();
			return false;
		}

		if (frm[prefix+'[endusertel]'].value != frm[prefix+'[confirmendusertel]'].value)
		{
			alert('Please confirm your telephone number');
			frm[prefix+'[confirmendusertel]'].focus();
			return false;
		}

		if (!frm[prefix+'[btphoneline]'].checked)
		{
			alert('Please confirm you have a BT phone line');
			frm[prefix+'[btphoneline]'].focus()
			return false;
		}

		if (!frm[prefix+'[confirmrequirements]'].checked)
		{
			alert('Please confirm you meet the minimum requirements');
			frm[prefix+'[confirmrequirements]'].focus();
			return false;
		}

		if (!IsNumeric(frm[prefix+'[ADSL_NO_OF_LAN]'].value))
		{
			alert('Number of IP addresses is not a numeric field');
			frm[prefix+'[ADSL_NO_OF_LAN]'].focus();
			return false;
		}

		if (d.getElementById('bbinfo'+parent_id).style.display == 'block')
		{
			if (!CheckFilled(frm[prefix+'[ADSL_INST_ADDR1]'])|| !IsAddress(frm[prefix+'[ADSL_INST_ADDR1]'].value))
			{
				alert('Please complete your ADSL installation address');
				frm[prefix+'[ADSL_INST_ADDR1]'].focus();
				return false;
			}

			if (!IsAddress(frm[prefix+'[ADSL_INST_ADDR2]'].value))
			{
				alert('ADSL installation address contains invalid characters');
				frm[prefix+'[ADSL_INST_ADDR2]'].focus();
				return false;
			}

			if (!CheckFilled(frm[prefix+'[ADSL_INST_ADDR3]'])|| !IsAlphaNumeric(frm[prefix+'[ADSL_INST_ADDR3]'].value))
			{
				alert('Please enter the town/city for your ADSL installation');
				frm[prefix+'[ADSL_INST_ADDR3]'].focus();
				return false;
			}

			if (!CheckFilled(frm[prefix+'[ADSL_INST_ADDR4]'])|| !IsAlphaNumeric(frm[prefix+'[ADSL_INST_ADDR4]'].value))
			{
				alert('Please enter the county for your ADSL installation');
				frm[prefix+'[ADSL_INST_ADDR4]'].focus();
				return false;
			}

			if (!CheckFilled(frm[prefix+'[ADSL_INST_POST_CODE]'])|| !IsAlphaNumeric(frm[prefix+'[ADSL_INST_POST_CODE]'].value))
			{
				alert('Please enter the postcode for your ADSL installation');
				frm[prefix+'[ADSL_INST_POST_CODE]'].focus();
				return false;
			}
		}
	}

	if (d.getElementById('otheraddress').style.display == 'block')
	{
		if (!CheckFilled(d.getElementById('Other_Address1'))|| !IsAddress(d.getElementById('Other_Address1')))
		{
			alert('Please complete your other delivery address');
			return false;
		}

		if (!IsAddress(d.getElementById('Other_Address2').value))
		{
			alert('Please complete your other delivery address');
			return false;
		}

		if (!CheckFilled(d.getElementById('Other_City'))|| !IsAlphaNumeric(d.getElementById('Other_City').value))
		{
			alert('Please enter the town/city for your other delivery address');
			return false;
		}

		if (!CheckFilled(d.getElementById('Other_County'))|| !IsAlphaNumeric(d.getElementById('Other_County').value))
		{
			alert('Please enter the county for your other delivery address');
			return false;
		}

		if (!CheckFilled(d.getElementById('Other_Postcode'))|| !IsAlphaNumeric(d.getElementById('Other_Postcode').value))
		{
			alert('Please enter the postcode for your other delivery address');
			return false;
		}
	}

	return true;
}

function ClearADSLInstall2(parent_id)
{
	var prefix = 'basket_product_id['+parent_id+']';
	var frm = d.frm_existing_customer || d.frm_newcustomer;
	if (frm[prefix+'[ADSL_INST_ADDR1]'])
	{
		frm[prefix+'[ADSL_INST_ADDR1]'].value = '';
		frm[prefix+'[ADSL_INST_ADDR2]'].value = '';
		frm[prefix+'[ADSL_INST_ADDR3]'].value = '';
		frm[prefix+'[ADSL_INST_ADDR4]'].value = '';
		frm[prefix+'[ADSL_INST_POST_CODE]'].value = '';
	}
}

function PopulateADSLInstall2(parent_id)
{
	var prefix = 'basket_product_id['+parent_id+']';
	var frm = d.frm_existing_customer || d.frm_newcustomer;
	frm[prefix+'[ADSL_INST_ADDR1]'].value = d.getElementById('Address1').value;
	frm[prefix+'[ADSL_INST_ADDR2]'].value = d.getElementById('Address2').value;
	frm[prefix+'[ADSL_INST_ADDR3]'].value = d.getElementById('City').value;
	frm[prefix+'[ADSL_INST_ADDR4]'].value = d.getElementById('County').value;
	frm[prefix+'[ADSL_INST_POST_CODE]'].value = d.getElementById('Postcode').value;
}

function toggleOtherAddress()
{
	var frm = d.frm_existing_customer || d.frm_newcustomer;
	var el_name = '';
	var parent_id;

	for (var i=0; i<frm.elements.length; i++)
	{
		el_name = frm.elements[i].name;

		if(el_name.indexOf('[use_address]') > -1)
		{
			for(var j=0; j<frm[el_name].length; j++)
			{
				if (frm[el_name][j].checked && frm[el_name][j].value == 'other')
				{
					d.getElementById('otheraddress').style.display = 'block';
					return true;
				}
			}
		}
	}
	d.getElementById('otheraddress').style.display = 'none';

	return true;
}

/* ---------------------------------   Login Form --------------------------------------- */
function validate_login()
{
	var x = document.frmlogin

	if(!CheckFilled(x.username)|| !IsAlphaNumeric(x.username))
	{
		alert("Please enter your username");
		return false;
	}

	if(!CheckFilled(x.password)|| !IsAlphaNumeric(x.password))
	{
		alert("Please enter your password");
		return false;
	}

	return true;
}



/* --------------------------------   CC Details -------------------------------------------- */




/* --------------------------------- DD Sign Up form ------------------------------------------ */
function dateThang()
{
	var dt = new Date();
	d.ddform2.dddate.value = dt.getDate() + "/" + (dt.getMonth() + 1) + "/"  + dt.getFullYear();
}


function checkForm(theForm)
{
	var errorMsg = "The following errors were encountered:\n\n";
	var errorFlag = false;

	// check user has confirmed they are the account holder
	if(!theForm.confirmaccholder.checked)
	{
		errorMsg = errorMsg + "- You must confirm you are the account holder\n";
		errorFlag = true;
	}

	// check user has agreed to t and cs
	if(!theForm.confirmtandc.checked)
	{
		errorMsg = errorMsg + "- Please indicate that you have read and agreed to the Terms and Conditions by ticking the relevant box.\n"
		errorFlag = true;
	}

	// check for company name
	if(!IsCompanyName(theForm.companyname.value) || !CheckFilled(theForm.companyname))
	{
		errorMsg = errorMsg + "- Company Name is invalid\n";
		theForm.companyname.focus();
		errorFlag = true;
	}

	// check for company address
	if (!IsAddress(theForm.companyaddress.value) || !CheckFilled(theForm.companyaddress))
	{
		errorMsg = errorMsg + "- Company Address is invalid\n";
		theForm.companyaddress.focus();
		errorFlag = true;
	}

	//check for account holder name
	if (!IsAlphaNumeric(theForm.accholder.value) || !CheckFilled(theForm.accholder))
	{
		errorMsg = errorMsg + "- Account Holder Name is invalid\n";
		theForm.accholder.focus();
		errorFlag = true;
	}

	//check for account number
	if (!IsNumeric(theForm.accnumber.value) || theForm.accnumber.value.length < 8)
	{
		errorMsg = errorMsg + "- Account Number is invalid\n";
		theForm.accnumber.focus();
		errorFlag = true;
	}

	// check sort code has been entered
	if (!IsNumeric(theForm.sortcode.value) || theForm.sortcode.value.length < 6)
	{
		errorMsg = errorMsg + "- Sort Code is invalid\n";
		theForm.sortcode.focus();
		errorFlag = true;
	}

	// check name of bank / building society has been entered
	if(!IsCompanyName(theForm.bankname.value) || !CheckFilled(theForm.bankname))
	{
		errorMsg = errorMsg + "- Bank Name or Building Society is invalid\n";
		theForm.bankname.focus();
		errorFlag = true;
	}

	// check for bank address
	if (!IsAddress(theForm.bankaddress1.value) || !CheckFilled(theForm.bankaddress1))
	{
		errorMsg = errorMsg + "- Bank or Building Society Address is invalid\n";
		theForm.bankaddress1.focus();
		errorFlag = true;
	}

	if (!IsAddress(theForm.bankaddress2.value))
	{
		errorMsg = errorMsg + "- Bank or Building Society Address is invalid\n";
		theForm.bankaddress2.focus();
		errorFlag = true;
	}

	// check for bank city or town
	if (!IsAlphaNumeric(theForm.bankcity.value) || !CheckFilled(theForm.bankcity))
	{
		errorMsg = errorMsg + "- Bank or Building Society City\Town is invalid\n";
		theForm.bankcity.focus();
		errorFlag = true;
	}

	// check for bank county
	if (!IsAlphaNumeric(theForm.bankcounty.value) || !CheckFilled(theForm.bankcounty))
	{
		errorMsg = errorMsg + "- Bank or Building Society County is invalid\n";
		theForm.bankcounty.focus();
		errorFlag = true;
	}

	//check for bank postcode
	if (!IsAlphaNumeric(theForm.bankpostcode.value) || !CheckFilled(theForm.bankpostcode))
	{
		errorMsg = errorMsg + "- Bank or Building Society Postcode is invalid\n";
		theForm.bankpostcode.focus();
		errorFlag = true;
	}

	if(errorFlag)
	{
		//Output any error messages
		alert(errorMsg);
		return false;
	}

	return true; //No errors encountered, submit the form
}




/* ------------------------------ Product Enquiry ------------------------------------------------ */
function product_enquiry()
{
	var x = d.frm_productenquiry

	if(!CheckFilled(x.contact_name))
	{
		alert("Please enter a contact name");
		x.contact_name.focus();
		return false;
	}

	if(!IsNumeric(x.telephone.value ) || !CheckFilled(x.telephone))
	{
		alert("Please enter a valid contact phone number");
		x.telephone.focus();
		return false;
	}

	if(!checkEmail(x.email.value))
	{
		alert("Please enter a valid email address");
		x.email.focus();
		return false;
	}

	if(!CheckFilled(x.preferred_contact))
	{
		alert("Please indicate a preferred method of contact.");
		x.preferred_contact.focus();
		return false;
	}

	if(!CheckFilled(x.enquiry_details))
	{
		alert("Please enter the details of your enquiry\n Please enter only letters or numbers");
		x.enquiry_details.focus();
		return false;
	}

	return true;
}


/* ------------------------------  Validate Credit Card --------------------------------------- */
function validate_cc()
{
	var thisForm = d.frm_ccdetails;
	var dt = new Date();

	// display generic error message
	var errorMsg = "The following errors were encountered:\n\n";
	var errorFlag = false;

	if(!IsAlphaSpecial(thisForm.cardholder.value) || !CheckFilled(thisForm.cardholder))
	{
		// make sure a cardholder name is entered
		errorMsg = errorMsg + "- Cardholder Name is invalid\n";
		errorFlag = true;
	}

	if (!CheckFilled(thisForm.cardtype.options[thisForm.cardtype.selectedIndex]))
	{
		// make sure a card type is selected
		errorMsg = errorMsg + "- Card Type has not been selected\n";
		errorFlag = true;
	}

	if(!IsNumeric(thisForm.Ecom_Payment_Card_Number.value) || thisForm.Ecom_Payment_Card_Number.value.length < 15)
	{
		// make sure the card number field contains numerical data
		errorMsg = errorMsg + "- Card Number is invalid\n";
		errorFlag = true;
	}

	// check start and expiry dates
	// start date
	startMonth = thisForm.Ecom_Payment_Card_StartDate_Month.options[thisForm.Ecom_Payment_Card_StartDate_Month.selectedIndex].value;
	startYear = thisForm.Ecom_Payment_Card_StartDate_Year.options[thisForm.Ecom_Payment_Card_StartDate_Year.selectedIndex].value;
	startDate = new Date((startYear*1) + 2000, startMonth - 1, 01);

	// expiry date
	expMonth = thisForm.Ecom_Payment_Card_ExpDate_Month.options[thisForm.Ecom_Payment_Card_ExpDate_Month.selectedIndex].value;
	expYear = thisForm.Ecom_Payment_Card_ExpDate_Year.options[thisForm.Ecom_Payment_Card_ExpDate_Year.selectedIndex].value;
	expiryDate = new Date((expYear*1) + 2000, expMonth - 1, 01);

	// compare dates
	theDifference = startDate - expiryDate;

	// make sure start date is before expiry date
	if(theDifference>=0)
	{
		errorMsg = errorMsg + "- Start Date cannot exist after Expiry Date\n";
		errorFlag = true;
	}

	// make sure start date occurrs before today
	startMonth = thisForm.Ecom_Payment_Card_StartDate_Month.options[thisForm.Ecom_Payment_Card_StartDate_Month.selectedIndex].value;
	startYear = thisForm.Ecom_Payment_Card_StartDate_Year.options[thisForm.Ecom_Payment_Card_StartDate_Year.selectedIndex].value;
	startDate = new Date((startYear*1) + 2000, startMonth - 1, 01);

	startDateDiff = dt - startDate;

	if(startDateDiff<=0)
	{
		errorMsg = errorMsg + "- Start Date cannot occurr after todays date\n";
		errorFlag = true;
	}

	// make sure expiry date is after today
	expMonth = thisForm.Ecom_Payment_Card_ExpDate_Month.options[thisForm.Ecom_Payment_Card_ExpDate_Month.selectedIndex].value;
	expYear = thisForm.Ecom_Payment_Card_ExpDate_Year.options[thisForm.Ecom_Payment_Card_ExpDate_Year.selectedIndex].value;
	expiryDate = new Date((expYear*1) + 2000, expMonth - 1, 01);

	expiryDiff = expiryDate - dt;

	if(expiryDiff<0)
	{
		errorMsg = errorMsg + "- Expiry Date has passed\n";
		errorFlag = true;
	}

	if(!IsNumeric(thisForm.Ecom_Payment_Card_Verification.value) || thisForm.Ecom_Payment_Card_Verification.value.length < 3)
	{
		errorMsg = errorMsg + "- CVV Number is invalid\n";
		errorFlag = true;
	}

	if(!IsAddress(thisForm.Ecom_BillTo_Postal_Street_Line1.value) || !CheckFilled(thisForm.Ecom_BillTo_Postal_Street_Line1))
	{
		errorMsg = errorMsg + "- Cardholder Address is invalid\n";
		errorFlag = true;
	}

	if(!IsAddress(thisForm.Ecom_BillTo_Postal_Street_Line2.value))
	{
		errorMsg = errorMsg + "- Cardholder Address1 is invalid\n";
		errorFlag = true;
	}

	if(!IsAlphaNumeric(thisForm.Ecom_BillTo_Postal_City.value) || !CheckFilled(thisForm.Ecom_BillTo_Postal_City))
	{
		errorMsg = errorMsg + "- Cardholder City\Town is invalid\n";
		errorFlag = true;
	}

	if(!IsAlphaNumeric(thisForm.Ecom_BillTo_Postal_StateProv.value) || !CheckFilled(thisForm.Ecom_BillTo_Postal_StateProv))
	{
		errorMsg = errorMsg + "- Cardholder County is invalid\n";
		errorFlag = true;
	}

	if(!IsAlphaNumeric(thisForm.Ecom_BillTo_Postal_PostalCode.value) || !CheckFilled(thisForm.Ecom_BillTo_Postal_PostalCode))
	{
		errorMsg = errorMsg + "- Cardholder Postcode is invalid\n";
		errorFlag = true;
	}

	if(errorFlag)
	{
		// the bit that actually displays the error message.
		alert(errorMsg);
		return false;
	}

	return true;
}


/* ----------------------------------------  Domain Checker Form -------------------------------------- */
function check_domain()
{
	var x = d.frm_domain;

	if(!CheckFilled(x.domain))
	{
		alert("Please enter a domain name");
		return false;
	}

	return true;
}

/* -----------------------------------   sub-domain checker ------------------------------------------- */
function check_subdomain()
{
	var x = d.frm_subdomain;

	if(!CheckFilled(x.domain) || !IsAlphaNumeric(x.domain.value))
	{
		alert("Please enter a sub-domain containing letters and numbers only");
		return false;
	}

	return true;
}

/*------------------------------------   ensure domain is chosen -------------------------------------- */
function choose_domain()
{
	var x = d.frm_choose_domain

	var element_count = x.elements.length;

	for(var i=0; i<element_count;i++)
		if(x.elements[i].type=='checkbox')
			if(x.elements[i].checked)
				return true;

	alert("Please select domain(s)");
	return false;
}

/*------------------------------------  Partners Join Form ----------------------------------------- */
function join_partners()
{
	var x = d.frm_joinpartners;

	if(!CheckFilled(x.contact_name)|| !IsAlpha(x.contact_name.value))
	{
		alert("Please enter a contact name");
		x.contact_name.focus();
		return false;
	}

	if(!IsAlphaSpecial(x.company_name))
	{
		alert("Please enter a company name");
		x.company_name.focus();
		return false;
	}

	if(!CheckFilled(x.telephone)|| !IsNumeric(x.telephone.value))
	{
		alert("Please enter a contact phone number");
		x.telephone.focus();
		return false;
	}

	if(!CheckFilled(x.email) || !checkEmail(x.email.value))
	{
		alert("Please enter a valid email address");
		x.email.focus();
		return false;
	}

	if(!CheckFilled(x.preferred_contact))
	{
		alert("Please enter a preferred method of contact");
		x.preferred_contact.focus();
		return false;
	}

	if(!CheckFilled(x.heard_about))
	{
		alert("Please indicate how you heard about Legend Communications plc");
		x.heard_about.focus();
		return false;
	}

	if(!CheckFilled(x.enquiry_details))
	{
		alert("Please enter the details of your enquiry");
		x.enquiry_details.focus();
		return false;
	}

	return true;
}

/*-----------------------------------  Support Feedback Form ----------------------------- */
function feedback()
{
	var x = d.frm_feedback;

	if(!CheckFilled(x.name))
	{
		alert("Please enter a contact name");
		x.name.focus();
		return false;
	}

	if(!CheckFilled(x.email) || !checkEmail(x.email.value))
	{
		alert("Please enter a valid email address");
		x.email.focus();
		return false;
	}

	if(!CheckFilled(x.telephone) || !IsNumeric(x.telephone.value))
	{
		alert("Please enter a valid contact phone number");
		x.telephone.focus();
		return false;
	}

	if(!CheckFilled(x.feedback_details))
	{
		alert("Please enter the details of your enquiry ");
		x.feedback_details.focus();
		return false;
	}

	return true;
}


/*---------------------------------------  Old legend.co.uk webmail function ------------------------------------- */
function doMailAction()
{
	// Script by Neil to perform regular expression on domain and choose correct atmail script //
	var reg1 = new RegExp("go-legend");
	var reg2 = new RegExp("golegend");

	if (d.loginPage.username.value!="")
	{
		if ((!reg1.test(d.loginPage.pop3host.value)) && (!reg2.test(d.loginPage.pop3host.value)))
		{
			 d.loginPage.action="http://212.69.225.56/atmail.pl";
			 d.loginPage.elements[0].name="username";
			 d.loginPage.elements[1].name="pop3host";
			 d.loginPage.elements[3].value="imap.legend.co.uk";
			 d.loginPage.elements[2].name="password";
			 d.loginPage.submit();
		}
		else
		{
			 d.loginPage.action="http://webmail.go-legend.net/atmail.pl";
			 d.loginPage.elements[0].name="username";
			 d.loginPage.elements[4].value="simple" ;
			 d.loginPage.elements[1].value="go-legend.net";
			 d.loginPage.elements[3].value="imap.visp.legend.net.uk";
			 d.loginPage.elements[2].name="password";
			 d.loginPage.submit();
		}

		return false;
	}
}

function close2()
{
	d.getElementById("message301").style.display = 'none';
}


/* ----------------------------------------  Validate password reminder request form --------------------------- */
function validate_pwordreminder()
{
	var x = document.password_reminder;

	if(!CheckFilled(x.txt_Name)||!IsAlpha(x.txt_Name.value))
	{
		alert("Please enter your name");
		x.txt_Name.focus();
		return false;
	}

	if(!CheckFilled(x.txtEmailaddress)||!checkEmail(x.txtEmailaddress.value))
	{
		alert("Please enter a valid email address") ;
		x.txtEmailaddress.focus();
		return false;
	}

	if(!IsAlphaSpecial(x.txt_Domain_Name.value))
	{
		alert("Domain name contains illegal characters.");
		x.txt_Domain_Name.focus();
		return false;
	}

	if(!CheckFilled(x.txt_Telephone_Number)|| !IsNumeric(x.txt_Telephone_Number.value))
	{
		alert("Please enter a contact telephone number");
		x.txt_Telephone_Number.focus();
		return false;
	}

	return true;
}

/* ----------------------------------------------  Customer Satisfaction Survey -------------------------- */
function CheckRadio(theElement)
{
	for(i = 0; i<theElement.length; i++)
		if(theElement[i].checked)
			return true;

	return false;
}

function validate_quiz()
{
	var x = document.quiz_form;

	if(!checkEmail(x.email.value))
	{
		alert("Please provide a valid email address\n");
		x.email.focus();
		return false;
	}

	for(var i=1; i<=20; i++)
	{
		if (!CheckRadio(x['q'+i]))
		{
			alert("Please select your answer for question "+i+".");
			return false;
		}
	}

	return true;
}

function openWindow(url, name, width, height, params)
{
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	var winParams = 'top='+top+',left='+left+',width='+width+',height='+height;
	if (params) winParams += ','+params
	return window.open(url, name, winParams);
}

function submitForm(formID)
{
	var frm;
	if (frm = document.getElementById(formID))
		frm.submit();

	return true;
}

/*
 * Functions to automatically disable submit buttons when a form is submitted, and show delayed "processing image".
 */

/* add 1 second delay before looking for forms elements, giving time for the page to load */
setTimeout('add_form_wait_img()', 1000);
function add_form_wait_img()
{
	var forms = document.getElementsByTagName('form');
	if (forms.length > 0)
	{
		waitImg = new Image();
		waitImg.src = '/resources/images/wait.gif';
	}

	for (var i=0; i<forms.length; i++)
	{
		if (forms[i].onsubmit)
		{
			forms[i].oldonsubmit = forms[i].onsubmit;
			forms[i].onsubmit = function () { return this.oldonsubmit() && show_wait_img(); }
		}
		else
		{
			forms[i].onsubmit = function () { return show_wait_img(); }
		}
	}
}

function show_wait_img()
{
	var process_timeout = 4000;
	if (typeof(process_timeout_override) != 'undefined') process_timeout = process_timeout_override;
	disable_submit_buttons();
	setTimeout('show_wait_img_add()', process_timeout);
	return true;
}

function show_wait_img_add()
{
	var img = document.createElement('div');
	img.className = 'waitimg';
	var main = document.getElementById('wrapper');
	main.appendChild(img);
}

function disable_submit_buttons()
{
	var inputs = document.getElementsByTagName('input');
	for (var i=0; i<inputs.length; i++)
	{
		if (inputs[i].getAttribute('type') == 'submit' || inputs[i].getAttribute('type') == 'image')
		{
			inputs[i].onclick = function () { alert('You have already submitted a form on this page');return false; }
			if (!inputs[i].getAttribute('name'))
				inputs[i].setAttribute('disabled', 'disabled');
		}
	}
	return true;
}
