/*
Util.js - For general javascript functions that are non implementation specific
*/
var errors = 0;
var registrationFormFields = new Array("email1Text", "emailAddressVerifyText", "logonPasswordText", "logonPasswordVerifyText", "firstNameText", "lastNameText", "phone1Text", "phone2Text", "address1Text", "address2Text", "address3Text", "cityText", "stateText", "countryText", "zipCodeText", "otherSpecifyText");
var addressFormFields = new Array("nickNameLabel", "firstNameLabel", "lastNameLabel", "phone1Label", "zipCodeText", "address1Label", "cityLabel", "countyLabel", "countryLabel");
var paymentFormFields = new Array("policyIdText", "cardHolderNameText", "accountText", "expiryDateText", "startDateText", "cardIssueText", "verificationNumberText");
var contactFormFields = new Array("nameText", "emailText", "dayPhoneText", "notesText");
var wishlistFormFields = new Array("sender_nameText", "recipient_nameText", "sender_emailText", "recipient_emailText", "wishlist_messageText");
var loginFormFields = new Array("logonIdText", "logonPasswordText");
var onPage = "";
var boxError = false;
var noPostCode = false;
var countryValue = "";
var busy = false;

// check an email address
function validateEmails(address1, address2, address1TextField) 
{
	if (address1.value != address2.value)
	{
		setErrorMsg("* Your 'confirmed' email address and email address do not match up");
		document.getElementById(address1TextField).style.color = "#cc0000";
		focusOnInput(address1);
	}
	else
	{
		if (!checkEmail(address1.value))
		{
			setErrorMsg("* Please enter a vaild email address e.g yourname@hotmail.com");
			document.getElementById(address1TextField).style.color = "#cc0000";
			focusOnInput(address1);
		}
	}
}
function checkEmail(address) 
{
	var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
	if (!filter.test(address)) 
	{
		return false;
	}
	else
	{
		errors = 0;
		return true;
	}
}

function checkPassword(passwordFormField, passwordVerifyFormField)
{
	var returnVar = true;
	var password = passwordFormField.value;
	var passwordVerify = passwordVerifyFormField.value;
	if (password != passwordVerify)
	{
		setErrorMsg("* Your passwords don't match");
		document.getElementById("logonPasswordText").style.color = "#cc0000";
		focusOnInput(passwordFormField);
	}
	else
	{
		if (password.length < 6) 
		{
			setErrorMsg("* Please ensure your password includes at least six characters and one number");
			document.getElementById("logonPasswordText").style.color = "#cc0000";
			focusOnInput(passwordFormField);
		}
		else
		{
			if (password.search(/[0-9]/) == -1)
			{
				setErrorMsg("* Please ensure your password includes at least six characters and one number");
				document.getElementById("logonPasswordText").style.color = "#cc0000";
				focusOnInput(passwordFormField);
			}
			else
			{
				errors = 0;
			}
		}
	}	 
}

function checkString(input, errorField, errorMessage, check)
{
	if (getErrors())
	{
		if(input != null && input.value != "")
		{
			if (check)
			{
				var filter=/^[a-zA-Z\-\s]+$/;
				if (!filter.test(input.value)) 
				{
					setErrorMsg("* " + errorMessage + " must only contain letters<br /><br />");
					document.getElementById(errorField).style.color = "#cc0000";
					focusOnInput(input);
				}
				else
				{
					errors = 0;
				}
			}
		}
		else
		{
			if (errorField == "address1Text")
			{
				setErrorMsg("* Please enter the " + errorMessage + "<br /><br />");
			}
			else
			{
				setErrorMsg("* Please enter your " + errorMessage + "<br /><br />");
			}
			document.getElementById(errorField).style.color = "#cc0000";
			focusOnInput(input);
		}
	}
}
function checkCounty(form)
{
	if( form.state == null || form.state.value == "" )
	{
		//put 'NONE' in for this as the user has not specified a county
		form.state.value = "NONE";
	}
}
function checkAlphanumeric(input, errorField, errorMessage)
{
	if(getErrors())
	{
		if(input != null && input.value != "")
		{
			//Check for address nickname as this is generally an email address and will require an @ sign
			if (errorMessage == "Address title")
			{
				var filter = /^[A-Za-z0-9-\s@.]+$/;
			}
			else
			{
				var filter = /^[A-Za-z0-9-\s.,]+$/;
			}
			if (!filter.test(input.value)) 
			{
				if (errorMessage == "Address title")
				{
					setErrorMsg("* " + errorMessage + " must only contain alphanumeric characters or @.");
				}
				else
				{
					setErrorMsg("* " + errorMessage + " must only contain alphanumeric characters or ,.-");
				}
				document.getElementById(errorField).style.color = "#cc0000";
				focusOnInput(input);
			}
			else
			{
				errors = 0;
			}
		}
		else
		{
			if (errorField == "address1Text")
			{
				setErrorMsg("* Please enter the " + errorMessage + "<br /><br />");
			}
			else
			{
				setErrorMsg("* Please enter your " + errorMessage + "<br /><br />");
			}
			document.getElementById(errorField).style.color = "#cc0000";
			focusOnInput(input);
		}
	}
}

function checkNumber(input, errorField, errorMessage)
{
	var filter=/^[0-9\s]+$/;
	if (getErrors())
	{
		if((input != null && input.value != "" && input.value.length > 9))
		{
			if (input.value.length > 20)
			{
				setErrorMsg("* " + errorMessage + " must be 20 characters or less");
				document.getElementById(errorField).style.color = "#cc0000";
				focusOnInput(input);
			}
			else
			{
				if (!filter.test(input.value)) 
				{
					setErrorMsg("* " + errorMessage + " must only contain numbers");
					document.getElementById(errorField).style.color = "#cc0000";
					focusOnInput(input);
				}
				else
				{
					errors = 0;
				}
			}
		}
		else
		{
			if (input.value == "")
			{
				setErrorMsg("* Please enter your " + errorMessage + "<br /><br />");
				document.getElementById(errorField).style.color = "#cc0000";
				focusOnInput(input);
			}
			else
			{
				if (!filter.test(input.value)) 
				{
					setErrorMsg("* " + errorMessage + " must only contain numbers");
					document.getElementById(errorField).style.color = "#cc0000";
					focusOnInput(input);
				}
				else
				{
					setErrorMsg("* Please enter your " + errorMessage + "<br /><br />");
					document.getElementById(errorField).style.color = "#cc0000";
					focusOnInput(input);
				}
			}
		}
	}
}

// check a UK postcode
function checkPostCode(input, errorField, errorMessage) {
	if (getErrors())
	{
		if (noPostCode)
		{
			input.value = countryValue;
		}
		else
		{
			var filter= /^([a-zA-Z]{1,2}[0-9][a-zA-Z]|[a-zA-Z]{1,2}[0-9]{1,2})\s?[0-9][a-zA-Z]{2}$/;
			if (input == null || input.value == "")
			{
				setErrorMsg("* Please enter your " + errorMessage + "<br /><br />");
				document.getElementById(errorField).style.color = "#cc0000";
				focusOnInput(input);
			}
			else
			{
				if (!filter.test(input.value))
				{
					setErrorMsg("* " + errorMessage + " must be in the correct format i.e. A12 3BC or AB24 3CD");
					document.getElementById(errorField).style.color = "#cc0000";
					focusOnInput(input);
				}
			}
		}
	}
}

// Submit a form on pressing "enter"
function submitenter(myfield,evt){ 
	evt=(evt)?evt:event; 
	charCode=(evt.which)?evt.which:evt.keyCode; 
	if(charCode==13){
		myfield.form.submit();
	} 
}

function focusOnInput(inputBox)
{
	inputBox.focus();
	inputBox.select();
}

function removeErrorMsg()
{
	if (document.getElementById("errors") != null)
	{
		document.getElementById("errors").style.visibility = "hidden";
		document.getElementById("errors").style.display = "none";
	}
	if (document.getElementById("error") != null)
	{
		document.getElementById("error").style.visibility = "hidden";
		document.getElementById("error").style.display = "none";
	}
}

function setErrorMsg(messageText)
{
	var message;
	if (boxError)
	{
		message = 	"<div class='errorBox'>\n" +
					"<h2>There has been an error</h2>\n" +
					"<p>Please check that you have filled out all fields marked *</p>\n" +
					"<br />\n" +
					"<li>" +
					messageText +
					"</li>" +
					"</div>";
	}
	else
	{
		message = messageText;
		document.getElementById("errors").style.color = "#cc0000";
	}
	if (document.getElementById("error") != null)
	{
		document.getElementById("error").style.visibility = "hidden";
		document.getElementById("error").style.display = "none";
		document.getElementById("errors").style.marginTop = "-20px";
	}
	document.getElementById("errors").innerHTML = message;
	errors = 1;
	moveToTop();
}

function setErrors()
{
	errors = 1;
}

function getErrors()
{
	if (errors == 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function resetErrorsSimple()
{
	errors = 0
}

function getBusy()
{
	return !busy;
}

function setBusy(isBusy)
{
	busy = isBusy;
}

function resetErrors(page)
{
	var fields;
	onPage = page;
	switch (page)
	{
		case "reg":
			fields = registrationFormFields;
			setBoxError(true);
			break;
		case "address":
			fields = addressFormFields;
			setBoxError(true);
			break;
		case "checkout":
			fields = paymentFormFields;
			setBoxError(true);
			break;
		case "contact":
			fields = contactFormFields;
			setBoxError(true);
			break;
		case "wishlist":
			fields = wishlistFormFields;
			setBoxError(true);
			break;
		case "login":
			fields = loginFormFields;
			setBoxError(true);
			break;
	}

	errors = 0;
	for (x = 0; x < fields.length; x++)
	{
		document.getElementById(fields[x]).style.color = "black";
	}
}

function setBoxError(boolVal)
{
	boxError = boolVal;
}

function getBoxError()
{
	return boxError;
}

function displayContents(page)
{
	var fields;
	var message = "";
	if (page == "reg")
	{
		fields = registrationFormFields;
	}
	else
	{
		if(page == "address")
		{
			fields = addressFormFields;
		}
	}
	for (x = 0; x < fields.length; x++)
	{
		//adjust the field value to remove the word Text off the end
		var subString = fields[x].substring(0, fields[x].length - 4);
		if (subString != "phone2" && subString != "address2" && subString != "address3" && subString != "country")
		{
			var fieldValue = document.getElementById(subString).value;
			message = message + fields[x] + " value is " + fieldValue + "\n";
		}
	}
	alert(message);
}

// Show the post code lookup section and the post code form input control if GB, otherwise don't
 
function showAndHidePostCodeAndLookup(form,postCodeSectionId,postCodeLabelId,inputField){
	var postCodeSectionElement = document.getElementById(postCodeSectionId); 
	var postCodeLabelElement = document.getElementById(postCodeLabelId);
	
	//First show/hide PostCode Lookup section
	if (form.country.value ==	"GB"){
		postCodeSectionElement.style.display="block"; //show element
	}
	else{
		postCodeSectionElement.style.display="none"; //hide element
	}

	//Next show/hide PostCode 
	if (form.country.value=="GB"){
		postCodeLabelElement.style.display="inline"; //show element
		inputField.style.visibility = 'visible'; //show form text field
		inputField.value = "";
	}
	else {
		postCodeLabelElement.style.display="none"; //hide element
		inputField.style.visibility = "hidden"; //hide form text field
		//If country is not GB, make the postcode field equal to the country name. This is because Maginus doesn't have a field for country name so we use postcode.
		inputField.value = form.country.options[form.country.selectedIndex].text;
	}
}

// Hide the post code lookup section
function hidePostCodeLookup(postCodeSectionId)
{
	var postCodeSectionElement = document.getElementById(postCodeSectionId);
	postCodeSectionElement.style.display="none";			
	
}

// Show the post code form input control if GB, otherwise don't
function showAndHidePostCode(form,postCodeLabelId,inputField){
	var postCodeLabelElement = document.getElementById(postCodeLabelId);
	var postCodeFind 		 = document.getElementById("btnFind");
	var postCodeElement      = inputField;
	
	//Show/hide PostCode 
	if (form.country.value=="EN" || form.country.value=="WA" || form.country.value=="EO" || form.country.value=="NN")
	{
		noPostCode = false;
		postCodeLabelElement.style.display = "inline"; //show element
		postCodeFind.style.display = "inline";
		postCodeElement.style.display      = "inline";
		postCodeLabelElement.style.visibility = 'visible'; //show form text field
		postCodeFind.style.visibility = "visible";
		postCodeElement.style.visibility         = 'visible'; //show form text field
		inputField.value = "";
	}
	else
	{
		noPostCode = true;
		countryValue = form.country.value;
		postCodeLabelElement.style.display = "none"; //show element
		postCodeFind.style.display		   = "none";
		postCodeElement.style.display      = "none";
		postCodeLabelElement.style.visibility = 'hidden'; //show form text field
		postCodeFind.style.visiblity = "hidden";
		postCodeElement.style.visibility         = 'hidden'; //show form text field
		//If country is not GB, make the postcode field equal to the country name. This is because Maginus doesn't have a field for country name so we use postcode.
		//form.zipCode.value = form.country.options[form.country.selectedIndex].text;
	}
}


//////////////////////////////////////////////////////////
// Checks whether a string contains a double byte character
// target = the string to be checked
//
// Return true if target contains a double byte char; false otherwise
//////////////////////////////////////////////////////////
function containsDoubleByte (target) {
     var str = new String(target);
     var oneByteMax = 0x007F;

     for (var i=0; i < str.length; i++){
        chr = str.charCodeAt(i);
        if (chr > oneByteMax) {return true;}
     }
     return false;
}

//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string
// arg2 = the maximum number of bytes allowed in your input field
// Return false is this input string is larger then arg2
// Otherwise return true...
//////////////////////////////////////////////////////////
function isValidUTF8length(UTF16String, maxlength) {
    if (utf8StringByteLength(UTF16String) > maxlength) return false;
    else return true;
}

//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string you want a byte count of...
// Return the integer number of bytes represented in a UTF-8 string
//////////////////////////////////////////////////////////
function utf8StringByteLength(UTF16String) {
  if (UTF16String === null) return 0;
  var str = String(UTF16String);
  var oneByteMax = 0x007F;
  var twoByteMax = 0x07FF;
  var byteSize = str.length;

  for (i = 0; i < str.length; i++) {
    chr = str.charCodeAt(i);
    if (chr > oneByteMax) byteSize = byteSize + 1;
    if (chr > twoByteMax) byteSize = byteSize + 1;
  }  
  return byteSize;
}

