// repeated in clientBundle and also ecom bundles
var globalReviewErrorMsg="Please review the error(s) below";
var matchingPasswordMsg="The new password and the retyped new password must be the same. This is to ensure the new password was typed correctly.";
var matchingFieldMessage="You must enter the same value in both fields.";
var validEmailMsg="You must enter a valid email address.";
var validPasswordMsg="The new password must be at least 6 characters long and contain both numbers and letters. It must not contain any spaces.";
var valueRequiredMsg="This field is required - you must enter a value.";
var eitherStartDateOrIssueMsg="Start/valid from date or issue number are required"
var fieldIncompleteMsg="This field has not been completely set "

function limitText(limitField, limitCount, limitNum) {
	if(limitField!=null && limitCount!=null && limitNum!=null)
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

function navigateToAnchor(){
   var anchor = document.getElementById("anchor");
   if (anchor != null) {
      if (anchor.value != ""){
         location.hash = anchor.value;
      }
   }
}

// this function runs onLoad from the login page to switch on the normal submit button 
// if JS is NOT available to us. If it is NOT available the submit button enclosed in the
// NOSCRIPT tags is used instead. 
function checkSubmitButton () {
	setJSCookie();
	var btnCreateAcctFake = document.getElementById("newAccountForm:btnCreateAccountFake");
	if (btnCreateAcctFake != null) {
		btnCreateAcctFake.style.display="inline";
		btnCreateAcctFake.style.visibility="visible";
		btnCreateAcctFake.disabled=false;
	}

	var btnChangeDetailsFake = document.getElementById("changeDetails:btnChangeDetailsFake");
	if (btnChangeDetailsFake != null) {
		btnChangeDetailsFake.style.display="inline";
		btnChangeDetailsFake.style.visibility="visible";
		btnChangeDetailsFake.disabled=false;
	}

}

// this function runs onLoad from the checkout page to switch on the normal submit button 
// if JS IS available to us. If it is NOT available the submit button enclosed in the
// NOSCRIPT tags is used instead. 
function checkPlaceOrderButton () {
	var btnPlaceOrderFake = document.getElementById("paymentMethod:btnPlaceOrderFake");
	if (btnPlaceOrderFake != null) {
		btnPlaceOrderFake.style.display="inline";
		btnPlaceOrderFake.style.visibility="visible";
		btnPlaceOrderFake.disabled=false;
	}
}

//this function runs onLoad from the changePassword page to switch on the normal submit button 
// if JS IS available to us. If it is NOT available the submit button enclosed in the
//NOSCRIPT tags is used instead. 
function checkChangePasswordButton () {
	setJSCookie();
	var btnChangePasswordFake = document.getElementById("changePasswordForm:btnChangePasswordFake");
	if (btnChangePasswordFake != null) {
		btnChangePasswordFake.style.display="inline";
		btnChangePasswordFake.style.visibility="visible";
		btnChangePasswordFake.disabled=false;
	}
	var btnForceChangePasswordFake = document.getElementById("changePasswordForm:btnForceChangePasswordFake");
	if (btnForceChangePasswordFake != null) {
		btnForceChangePasswordFake.style.display="inline";
		btnForceChangePasswordFake.style.visibility="visible";
		btnForceChangePasswordFake.disabled=false;
	}

}

function setGlobalMessage(formName, message) {
	
	var messageDivName=(formName==null? '' : formName+ ":") + "prolog_messageBlock:js_message_block";
	var objForm= document.getElementById(formName);
	var jsMsgBlock = document.getElementById (messageDivName);
	if (jsMsgBlock==null) {
		return;
	}
	// h2 header
	var heading1=document.createElement("h2");
	var heading1Text=document.createTextNode("Messages");
	heading1.appendChild (heading1Text);
	jsMsgBlock.appendChild (heading1);

	// message div
	var messageDiv1=document.createElement("div");
	messageDiv1.id=messageDivName+ ":prolog_local_messages";
	messageDiv1.style.marginBottom="15px";

	// message div content
	var span1=document.createElement("span");
	span1.setAttribute("id", messageDiv1.id + "_span" );
	span1.setAttribute ("class", "prolog_message_error");      // for firefox
	span1.setAttribute ("className", "prolog_message_error");  // for ie
	var message1=document.createTextNode(message);
	span1.appendChild (message1);
	
	messageDiv1.appendChild (span1);

	var br1=document.createElement("br");
	messageDiv1.appendChild (br1);
	
	jsMsgBlock.appendChild (messageDiv1);
}

//this function duplicates the server based functionality when javascript is available.
function checkBeforeChangePassword () {
	var changePasswordFormName="changePasswordForm";
	if (validatePasswordForm(changePasswordFormName)) {
		// no fails, so try submit.
		var submitButton = document.getElementById(changePasswordFormName+ ':btnChangePassword');
		var submitButtonForce = document.getElementById(changePasswordFormName+ ':btnForceChangePassword');
		
		// if (we're in force mode), click that otherwise use normal click
		if (submitButtonForce != null) {
			submitButtonForce.click();
		} else {
			submitButton.click();
		}
	} else {
		setGlobalMessage (changePasswordFormName, globalReviewErrorMsg);
	}

}	
//this function duplicates the server based functionality when javascript is available.
function checkBeforePlaceOrder () {
	var paymentMethodFormName="paymentMethod";
	if (validatePaymentMethodForm(paymentMethodFormName)) {
		// no fails, so try submit.
		var submitButton = document.getElementById(paymentMethodFormName+ ':btnPlaceOrder');
		submitButton.click();
	} else {
		// the message block is not within a form. 
		setGlobalMessage (null, globalReviewErrorMsg);
	}
}

// this function duplicates the server based functionality when javascript is available.
function checkBeforeChangeDetails () {
	var changeDetailsFormName="changeDetails";
	if (validatePasswordForm(changeDetailsFormName)) {
		// no fails, so try submit.
		var submitButton = document.getElementById(changeDetailsFormName+ ':btnChangeDetails');
		submitButton.click();
	} else {
		setGlobalMessage (changeDetailsFormName, globalReviewErrorMsg);
	}
}

// this function duplicates the server based functionality when javascript is available.
function checkBeforeCreateAccount () {
	var newAcctFormName="newAccountForm";
	if (validateDetailsForm(newAcctFormName)) {
		// no fails, so try submit.
		var submitButton = document.getElementById(newAcctFormName+ ':btnCreateAccount');
		submitButton.click();
	} else {
		setGlobalMessage (newAcctFormName, globalReviewErrorMsg);
	}
}

//this function duplicates the server based functionality when javascript is available.
 function validatePaymentMethodForm (formName) {
// should keep this in line with changeCardType()	
	
	var ccardNumber = document.getElementById("paymentMethod:winticard:ccardNumber");
	var scardNumber = document.getElementById("paymentMethod:winticard:scardNumber");
	var startMonthSelect = document.getElementById("paymentMethod:winticard:startMonth");	
	var startYearSelect = document.getElementById("paymentMethod:winticard:startYear");	
	var expiryMonthSelect = document.getElementById("paymentMethod:winticard:month");	
	var expiryYearSelect = document.getElementById("paymentMethod:winticard:year");	
	var issueNo = document.getElementById("paymentMethod:winticard:issueno");
	
	var typeSel = document.getElementById("paymentMethod:paymentMethods");
	if (typeSel == null){
		// if they chose no method, nothing to validate. 
		return false;
	}
	
	var bMissingMandatory=false;
	var optionValue = typeSel.options[typeSel.selectedIndex].value;
	if (optionValue == "MC" || optionValue == "VI" || optionValue == "VP"){
		// check ccard, expiry date 
		if (! checkRequired (ccardNumber, formName+":winticard", "CardNumber")) {
			bMissingMandatory=true; }
		
		if (! checkRequired (expiryMonthSelect, formName+":winticard", "ExpiryDate")) {
			bMissingMandatory=true; }

		if (! checkRequired (expiryYearSelect, formName+":winticard", "ExpiryDate")) {
			bMissingMandatory=true; }
		
		if (bMissingMandatory==true) {
			return false;
		}
		return true;
	}

	if (optionValue == "AX"){
		// check ccard, expiry and start
		if (! checkRequired (ccardNumber, formName+":winticard", "CardNumber")) {
			bMissingMandatory=true; }
		
		if (! checkRequired (expiryMonthSelect, formName+":winticard", "ExpiryDate")) {
			bMissingMandatory=true; }

		if (! checkRequired (expiryYearSelect, formName+":winticard", "ExpiryDate")) {
			bMissingMandatory=true; }
		
		if (bMissingMandatory==true) {
			return false;
		}
		return true;
	}
	
	if (optionValue == "SW"){
		// check scard, start, expiry, maestro, issue
		if (! checkRequired (scardNumber, formName+":winticard", "CardNumber")) {
			bMissingMandatory=true; }

		if (! checkRequired (expiryMonthSelect, formName+":winticard", "ExpiryDate")) {
			bMissingMandatory=true; }

		if (! checkRequired (expiryYearSelect, formName+":winticard", "ExpiryDate")) {
			bMissingMandatory=true; }

		if (bMissingMandatory==true) {
			return false;
		}
		
		// either start date, or issue MUST be set. 
		// 	do we have a complete start date?
		var bStartMonthPresent=checkRequired (startMonthSelect, formName+":winticard", null);
		var bStartYearPresent=checkRequired (startYearSelect, formName+":winticard", null);
		var bStartDateComplete=(bStartMonthPresent && bStartYearPresent);  
		var bStartDateMissing=(!bStartMonthPresent && !bStartYearPresent);  
		var bIssuePresent=checkRequired (issueNo, formName+":winticard", null);

		// start date only partially complete
		if ( !bStartDateComplete && !bStartDateMissing ) {
			// create and set required message
			startDateDiv=document.getElementById(formName+":winticard" + ":divStartDateMsg");
			clearMessageSpan (startDateDiv);
			buildMessageSpan (startDateDiv, fieldIncompleteMsg);
			return false;
		}
		
		if (! ( bIssuePresent || bStartDateComplete ) )  {
			// create and set required message
			issueNoDiv=document.getElementById(formName+":winticard" + ":divIssueNoMsg");
			clearMessageSpan (issueNoDiv);
			buildMessageSpan (issueNoDiv, eitherStartDateOrIssueMsg);
			return false;		
		}
		
		return true;
	}
	
	if (optionValue == "CR"){
		// currently no validation required.  
		if (bMissingMandatory==true) {
			return false;
		}
		return true;
	}
	
	return false;
}


//this function duplicates the server based functionality when javascript is available.
function validatePasswordForm (formName) {
	// the password fields dont current exist on the ChangePassword form.  
	var inpOriginalPassword= document.getElementById(formName + ":originalPassword");
	var inpNewPassword= document.getElementById(formName + ":passwordNew");
	var inpNewRetypePassword= document.getElementById(formName + ":newPasswordRetype");

	// sometimes the browser fills in the old password 
	
	// mandatory fields
	var bMissingMandatory=false;
	if (! checkRequired (inpOriginalPassword, formName, "OriginalPassword")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpNewPassword, formName, "PasswordNew")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpNewRetypePassword, formName, "PasswordNewRetype")) {
		bMissingMandatory=true; }

	if (bMissingMandatory==true) {
		return false;
	}

	if (! validatePassword (inpNewPassword, formName, "PasswordNew")) {
		return false;
	}
	if (! validateMatching (inpNewPassword, inpNewRetypePassword, formName, "PasswordNew", matchingPasswordMsg)) {
		return false;
	}
	
	return true;	
}


//this function duplicates the server based functionality when javascript is available.
function validateDetailsForm (formName) {
	// the password fields dont current exist on the ChangeDetails form.  
	var inpForename= document.getElementById(formName + ":forename");
	var inpSurname = document.getElementById(formName + ":surname");
	var inpAddressLine1 = document.getElementById(formName + ":addressLine1");
	var inpAddressLine2 = document.getElementById(formName + ":addressLine2");
	var inpAddressLine3 = document.getElementById(formName + ":addressLine3");
	var inpTown = document.getElementById(formName + ":town");
	var inpCounty = document.getElementById(formName + ":county");
	var inpCountry = document.getElementById(formName + ":country");
	var inpPostcode = document.getElementById(formName + ":postcode");
	var inpEmail = document.getElementById(formName + ":email");
	var inpConfirmEmail = document.getElementById(formName + ":confirmEmail");
	var inpTelephone = document.getElementById(formName + ":telephone");
	var inpMobile = document.getElementById(formName + ":mobile");
	var inpPasswordNew = document.getElementById(formName + ":passwordNew");
	var inpReEnterPassword = document.getElementById(formName + ":reEnterPassword");

	// mandatory fields
	var bMissingMandatory=false;
	if (! checkRequired (inpForename, formName, "Forename")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpSurname, formName, "Surname")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpAddressLine1, formName, "AddressLine1")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpTown, formName, "Town")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpPostcode,formName,"Postcode")) {
		bMissingMandatory=true; }
	if (! checkRequired (inpEmail, formName, "Email")) {
		bMissingMandatory=true; }

	// not needed for changeDetails
	if (inpPasswordNew != null) {
		if (! checkRequired (inpPasswordNew, formName, "Password")) {
			bMissingMandatory=true; }
		if (! checkRequired (inpReEnterPassword, formName, "Password2")) {
			bMissingMandatory=true; }
	} 
	
	if (bMissingMandatory==true) {
		return false;
	}

	// content validation
	if (! validateEmailAddress (inpEmail, formName, "Email")) {
		return false;
	}
	
	if (! validateMatching (inpEmail, inpConfirmEmail, formName, "Email", matchingFieldMessage)) {
		return false;
	}
	// not needed for changeDetails
	if (inpPasswordNew != null) {
		if (! validatePassword (inpPasswordNew, formName, "Password")) {
			return false;
		}
		if (! validateMatching (inpPasswordNew, inpReEnterPassword, formName, "Password", matchingPasswordMsg)) {
			return false;
		}
	}
	
	return true;	
}

function validateEmailAddress (inputField, formName, fieldName) {
	// get error div eg. divPasswordMsg
	var messageDiv= document.getElementById(formName + ":div" + fieldName + "Msg");
	
	if(inputField!=null) {
		var emailAddress=inputField.value;
		clearMessageSpan (messageDiv);
	
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	
		if (! emailPattern.test(emailAddress)) {
			// create and set required message
			buildMessageSpan (messageDiv, validEmailMsg);
			return false;		
		}
	}
	
	return true;
}

function validatePassword (inputField, formName, fieldName) {
	// get error div eg. divPasswordMsg
	var messageDiv= document.getElementById(formName + ":div" + fieldName + "Msg");
	
	clearMessageSpan (messageDiv);

	if(inputField!= null) {
		// trim whitespace leading and trailing
		var password=inputField.value.replace (/^\s*/, '').replace(/\s*$/, '');

		// min length 6
		// only letters and numbers, no punctuation
		// no embedded spaces 
		var passwordPattern = /^(?=[\w]{6,})(?=.*?\d)(?=.*?[A-Za-z])[\w]*$/;
		 
		if (! passwordPattern.test(password)) {
			// create and set required message
			buildMessageSpan (messageDiv, validPasswordMsg);
			return false;		
		}

	}
		
	return true;
}

function validateMatching (inputField1, inputField2, formName, fieldName, message) {
	// get error div eg. divPasswordMsg
	var messageDiv= document.getElementById(formName + ":div" + fieldName + "Msg");
	clearMessageSpan (messageDiv);

	if(inputField1 != null && inputField2 != null) {
		if (inputField1.value != inputField2.value) {
			// create and set required message
			buildMessageSpan (messageDiv, message);
			return false;		
		}
	}	
	
	return true;
}

function checkRequired (inputField, formName, fieldName) {
	// get error div eg. divPasswordMsg
	var messageDiv= document.getElementById(formName + ":div" + fieldName + "Msg");

	// remove existing SPAN child in case field now passes validation.
	if (fieldName != null) {
		clearMessageSpan (messageDiv);
	}
	
	if(inputField != null) {
		// SELECT statements will be -1. 
		if (inputField.value==null || inputField.value=='' || inputField.value==-1) {		
			// create and set required message
			if (fieldName != null) {
				buildMessageSpan (messageDiv, valueRequiredMsg);
			}
			return false;		
		}
	}	

	return true;
}

function clearMessageSpan (messageDiv) {
	// remove existing SPAN child in case field now passes validation.
	// this needed a messageDiv null check
	if(messageDiv!=null) {
		var existingSpans=messageDiv.getElementsByTagName("span");
		if (existingSpans != null && existingSpans.length > 0) { 
			messageDiv.removeChild (existingSpans[0]);
		}
	}	
}

function buildMessageSpan (messageDiv, messageText) {	
	if(messageDiv!=null) {
		var messageSpan=document.createElement("span");
		messageSpan.setAttribute("id", messageDiv.id + "_span" );
		messageSpan.setAttribute("class", "addressGridItemTextError itemClearRight spanTextLeftFull") 
		messageSpan.setAttribute("className", "addressGridItemTextError itemClearRight spanTextLeftFull") 
		var messageSpanText=document.createTextNode(messageText);
		messageSpan.appendChild (messageSpanText);
		messageDiv.appendChild (messageSpan);
	}	
}

// this is called Onload() from the checkout page, it is also called in JS each time the payment type is changed. 
function changeCardType(){
// should keep this in line with validatePaymentMethodForm()
	
	checkPlaceOrderButton();
	
	var cardNumberText = document.getElementById("paymentMethod:winticard:cardNumberText");
	var cardNumberMsgDiv = document.getElementById("paymentMethod:winticard:divCardNumberMsg");
	var ccardNumber = document.getElementById("paymentMethod:winticard:ccardNumber");
	var scardNumber = document.getElementById("paymentMethod:winticard:scardNumber");
	var ccardNumberMsg = document.getElementById("paymentMethod:winticard:msgccardNumber");
	var scardNumberMsg = document.getElementById("paymentMethod:winticard:msgscardNumber");
	var start = document.getElementById("paymentMethod:winticard:startDateDiv");	
	var startMonthSelect = document.getElementById("paymentMethod:winticard:startMonth");	
	var startYearSelect = document.getElementById("paymentMethod:winticard:startYear");	
	var expiry = document.getElementById("paymentMethod:winticard:expiryDateDiv");
	var expiryMonthSelect = document.getElementById("paymentMethod:winticard:month");	
	var expiryYearSelect = document.getElementById("paymentMethod:winticard:year");	
	var issue = document.getElementById("paymentMethod:winticard:issuenoDiv");
	var issueNo = document.getElementById("paymentMethod:winticard:issueno");
	var maestroCheck = document.getElementById("paymentMethod:winticard:maestroCheck");
	var startDateCheck = document.getElementById("paymentMethod:winticard:startAndExpiryDateValidator");
	var expiryDateCheck = document.getElementById("paymentMethod:winticard:expiryDateValidator");
	
	var typeSel = document.getElementById("paymentMethod:paymentMethods");
	if (typeSel != null){
		var optionValue = typeSel.options[typeSel.selectedIndex].value;
		if (optionValue == "MC" || optionValue == "VI" || optionValue == "VP"){
			// enable
			cardNumberText.style.display="block";
			cardNumberMsgDiv.style.display="block";
			ccardNumber.style.display = "block";
			ccardNumber.disabled = false;
			if (ccardNumberMsg != null) {
				ccardNumberMsg.style.display = "block";
				ccardNumberMsg.disabled = false;
			}
			expiryMonthSelect.disabled = false;
			expiryYearSelect.disabled = false;

			expiry.style.display = "block";
			expiryDateCheck.disabled = false;
			// disable
			scardNumber.style.display = "none";
			scardNumber.disabled = true;
			scardNumber.value='';
			if (scardNumberMsg != null) {
				scardNumberMsg.style.display = "none";
				scardNumberMsg.disabled = true;
			}

			start.style.display = "none";
			startMonthSelect.disabled = true;
			startYearSelect.disabled = true;
			
			issue.style.display = "none";
			issueNo.disabled = true;
			
			maestroCheck.disabled = true;
			startDateCheck.disabled = true;
		}
		else if (optionValue == "AX"){
			// enable
			cardNumberText.style.display="block";
			cardNumberMsgDiv.style.display="block";
			ccardNumber.style.display = "block";
			ccardNumber.disabled = false;
			if (ccardNumberMsg != null) {
				ccardNumberMsg.style.display = "block";
				ccardNumberMsg.disabled = false;
			}

			expiry.style.display = "block";
			expiryDateCheck.disabled = false;
			expiryMonthSelect.disabled = false;
			expiryYearSelect.disabled = false;
			
			// disable
			start.style.display = "false";
			startDateCheck.disabled = true;
			startMonthSelect.disabled = true;
			startYearSelect.disabled = true;
			scardNumber.style.display = "none";
			scardNumber.disabled = true;
			if (scardNumberMsg != null) {
				scardNumberMsg.style.display = "none";
				scardNumberMsg.disabled = true;
			}
			issue.style.display = "none";
			issueNo.disabled = true;
			maestroCheck.disabled = true;
		}
		else if (optionValue == "SW"){
			// enable
			cardNumberText.style.display="block";
			cardNumberMsgDiv.style.display="block";
			scardNumber.style.display = "block";
			scardNumber.disabled = false;
			if (scardNumberMsg != null) {
				scardNumberMsg.style.display = "block";
				scardNumberMsg.disabled = false;
			}
			start.style.display = "block";
			expiry.style.display = "block";
			startMonthSelect.disabled = false;
			startYearSelect.disabled = false;
			expiryMonthSelect.disabled = false;
			expiryYearSelect.disabled = false;
			
			issue.style.display = "block";
			issueNo.disabled = false;
			maestroCheck.disabled = false;
			startDateCheck.disabled = false;
			expiryDateCheck.disabled = false;
			// disable
			ccardNumber.style.display = "none";
			ccardNumber.disabled = true;
			if (ccardNumberMsg != null) {
				ccardNumberMsg.style.display = "none";
				ccardNumberMsg.disabled = true;
			}
		}
		else if (optionValue == "CR"){
			// enable
			
			// disable
			cardNumberText.style.display="none";
			cardNumberMsgDiv.style.display="none";
			ccardNumber.style.display = "none";
			ccardNumber.disabled = true;
			if (ccardNumberMsg != null) {
				ccardNumberMsg.style.display = "none";
				ccardNumberMsg.disabled = true;
			}
			scardNumber.style.display = "none";
			scardNumber.disabled = true;
			if (scardNumberMsg != null) {
				scardNumberMsg.style.display = "none";
				scardNumberMsg.disabled = true;
			}

			start.style.display = "none";
			expiry.style.display = "none";
			startMonthSelect.disabled = true;
			startYearSelect.disabled = true;
			expiryMonthSelect.disabled = true;
			expiryYearSelect.disabled = true;

			issue.style.display = "none";
			issueNo.disabled = true;
			maestroCheck.disabled = true;
			startDateCheck.disabled = true;
			expiryDateCheck.disabled = true;
		} 
	}	
}

function setJSCookie(){
	// **************************************************************
	// if you change name or path, change it also in HSECustomerBean
	// **************************************************************
	
	// if its already set, and its true
	var cookieValue=readCookie("JSEnabled");	
	if (cookieValue != null && cookieValue == 'true') {
		return;
	}
	
	createCookie("JSEnabled","true", null, "/hse");
}