var spanTextBoxCityHtml = document.getElementById("spanTextBoxCity").innerHTML;
var spanComboBoxCityHtml = document.getElementById("spanComboBoxCity").innerHTML;
document.getElementById("spanComboBoxCity").innerHTML = "";

function submitForm()
{
	var objForm = document.getElementById("buyStarfForm");
	if (validator(objForm))
	{
		// set the hidden fields
		document.getElementById("postalAddress").value = objForm.address.value;
		document.getElementById("postalSuburb").value = objForm.addressSuburb.value;
		document.getElementById("phone_area_code").value = objForm.contact[0].value;
		document.getElementById("phone").value = objForm.contact[1].value;
		document.getElementById("buyStarfForm").submit();
	}
	else
	{
		var sLoc = window.location.toString().replace("#start", "");
		window.location = sLoc + "#start";
	}
}

function validator(objForm)
{
	var ele = objForm.elements;
	var objValidation = document.getElementById("divValidation");
	objValidation.innerHTML = "";
	var bValidationFailed = 0;
	var sIncompleteMessage = "<span class=\"validationFailedSmall\">field incomplete &gt;&gt;</span>";
	for (var i=0; i<ele.length; i++)
	{
		if (ele[i].type == 'text' || ele[i].type == 'select-one' || ele[i].type == 'password')
		{
			if (ele[i].value == '' && ele[i].style.display != 'none')
			{
				var objLabel = document.getElementById(ele[i].name);
				if (objLabel.innerHTML.indexOf(sIncompleteMessage) == -1)
					objLabel.innerHTML += sIncompleteMessage;
				bValidationFailed = 1;
			}
		}
	}
	// validate user name
	var sUserNameMessage = validateUserName(objForm.user_name);
	if (sUserNameMessage != "")
	{
		bValidationFailed = 1;
		objValidation.innerHTML += sUserNameMessage + "<BR><BR>";
	}
	// validate email address
	if (!checkEmail(objForm.email))
	{
		bValidationFailed = 1;
		objValidation.innerHTML += "The format of your email address seems incorrect.<BR><BR>";
	}
	// now check whether the passwords match
	if (objForm.password.value != objForm.password1.value)
	{
		bValidationFailed = 1;
		objValidation.innerHTML += "The passwords you have entered do not match.<BR><BR>";
	}
	// finally check whehter they have agreed to the terms
	if (!objForm.termsAndCondition.checked)
	{
		bValidationFailed = 1;
		objValidation.innerHTML += "You have not agreed to the Terms of Use.<BR><BR>";
	}
	// display any error messages and return whehter the form was validated successfully
	if (objValidation.innerHTML != "") objValidation.style.display = '';
	return !bValidationFailed;
}

// make sure the user name's format is valid
function validateUserName(obj)
{
	var str = obj.value;
	if (str != '')
	{
		if(!(/^[a-z0-9_]{4,15}$/i).test(str))
			return "Your user name must be between 4-15 characters and must contain only alpha, numeric or underscore characters.";
	}
	return "";
}

// return the number of alpha characters in the input string
function alphaNum(str)
{
	var num = 0;
	for (var i=0; i<str.length; i++)
	{
		if (/[a-z]/i.test(str.charAt(i)))
		num++;
	}
	return num;
}

// return the number of numeric characters in the input string
function numericNum(str)
{
	var num = 0;
	for (var i=0; i<str.length; i++)
	{
		if (/[0-9]/.test(str.charAt(i)))
			num++;
	}
	return num;
}

// make sure the password is alpha-numeric (at least 2 numeric and 4 alpha) and at least 6 characters
function validatePassword(obj)
{
	var ok = 0;
	var str = obj.value;
	if (str != '')
	{
		if (/^[a-zA-Z0-9]{6,}$/.test(str))
		{
			// find out how many alpha and numeric characters exist
			if (alphaNum(str) < 4)
				ok = 0;
			else if (numericNum(str) < 2)
				ok = 0;
			else
				ok = 1;
		}
		// alert error if necessary
		if (!ok)
		{
			alert('The password must contain at least 6 but not greater than 15 characters.  There must be at least 4 alpha and 2 numeric characters.\n\nE.g. abcd12');
			obj.value = '';
			obj.focus();
		}
	}
}

function findPostalCode()
{
	var objResidence = document.getElementById('form_residence');
	if (objResidence.value == '')
	{
		alert("Please select the Location first.");
		return;
	}
	else
	{
		var sText = objResidence[objResidence.selectedIndex].text.replace(" ", "+");
		window.open('http://www.google.com/search?q=' + sText + '+Postal+Code&btnI=3564','','scrollbars=yes, resizable=yes, top=0, left=0, width=630, height=530');
	}
}

function locationOnChange(obj)
{
	if (obj.value != "")
	{
		document.getElementById("country").value = obj.options[obj.selectedIndex].text;
		document.getElementById("phone_country_code").value = countryCode[obj.value];
		document.getElementById("mobile_country_code").value = countryCode[obj.value];
		var objTextboxSpan = document.getElementById("spanTextBoxCity");
		var objComboboxSpan = document.getElementById("spanComboBoxCity");
		if (obj.value == "4")
		{
			objTextboxSpan.innerHTML = "";
			objComboboxSpan.innerHTML = spanComboBoxCityHtml;
		}
		else
		{
			objTextboxSpan.innerHTML = spanTextBoxCityHtml;
			objComboboxSpan.innerHTML = "";
		}
	}
}

function loadSpecialCode()
{
	var sSpecialCode = getCookie("specialCode");
	if (sSpecialCode != null)
	{
		document.getElementById("specialCode").value = sSpecialCode;
		if (sSpecialCode == 'C59C90F7-B6F3-461A-AE26-0874281C7E03')
		{
			var objRight = document.getElementById('signup-right');
			objRight.innerHTML = objRight.innerHTML.replace('99.00', '9.00');
		}
	}
}

function loadSource()
{
	var sSource = getCookie("resellerId");
	if (sSource != null)
	{
		//if (sSource == 'F18B9360-98B6-4419-81D0-669E19CC2AFF')
		//{
		//	var objEmail = document.getElementById('ContactEmail');
		//	objEmail.href = 'mailto:carolep@wt.co.nz';
		//	objEmail.innerHTML = 'carolep@wt.co.nz';
		//}
		document.getElementById('src').value = sSource;
		document.getElementById('form_source').style.display = 'none';
		document.getElementById('form_source').parentNode.parentNode.style.display = 'none';
	}
	else
	{
		//document.getElementById('IntroOffer').style.display = 'none';
	}
}

// onload
var queryString = getQueryString();
var sErrorMsg = findQueryString(queryString, "errorMsg");
if (sErrorMsg != null)
{
	var objValidation = document.getElementById("divValidation");
	objValidation.innerHTML = sErrorMsg + "<BR><BR>";
	objValidation.style.display = '';
	
	// populate the form
	var objForm = document.getElementById("buyStarfForm");
	var objEle = objForm.elements;
	var bUpdateStates = false;
	for (var iLoop = 0; iLoop < objEle.length; iLoop++)
	{
		var sValue = findQueryString(queryString, objEle[iLoop].name);
		if (sValue != null)
		{
			if (objEle[iLoop].type == 'text')
			{
				objEle[iLoop].value = sValue;
			}
			else if (objEle[iLoop].type == 'select-one')
			{
				var objOptions = objEle[iLoop].options;
				for (var jLoop = 0; jLoop < objOptions.length; jLoop++)
				{
					if (objOptions[jLoop].value == sValue)
					{
						objEle[iLoop].selectedIndex = jLoop;
						// check if the select-one object is one that has an onchange event
						if (objEle[iLoop].name == 'residence')
						{
							locationOnChange(objEle[iLoop]);
							bUpdateStates = true;
						}
						break;
					}
				}
			}
		}
	}
	
	// double check the states field as the onchange event changes the HTML
	if (bUpdateStates)
	{
		var objStates = document.getElementById('form_city');
		if (objStates.type == 'select-one')
		{
			for (var iLoop = 0; iLoop < objStates.options.length; iLoop++)
			{
				if (objStates.options[iLoop].value == findQueryString(queryString, "city"))
				{
					objStates.selectedIndex = iLoop;
					break;
				}
			}
		}
	}
	
	// phone number needs special logic
	var sPhoneArea = findQueryString(queryString, "phone_area_code");
	var sPhone = findQueryString(queryString, "phone");
	document.getElementById('form_phone_area_code').value = (sPhoneArea == null) ? "" : sPhoneArea;
	document.getElementById('form_phone').value = (sPhone == null) ? "" : sPhone;
	
	// lastly, turn agree to TOB on and add the special code if it exists
	document.getElementById('form_termsAndCondition').checked = true;
}
else
{
	var objLocation = document.getElementById('form_residence');
	objLocation.selectedIndex = 1;
	locationOnChange(objLocation);
}
loadSpecialCode();
loadSource();
