var supportedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' +
					 'ÂÄÀÁÃÅÇÉÊËÈÍÎÏÌÑÔÖÒÓÕÛÜÙÚÝÆâäàáãåçéêëèíîïìñôöòóõûüùúÿýæß¤°ªº' +
					 ' -|`¬!£$%^&*()_=+[{]};:\'@#~,<.>/?'

// CVS ID $Id: jdw_acctvalid.js,v 1.9.2.4 2004/11/04 14:07:50 paulcrisp Exp $
// CVS ID $Name:  $
// ==============================================================================
// This file requires global variables defined in messages.js files according to
// the language of the title, which correspond to the validation messages that
// pop up to the user.
// ==============================================================================

function checkAccountNumber(accountnumber) {
	if(arguments[1]=='forgot'){
		missingMsg = forgottenIncompleteDetails;
	} else {
		missingMsg = accountNumberlengthvalidationmsg;
	}
    // No account number entered
    if(isEmpty(accountnumber.value)){
    	window.alert(missingMsg);
    	accountnumber.focus();
        return false;
    } else if(accountnumber.value.length != 8) {
    // account number must be of the format 1 Character + 7 numbers
        window.alert(accountNumberValidationMsg);
        accountnumber.focus();
        return false;
    } else if (!charInString(accountnumber.value.charAt(0), lowercaseLetters + uppercaseLetters )) {
    // check first char is either upper or lower case letter
        window.alert(accountNumberValidationMsg);
        accountnumber.focus();
        return false;
    } else {
    // first char must be a letter so now check that the next seven chars are numbers
	    for (j=1; j< accountnumber.value.length; j++) {
	           x = accountnumber.value.charAt(j);
	           
	           if (!charInString(x, digits)) {
	              window.alert(accountNumberValidationMsg);
	              accountnumber.focus();
	              return false;
	           }
	    }
        
        return true;
    }
}

function checkTitle(customertitle) {
    
    if (isEmpty(customertitle.value))
    {
        window.alert(titleValidationMsg);
        return false;
    }
    else
    {
        return true;
    }
}

function checkFirstName(firstname) {
	var messages = checkFirstName.arguments; 
    
    if (!containsNoUnsupportedChars(firstname, "name")) {
		return false;
	}
	else if (isEmpty(firstname.value)) {
        
        window.alert(forenameValidationMsg);
        
        firstname.focus();
        return false;
    }
    else if (trimWhiteSpace(firstname.value).length < 2) {
    
    	window.alert(forenameLengthValidationMsg);
    
        firstname.focus();
        return false;
    }
    else {
		return true;
    }
}

function checkInitial(initial) {
	if (!containsNoUnsupportedChars(initial, "name")) {
		return false;
	} else {
		return true;
	}
}

function checkSurname(surname, showSurnameValidationMsg) {
    var messages = checkSurname.arguments;
    
    if (!containsNoUnsupportedChars(surname, "name")) {
		return false;
	}
	else if (isEmpty(surname.value)) {
		if (showSurnameValidationMsg){
			window.alert(surnameValidationMsg); 
		} else {
			window.alert(forgottenIncompleteDetails); 	   	        	
		}    	
        surname.focus();
        return false;
    }
    else if (trimWhiteSpace(surname.value).length < 2) {
    	window.alert(surnameLengthValidationMsg);
        surname.focus();
        return false;
    }
    else {
		return true;
    }
}

function checkDOB(required, inputDay, inputMonth, inputYear) {	
    if (required) {
        if ((inputYear == "") && (inputMonth == "") && (inputDay == "")) {
            window.alert(forgottenIncompleteDetails);
            return false;
        }
    }

    if (!required) {
        if ((inputYear == "") && (inputMonth == "") && (inputDay == "")) {
        	window.alert(dobReqMsg);
            return false;
        }
    }

    if (!isDate(inputYear, inputMonth, inputDay)) {
        if (required) {
            window.alert(dobValMsg1);
        } else {
            window.alert(dobValMsg2);
        }
        return false;
    }
    else
    {
        var intInputYear = parseInt(inputYear,10);
        var intInputMonth = parseInt(inputMonth,10);
        var intInputDay = parseInt(inputDay,10);
        var now = new Date();
        var intCurrYear = now.getFullYear();
        var intCurrMonth = now.getMonth() + 1;
        var intCurrDay = now.getDate();
        if ( intInputYear < 1890
            || intInputYear > intCurrYear
            || ((intInputYear == intCurrYear) && (intInputMonth > intCurrMonth) )
            || ((intInputYear == intCurrYear) && (intInputMonth == intCurrMonth) && (intInputDay > intCurrDay )))
        {
            window.alert(dobValMsg1);
            return false;
        }
        else
        {
            return true;
        }
    }
}


function checkHomePhone(phoneNumber) { 
    // remove any spaces in the field value for mobile phone number
    phoneNumber.value = phoneNumber.value.replace(/\s*/g,"");

    if ((phoneNumber.value.length > 0) && (phoneNumber.value.length < 10)) {
        window.alert(homeNumberShortValMsg);
        phoneNumber.focus();
        return false;
    } else if (phoneNumber.value.length > 11) {
    	window.alert(homeNumberLongValMsg);
        phoneNumber.focus();
        return false;
    } else if (!checkPhone(phoneNumber.value)) {
        window.alert(homeNumberInvalidValMsg);
        phoneNumber.focus();
        return false;
    }
    
    return true;
}

function checkPhoneNumberProvided(phoneNumberFields) {
	for ( i = 0 ; i < phoneNumberFields.length ; i++ ) {
	    if (!isEmpty(phoneNumberFields[i].value)) {
	        return true;
	    }
	}
	window.alert(noNumberGivenValMsg);
	phoneNumberFields[0].focus();
    return false;
}

function checkShortHomePhone(phoneNumber) { 
	return _checkHomePhone(phoneNumber, 9, arguments[1], arguments[2]); 
}

function _checkHomePhone(phoneNumber, len) {
    // remove any spaces in the field value for mobile phone number
    phoneNumber.value = phoneNumber.value.replace(/\s*/g,"");

    if ((phoneNumber.value.length > 0)
        && (phoneNumber.value.length < len)) {
        window.alert(homeNumberShortValMsg);
        phoneNumber.focus();
        return false;
    } else if (!checkPhone(phoneNumber.value)) {
        window.alert(homeNumberInvalidValMsg);
        phoneNumber.focus();
        return false;
    }
    
    return true;
}

function checkWorkPhone(phoneNumber) { 
	// remove any spaces in the field value for mobile phone number
    phoneNumber.value = phoneNumber.value.replace(/\s*/g,"");

    if ((phoneNumber.value.length > 0) && (phoneNumber.value.length < 10)) {
        window.alert(workNumberShortValMsg);
        phoneNumber.focus();
        return false;
    } else if (phoneNumber.value.length > 11) {
    	window.alert(workNumberLongValMsg);
        phoneNumber.focus();
        return false;
    } else if (!checkPhone(phoneNumber.value)) {
        window.alert(workNumberInvalidValMsg);
        phoneNumber.focus();
        return false;
    }
    
    return true;
}

function heckShortWorkPhone(phoneNumber) { return _checkWorkPhone(phoneNumber, 9); }

function _checkWorkPhone(phoneNumber, len) {	
	// remove any spaces in the field value for mobile phone number
    phoneNumber.value = phoneNumber.value.replace(/\s*/g,"");
    if ((phoneNumber.value.length > 0)
        && (phoneNumber.value.length < 11)) {
        window.alert(workNumberShortValMsg);
        phoneNumber.focus();
        return false;
    } else if (!checkPhone(phoneNumber.value)) {
        window.alert(workNumberInvalidValMsg);
        phoneNumber.focus();
        return false;
    }
    return true;
}

function checkMobilePhone(mobilenumber) {
    // remove any spaces in the field value for mobile phone number
    mobilenumber.value = mobilenumber.value.replace(/\s*/g,"");
    if ((mobilenumber.value.length > 0)
        && (mobilenumber.value.length != 11)) {
        window.alert(mobileValidationMsg);
        mobilenumber.focus();
        return false;
    } else if (!checkPhone(mobilenumber.value)) {
        window.alert(mobileValidationMsg);
        mobilenumber.focus();
        return false;
    }
    return true;
}

function checkEvent(event) {
    if(typeof event == "undefined") {
        return false;
    }
    
 	if ( typeof event[0] == "undefined" ) { // means it is a single event ie: not an array
		if (event.checked) {
			return true;
		} 
	} else {
	   //if at least one checkbox is checked we return true
	   for(var i=0; i<event.length; i++) {
	          if (event[i].checked) {
	             return true;
	          }
	   }   
   }
   //if no checkboxes were checked, flag an error
   window.alert(eventValidationMsg);
   return false;
}

function checkShortMobilePhone(mobilenumber)
{
    // remove any spaces in the field value for mobile phone number
    mobilenumber.value = mobilenumber.value.replace(/\s*/g,"");
    if ((mobilenumber.value.length > 0)
          && !((mobilenumber.value.length == 10) || (mobilenumber.value.length == 11)))
    {
        window.alert(mobileValidationMsg);
        mobilenumber.focus();
        return false;
    }
    else if (!checkPhone(mobilenumber.value))
    {
        window.alert(mobileValidationMsg);
        mobilenumber.focus();
        return false;
    }
    return true;
}

function checkPostcodeEntered(postcode) {
	if (isEmpty(stripWhitespace(postcode.value))) {
        window.alert(forgottenIncompleteDetails);
        postcode.focus();
        return false;
    }
    
    return true;
}

function checkSinglePostcode(postcode, page, firstorder, addressType)
{	if (!postcode.value || isEmpty(stripWhitespace(postcode.value))) { 
        window.alert(forgottenIncompleteDetails);
        postcode.focus();
        return false;
    } else if (stripWhitespace(postcode.value.toUpperCase()) == "M606ES") {
          // We are not allowed to register Lever St as a primary address.
        if ((addressType == null && page == null) ||
            ((addressType == "primary") && 
            ((page.value == "address") || 
            (page.value == "oldaddress") || 
            (page.value == "accountaddressbookamend") || 
            (page.value == "existingcustomerreg")))) {
            window.alert(postcodePrimaryProhibitedMsg);
            postcode.focus();
            return false;
        } else if((page.value == "accountaddressbooknew" || 
        		   page.value == "accountaddressbookmanual") && 
        		   (firstorder != null && firstorder.value == "false")) {
        	// We are not allowed to have Lever St as a secondary address until we have placed our first order.
            window.alert(postcodeSecondaryProhibitedMsg);
            postcode.focus();
            return false;
        }
        
        return true;
    } else {
        return true;
    }
}

function checkHousePostcode(housenumber, postcode, page, firstorder) {
	if (isEmpty(stripWhitespace(housenumber.value))) {
        window.alert(enterHouseNumberMsg);
        housenumber.focus();
        return false;
    }

    postcode.value = postcode.value.toUpperCase();
    return true;
}

function checkAddress(housenumber, town, postcode) {
	if (isEmpty(stripWhitespace(housenumber.value)))
    {
        window.alert(enterHouseNumberMsg);
        housenumber.focus();
        return false;
    } else if (isEmpty(stripWhitespace(town.value))) {
        window.alert(enterTownMsg);
        town.focus();
        return false;
    } else if (isEmpty(stripWhitespace(postcode.value))) {
        window.alert(postcodeValidationMsg);
        postcode.focus();
        return false;
    } else {
        postcode.value = postcode.value.toUpperCase();
        return true;
    }
}

function checkTimeAtAddress(addressYears, addressMonths) {
    if ((isEmpty(addressYears.value) && isEmpty(addressMonths.value)) ||
         (addressYears.value == 0) && (addressMonths.value == 0)) {
        window.alert(emptyTimeAtAddrMsg);
        addressYears.focus();
        return false;
    }
    else if (addressMonths.value > 11) {
        window.alert(timeYearsMonthsMsg);
        addressYears.focus();
        return false;
    } else {
        ya = addressYears.value;
        for (j=0; j<ya.length; j++) {
           x = ya.charAt(j);
           if (!charInString(x, digits)) {
              window.alert(invalidCharsYearsMsg);
              addressYears.focus();
              return false;
           }
        }
        ma = addressMonths.value;
        for (j=0; j<ma.length; j++) {
           x = ma.charAt(j);
           if (!charInString(x, digits)) {
              window.alert(invalidCharsMonthsMsg);
              addressMonths.focus();
              return false;
           }
        }
        return true;
    }
}

function checkEmail(email)
{
    var tEmail = trimWhiteSpace(email.value);
	if (!tEmail || isEmpty(tEmail)) {
       alert(forgottenIncompleteDetails);
       email.focus();
       return false;
    } else {
        return ValidateEmail(tEmail, checkEmail.arguments[1]);
    }
}

function check2Email(email,email2) {
    var tEmail = trimWhiteSpace(email.value);
    var tEmail2 = trimWhiteSpace(email2.value);
    if (isEmpty(tEmail)){
       alert(emailValidationMessage);
       email.focus();
       return false;
    } else if(!ValidateEmail(tEmail)){
        email.focus();
        return false;
    } else if (tEmail != tEmail2){
        window.alert(noMatchEmailValidationMessage);
        email.focus();
        return false;
    } else {
    	return true;
    }
}

function checkPassword(password, validatedPassword, invalidCharsMsg) {
    if (isEmpty(password.value)) {
        window.alert(enterPasswordValMsg);
        password.focus();
        return false;
    } else if (password.value.length < 6 || password.value.length > 20) {
        window.alert(passwordInvalidLengthMsg);
        password.focus();
        return false;
    } else if (password.value != validatedPassword.value) {
        window.alert(passwordsDontMatchMsg);
        password.focus();
        return false;
    } else if (password.value.toUpperCase() == 'PASSWORD') {
        window.alert(passwordNotPassword);
        password.focus();
        return false;
    } else if (indexOfIllegalChars(password.value,supportedChars) > -1) {
        window.alert(passwordInvalidCharsMsg);
        password.focus();
        return false;        
    }
    return true;
}

function checkSinglePassword(password) {
    if(arguments[1]==='forgot'){
    	message = forgottenIncompleteDetails;
    } else {
    	message = enterPasswordValMsg;
    }
    
    if (isEmpty(password.value))
    {
        window.alert(message);
        return false;
    } else {
        return true;
    }
}

function checkID(customerservicesId)
{
    if (isEmpty(customerservicesId.value)) {
        window.alert(emptyIdValMsg);
        customerservicesId.focus();
        return false;
    } else {
        for (j=0; j< customerservicesId.value.length; j++) {
           x = customerservicesId.value.charAt(j);
           if (!charInString(x, validAcctRefChars)) {
              window.alert(invalidIdValMsg);
              customerservicesId.focus();
              return false;
           }
        }
        return true;
    }
}


//This is for entering a new address
function checkAddressDetails(description, deliveryName) {	
	var doSubmit = true;
    
    if (isEmpty(description.value)) {
        doSubmit = false;
        alert(noAddressDescriptionMsg);
        description.focus();
    }

     if ((doSubmit) && (isEmpty(deliveryName.value))) {
         doSubmit = false;
         alert(noDeliveryNameMsg);
         deliveryName.focus();
     }
     
     if ((doSubmit) && !(validCharsForDeliveryname(deliveryName.value)))
     {
     	 doSubmit = false;
     	 alert("Invalid characters in Delivery name.");
     	 deliveryName.focus();
     	    
     }

    return doSubmit;
}

function ValidateEmail(eMail) {		
    errorStr = '';
    illegal = illegalChars(eMail, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.&@_-1234567890\'');
    if (illegal == true) {
        errorStr += emailValidationMessage;
     } else {
        if (eMail.length < 7 || eMail.length > 250) { errorStr = emailValidationMessage; }
        if (eMail.charAt(0) == '@') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(0) == '.') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(0) == '-') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(0) == '_') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(eMail.length-1) == '@') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(eMail.length-1) == '.') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(eMail.length-1) == '-') { errorStr = emailValidationMessage;  }
        if (eMail.charAt(eMail.length-1) == '_') { errorStr = emailValidationMessage;  }
        if (eMail.indexOf('@') == -1) { errorStr = emailValidationMessage; }
        if (eMail.indexOf('.') == -1) { errorStr = emailValidationMessage;  }
        if (eMail.indexOf('@.') > -1) { errorStr = emailValidationMessage;  }

        var count = 0;
        var atcount = 0;
        for (count = 0; count <= eMail.length; count++) {
            if (eMail.charAt(count) == "@") {
                atcount = atcount + 1;
            }
        }
        if (atcount >= 2) { errorStr = emailValidationMessage; }
    }

    if (errorStr != null && errorStr.length > 2) {
        alert(errorStr);
        return false;
    } else {
        return true;
    }
}

function checkCountry(country) {
	// A country must be specified
	if (!country.value || isEmpty(stripWhitespace(country.value))) {
        window.alert(countryValidationMsg);
        country.focus();
        return false;
    } else {
        return true;
    }
}

function checkInternationalAddress(address1, address2, address3, postcode, town, townLabel, confirmation) {
   	// Address 1 must only contain allowed characters
    if ( !containsNoUnsupportedChars(address1, "address") ) {
    	return false;
    }
	// Address1 must be a minimum of two characters
	if (isEmpty(stripWhitespace(address1.value)) || (address1.value.length < 2)) {
		window.alert(address1ValidationMsg);
		address1.focus();
	    return false;
	}
	// Address 2 and Address 3 must only contain allowed characters
	if ( !containsNoUnsupportedChars(address2, "address" ) ||
	        	!containsNoUnsupportedChars(address3, "address") ) {
	    return false;
	}
	// Postcode must only contain allowed characters
	if ( !containsNoUnsupportedChars(postcode, "address") ) {
		return false;
	}
	// Postcode must be a minimum of one character
	if ( isEmpty(stripWhitespace(postcode.value)) || (postcode.value.length < 1)) {
		window.alert(postcodeZipcodeValidationMsg);
		postcode.focus();
		return false;
	}
	// Town must only contain allowed characters
	if ( !containsNoUnsupportedChars(town, "address") ) {
		return false;
	}
	// Town must be a minimum of two characters
	if ( isEmpty(stripWhitespace(town.value)) || (town.value.length < 2) ) {
		var validationMsg = townValidationMsg.replace("<>", townLabel);
		window.alert(validationMsg);
		town.focus();
		return false;
	}
	// The user must have confirmed the address details
	if ( confirmation.checked == false ) {
		window.alert(addressConfirmationMsg);
		confirmation.focus();
		return false;
	}
	return true;
}

function checkContactPhone(phoneNumber) {
    // remove any spaces in the field value for mobile phone number
    phoneNumber.value = phoneNumber.value.replace(/\s*/g,"");

    if (phoneNumber.value.length < 9) {
        window.alert(contactNumberShortValMsg);
        phoneNumber.focus();
        return false;
    } else if (!checkPhone(phoneNumber.value)) {
        window.alert(contactNumberInvalidValMsg);
        phoneNumber.focus();
        return false;
    }

    return true;
}

function containsNoUnsupportedChars(textField, textLabel) {
	illegalCharIndex = indexOfIllegalChars(textField.value,supportedChars);
	
	if (illegalCharIndex != -1) {
		var validationMsg = illegalCharacterMsg.replace("<>", textLabel);
		validationMsg = validationMsg.replace("<>", textField.value.charAt(illegalCharIndex));
		window.alert(validationMsg);
		textField.focus();
		return false;
	}
	return true;
}
