/* This following functions make sure all of the fields are filled out properly in the
    passed-in form. If not, it displays an appropriate error message in the 'errorMsg' DIV
    of the calling page.
*/

// function to validate the fields on the login page
function validateLogin(currentForm){

	var msg = "";
	// check the required fields
    msg += getFieldTest("login", currentForm.userName.value);
    msg += getFieldTest("login password", currentForm.userPassword.value);

	if (msg != ""){
    	msg = "<ul>" + msg + "</ul>"
		writeErrorMsg(msg);
		return false;
	} else {
		return true;
	}
}

function validateRegistration(currentForm){

	var msg = "";
	var textRegEx = /^[A-Za-z0-9 ]+$/;
	var textOptionalRegEx = /^[A-Za-z0-9 ]*$/;

	// check the required fields
    msg += getFieldTest("first name", currentForm.fname.value);
    msg += getFieldTest("last name", currentForm.lname.value);
    msg += getFieldTest("address 1", currentForm.address1.value);
    msg += getFieldTest("city", currentForm.city.value);

    if (currentForm.country.selectedIndex > 0){
        if (currentForm.country.options[currentForm.country.selectedIndex].text == "UNITED STATES"){
            if (currentForm.state.selectedIndex <= 0){
                msg += "<li>You must select a state from the drop down.</li>";
            }
            msg += getFieldTest("postal code", currentForm.zip.value);
        }
    } else {
        msg += "<li>You must select a country from the drop down.</li>";
    }

    if (currentForm.country.options[currentForm.country.selectedIndex].text == "UNITED STATES" || currentForm.country.options[currentForm.country.selectedIndex].text == "CANADA"){
        msg += getFieldTest("phone", currentForm.phone.value);
        if (!isBlank(currentForm.fax.value)){
            msg += getFieldTest("fax number", currentForm.fax.value);
        }
    } else {
        if (isBlank(currentForm.phone.value)){
            msg += "<li>You must enter your phone number</li>";
        }
    }

    msg += getFieldTest("email address", currentForm.email.value);
    msg += getFieldTest("user name", currentForm.userName.value);
    msg += getFieldTest("password", currentForm.password.value);
    msg += getFieldTest("confirming password", currentForm.confirmPassword.value);
    if (currentForm.industryType.selectedIndex <= 0){
        msg += "<li>You must select an industry type from the drop down.</li>";
    }

    if (currentForm.password.value != currentForm.confirmPassword.value){
        msg += "<li>Your password and confirming password do not match, please reenter them</li>"
    }

    if (!textOptionalRegEx.test(currentForm.address2.value) || !textOptionalRegEx.test(currentForm.company.value)){
        msg += "<li>Company and Address 2 are not required.  However if filled in they may contain only letters, digits, and spaces.</li>";
    }

	if (msg != ""){
    	msg = "<ul>" + msg + "</ul>"
		writeErrorMsg(msg);
	} else {
	    document.registerform.submit();
	}
}



function validateProfileUpdate(currentForm){

	var msg = "";

	// check the required fields
    msg += getFieldTest("first name", currentForm.fname.value);
    msg += getFieldTest("last name", currentForm.lname.value);
    msg += getFieldTest("address 1", currentForm.address1.value);
    msg += getFieldTest("city", currentForm.city.value);

    if (currentForm.country.selectedIndex > 0){
        if (currentForm.country.options[currentForm.country.selectedIndex].text == "UNITED STATES"){
            if (currentForm.state.selectedIndex <= 0){
                msg += "<li>You must select a state from the drop down.</li>";
            }
            msg += getFieldTest("postal code", currentForm.zip.value);
        }
    } else {
        msg += "<li>You must select a country from the drop down.</li>";
    }

    if (currentForm.country.options[currentForm.country.selectedIndex].text == "UNITED STATES" || currentForm.country.options[currentForm.country.selectedIndex].text == "CANADA"){
        msg += getFieldTest("phone", currentForm.phone.value);
        if (!isBlank(currentForm.fax.value)){
            msg += getFieldTest("fax number", currentForm.fax.value);
        }
    } else {
        if (isBlank(currentForm.phone.value)){
            msg += "<li>You must enter your phone number</li>";
        }
    }

    msg += getFieldTest("email address", currentForm.email.value);
    msg += getFieldTest("user name", currentForm.userName.value);
    msg += getFieldTest("password", currentForm.password.value);
    msg += getFieldTest("confirming password", currentForm.confirmPassword.value);

    if (currentForm.password.value != currentForm.confirmPassword.value){
        msg += "<li>Your password and confirming password do not match, please reenter them</li>"
    }

    // validate CC info
    var ccMsg = ""
    if (!currentForm.ccType[4].checked){
        // only check the cc num if it has changed - or the * will cause a validation error
        if (currentForm.isccNumChanged.value == "yes"){
            ccMsg += getFieldTest("credit card number", currentForm.ccNumber.value);
        }
        ccMsg += getFieldTest("expiration date", currentForm.expDate.value);
        // if the exp date is a valid format check to make sure it isn't expired
        if (getFieldTest("expiration date", currentForm.expDate.value) == ""){
            var mm = currentForm.expDate.value.substr(0,2);
            var yy = currentForm.expDate.value.substr(2,2);
            var currYear = String(new Date().getFullYear());
            currYear = currYear.substr(2,2);
            var currMonth = String(new Date().getMonth());
            if (currMonth.length == 1)
                currMonth = "0" + currMonth;
            var newExpDate = yy + "" + mm;
            var newCurrDate = currYear + "" + currMonth;
            if (newExpDate < newCurrDate){
                ccMsg += "<li>Your credit card has expired, please check the date or enter a new card.</li>";
            }
        }
        if (isBlank(currentForm.ccNumber.value) && isBlank(currentForm.expDate.value)){
            ccMsg += "<li>If you do not wish to save credit card information, select the select the \"No Credit Card\" Card Type option.</li>";
        }
    } else {
        // only check the cc num if it has changed - or the * will cause a validation error
        if (currentForm.isccNumChanged.value == "yes"){
            ccMsg += getFieldTest("credit card number", currentForm.ccNumber.value);
        }
        ccMsg += getFieldTest("expiration date", currentForm.expDate.value);
        if (!isBlank(currentForm.ccNumber.value) || !isBlank(currentForm.expDate.value)){
            ccMsg += "<li>You must select a card type other than \"No Credit Card\".</li>";
        } else {
            ccMsg = "";
        }
    }

    msg += ccMsg;
	if (msg != ""){
    	msg = "<ul>" + msg + "</ul>"
		writeErrorMsg(msg);
		return false;
	} else {
		return true;
	}
}

// shipping info validator

function shipAddressVerify(currentForm){

	var msg = "";

	// check the required fields
	msg += getFieldTest("shipping name", currentForm.shipName.value);
	msg += getFieldTest("address 1", currentForm.address1.value);
	msg += getFieldTest("city", currentForm.city.value);
	msg += getFieldTest("zip code", currentForm.zip.value);
    msg += getFieldTest("e-mail", currentForm.email.value);

    var currCountry = currentForm.country.options[currentForm.country.selectedIndex].value;

    if (currCountry == "UNITED STATES" || currCountry == "CANANDA" || currCountry == "MEXICO") {
        if (currentForm.state.selectedIndex < 0){
            msg += "<li>Please select a state from the list.</li>";
        }
    }

    if (currentForm.country.selectedIndex <= 0){
        msg += "<li>Please select a country from the list.</li>";
    }

    if (currentForm.selectedShipMethod.value == undefined || currentForm.selectedShipMethod.value == ""){
    	msg += "<li>Please select a shipping method.</li>";
	}


	if (msg != ""){
    	msg = "<ul>" + msg + "</ul>"
		writeErrorMsg(msg);
		return false;
	} else {
		return true;
	}
}

/* function takes the passed in value and field name and makes sure it is correctly entered.
    This way the individual form validators can choose which fields to validate.
    Returns a string that is to be added to the error message in the caller.
*/
function getFieldTest(fieldName, fieldValue){
    // set reg ex for specific fields to test
	var zipRegEx = /^\d{5}(-\d{4})?$/;
    var canadaZipRegEx = /^[A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d$/;
	var phoneRegEx = /^\d{3}-\d{3}-\d{4}$/;
	var phoneExtRegEx = /^\d{3,5}$/;
	var stateRegEx = /^[A-Za-z]+$/;
	var cityRegEx = /^[A-Za-z ]+$/;
	var textRegEx = /^[A-Za-z0-9 ]+$/;
	var quotedEmailRegEx = /^(".+")(\.".+")*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    var regEmailRegEx = /^\w+((-\w+)|(\.\w+)|(-?))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    //var regEmailRegEx = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
	var quantityRegEx = /^\d+$/;

    // credit card verification expressions
    var dateRegEx = /^\d{4}$/;
    var cardNumRegEx = /^\d{16}$/;
    var vCodeRegEx = /^\d{3}|\d{4}$/;

    var returnMsg = "";

    if (fieldName != "quantity" && fieldName != "size" && fieldName != "color"){
        if (!isBlank(fieldValue)){
            switch (fieldName){
            	case "zip code":
            	case "postal code":
            		if (!zipRegEx.test(fieldValue) && !canadaZipRegEx.test(fieldValue)){
            			returnMsg = "<li>Enter your zip or postal code as a 5 digit or zip + 4 number (must all be numbers). <br>Or, for Canadian, AnA nAn (A is any letter and n is a number).</li>";
            		}
            		break;
            	case "phone number":
            	case "phone":
            		if (!phoneRegEx.test(fieldValue)){
            			returnMsg = "<li>Your phone number should be entered as 555-555-5555 (must all be numbers).</li>";
            		}
            		break;
            	case "fax number":
            		if (!phoneRegEx.test(fieldValue)){
            			returnMsg = "<li>Your fax should be entered as 555-555-5555 (must all be numbers).</li>";
            		}
            		break;
            	case "cell number":
            		if (!phoneRegEx.test(fieldValue)){
            			returnMsg = "<li>Your cell phone should be entered as 555-555-5555 (must all be numbers).</li>";
            		}
            		break;
            	case "pager number":
            		if (!phoneRegEx.test(fieldValue)){
            			returnMsg = "<li>Your pager should be entered as 555-555-5555 (must all be numbers).</li>";
            		}
            		break;
            	case "e-mail":
            	case "email address":
            		if (!quotedEmailRegEx.test(fieldValue) && !regEmailRegEx.test(fieldValue)){
            			returnMsg = "<li>Your email address should be entered as mailbox@domain.extension.</li>";
            		}
            		break;
            	case "credit card number":
            		if (!cardNumRegEx.test(fieldValue)){
                        returnMsg = "<li>Please enter a valid 16 digit credit number with no spaces or dashes.</li>";
                    }
            		break;
            	case "state":
            		if (!stateRegEx.test(fieldValue)){
                        returnMsg = "<li>Please enter letters only for your state.</li>";
                    }
            		break;
            	case "city":
            		if (!cityRegEx.test(fieldValue)){
                        returnMsg = "<li>Please enter letters only for your city.</li>";
                    }
            		break;
            	case "verification code":
            		if (!vCodeRegEx.test(fieldValue)){
                        returnMsg = "<li>Please enter the three or four digit Card Security Code from your credit card.</li>";
                    }
            		break;
            	case "expiration date":
            		if (!dateRegEx.test(fieldValue)){
                        returnMsg = "<li>The expiration date must be in the form mmyy.</li>";
                    } else {

						var expDate = fieldValue
                        var mm = expDate.substr(0,2);
                        var yy = expDate.substr(2,2);
                        if (mm < 1 || mm > 12){
                            returnMsg = "<li>The expiration month must be between 01 and 12.</li>";
                        }
                    }
            		break;
            	case "shirt quantity":
            		if (!quantityRegEx.test(fieldValue)){
                        returnMsg = "<li>Please enter the quantity of shirts you want to order as a whole number greater than or equal to 1.</li>";
                    }
            		break;
            	case "first name":
            		if (!textRegEx.test(fieldValue)){
                        returnMsg = "<li>First Name may contain only letters, digits, and spaces.</li>";
                    }
            		break;
            	case "last name":
            		if (!textRegEx.test(fieldValue)){
                        returnMsg = "<li>Last Name may contain only letters, digits, and spaces.</li>";
                    }
            		break;
            	case "address 1":
            		if (!textRegEx.test(fieldValue)){
                        returnMsg = "<li>Address may contain only letters, digits, and spaces.</li>";
                    }
            		break;
            	case "user name":
            		if (!textRegEx.test(fieldValue) && !quotedEmailRegEx.test(fieldValue) && !regEmailRegEx.test(fieldValue)){
                        returnMsg = "<li>User Name may contain only letters, digits, and spaces. Or be a valiD email address.</li>";
                    }
            		break;
            	case "password":
            		if (!textRegEx.test(fieldValue)){
                        returnMsg = "<li>Password may contain only letters, digits, and spaces.</li>";
                    }
            		break;
            	default:
            	    returnMsg = "";
            } // end switch
        } else { // the field is blank
            if (fieldName != "fax number" && fieldName != "mobile number" && fieldName != "pager number" && fieldName != "cell number"){
                returnMsg = "<li>You must have an entry for your " + fieldName + ".</li>";
            }
        } // end if not blank
    } else if ((fieldName == "quantity" || fieldName == "size" || fieldName == "color") && parseInt(fieldValue) < 1){
        returnMsg = "<li>You must select a " + fieldName + " to order.</li>";
    }

    return returnMsg;
}

// function checks text entries to make sure they are not all whitespace characters
function isBlank(tVal){
	for (var i = 0; i < tVal.length; i++){
		var c = tVal.charAt(i);
		if((c != ' ') && (c != '\n') && (c != '\t'))
			return false;
	}
	return true;
}

// this function shows passed in error message in the errors div on the calling page
function writeErrorMsg(msg){
    if (browserName == "Microsoft Internet Explorer"){
		document.all["errors"].innerHTML = msg;
		document.all["errorMsg"].style.display = "";
		window.scrollTo(0,0);
	} else {
		document.getElementById('errors').innerHTML = msg;
		document.getElementById('errorMsg').style.display = "";
		window.scrollTo(0,0);
	}
}

// This function will set the border and background color of an input to
// red if a required field is left blank or clear it if it properly completed
function setRequiredWarning(theElem, setWarning) {
    if (setWarning) {
        theElem.style.border = "1px solid #f00";
        theElem.style.backgroundColor = "#fcc";
    } else {
        theElem.style.border = "1px solid #049";
        theElem.style.backgroundColor = "#fff";
    }
}