//this is a set of functions used to validate form information, they return false if invalid, and true if valid

/*
    validates email addresses
    textInput (javascript object): the input field being validated
    validIfEmpty (bool): is the string valid if it is empty?
*/
function validEmail(textInput, validIfEmpty){
    var regEx = /^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._\-])?([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/;
    var text = $(textInput).val();
    return (text.match(regEx));
}

/*
    validates only alphaNumeric input, names address and so on
    textInput (javascript object): the input field being validated
    validIfEmpty (bool): is the string valid if it is empty?
*/
function validAlphaNumeric(textInput, validIfEmpty){
    var text = $(textInput).val();
    var regEx = /^[0-9A-Za-z\\\/\, \.\-#]+$/;
    if(validIfEmpty){
        var regEx = /^[0-9A-Za-z\\\/\, \.\-#]*$/;
    }
    return(text.match(regEx));
}

function validPhone(textInput, validIfEmpty){
	var text = $(textInput).val();
	var regEx = /^(\([2-9]\d{2}\)|[2-9]\d{2})[ -\.]?[2-9]\d{2}[ -\.]?\d{4}$/
	
	if(validIfEmpty && text == ""){
		return true;
	}else{
		return text.match(regEx);		
	}
}

/*
    validates zip codes
    textInput (javascript object): the input field being validated
    validIfEmpty (bool): is the string valid if it is empty?
*/
function validZip(textInput, validIfEmpty){
    return(validAlphaNumeric(textInput, validIfEmpty));
}

/*
 	This function validates select boxes, this means any selection has been made
    to work the select menus should have the default option with a blank value
*/
function selectValidation(selectMenu){
    var text = $(selectMenu).children(":selected").val();
    return (text != "");
}

function checkShipping(){

	//are teh shipping fields exposed?
	if(!$("#ship2diff").is(":checked")){
		return true;
	}
	
	//check first name
	if(!validAlphaNumeric($("#s_firstname"), false)){
		alert("The Shipping address requires a first name.");
		$("#s_firstname").focus().select();	
		return false;			
	}
	
	//check last name
	if(!validAlphaNumeric($("#s_lastname"), false)){
		alert("The Shipping address requires a last name.");
		$("#s_lastname").focus().select();	
		return false;			
	}
	
	//check address name
	if(!validAlphaNumeric($("#s_address"), false)){
		alert("The Shipping address field is invalid.");
		$("#s_address").focus().select();	
		return false;			
	}
	
	//check city
	if(!validAlphaNumeric($("#s_city"), false)){
		alert("The Shipping address requires an city.");
		$("#s_city").focus().select();	
		return false;			
	}
	
	//check zip
	if(!validZip($("#s_zipcode"), false)){
		alert("The Shipping address zip code is invalid.");
		$("#s_zipcode").focus().select();	
		return false;			
	}
	
	return true;	
}
