/*
Util.js - For general javascript functions that are non implementation specific
*/
// New Strict regex to impove data quanlity .. dedmondson-09/2007
// Updated 11/2008 by Lewis Keen - handles postcodes such as W1G 6LA
var REGEXP_POSTCODE = new RegExp('^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$');
var REGEXP_EMAIL = new RegExp('^[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$');

//Arrays of required fields on different pages, required in order to remove the error messages
var registrationFields = new Array("email1", "emailAddressVerify", "logonPassword", "logonPasswordVerify", "firstName", "lastName", "phone1", "address1", "adpostTown", "adcounty", "zipCode");
var checkoutRegister1Fields = new Array("email1", "emailAddressVerify", "logonPassword", "logonPasswordVerify");
var checkoutRegister2Fields = new Array("firstName", "lastName", "phone1", "address1", "adpostTown", "adcounty", "zipCode");
var sendWishListFields = new Array("sender_name", "recipient_name", "sender", "recipient");
var registerSchoolFields = new Array("fullName2", "schoolName", "phone", "address1", "city", "state", "postcode");
var registerSchoolHelpFields = new Array("fullName1", "addInfo1", "phone");
var updateAddressFields = new Array("firstName", "lastName", "phone1", "address1", "city", "state", "zipCode");
var addAddressFields = new Array("firstName", "lastName", "phone1", "address1", "adpostTown", "adcounty", "zipCode");
var amendSchoolAddressFields = new Array("schoolName", "address1", "city", "county", "postcode");
var sendToAFriendFields = new Array("fromname", "toname", "fromemail", "toemail");
var paymentFields = new Array("policyId", "cardHolderName", "cardNumber", "cardExpiry", "cardStart", "cardIssue", "verificationNumber");

// Altered to stricter regex : dedmondson-09/2007

//Create the standard error message displayed in the top error bar
var standardErrorMessage = "All required fields have not been completed. Please ensure they are all filled in and re-submit the form.";

//Create var busy to deal with double clicking the form and error to be set when an error is found
var busy = false;
var error = false;

//Get and set methods for busy (above)
function getBusy()
{
	return busy;
}
function setBusy(isBusy)
{
	busy = isBusy;
}
//Get and set methods for error (above)
function getError()
{
	return error;
}
function setError(hasError)
{
	error = hasError;
}


function checkEmail(address) 
{
  if (!address.match(REGEXP_EMAIL)) 
  {
    return false;
  }
  return true;
}

// Altered to stricter regex : dedmondson-09/2007
function checkPostCode(pcode) 
{
  if (!pcode.toUpperCase().match(REGEXP_POSTCODE)) 
  {
    return false;
  }
  return true;
}

// 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();
	} 
} 

// Override form submit to send to allow use in an if statement"
function submitenter(evt){ 
	evt=(evt)?evt:event; 
	charCode=(evt.which)?evt.which:evt.keyCode; 
	if(charCode==13){
		return true;
	} 
} 

// 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 + "Label");
	var postCodeElement      = document.getElementById(postCodeLabelId);
	
	//Show/hide PostCode 
	if (form.country.value=="GB"){
		postCodeLabelElement.style.display ="inline"; //show element
		postCodeElement.style.display      = "inline";
		postCodeLabelElement.style.visibility = 'visible'; //show form text field
		postCodeElement.style.visibility         = 'visible'; //show form text field
		postCodeElement.value = "";
	}
	else
	{
		postCodeLabelElement.style.display ="none"; //show element
		postCodeElement.style.display      = "none";
		postCodeLabelElement.style.visibility = 'hidden'; //show form text field
		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.
		postCodeElement.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;
}

//Create the function to display on screen error messages to the user when they have filled in form fields incorrectly
function setErrorMessage(fieldName, errorMessage)
{
	//Set an error on the top error message bar (always called javascriptErrors)
	var errorBar = document.getElementById("javascriptErrors");
	errorBar.className = "errorBox";
	errorBar.innerHTML = standardErrorMessage;
	
	//Get all the relevant fields to highlight, these will show where the error has occurred
	var label = document.getElementById(fieldName + "Label");
	var container = document.getElementById(fieldName + "Container");
	var message = document.getElementById(fieldName + "ErrorMessage");
	if(document.getElementById(fieldName + "ErrorImage") != null)
	{
		var image = document.getElementById(fieldName + "ErrorImage");
	}
	
	//Set the error class to the fields
	label.className = "errorChange";
	container.className = "errorChange";
	message.className = "errorMessage";
	if(document.getElementById(fieldName + "ErrorImage") != null)
	{
		image.className = "showErrorImage";
	}
	//Add the message to the messages div
	message.innerHTML = errorMessage;
}

//Create function to remove all error messages when the form is submitted, this will loop through the available form fields
function removeErrorMessages(pageName)
{
	setError(false);
	var fields;
	standardErrorMessage = "All required fields have not been completed. Please ensure they are all filled in and re-submit the form.";
	
	//Remove the commerce error messages if they exist
	var commerceErrorBar = document.getElementById("commerceErrors");
	if (commerceErrorBar != null)
	{
		commerceErrorBar.className = "hide";
	}
	
	//remove the top error message bar (always called javascriptErrors)
	var errorBar = document.getElementById("javascriptErrors");
	errorBar.className = "hide";
	errorBar.innerHTML = "";
	
	//Find the array to work with, this specifies the required fields for that page, arrays are defined at the top of this js file
	switch (pageName)
	{
		case "register":
			fields = registrationFields;
			break;
		case "checkoutRegister1":
			fields = checkoutRegister1Fields;
			break;
		case "checkoutRegister2":
			fields = checkoutRegister2Fields;
			break;
		case "sendWishList":
			fields = sendWishListFields;
			break;
		case "registerSchool":
			fields = registerSchoolFields;
			break;
		case "registerSchoolHelp":
			fields = registerSchoolHelpFields;
			break;
		case "updateAddress":
			fields = updateAddressFields;
			break;
		case "addAddress":
			fields = addAddressFields;
			break;	
		case "amendSchoolAddress":
			fields = amendSchoolAddressFields;
			break;
		case "sendToFriend":
			fields = sendToAFriendFields;
			break;
		case "payment":
			fields = paymentFields;
			break;
	}
	for (x = 0; x < fields.length; x++)
	{
		//Get all the relevant fields to remove errors from
		var label = document.getElementById(fields[x] + "Label");
		var container = document.getElementById(fields[x] + "Container");
		var message = document.getElementById(fields[x] + "ErrorMessage");
		if(document.getElementById(fields[x] + "ErrorImage") != null)
		{
			var image = document.getElementById(fields[x] + "ErrorImage");
		}
		
		//Change classes to hide and remove the error text
		label.className = "";
		container.className = "";
		message.className = "hide";
		if(document.getElementById(fields[x] + "ErrorImage") != null)
		{
			image.className = "hide";
		}
		//Add the message to the messages div
		message.innerHTML = "";
	} 
}

//Create function to remove single error messages when the form is submitted
function removeSingleErrorMessage(fieldName)
{
	setError(false);
	standardErrorMessage = "All required fields have not been completed. Please ensure they are all filled in and re-submit the form.";
	
	//Remove the commerce error messages if they exist
	var commerceErrorBar = document.getElementById("commerceErrors");
	if (commerceErrorBar != null)
	{
		commerceErrorBar.className = "hide";
	}
	
	//remove the top error message bar (always called javascriptErrors)
	var errorBar = document.getElementById("javascriptErrors");
	errorBar.className = "hide";
	errorBar.innerHTML = "";
	
	//Get all the relevant fields to remove errors from
	var label = document.getElementById(fieldName + "Label");
	var container = document.getElementById(fieldName + "Container");
	var message = document.getElementById(fieldName + "ErrorMessage");
	if(document.getElementById(fieldName + "ErrorImage") != null)
	{
		var image = document.getElementById(fieldName + "ErrorImage");
	}
		
	//Change classes to hide and remove the error text
	label.className = "";
	container.className = "";
	message.className = "hide";
	if(document.getElementById(fieldName + "ErrorImage") != null)
	{
		image.className = "hide";
	}
	//Add the message to the messages div
	message.innerHTML = "";
}

function setStandardErrorMessage(message)
{
	moveToTop();
	standardErrorMessage = message;
	//Set an error on the top error message bar (always called javascriptErrors)
	var errorBar = document.getElementById("javascriptErrors");
	errorBar.className = "errorBox";
	errorBar.innerHTML = standardErrorMessage;
}

function removeErrorBar()
{
	setError(false);
	standardErrorMessage = "All required fields have not been completed. Please ensure they are all filled in and re-submit the form.";
	
	//Remove the commerce error messages if they exist
	var commerceErrorBar = document.getElementById("commerceErrors");
	if (commerceErrorBar != null)
	{
		commerceErrorBar.className = "hide";
	}
	
	//remove the top error message bar (always called javascriptErrors)
	var errorBar = document.getElementById("javascriptErrors");
	errorBar.className = "hide";
	errorBar.innerHTML = "";
}

//Taken from TBP to calculate the characters remaining in a text box when submitting an error or sending wishlist
function calculateCharactersLeft(textAreaId,messageFieldId,characterLimit)
{
	var textAreaInput = document.getElementById(textAreaId);
	var charactersLeft = document.getElementById(messageFieldId);
	if(textAreaInput != null && charactersLeft != null)
	{
		if(textAreaInput.value.length > characterLimit)
		{
			textAreaInput.value = textAreaInput.value.slice(0,characterLimit);
		}
		if (characterLimit - textAreaInput.value.length == 1000)
		{
			charactersLeft.innerHTML = "(1,000 characters remaining)";
		}
		else
		{
			charactersLeft.innerHTML = "(" + (characterLimit - textAreaInput.value.length) + " characters remaining)";
		}
	}
}

//Code to show or hide the order information on the order history page
function showHideOrderDetails(orderNo)
{
	//Possible images
	var showImage = "/siteimages/PUFFIN/buttons/showdetails-small.gif";
	var hideImage = "/siteimages/PUFFIN/buttons/hidedetails-small.gif";
	
	//Get div to show or hide and the images to change
	var divToShow = document.getElementById("orderInformation" + orderNo);
	var showHideImage1 = document.getElementById("showHideImage" + orderNo);
	
	//Check whether the extra information div is currently showing or hidden
	if (divToShow.className == "hide")
	{
		divToShow.className = "show";
		//Change the image displayed to the user
		showHideImage1.src = hideImage;
	}
	else
	{
		divToShow.className = "hide";
		//Change the image displayed to the user
		showHideImage1.src = showImage;
	}
}
function showInNewWindow(contentPageURL,width,height)
{
	window.open (contentPageURL,'name','width='+width+',height='+height+',resizable=no,scrollbars=yes');
}

function changeNumResults(select, categoryUrl)
{
	var index = select.selectedIndex;
	var numToShow = select.options[ index ].value;
	window.location = categoryUrl + "&numResults=" + numToShow;
}
function changePageNumber(select, categoryUrl)
{
	var pageNum = select.value;
	window.location = categoryUrl + "&pageNum=" + pageNum;
}
function showHideTitles(itemId)
{
	var title = document.getElementById("setTitle" + itemId);
	var items = document.getElementById("setItems" + itemId);
	if (items.className == 'show')
	{
		items.className = "hide";
		title.innerHTML = "show titles";
	}
	else
	{
		items.className = "show";
		title.innerHTML = "hide titles";
	}
}
function showHideMailingPrefs(form)
{
	var saveButton = document.getElementById("submitMailingPrefs");
	var mailPrefsText = document.getElementById("mailOptions");
	var message	= document.getElementById("message");
	var image = document.getElementById("subscribeImage");
	var subscribedText = document.getElementById("subscribed");
		
	if (saveButton.className == "hide")
	{
		saveButton.className = "show";
		message.className 	 = "show";
		mailPrefsText.className = "";
		image.src = "/siteimages/PUFFIN/buttons/unsubscribe.gif";
		//Update the text to say subscribed
		subscribedText.className  = "subscribed";
		subscribedText.innerHTML = "You are currently receiving newsletters";
		
		//Change the checkboxes to be enabled
		form.threePlus.disabled = false;
		form.sevenPlus.disabled = false;
		form.ninePlus.disabled = false;
	}
	else
	{
		saveButton.className = "hide";
		message.className 	 = "hide";
		mailPrefsText.className = "faded";
		image.src = "/siteimages/PUFFIN/buttons/subscribe.gif";
		//Change the textboxes to be disabled
		form.threePlus.disabled = true;
		form.sevenPlus.disabled = true;
		form.ninePlus.disabled = true;
		//Uncheck the text boxes
		form.threePlus.checked = false;
		form.sevenPlus.checked = false;
		form.ninePlus.checked = false;
		
		prepareSubmitMailPreferencesUpdate(form);
	}
}
//Function to change the mailing preferences update screen to allow the user to change their preferences
function editMailingPreferences(form)
{
	//If clicked, change image to save image, hide tick and cross images and show checkboxes.
	document.getElementById("editButton").className = "hide";
	document.getElementById("saveChangesButton").className = "";
	//Remove images
	document.getElementById("threePlusImage").className = "hide";
	document.getElementById("sevenPlusImage").className = "hide";
	document.getElementById("ninePlusImage").className = "hide";
	//Show check boxes
	form.threePlus.className = "checkbox";
	form.sevenPlus.className = "checkbox";
	form.ninePlus.className = "checkbox";
}

function showHideLookInside()
{
	var title = document.getElementById("lookInsideTitle");
	var content = document.getElementById("lookInsideContent");
	
	if (title.className == "show")
	{
		//Title must be shown and the content is not. Change to show content
		title.className = "hide";
		content.className = "show";
	}
	else
	{
		//Content must be showing, change the display to show only the title
		title.className = "show";
		content.className = "hide";
	}
}
function checkNumber(input)
{
	var filter=/^[0-9\s]+$/;

	if(input != null && input.value != "")
	{
		if (!filter.test(input.value)) 
		{
			//setErrorMsg("* " + errorMessage + " must only contain numbers");
			setStandardErrorMessage("Quantity must be a positive number");
			input.focus();
			setError(true);
		}
	}
}
function checkBusyAndSubmit(url)
{
	if (!getBusy())
	{
		window.location = url;
	}
}
function moveToTop()
{
	var url = "" + window.location;
	if (url.indexOf("#") == -1)
	{
		window.location = url + "#";
	}
	else
	{
		url.substring(0, url.length - 2);
		window.location = url;
	}
}