// validateLotto_en.js
// Author: Patti DiSabatino
// Usage: Perform Validation for Lottoadvance English web form pages
		var bFormIsOK = true;
		var sErrorLog = "";
		var iErrorCounter = 0;
		var arrNumbers = new Array(6);		
		
	function validateRenew(){
		/** 
			Purpose: Performs a series of tests to validate the Subscription Renewal 
							form, once the "Submit" button has been clicked	
				Author:	Patti DiSabatino	
		*/ 
			clearErrorLog();
			
			checkDateAndNumber();
			
			var sNumBoards = document.forms[0].numBoards.value;
	 		if ( sNumBoards == "-1"){
	 		 	addToErrorLog("Please select a Plan Type.");	 
   			}
    		
    		checkRenewalOption();
					
    	   	checkAddressFieldsFilledIn("subscriber");	
    	    
			checkAddressChange();			
			
			checkCreditCard();
			
			checkCardNumberFormat();
			
			if(! document.forms[0].elements['isContractChecked'].checked){
				addToErrorLog("You must agree to the Lotto Advance subscription terms and conditions.");
			}
				
			if(! isErrorLogEmpty()){
				alert(getErrorLog());
				clearErrorLog();
				checkPastExpiry();
				return false;
			}	
			else 
			{
				checkPastExpiry();
				return true;
			}
	}
	
	function validateNew(){
		/** 
			Purpose:  Performs a series of tests to validate the New Subscription
							Form, once the "Submit" button has been clicked
			Author:	Patti DiSabatino
		*/ 
			clearErrorLog();
			
			var sNumBoards = document.forms[0].numBoards.value;
	 		if ( sNumBoards == "-1"){
	 		 	addToErrorLog("Please select a Plan Type.");	 
	 		}
			
			checkBoardsFilledIn();
			
		    checkAddressFieldsFilledIn("subscriber");				
			
			if (window.document.forms[0].subscriptionType.value=="Gift"){
				checkAddressFieldsFilledIn("gifter");
			}
			
			checkCreditCard();
			
			checkCardNumberFormat();
			
			if(! document.forms[0].elements['isContractChecked'].checked){
				addToErrorLog("You must agree to the Lotto Advance subscription terms and conditions.");
			}
			
			if ((document.forms[0].retailerLocationNum.value != "") && (document.forms[0].retailerLocationNum.value !=null)){
				checkNumeric("Retailer","Location Number", document.forms[0].retailerLocationNum.value);	
			}
					
			if(! isErrorLogEmpty()){
				alert(getErrorLog());
				clearErrorLog();
				return false;
			}	
			else 
			{
				return true;
			}
	}
		
	/** 
		Purpose: Performs a series of tests to validate Wizard page1, for both subscribe and renew 	
		Author:	Annie Liu	
	*/ 
	function validatePage1(){
	        		
			clearErrorLog();
			
			if ((window.document.forms[0].action.value=="renew")||(window.document.forms[0].action.value=="renewDisc")){
			     checkDateAndNumber();
		   	}	
			
			var sNumBoards = document.forms[0].numBoards.value;
	 		if ( sNumBoards == "-1"){
	 		 	addToErrorLog("Please select a Plan Type.");	 
	 		}
			
		    if ((window.document.forms[0].action.value=="subscribe")||(window.document.forms[0].action.value=="subscribeDisc")){
				checkBoardsFilledIn();
			}
			
		    if ((window.document.forms[0].action.value=="renew") ||(window.document.forms[0].action.value=="renewDisc")){
			    	checkRenewalOption();	
		  	}	
							
			if(! isErrorLogEmpty()){
				alert(getErrorLog());
				clearErrorLog();
				return false;
			}	
			else 
			{
				return true;
			}
	}
	/** 
		Purpose: Performs a series of tests to validate Wizard page2, for both subscribe and renew 	
		Author:	Annie Liu	
	*/ 
	function validatePage2(){
	
	       		
			clearErrorLog();
			
		    checkAddressFieldsFilledIn("subscriber");	
		    checkDateOfBirth();
		    
		    /*if ((window.document.forms[0].action.value=="subscribe")||(window.document.forms[0].action.value=="subscribeDisc")){
							
			    if (window.document.forms[0].subscriptionType.value=="Gift"){
				    checkAddressFieldsFilledIn("gifter");
		     	}
			}*/
			if ((window.document.forms[0].action.value=="renew") ||(window.document.forms[0].action.value=="renewDisc")){
			     checkAddressChange();	
		  	}	
		  	
		  	if ((window.document.forms[0].action.value=="subscribe")||(window.document.forms[0].action.value=="subscribeDisc")){
						
			    if ((document.forms[0].retailerLocationNum.value != "") && (document.forms[0].retailerLocationNum.value !=null)){
				   checkNumeric("Retailer","Location Number", document.forms[0].retailerLocationNum.value);	
			    }
			}
		  		
			if(! isErrorLogEmpty()){
				alert(getErrorLog());
				clearErrorLog();
				return false;
			}	
			else 
			{
				return true;
			}
	}
	/** 
		Purpose: Performs a series of tests to validate Wizard page3, for both subscribe and renew 	
		Author:	Annie Liu	
	*/ 
	function validatePage3(){
	
	       	
			clearErrorLog();
			checkCreditCard();
			checkCardNumberFormat();
			
			if(! document.forms[0].elements['isContractChecked'].checked){
				    addToErrorLog("You must agree to the Lotto Advance subscription terms and conditions.");
			}
		  	
		    
		   /* if ((window.document.forms[0].action.value=="subscribe")||(window.document.forms[0].action.value=="subscribeDisc")){
						
			    if ((document.forms[0].retailerLocationNum.value != "") && (document.forms[0].retailerLocationNum.value !=null)){
				   checkNumeric("Retailer","Location Number", document.forms[1].retailerLocationNum.value);	
			    }
			}*/
				  		
			if(! isErrorLogEmpty()){
				alert(getErrorLog());
				clearErrorLog();
				return false;
			}	
			else 
			{
				return true;
			}
	}
			
		function getErrorLog(){
		/** 
			Purpose: Returns the list of error messages contained in the error log.
			Returns: String
			Author: Justin Edmeade
		*/
			if(isErrorLogEmpty()){
				return sErrorLog;
			}else{
				return sErrorLog + "\nPlease make these corrections before clicking the submit button. Thank you.";
			}
		}
		
		function isErrorLogEmpty(){
		/** 
			Purpose: Determines if the error log is empty.
			Returns: Boolean
			Author: Justin Edmeade
		*/
			if(sErrorLog == ""){
				return true;
			}else{
				return false;
			}
		}
		
		function clearErrorLog(){
		/** 
			Purpose: Clears the error log of all messages.			
			Author: Justin Edmeade	
		*/	
			sErrorLog = "";
			sErrorLog.length = 0;
			iErrorCounter = 0;
		}
		
		function addToErrorLog(sErrMessage){	
		/** 
			Purpose: Adds an error message to the log (a string variable) that stores any error messages encountered
			         while validating the form.
			Author: Justin Edmeade
		*/				
			
			if(iErrorCounter == 0){
				sErrorLog = "The following problems were encountered while processing the form:\n\n";
			}
			
			iErrorCounter++; //Advance the error counter
			
			sErrorLog += iErrorCounter; 
			sErrorLog += ". ";
			sErrorLog += sErrMessage;
			sErrorLog += "\n";
		}
		
	function checkBoardsFilledIn(){
		/** 
			Purpose: Ensures that each box of every board selected is filled in correctly.
			Author: Justin Edmeade
			Modified By: Patti DiSabatino
		*/
			
			//Determine the number of boards selected by the User.	
				var lottoForm = window.document.forms[0];			
				var sDrawPlan = new String();		 
				var sNumber = "";
				var sLottoPickID = "";
				var bEmptySquare = false;
				var bInvalidNumber = false;
				var bDuplicateNumber = false;				
				
				sDrawPlan = lottoForm.elements["numBoards"].value;				
				clearDuplicateNumberArray();			
				
			//Test each box of every User selected board for completeness (i.e. filled in with a valid number; non-duplicate).
				for(var iBoardNum = 1; iBoardNum <= parseInt(sDrawPlan); iBoardNum++){
				
					sLottoPickID = "board" + iBoardNum + ".qp";
					if(! lottoForm.elements[sLottoPickID][0].checked){
					
						for(var iBoxNum = 0; iBoxNum <= 5; iBoxNum++){
							sNumber = eval("lottoForm.elements['board" + iBoardNum + ".boardNumbers[" + iBoxNum + "]" + "'].value");	
							if (sNumber.charAt(0) == "0") {
							 	sNumber = sNumber.charAt(1); 
							 }
						
							if(sNumber == ''){
								bEmptySquare = true;
								bFormIsOK = false;							
							}
							
							if((parseInt(sNumber) < 1) || (parseInt(sNumber) > 49)){
								bInvalidNumber = true;
								bFormIsOK = false;		 			
							}
							
							if(isDuplicateNumber(sNumber,iBoxNum)){
								bDuplicateNumber = true;
								bFormIsOK = false; 
							}
						}						
						clearDuplicateNumberArray();
					}
				}			
				
				
			//If any errors were found, report them to the error log for later reporting to the User.
				if(bEmptySquare){
					addToErrorLog("One or more empty boxes were detected for the " + 
											" board(s) you selected.  Please ensure that all boards are completely filled in.");
				}
				
				if(bInvalidNumber){
					addToErrorLog("One or more invalid numbers were detected.  Please enter a number between 1 and 49 only.");
				}
				
				if(bDuplicateNumber){
					addToErrorLog("Duplicate numbers were detected.  Please ensure that all numbers are unique for each board played.");
				}				
		}
		
		function isDuplicateNumber(iVal,iArrPos){
		/** 
			Purpose: Determines if a number is a duplicate number for a given board.
			Returns: Boolean.
			Author: Justin Edmeade
			Modified By: Patti DiSabatino
		*/
			
			var bDuplicateFound = false;
			if(iVal == ""){return false;}
			arrNumbers[iArrPos] = iVal;						
			
			for(var iIndex = 0; iIndex <= arrNumbers.length; iIndex++){
				if((iIndex != iArrPos) && (arrNumbers[iIndex] == iVal)){					
					bDuplicateFound = true;			
					break;		
				}
			}			
			
			if(bDuplicateFound){			
				return true;
			}else{			
				return false;
			}
		}		
				
		function clearDuplicateNumberArray(){
		/** 
			Purpose: Clears the duplicate number array.			
			Author: Justin Edmeade
		*/		
			for(var iIndex = 0; iIndex < arrNumbers.length; iIndex++){
				arrNumbers[iIndex] = '';
			}
		}	
		
		function checkAddressFieldsFilledIn(whichID){
		/** 
			Purpose: Ensures that name, address, phone and email fields are entered.
			Author: Justin Edmeade
			Modified By: Patti DiSabatino
		*/
			var lottoForm = window.document.forms[0];
			var sElementName = new String();
			var sPersonIdentity = "";
			var sPersonPrefix = "";
			
			if(whichID == 'subscriber'){
						sPersonIdentity = "Subscriber's";
			} else {
						sPersonIdentity = "Gift Giver's";
					}
			
			for(var iElementID = 0; iElementID < lottoForm.elements.length; iElementID++){
				iPrefix = whichID.length;
				sElement = lottoForm.elements[iElementID];	
				sElementName = sElement.name;				
				sPersonPrefix = sElementName.substr(0, iPrefix);

				if (sElementName.substr(iPrefix + 1, 'address.'.length) == 'address.') {
					iPrefix += 'address.'.length;
				}
				
				if((sPersonPrefix == whichID)){
				    if 	(lottoForm.elements[iElementID].value == '') {
                   	switch(sElementName.substr(iPrefix + 1, sElementName.length - iPrefix)){
						case "lastName":							
							addToErrorLog("Please enter the " + sPersonIdentity + " Last Name.");
							break;
						case "firstName":
							addToErrorLog("Please enter the " + sPersonIdentity + " First Name.");
							break;
						/*case "streetNumber":
							addToErrorLog("Please enter the " + sPersonIdentity + " Street Number.");
							break;
						case "streetName":
							addToErrorLog("Please enter the " + sPersonIdentity + " Street Name.");
							break;*/
						case "address1":
							addToErrorLog("Please enter the " + sPersonIdentity + " Street Address.");
							break;	
						case "city":
							addToErrorLog("Please enter the " + sPersonIdentity + " City.");
							break;
						case "postalCode":
							addToErrorLog("Please enter the " + sPersonIdentity + " Postal Code.");
							break;
						case "phoneAreaCode":
							addToErrorLog("Please enter the " + sPersonIdentity + " Area Code.");
							break;
						case "phoneExchange":
							addToErrorLog("Please enter the first 3 digits of the " + sPersonIdentity + " telephone number.");
							break;
						case "phoneNumber":
							addToErrorLog("Please enter the last 4 digits of the " + sPersonIdentity + " telephone number.");
							break;
						case "email":
							addToErrorLog("Please enter the " + sPersonIdentity + " Email Address.");
							break;
						case "emailConfirm":
							addToErrorLog("Please confirm the " + sPersonIdentity + " Email Address.");
							break;
						}
					}
					else
					{
						switch(sElementName.substr(iPrefix + 1, sElementName.length - iPrefix)){
						case "lastName":
							checkAlpha(sPersonIdentity, "last name", sElement.value);
							break;
						case "firstName":
							checkAlpha(sPersonIdentity,"first name", sElement.value);
							break;
						/*case "streetNumber":
							checkNumeric(sPersonIdentity, "street number", sElement.value);
							break;*/
						//case "streetName":
						//	checkAlphaNumeric(sPersonIdentity, "street name", sElement.value);
						//	break;
						case "city":
							checkAlpha(sPersonIdentity, "city", sElement.value);
							break;
						case "postalCode":
							checkCanadianPostal(sElement.value, sPersonIdentity);
							break;
						case "phoneAreaCode":
							if (sElement.value.length < 3) {
								addToErrorLog("The area code for the " + sPersonIdentity + " telephone number does not appear to be in the correct format.");
								break;
							} else{
								checkNumeric(sPersonIdentity, "area code", sElement.value);					
								break;
							}
						case "phoneExchange":
							if (sElement.value.length < 3){
								addToErrorLog("The first set of numbers in the " + sPersonIdentity + " telephone number does not appear to be in the correct format.");
								break;
							} else {
								checkNumeric(sPersonIdentity, "first set of numbers in the telephone number", sElement.value);
								break;
							}
						case "phoneNumber":
							if (sElement.value.length < 4) {
								addToErrorLog("The second set of numbers in the " + sPersonIdentity + " telephone number does not appear to be in the correct format.");
								break;
							} else {
								checkNumeric(sPersonIdentity, "second set of numbers in the telephone number", sElement.value);
								break;
							}	
						case "phoneExtension":
							checkNumeric(sPersonIdentity, "telephone extension number", sElement.value);
							break;
						case "email":
							checkEmail(sElement.value, sPersonIdentity);
							emailAddress = sElement.value;
							break;
						case "emailConfirm":
							if (sElement.value.toUpperCase() != emailAddress.toUpperCase()) {
								addToErrorLog("The " + sPersonIdentity + " email and confirmation email must match.");
							}
							break;
						}
					}
				}
			  }	
		  }				
		  
	function checkAddressChange(){
		/** 
			Purpose: Checks address changed flag and effective date
							If the flag is checked, date must be entered
							If the date is entered, flag must be checked
			Usage:	Used by the Subscription Renewal form
			Author:	Patti DiSabatino
		*/
		var lottoForm = window.document.forms[0];
		var changeFlag = lottoForm.changeAddress[0];
		var changeDay = lottoForm.changeDay.value;
		var changeMonth = lottoForm.changeMonth.value;
		var changeYear = lottoForm.changeYear.value;
		var today = new Date();
		var thisYear = today.getFullYear();
				
		if (! changeFlag.checked && ((changeDay.length > 0 && changeDay.value != "") || 
														(changeMonth.length > 0 && changeMonth.value != "") ||
														( changeYear.length > 0 && changeYear.value !=""))){
			addToErrorLog("Please check the Change of Address box.");
		}
				
		if (changeFlag.checked && (changeDay.length == 0 || changeMonth.length == 0 || changeYear.length == 0)){
			addToErrorLog("Please complete all fields in the change of address effective date.");
		}
		
		if (changeFlag.checked) {
			if (parseInt(changeDay) < '1' || parseInt(changeDay) > '31' || isNaN(changeDay)){
				addToErrorLog("Please enter a valid change of address effective day.");
			}
			if (parseInt(changeMonth) < '1' || parseInt(changeMonth) > '12' || isNaN(changeMonth)){
				addToErrorLog("Please enter a valid change of address effective month.");
			}
			if (parseInt(changeYear) < '1' || parseInt(changeYear) > thisYear || isNaN(changeYear)){
				addToErrorLog("Please enter a valid change of address effective year.");
			}
		}
		
	}						
		
		
	function isMOD10(sCardNumber){
		/** 
			Purpose: Determines if the credit card number is valid according to the MOD10/LUHN formula.
			Returns: Boolean
			Author: Justin Edmeade
		*/
			
			var cardNumber = new Array(15);
			var isMOD10 = false;
			var posCounter = 1;
			var elementValue = new String();
			var checkSum = 0;
		
			/*1. Store credit card digits in an array object.   */
			
				for(var i=0; i < sCardNumber.length; i++)
				{
					cardNumber[i] = sCardNumber.charAt(i);
				}
			
			
			/*2.  Multiply every other digit by 2 starting from the 2nd last digit  (i.e. to the left of the check digit).  If the result is a two digit number then
			      add the two digits e.g. 18 -> 1 + 8 = 9   */
				  
				cardNumber.reverse();
				for(var j=0; j < cardNumber.length; j++)
				{
				
					if((posCounter % 2) == 0)
					{
						cardNumber[j] = parseInt(cardNumber[j]) * 2;
						elementValue = cardNumber[j].toString();
						
						if(elementValue.length == 2)
						{
							cardNumber[j] = parseInt(elementValue.charAt(0)) + parseInt(elementValue.charAt(1));
						}
						
					}
					posCounter++;
					
				}				
				
			/*3.  Add up the numbers to arrive at a CHECKSUM  */
			
				for(var k=0; k < cardNumber.length; k++)
				{
					checkSum += parseInt(cardNumber[k]);
				}
				
			
			/*4.  Perform the MOD 10 test using the CHECKSUM  */
				
				if((checkSum % 10) == 0)
				{
					isMOD10 = true;
				}
			
				
				return isMOD10;
				
	}
	
	
	function getCardType(){
		/** 
			Purpose: Returns one of the 2 supported credit card types - Visa OR Master Card
			         This algorithm is a subset of the one authored by Patti DiSabatino in the "checkCreditCard" function.
			Returns: String
			Author: Justin Edmeade
		*/
		
		var lottoForm = window.document.forms[0];
		var radio1 = "";
		var radio2 = "";
		var sElementName = new String();
		var sElement="";
		var sCardType = "Visa";
		var sPrefix = "";
		var sLen = 0;
				
		for(var iElementID = 0; iElementID < lottoForm.elements.length; iElementID++){		
				sElement = lottoForm.elements[iElementID];	
				sElementName = sElement.name;				
				sPrefix = sElementName.substr(0, 10);
				sLen = sPrefix.length;
						
				if(sPrefix == "creditCard"){		
					if 	(sElementName.substr((sLen + 1), (sElementName.length - sLen)) == "cardType"){
						if (sElement.value == "Visa"){
							radio1= sElement;
						}
						if (sElement.value == "Master Card") {
							radio2 = sElement;
						}
						
						if (radio2.checked == true){
							sCardType = "Master Card"
							break;
						}						
					}	
				
				}
				
		}
		
		return sCardType;
		
	}
			
	function checkCardNumberFormat(){
		/** 
			Purpose: 		Validates the credit card number format based on a set of pre-determined rules.
			Dependencies:   function getCardType()
							function isMOD10()
			Disclaimer: 	Credit card number logic continually evolves.  This code does not and cannot
					    	guarantee to accurately  validate ALL credit card numbers.
			Author: 		Justin Edmeade
		*/
		
		//Declarations
			var formatIsOK = true;
			var sCreditCardType = new String();
			var radio1 = "";
			var radio2 = "";
			
			var sCreditCard_FourDigits_First = new String();
			var sCreditCard_FourDigits_Second = new String();
			var sCreditCard_FourDigits_Third = new String();
			var sCreditCard_FourDigits_Fourth = new String();
			var sCreditCardNumber = new String();
		
		//Retrieve Form object
			var lottoForm = window.document.forms[0];			
		
		//Retrieve the credit card type from the Form Object
			sCreditCardType = getCardType();	
						
		//Retrieve credit card number from Form object
			sCreditCard_FourDigits_First  = lottoForm.elements["creditCard.cardNumbers[0]"].value;	
			sCreditCard_FourDigits_Second  = lottoForm.elements["creditCard.cardNumbers[1]"].value;	
			sCreditCard_FourDigits_Third  = lottoForm.elements["creditCard.cardNumbers[2]"].value;	
			sCreditCard_FourDigits_Fourth  = lottoForm.elements["creditCard.cardNumbers[3]"].value;	
			
		//Get full card number
			sCreditCardNumber += sCreditCard_FourDigits_First;
			sCreditCardNumber += sCreditCard_FourDigits_Second;
			sCreditCardNumber += sCreditCard_FourDigits_Third;
			sCreditCardNumber += sCreditCard_FourDigits_Fourth;
						
	//Card type prefix testing
		if(sCreditCardType=="Visa"){
			
			if(sCreditCard_FourDigits_First.substr(0,1) != "4")
				formatIsOK=false;
								
		}else{
				
			var sMasterCardPrefix = 0;
			
			sMasterCardPrefix = parseInt(sCreditCard_FourDigits_First.substr(0,2));
			
			if(sMasterCardPrefix < 51 || sMasterCardPrefix > 55)
				formatIsOK=false;
				
		}
		
	//Mod 10 formula test
		if(! isMOD10(sCreditCardNumber)){
			formatIsOK=false;
		}
		
		if(! formatIsOK)
			addToErrorLog("The credit card number does not appear to be a valid " + sCreditCardType + " number. Please check the number.");
			
	}
		
		
	function checkCreditCard(){ 
		/** 
			Purpose: 		Ensures credit card information is entered.  Does not check whether credit card number is valid

			Author: 		Patti DiSabatino
			Modified by:	Justin Edmead, January 2006.  
			             	Removed the check that forces a 16 digit card number for Visa.  13 digit Visa numbers are a 
							possibility.
		*/
		var lottoForm = window.document.forms[0];
		var radio1 = "";
		var radio2 = "";
		var sElementName = new String();
		var sElement="";
		var sPrefix = "";
		var sLen = 0;
		var today = new Date();
		var dateToValidate = new Date();
		var iMonth = "";
		var iYear = ""; 
		//Added January 2006 by Justin Edmeade
		var sCardType = "";
				
		for(var iElementID = 0; iElementID < lottoForm.elements.length; iElementID++){		
				sElement = lottoForm.elements[iElementID];	
				sElementName = sElement.name;				
				sPrefix = sElementName.substr(0, 10);
				sLen = sPrefix.length;
			
				if(sPrefix == "creditCard"){		
					if 	(sElementName.substr((sLen + 1), (sElementName.length - sLen)) == "cardType"){
						if (sElement.value == "Visa"){
							radio1= sElement;
						}
						if (sElement.value == "Master Card") {
							radio2 = sElement;
						}
						
						if ((radio1.checked == false) && ( radio2.checked == false)){
								addToErrorLog("Please select a credit card type."); 
						}						
						
						
						//Added January 2006 by Justin Edmeade
						if (radio1.checked == true){
								sCardType = "Visa"; 
						}	
						
						//Added January 2006 by Justin Edmeade
						if (radio2.checked == true){
								sCardType = "Master Card"; 
						}
							
					}	
					
					if 	(sElement.value == '') {					
						switch(sElementName.substr((sLen + 1), (sElementName.length - sLen)) ){
						case "cardNumbers[0]":
							addToErrorLog("Please enter the first set of credit card numbers.");
							break;
						case "cardNumbers[1]":
							addToErrorLog("Please enter the second set of credit card numbers.");
							break;
						case "cardNumbers[2]":
							addToErrorLog("Please enter the third set of credit card numbers.");
							break;
						case "cardNumbers[3]": 
							addToErrorLog("Please enter the last set of credit card numbers.");
							break;
						case "cardExpiryMonth":
							addToErrorLog("Please enter the credit card expiry month.");
							break;
						case "cardExpiryYear":
							addToErrorLog("Please enter the credit card expiry year.");
							break;
						case "cardHolderName":
							addToErrorLog("Please enter the card holder's name.");
							break;
						}  	 // end switch
					}
					 else {
						if 	(sElement.value.length > 0) {
							switch(sElementName.substr((sLen + 1), (sElementName.length - sLen))){
							case "cardNumbers[0]":
								if (sElement.value.length < 4){
									addToErrorLog("The first set of credit card numbers does not appear to be in the correct format.");
									break;
								} else {
									checkNumeric("first set of", "credit card numbers", sElement.value);
									break;
								}
							case "cardNumbers[1]":
									if (sElement.value.length < 4){
									addToErrorLog("The second set of credit card numbers does not appear to be in the correct format.");
									break;
								} else {
									checkNumeric("second set of", "credit card numbers", sElement.value);
									break;
								}
							case "cardNumbers[2]":
									if (sElement.value.length < 4){
									addToErrorLog("The third set of credit card numbers does not appear to be in the correct format.");
									break;
								} else {
									checkNumeric("third set of", "credit card numbers", sElement.value);
									break;
								}
							case "cardNumbers[3]": 
							
								//Added January 2006 by Justin Edmeade  (i.e. outer if statement)
								if(sCardType != "Visa"){
									
									if (sElement.value.length < 4){
									addToErrorLog("The fourth set of credit card numbers does not appear to be in the correct format.");
									break;
								} else {
									checkNumeric("fourth set of", "credit card numbers", sElement.value);
									break;
								}
							}
							case "cardExpiryMonth":
								iMonth = parseInt(sElement.value);
								break;
							case "cardExpiryYear":
								iYear = parseInt(sElement.value);
								break;
							case "cardHolderName":
								checkAlpha("credit card", "holder's name",sElement.value);
							}		// end switch			
						}
					}
				}
			}
			dateToValidate.setMonth(iMonth - 1);	// JS numbers months from 0 to 11
			dateToValidate.setFullYear(iYear);		
			if ((dateToValidate.getMonth() < today.getMonth()) && (dateToValidate.getFullYear() == today.getFullYear())){ 
				addToErrorLog("Credit card expiry date is invalid.");
			}
		}
		
	function checkNumeric(displayName, whichField, fieldValue){ 
		/** 
			Purpose: Ensures that field passed in contains numbers only
			Author: 	Patti DiSabatino
		*/
		var strValue = fieldValue.toString();
		var validChars = "0123456789";
		var iNumCounter = 0;                               
         for (var n = 0; n < fieldValue.length; n++) {
              if (validChars.indexOf(fieldValue.substring(n, n+1)) == -1) {
                iNumCounter++;
              }
   	 	}   	 	
   	 	if(iNumCounter > 0) {
   	 		  addToErrorLog("The " + displayName + " " + whichField + " does not appear to be in the correct format.");
		}
    // This ensures that numbers don't total zero...initially used for credit card checking, but removed.
	//	if(parseInt(fieldValue) == '0' ){
	//		addToErrorLog("The " + displayName + " " + whichField + " does not appear to be in the correct format.");
	//	}
	}
	
	function checkCanadianPostal(whichField, displayName){ 
		/** 
			Purpose: Ensures that postal code format is correct
							Does not check that postal code is valid
			Author:	Patti DiSabatino
		*/
		//postalFormat = /[a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9]/;
		postalFormat = /[a-zA-Z][0-9][a-zA-Z](\s)*[0-9][a-zA-Z][0-9]/; 
		 if((whichField.length > 0) && (! (postalFormat.test(whichField))) ){
			addToErrorLog("The " + displayName + " postal code does not appear to be in the correct format.");
		}
	}
	
	function checkUSZip(whichField, displayName){ 
		
		postalFormat1=/^\d{5}-\d{4}$/; 
		postalFormat2=/^\d{5}$/; 
		if((whichField.length > 0) && (postalFormat1.test(whichField)||postalFormat2.test(whichField))){
		}else{
		   addToErrorLog("The " + displayName + " zip code does not appear to be in the correct format.");
		}
	}
	function checkPostalZipCode(whichField, country){
	   if(country=='Canada'){
	      checkCanadianPostal(whichField,"")
	   }else if(country=='US'){
	      checkUSZip(whichField,"")
	   }
	   
	}
	function checkAlpha(displayName, whichField, fieldValue){ 
		/** 
			Purpose: Ensures that the field passed in contains characters only.
			Author:   Patti DiSabatino
		*/
			
		charField = /(\d+)|(^\s+)/;
		if((fieldValue.length > 0) && (charField.test(fieldValue))){
			addToErrorLog("The " + displayName + " " + whichField + " must contain only alphabetical characters.");
		}
	}
	
	function checkAlphaNumeric(displayName, whichField, fieldValue)
	{
		/** 
			Purpose: Ensures that field passed in is characters, numbers or a combination of both
			Author:	Patti DiSabatino
		*/
			
		alphaNumField= /\W+/;
		if((fieldValue.length>0) && (alphaNumField.test(fieldValue))){
			addToErrorLog("The " + displayName + " " + whichField + " must contain only alpha or number characters.");
		}
	}
	
	function checkEmail(whichField, displayName){ 
		/** 
			Purpose: Ensures that the email address is formatted correctly.
						    Does not test that the email address is valid.
			Author:	Patti DiSabatino
		*/
			
		emailField1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
		emailField2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/;
		if((whichField.length > 0) && (! (! emailField1.test(whichField) && emailField2.test(whichField))) ){
			addToErrorLog("The " + displayName + " email  is not a valid email address.");
		}
	}
	
	function checkDateAndNumber(){
		/** 
			Purpose: Tests Subscription Number and Expiry Dates
			Usage:	Used by the Subscription Renewal Form.
			Author:	Patti DiSabatino
		*/
			var lottoForm = window.document.forms[0];
			
			if (lottoForm.subExpiryDay.value == "-1") {
				addToErrorLog("Please select a valid Subscription Expiry Day.");
			}
			
			if (lottoForm.subExpiryMonth.value == "-1") {
				addToErrorLog("Please select a valid Subscription Expiry Month.");
			}
			
			if (lottoForm.subExpiryYear.value == "-1") {
				addToErrorLog("Please select a valid Subscription Expiry Year.");
			}
			
			if (lottoForm.subscriptionNumber.value == ""){
				addToErrorLog("Please enter the Subscription Number.");
			}
			else if(lottoForm.subscriptionNumber.value.length > 0){
					checkNumeric("Subscription", "Number", lottoForm.subscriptionNumber.value);
			}	
	}
		
	
	function checkDateOfBirth(){
			var isDateIncomplete=-1;
		    var sDay = document.forms[0].elements['subscriber.birthDate.birthDateDay'].value;
			var sMonth = document.forms[0].elements['subscriber.birthDate.birthDateMonth'].value;
			var sYear = document.forms[0].elements['subscriber.birthDate.birthDateYear'].value;
			if(sDay=="-1"){
				addToErrorLog("Please select a valid Day for Date of Birth.");
				isDateIncomplete=1;
			}
			if(sMonth=="-1"){
				addToErrorLog("Please select a valid Month for Date of Birth.");
				isDateIncomplete=1;
			}
			if(sYear=="-1"){
				addToErrorLog("Please select a valid Year for Date of Birth.");
				isDateIncomplete=1;
			}
			if(isDateIncomplete==1){
			   return;
			}
			
			// Concatenate day, month, year into one date object
			var sBirthDate = new Date(sYear, sMonth-1, sDay);			
	    	// Calculate the difference
			var today = new Date();
			var diff = today.getTime()-sBirthDate.getTime();
			var milliSecondsIn18Year = 1000 * 60 * 60 * 24 * 365 * 18;
			var diff = today.getTime()-sBirthDate.getTime()-milliSecondsIn18Year;
			if (diff < 0 ) {			
			    addToErrorLog("Subscriber must be 18 years of age or older! \n    Date of Birth entered does not meet OLG age requirements. \n    Order cannot be submitted as entered.");
	
			} 
	}
		
		
	function checkRenewalOption(){
		/** 
			Purpose: Tests to ensure that either a Renewal Option has been selected. 
							If "Renewal with Changes" is selected, further performs board and
							board number checking
			Usage:	Used by the Subscription Renewal Form
			Author:	Patti DiSabatino
		*/
			
			var lottoForm = window.document.forms[0];
			var radio1 = "";
			var radio2 = "";
			var sElementName = new String();
			var sElement="";
			
			for(var iElementID = 0; iElementID < lottoForm.elements.length; iElementID++){		
						sElement = lottoForm.elements[iElementID];	
						sElementName = sElement.name;			
					
						if(sElementName == "subscriptionOrder"){		
							if (sElement.value == "SN"){
								radio1= sElement;
							}
						
							if (sElement.value == "SC") {
								radio2 = sElement;
							}
					}								
			}
			if ((radio1.checked == false) && ( radio2.checked == false)){
						addToErrorLog("Please select a renewal option."); 
			}		
			
			if (radio2.checked == true) { 
				checkBoardsFilledIn();	
				checkBoards();
			} 
	}
		
	function checkBoards(){
		/** 
			Purpose: Ensures that the number of boards filled in matches the number of
						   boards selected in the Draw Plan
			Usage:    Used by the Subscription Renewal Form
			Author:	Patti DiSabatino
		*/
			
		var lottoForm = window.document.forms[0];
		var sDrawPlan = "";
		var sBoardNum = "";
		var sLottoPickID ="";
		var iCounter = 0;
		var iFound = false;
		
		sDrawPlan = lottoForm.elements["numBoards"].value;		
		
			for(var iBoardNum = 1; iBoardNum <= 5; iBoardNum++){
				sBoardNum = "board" + iBoardNum;
				sLottoPickID = sBoardNum + ".qp";
						
				if(lottoForm.elements[sLottoPickID][0].checked){		
					iCounter++;
				}		
			for(var iBoxNum = 0; iBoxNum <= 5; iBoxNum++){	
				sNumber = eval("lottoForm.elements['board" + iBoardNum + ".boardNumbers[" + iBoxNum + "]" + "'].value");	
				
				if(sNumber != '') {
				iFound = true;
				}				
			}	
			if (iFound == true) {
					iCounter++;
				iFound = false;
				}			 
			}	
		
			if (iCounter != sDrawPlan){
				addToErrorLog("Please ensure you have entered numbers or Lotto Pick for the appropriate number of boards.");
				iCounter = 0;
			}	
		}		

	function checkPastExpiry() {
		var sDrawPlan = window.document.forms[0].elements["dateStatus"].value;
		if (sDrawPlan == "1") {
			alert("Please be advised, based on the date your current subscription expires, there will be an interruption to your subscription. " + 
					"To continue with your subscription press 'ok' and complete the LOTTO ADVANCE subscription form. " +
					"If you have any questions, please contact the Contact Centre at 1-800-387-0098.");
			}
			}		 
			
	
	function validateNumbers(gameName, theForm, minNum, maxNum, minVal, maxVal, allowDups) {
	var usedNums = new Array(10);
	var usedNumsCount = 0;
	var checkNums = true;
	var nonNumeric = false;
	var minValErr = false;
	var maxValErr = false;
	var repeatNumErr = false;

	for (x=0; x<maxNum; x++) {
		theField = eval('theForm.num' + (x+1));
		theField.value = Trim(theField.value);
		if(theField.value.length==0 || theField.value=='') {
			if(x < minNum);
			usedNums[x] = null;
		} else {
			usedNumsCount++;
			usedNums[x] = theField.value;
		}
	}
	
	if(minNum > usedNumsCount) checkNums=false;

	if(!checkNums) {
		alert('For ' + gameName + ' you need to enter at least '  + minNum + ' numbers.');
	} else {
		for(x=0; x<maxNum; x++) {
			if(usedNums[x]!=null && isNaN(usedNums[x])) {
				checkNums = false;
				nonNumeric = true;
			}
			if(usedNums[x]!=null && usedNums[x]<minVal) {
				checkNums = false;
				minValErr = true;
			}
			if(usedNums[x]!=null && usedNums[x]>maxVal) {
				checkNums = false;
				maxValErr = true;
			}
			if(!allowDups && usedNums[x]!=null) {
				for(y=0; y<maxNum; y++) {
					if(x!=y) {
						if(Number(usedNums[x])==Number(usedNums[y])) {
							checkNums = false;
							repeatNumErr = true;
						}
					}
				}
			}
		}
		if(!checkNums && nonNumeric) {
			alert('Please enter numeric values only.');
		} else if(!checkNums && minValErr) {
			alert('You cannot search for numbers lower than ' + minVal + ' in ' + gameName + '.');
		} else if(!checkNums && maxValErr) {
			alert('You cannot search for numbers higher than ' + maxVal + ' in ' + gameName + '.');
                
        } else if(!checkNums && repeatNumErr) {
			alert('You have entered the same number more than once.	');
		}
	}
	return checkNums
}

function validatePLNumbers(gameName, theForm, minNum, maxNum, minVal, maxVal, allowDups) {
  	var total=0;
	for(var i=0; i < document.PokerLottoForm.pokerLottoItems.length; i++){
	if(document.PokerLottoForm.pokerLottoItems[i].checked)
	total=total+1;
	}
	if(total=="" ||total<maxNum ||total> maxNum) 
    {
	 	alert('For ' + gameName + ' you need to select '  + minNum + ' cards.');
	 	return false; 
	}
	return true; 
} 

function validateRPSNumbers(gameName, theForm, minNum, maxNum, minVal, maxVal, allowDups) {
  	var total = 0;
	for (var i=0; i < document.RockPaperScissorsForm.elements.length; i++){
		if(document.RockPaperScissorsForm.elements[i].checked) {
			total = total + 1;
		}
	}
	if(total=="" || total < maxNum ||total > maxNum) {
	 		alert('For ' + gameName + ' you need to select '  + minNum + ' throws.');
	 		return false; 
	}
	return true; 
} 
function LTrim(str) {
	//modified to cut decimals AND spaces
	var whitespace = new String(". \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1) j++;
		s = s.substring(j, i);
	}
	return s;
}




function RTrim(str) {
	//modified to cut decimals AND spaces
	var whitespace = new String(". \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;       // Get length of string
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) i--;
		s = s.substring(0, i+1);
	}
	return s;
}

function Trim(str) {
	return RTrim(LTrim(str));
}


/** 
  Purpose: Performs a series of tests to validate Wizard page2, for both subscribe and renew 	
  Author:	Annie Liu	
 */ 
function validateContactForm(){
	
	        clearErrorLog();
			
		  	var contactForm = window.document.forms[0];
			var sElementName = new String();
			
			var sPersonPrefix = "";
			var  whichID='contactor';
			for(var iElementID = 0; iElementID < contactForm.elements.length; iElementID++){
				iPrefix = whichID.length;
				sElement = contactForm.elements[iElementID];	
				sElementName = sElement.name;				
				sPersonPrefix = sElementName.substr(0, iPrefix);

				if (sElementName.substr(iPrefix + 1, 'address.'.length) == 'address.') {
					iPrefix += 'address.'.length;
				}
				
				if((sPersonPrefix == whichID)){
					if 	(contactForm.elements[iElementID].value == '') {
                   	switch(sElementName.substr(iPrefix + 1, sElementName.length - iPrefix)){
						case "lastName":							
							addToErrorLog("Please enter the Last Name.");
							break;
						case "firstName":
							addToErrorLog("Please enter the First Name.");
							break;
						case "addressline1":
						   if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							  addToErrorLog("Please enter the Street Address.");
						    }	
							break;	
						case "city":
						   if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							 addToErrorLog("Please enter the City.");
							}
							break;
						case "province":
							if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							  addToErrorLog("Please enter the Province.");
							}
							break;	
						case "postalCode":
							if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							  addToErrorLog("Please enter the Postal Code.");
							}
							break;
						case "areaCode":
							if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							  addToErrorLog("Please enter the Area Code.");
							}
							break;
						case "exchange":
							if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							  addToErrorLog("Please enter the first 3 digits of the telephone number.");
							}
							break;
						case "number":
							if(document.forms[0].elements['category'].value=='lostStolenTicket'){
							  addToErrorLog("Please enter the last 4 digits of the  telephone number.");
							}
							break;
						case "emailAddress":
							addToErrorLog("Please enter the Email Address.");
							break;
						case "emailConfirm":
							addToErrorLog("Please confirm the Email Address.");
							break;
						}
					}
					else
					{
						switch(sElementName.substr(iPrefix + 1, sElementName.length - iPrefix)){
						case "lastName":
							checkAlpha("", "last name", sElement.value);
							break;
						case "firstName":
							checkAlpha("","first name", sElement.value);
							break;
						case "city":
							checkAlpha("", "city", sElement.value);
							break;
						/*case "province":
							checkAlpha("", "province", sElement.value);
							break;	*/
						/*case "postalCode":
							//checkCanadianPostal(sElement.value, "");
							checkPostalZipCode(sElement.value, contactForm.elements["contactor.address.country"].value);
							break;*/
						case "areaCode":
							if (sElement.value.length < 3) {
								addToErrorLog("The area code for the  telephone number does not appear to be in the correct format.");
								break;
							} else{
								checkNumeric("", "area code", sElement.value);					
								break;
							}
						case "exchange":
							if (sElement.value.length < 3){
								addToErrorLog("The first set of numbers in the telephone number does not appear to be in the correct format.");
								break;
							} else {
								checkNumeric("", "first set of numbers in the telephone number", sElement.value);
								break;
							}
						case "number":
							if (sElement.value.length < 4) {
								addToErrorLog("The second set of numbers in the telephone number does not appear to be in the correct format.");
								break;
							} else {
								checkNumeric('', "second set of numbers in the telephone number", sElement.value);
								break;
							}	
						case "extension":
							checkNumeric("", "telephone extension number", sElement.value);
							break;
						case "emailAddress":
							checkEmail(sElement.value, '');
							emailAddress = sElement.value;
							break;
						case "emailConfirm":
							if (sElement.value.toUpperCase() != emailAddress.toUpperCase()) {
								addToErrorLog("The email and confirmation email must match.");
							}
							break;
						}
					}
				}
			}	
				  
		   if(! document.forms[0].elements['contactor.over18'].checked){
				addToErrorLog("You must be 18 years or older.");
			}
			if(document.forms[0].elements['category'].value=='lostStolenTicket'){
			   
			    if(document.forms[0].elements['ticket.ticketType'].value==''){
			        addToErrorLog("Please enter the ticket type.");
			    }
			    var char_num =document.forms[0].elements['ticket.selectionsPlayed'].value.length;
			    if(char_num>200){ 
			        addToErrorLog("Selections Played limit to 200 characters.");
			    }
			    checkNumeric("", "Ticket cost dollar", Trim(document.forms[0].elements['ticket.dollars'].value));
			    checkNumeric("", "Ticket cost cents", Trim(document.forms[0].elements['ticket.cents'].value));
		 	    var char_num =document.forms[0].elements['ticket.addlInfo'].value.length;
			    if(char_num>2000){ //trim?
			        addToErrorLog("additional infomation limit to 2000 characters.");
			    }
			}else{
			    var char_num =document.forms[0].elements['contactText'].value.length;
			    if(char_num>2000){ //trim?
			        addToErrorLog("Suggestion/Question / Comment limite to 2000 characters.");
			    }
			}
			if(! isErrorLogEmpty()){
				alert(getErrorLog());
				clearErrorLog();
				return false;
			}	
			else 
			{
				return true;
			}
}
 
function gife_cert() {
    alert("GIFT CERTIFICATE WILL BE SENT TO YOU, THE\n PURCHASER.  The gift certificate must be redeemed \n within 365 days of the date of purchase, otherwise \n the subscription will automatically be activated in the \n name of the purchaser below who will be the subscriber.");
}

  function checkDate() {
		/** 
			Purpose:  Ensures that the Subscription Expiry Date entered
					 		adheres to the business rules
			Usage:     Used by the Subscription Renewal Form
			Author:	Patti DiSabatino
		*/
	
		// Get the day, month and year of expiry entered on form
		var lottoForm = window.document.forms[0];
		var sDay = lottoForm.subExpiryDay.value;
		var sStringMonth = lottoForm.subExpiryMonth.value;
		var iMonth = 0;
		var sYear = lottoForm.subExpiryYear.value;
		var monthNames = new Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
		
		// Only perform the check if all three fields are filled in
		if ((sDay != "-1")  && (sStringMonth != "-1")  && (sYear != "-1")) 
		{
			// Match the month
			for (var i = 0; i < monthNames.length; i++)
			{
				if (monthNames[i] == sStringMonth.toUpperCase())
					iMonth = i;
			}
			
			// Concatenate day, month, year into one date object
			var sExpiryDate = new Date(sYear, iMonth, sDay);			
			
			// Calculate the difference
			var today = new Date();
			var diff = sExpiryDate.getTime() - today.getTime();
			var milliSecondsInDay = 1000 * 60 * 60 * 24.0015;
			var subExpDate = Math.round(diff / milliSecondsInDay);
						
			// Is the subscription expiry date in the past and on a valid draw date?
			if (subExpDate < 0 && (sExpiryDate.getDay() == 3 || sExpiryDate.getDay() == 6)) {			
				document.forms[0].dateStatus.value="1";
						
			// Is the date within two weeks of expiry and on a valid draw date?
			} else if (subExpDate >= 0 && subExpDate <= 15 && (sExpiryDate.getDay() == 3 || sExpiryDate.getDay() == 6)) {
				//alert ("Please be advised, based on the date your current subscription expires, there will be an interruption to your subscription. " +
	   			//	"Please contact our Contact Centre at 1-800-387-0098 for further details.");
	   			//document.forms[0].dateStatus.value="";
	   		 	//clearDateFields();
	   		 	document.forms[0].dateStatus.value="1";
	   		 	
			} else if (sExpiryDate.getDay() != 3 && sExpiryDate.getDay() != 6)  {
				alert("This is not a valid expiry date."); 
				document.forms[0].dateStatus.value="";
				clearDateFields();
			} else {
				document.forms[0].dateStatus.value="";
			}
		}	
	}
	
