/*
 * validate.js - Javascript validation functions
 */


// validates that the field does not conatin digits
// i.e. the validation fails if the field contains digits
function validateNoDigits(validationIndex) {

    // fail if the field contains digits
    if (/[0-9]/.test(theForm[validation[validationIndex][0]].value)) {
    
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    return null;
}



// Validate the contents of an optional field from the rules
// matching the specific field type. If the field is empty,
// the validation passes. If not, the validation is passed
// on to the relevant validation function:
//    type          validation function
//    ----------    -------------------
//    "number"      validateNumber
//
function validateOptionalField(validationIndex, type) {

    if(theForm[validation[validationIndex][0]].value.trim() == "") {
        return null
    }
    else {
        if (type == "number") {
            if (validateNumber(validationIndex) != null ) {
                setErrorText(validation[validationIndex][0]);
                return validation[validationIndex][1];
            }
        }
    }
}

// Validate the field as a mandatory value, i.e. the function
// requires that the field is non-empty.
function validateTextField(validationIndex) {

    if(theForm[validation[validationIndex][0]].value !== undefined)
    {
        if (theForm[validation[validationIndex][0]].value.trim() == "") {
        
            setErrorText(validation[validationIndex][0]);
            return validation[validationIndex][1];
        }
    }
    else
    {
        var validateObject = document.getElementsByName(validation[validationIndex][0]);
        var validateLength = validateObject.length;
        var validateFound = false;
        for(var validateCount = 0;validateCount < validateLength;validateCount++)
        {
            if(validateObject[validateCount].checked)
                validateFound = true;
        }
        if(validateFound == false)
            return validation[validationIndex][1];
    }
    return null;
}

/*
function valButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}
*/

// Validate the field as a mandatory value, i.e. the function
// requires that the field is non-empty.
function validateCCNumberLength(validationIndex) {

var re9digit=/^\d{16}$/ ; //regular expression defining a 9 digit Order number
var fieldValue = theForm[validation[validationIndex][0]].value;
if (!fieldValue.match(re9digit)) 
 {
  setErrorText(validation[validationIndex][0]);
  return validation[validationIndex][1];
 }
 return null;
}



// Validate the field contains characters from the lower part
// of ISO8859 (i.e. only characters common to all of the 
// ISO-8859-x character set): 0x20-0x7E
function validateISO8859(validationIndex) {

    if (!/^[ -~\xa1-\xff]*$/.test(theForm[validation[validationIndex][0]].value)) {

        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    return null;
}

// 
function validateOneFieldNotEmpty(validationIndex) {

    var atLeastOneFilled = false;
    
    for (var i = 1; i < arguments.length; i++) {
    
        if (isFieldFilled(arguments[i]) != "") {
            atLeastOneFilled = true;
        }
    
    }
    
    if (!atLeastOneFilled) {
        
        // set error condition
        for (var i = 1; i < arguments.length; i++) {
            setErrorText(arguments[i]);
        }
        
        return validation[validationIndex][1];
    }
    else {
        
        // clear error condition
        for (var i = 1; i < arguments.length; i++) {
            //setErrorText(arguments[i], true);
        }
        
        return null;
    }
}

//Validates the OrderId filed in the pay order Form
//KPIA - Nov 20- 2009
function validateOrderField(validationIndex){
var re9digit=/^\d{9}$/ ; //regular expression defining a 9 digit Order number
var fieldValue = theForm[validation[validationIndex][0]].value;
if (!fieldValue.match(re9digit)) 
 {
  setErrorText(validation[validationIndex][0]);
  return validation[validationIndex][1];
 }
 return null;
}

//Validates the additional identifier (name) in the payorder form
function validateAdditionalIdentifierField(validationIndex) {
    var stringRegExp = "^[ -~\u00a1-\u00ff]{1,60}$";
    var re9digit=/^\d{1,60}$/ ; //regular expression defining a 9 digit Order number
    
    var fieldValue = theForm[validation[validationIndex][0]].value;
    
    if (!fieldValue.match(stringRegExp)){
        setErrorText(validation[validationIndex][0]);
    return validation[validationIndex][1];
    }
    
  return null;
}

function validateCVV2Field(validationIndex){
var re9digit=/^\d{3}$/ ; //regular expression defining a 9 digit Order number
var fieldValue = theForm[validation[validationIndex][0]].value;
if (!fieldValue.match(re9digit)) 
 {
  setErrorText(validation[validationIndex][0]);
  return validation[validationIndex][1];
 }
 return null;
}



// Validate the field as a password.
// Checks that the field is at least six characters in length
// and that the field contains at least one digit and one letter (a-z).
function validatePasswordField(validationIndex) {

    if (theForm[validation[validationIndex][0]].value == "") {
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    if (theForm[validation[validationIndex][0]].value.length < 6) {
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    var tmp = theForm[validation[validationIndex][0]].value;
    //check that the password contains digits and letters
    if ((/\d/.test(tmp) == false) ||
        ( /\D/.test(tmp) == false)){
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    return null;
}

// Returns whether the field length is within the specified 
// interval.
function isFieldLengthWithinLimits(validationIndex, min, max) {
    
    var fieldValue = theForm[validation[validationIndex][0]].value;
    if ((fieldValue.length >= min ) && (fieldValue.length <= max )){
        return true;
    }
    return false;
}

// Validate as a number, using the isANumber function.
// Note that this function accepts empty fields!
// Combine with validateTextField to check for empty fields.
function validateNumber(validationIndex) {

    var fieldValue = theForm[validation[validationIndex][0]].value;

    if ( !isANumber( fieldValue ) ) {
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }

    return null;
}

// Validate the field as an e-mail using the isEmail function.
function validateEmail(validationIndex) {

    if ( !isEmail( theForm[validation[validationIndex][0]].value ) ) {
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    return null;
}

// Validate the field as an e-mail and check that the value is
// the same as the value in the field by the name fieldToValidateAgainst.
// This function is deprecated. Instead, use two separate validation
// rules in the validation array (use validateEmail, followed by 
// duplicateTextField).
function duplicateEmail(validationIndex, fieldToValidateAgainst) {

    var otherFieldValue = theForm[fieldToValidateAgainst].value;
    var thisFieldValue = theForm[validation[validationIndex][0]].value;
    
    if ( !isEmail( thisFieldValue ) || otherFieldValue != thisFieldValue ) {
        
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }
    
    return null;
}

// Validate that the field is equal to the field by the name fieldToValidateAgainst.
function duplicateTextField(validationIndex, fieldToValidateAgainst) {

    var otherFieldValue = theForm[fieldToValidateAgainst].value;
    var thisFieldValue = theForm[validation[validationIndex][0]].value;

    if (otherFieldValue != thisFieldValue) {
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }

    return null;
}

// Validate that the field is checked, assuming that the field
// is a check box.
function validateCheckbox(validationIndex) {

    if ( !theForm[validation[validationIndex][0]].checked ) {

        checkBoxName = validation[validationIndex][0] + "_text";
        checkBoxField = document.getElementById(checkBoxName);
        checkBoxField.className = "errorFormCheckBox";

        return validation[validationIndex][1];
    }

    return null;
}

// Validates the field as a numeric field, allowing one dash (-)
// This functions is probably (or rather hopefully) not used, 
// as localised versions are defined in <locale>/js/IrwAddress.js.
function validateZipCode(validationIndex) {

    var fieldValue = theForm[validation[validationIndex][0]].value;

    var tempVal = fieldValue.substring(0,fieldValue.indexOf('-')) + fieldValue.substring(fieldValue.indexOf('-')+1, fieldValue.length);

    if ( fieldValue == "" || !isANumber( tempVal ) ) {
        setErrorText(validation[validationIndex][0]);
        return validation[validationIndex][1];
    }

    return null;
}


// checks to see if the field with the specified ID has been filled
// used especially to check for date fields

//  TOTM  updated - dated may 12-2009  -- added a NULL check
function isFieldFilled(fieldID) {

    // ugly workaround for handling the various date fields
    if (fieldID == 'cardExpiryDate') {
        return isFieldFilled('cardExpiryYear') && isFieldFilled('cardExpiryMonth');
    }
    else if (fieldID == 'cardStartDate') {
        return isFieldFilled('cardStartDateYear') && isFieldFilled('cardStartDateMonth');
    }
    else if (fieldID == 'cardBirthDate') {
        return isFieldFilled('cardBirthDateYear') && isFieldFilled('cardBirthDateMonth') && isFieldFilled('cardBirthDateDay');
    }
    else {
    if(document.getElementById(fieldID)!=null){
        if (document.getElementById(fieldID).type == 'select-one'){
            return document.getElementById(fieldID) && document.getElementById(fieldID).options[document.getElementById(fieldID).selectedIndex].text != "";
        }
        return document.getElementById(fieldID) && document.getElementById(fieldID).value;
    }
    }
}



// Changes the CSS class of the HTML element with the ID
// "<fieldID>_text" to "errorFormText" and the CSS class
// of the element with ID "<fieldID>" to "errorFormBox".
function setErrorText(fieldID, clearError) {

    // ugly workaround for handling the various date fields
    if (fieldID == 'cardExpiryDate') {
        setErrorText('cardExpiryYear', clearError);
        setErrorText('cardExpiryMonth', clearError);
    }
    else if (fieldID == 'cardStartDate') {
        setErrorText('cardStartDateYear', clearError);
        setErrorText('cardStartDateMonth', clearError);
    }
    else if (fieldID == 'cardBirthDate') {
        setErrorText('cardBirthDateYear', clearError);
        setErrorText('cardBirthDateMonth', clearError);
        setErrorText('cardBirthDateDay', clearError);
    }
    
    textFieldName = fieldID + "_text";
    theTextField = document.getElementById(textFieldName);
    theField = document.getElementById(fieldID);
    
    if (theTextField) theTextField.className = "errorFormText";
    if (theField) theField.className = "errorFormBox";
}


// Reset the CSS classes for all validation form fields
// and remove the error text from the error div.
function resetClasses() {

    var theField = "";
    var theTextField = "";
    
    var theDiv = document.getElementById(tierName);
    
    // reset all form fields in all forms
    for (var formNum=0; formNum < document.forms.length; formNum++) {
        
        for (var fieldNum=0; fieldNum < document.forms[formNum].elements.length; fieldNum++) {
            
            if (document.forms[formNum].elements[fieldNum].className == 'errorFormBox') {
                document.forms[formNum].elements[fieldNum].className = '';
            }
        }
    }
    
    // reset all form text prompts
    for (var i = 0; i < validation.length; i++) {
    
        var testField = document.getElementById(validation[i][0]+'_text');
        if (testField && testField.className == 'errorFormText') {
            testField.className = 'formText';
        }
    }
    
    theDiv.innerHTML = "";
    theDiv.className = "errorTierOff";
}


// locate and return the index of the specified field
// in the validation array
function indexOfValidationField(field) {
    for (var i=0; i<validation.length; i++) {
        if (validation[i][0] == field) {
            return i;
        }
    }
}

// Returns whether the parameter is a digit
function isDigit (c) {
    return ((c >= "0") && (c <= "9"))
}

// Returns whether the parameter is numeric.
// Note that in this context, empty strings are considered numeric
function isANumber (s) {
    // accept only zero or more digits
    return /^\d*$/.test(s);
}

// Returns whether the parameter is an e-mail using a
// rather simplistic test (must have at most one "@"
// with at least one character before, at least one dot,
// and at least one character before and after the dot.
function isEmail (s) {
    return /^[^@]+@[^@]+\.[^@]+$/.test(s);
}

// function commits any form that doesn't need validation
function submitForm(form) {
    theForm = document.forms[form];
    theForm.submit();
}


// trim all leading and trailing whitespace from the parameter
function trimAllWhitespaces(str) {
    // group any non-whitespace characters within the string
    // and extract and return that group
    return /^\s*(\S*)\s*$/.exec(str)[1];
}


// some global validation parameters (UGH!)
var theForm = null;
var validation = new Array();

var tierName;
var formName;


// perform validation on the specified form
// if the form validates, it will be submitted
// returns false if validation fails (this allows
// the function to be used as the onclick handler
// of a submit button)
//
// Somebody please clean up this function. PLEASE!
function validate(form) {

    var errorMessage = "";
    
    tierName  = form + "ErrorTier";
    formName = form;
    
    var theDiv = document.getElementById(tierName);
    var billingHeader = false;
    var shippingHeader = false;
    var useBillingAsShipping = false;
    
    theForm = document.forms[formName];
    
    validation = eval(theForm);

    resetClasses();
    
    if (theForm.validationMode != null) {
        setAddressControlVariables();
    }
    
    // check if there is a field called shipToBillAddr in the form
    // if so, read the value from this to decide to use billing address as
    // shipping address
    if (theForm.shipToBillAddr != null ) {
        useBillingAsShipping = theForm.shipToBillAddr.checked;
    }
    
    for (var i=0; i<validation.length; i++)
    {
        // if the fieldname defined in the validation array doesn't exist
        // in the form, skip it

        if ((!document.getElementById(validation[i][0]+"_field")) && (!document.getElementById(validation[i][0]+"_text"))) {
            continue;
        }

        // if billingaddress is to be used as shipping then validate
        // the billing address using both shipping and billing address
        // validators. This is done by copying the value from the billing
        // address field (if it exists)
        if (useBillingAsShipping) {
            
            var fieldName = validation[i][0];
            if(fieldName.substring(0,5) == 'ship_') {
                var billingFieldName = fieldName.substring(5);
                if (theForm[billingFieldName]) {
                    theForm[fieldName].value = theForm[billingFieldName].value;
                }
            }
        }
        
        // if the function to call exists (index 2), call it
        if (validation[i][2]) {
        
            var argumentList = new Array();
            
            // create the argument list to pass to apply
            argumentList.push(i);
            for (var j=0; j< validation[i][3].length; j++) {
                argumentList.push(validation[i][3][j]);
            }
            
            // call the function
            functionReturn = eval(validation[i][2]).apply(this, argumentList);
            
            if (functionReturn) {

                                //
                                // Set focus on the first form field only.
                                //
                                if (errorMessage == "")
                                {
                                    focusField = document.getElementById(validation[i][0]);
                                    if (focusField) {
                                        focusField.focus();
                                    }
                                }

                theBillingIndex = indexOfValidationField("shipToBillAddr");
                
                if (theBillingIndex < i && !billingHeader ) {
                    errorMessage += "<h1>" + js_fn_shipping_address + "</h1>";
                    billingHeader = true;
                }
                else if ((theBillingIndex >= i) && !shippingHeader) {
                    errorMessage += "<h1>" + js_fn_billing_address + "</h1>";
                    shippingHeader = true;
                }
                else if ( indexOfValidationField("termsAndConditions") == i) {
                    errorMessage += "<h1>" + js_fn_privacy_policy + "</h1>";
                }
                
                errorMessage += "<li>" + functionReturn + "</li>";
            }
        }
    }

    if (errorMessage !== "") {
        
            if(form=='login'){
                theDiv.innerHTML = errorMessage;
                theDiv.className = "welcomeErrorTierOn";
            }else{
           
                    theDiv.innerHTML = errorMessage;
                    theDiv.className = "errorTierOn";
            }
        // allow this function to be used in the onclick handler of a submit button...
        return false;
    }
    else {
        theDiv.className = "errorTierOff";
        
        if(formName === 'signup') {
            copyVariables(theForm);
            if (typeof(validateJurisdictionFields) === "function") {
                validateJurisdictionFields();
            }
        }
        
        // we cannot assume that this function is used in the onclick handler of a submit button, so submit the form manually...
        //theForm.submit();
        
        return true;
    }
}


/**
 * Add a trim method to the String class.
 * Use regexp "\S.*\S|\S". This will return null if the input
 * string is empty or consists only of whitespaces, or an array
 * with the matching string (the trimmed string) otherwise.
 */
String.prototype.trim = function() {
    var s = this.match(/\S.*\S|\S/);
    return (s==null) ? "" : s[0];
}

/**
 * This function validates check out login page.
 */
function respondToCheckOutLogin(e) {
    irwstatSetTrailingTag('IRWStats.pageFunctionality', 'logon in checkout');
    if(!validate('login')) {
        return false;
    }
    document.login.submit();
}

/**
 * This function handles the submission of the form on
 * payorder when the user uses the enterkey to submit
 * the form.
 */

function submitEnter(e) {
    "use strict";
    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    } else if (e) {
        keycode = e.which;
    } else {
        return true;
    }
    if (keycode === Event.KEY_RETURN) {
        if (validate('distrOrderIdInputForm')) {
            //document.distrOrderIdInputForm.submit();
            toggleLiteBox();
        }
        return false;
    } else {
        return true;
    }
}
