var errorClass = 'required';

function validate() {
	errors = [];
	fields.each(function(field){
		if(field.type == 'pick-one'){
			var pickone = new Array();
			// Validate every field and check for the "error" class
			field.inputs.each(function(input){
				input.required = false;
				validateField(input);
				
				input.required = true;
				pickone.push(validateRequired(input));
			});
			
			// Now Check to see if one field validated
			if(!pickone.contains(true)){ // one item is valid
				errors.push(field.errorMessage);
				field.inputs.each(function(input){
					$(input.displayControl).addClass(errorClass);
				});
			}
		} else {
			validateField(field);	
		}
	});
	
	return errors;
}

function validateField(field){
	var valid = true;
	switch(field.type){
		case 'string':
			if(false == validateRequired(field)) {
				errors.push(field.errorLabel + ' is required.');
				valid = false;
			}
			
			if(true == valid){
				if(false == validateFormat(field)){
					errors.push(field.errorLabel + ' is not valid.');
					valid = false;
				}
			}
			
			if(true == valid){
				if(false == validateLength(field)){
					errors.push(field.errorLabel + ' is too long.');
					valid = false;
				}
			}
			
			if(false == valid) {
				$(field.displayControl).addClass(errorClass);
			} else {
				$(field.displayControl).removeClass(errorClass);
			}
			
			break;
		case 'select': 
			if(false == validateRequired(field)) {
				errors.push(field.errorLabel + ' is required.');
				valid = false;
			}

			if(false == valid) {
				$(field.displayControl).addClass(errorClass);
			} else {
				$(field.displayControl).removeClass(errorClass);
			}
		
			break;
		case 'email': 
			if(false == validateRequired(field)) {
				errors.push(field.errorLabel + ' is required.');
				valid = false;
			}

			if(true == valid){
				if('' != $(field.name).get('value'))
				{
					if(!isValidEmailAddress($(field.name).get('value'))){
						errors.push(field.errorLabel + ' is not valid.');
						valid = false;
					}
				}
			}
			
			if(true == valid){
				if(false == validateLength(field)){
					errors.push(field.errorLabel + ' is too long.');
					valid = false;
				}
			}
			
			if(false == valid) {
				$(field.displayControl).addClass(errorClass);
			} else {
				$(field.displayControl).removeClass(errorClass);
			}
			break;
		case 'phone': 
			if(false == validateRequired(field)) {
				errors.push(field.errorLabel + ' is required.');
				valid = false;
			}

			if(true == valid){
				if('' != $(field.name).get('value'))
				{
					if(!isValidPhoneNumber($(field.name).get('value'))){
						errors.push(field.errorLabel + ' is not valid.');
						valid = false;
					}
				}
			}
			
			if(true == valid){
				if(false == validateLength(field)){
					errors.push(field.errorLabel + ' is too long.');
					valid = false;
				}
			}
			
			if(false == valid) {
				$(field.displayControl).addClass(errorClass);
			} else {
				$(field.displayControl).removeClass(errorClass);
			}
			break;
			
		case 'zipcode': 
			if(false == validateRequired(field)) {
				errors.push(field.errorLabel + ' is required.');
				valid = false;
			}

			if(true == valid){
				if('' != $(field.name).get('value'))
				{
					if(!isValidUSZipCode($(field.name).get('value'))){
						errors.push(field.errorLabel + ' is not valid.');
						valid = false;
					}
				}
			}
			
			if(true == valid){
				if(false == validateLength(field)){
					errors.push(field.errorLabel + ' is too long.');
					valid = false;
				}
			}
			
			if(false == valid) {
				$(field.displayControl).addClass(errorClass);
			} else {
				$(field.displayControl).removeClass(errorClass);
			}
			break;
	}
}

function validateRequired(field){
	var result = true;
	if(true == field.required) {
		switch(field.type){
		case 'select':
			if('' == $(field.name).value || 0 > $(field.name).value){
				result = false;
			}
			break;
		default:
			if($(field.name).get('value') === ''){
				result = false;
			}
			break;
		}
	}
	return result;
}

function validateFormat(field){
	var result = true;
	if(null != field.format){
		var value = $(field.name).get('value');
		if('' != value) {
			if(!isValidFormat(value, field.format)){
				result = false;
			}
		}
	}
	return result;
}

function validateLength(field){
	var result = true;
	if(null != field.length){
		if($(field.name).get('value').lenght > field.length){
			result = false;
		}
	}
	return result;
}


function isValidPhoneNumber( strValue ) {
/************************************************
REMARKS: Removes all elements to leave numbers 
only. Numbers must equal 10 digits. 
(area code + phone number)
*************************************************/
	var temp = strValue.replace(/[\(\)\.\-\ ]/g, "");
	return (temp.length == 10);
}

function isValidEmailAddress( strValue ) {
/************************************************
REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
  var objRegExp  = /(^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$)/i;
  //check for valid email
  return objRegExp.test(strValue);
}

function isValidUSZipCode( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999
*************************************************/
  var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function isValidFormat( value, regEx) {
	return regEx.test(value);
}

function isValidUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
*************************************************/
  //var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
  var objRegExp = /^[0,1]?\d{1}(\-|\/|\.)(([0-2]?\d{1})|([3][0,1]{1}))(\-|\/|\.)(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;

  //check to see if in correct format
  if(!objRegExp.test(strValue)) {
    return false; //doesn't match pattern, bad date
  } else {
    var strSeparator = strValue.replace(/\d/g,"").substring(0,1); //find date separator
    var arrayDate = strValue.split(strSeparator); //split date into month, day, year
    //create a lookup for months not equal to Feb.
    var arrayLookup = { 1 : 31, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, 8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31};
    var intDay = parseInt(arrayDate[1]);
    var intMonth = parseInt(arrayDate[0]);
    
    //check if month value and day value agree
    if(arrayLookup[intMonth] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay !== 0){
        return true; //found in lookup table, good date
	  }	        
    } else {
      //check for February
      var intYear = parseInt(arrayDate[2]);
      if( ((intYear % 4 === 0 && intDay <= 29) || (intYear % 4 !== 0 && intDay <=28)) && intDay !== 0) {
        return true; //Feb. had valid number of days
      }
    }
  }
  return false; //any other values, bad date
}


// masking functions - attempt to parse and reformat 
// element's values as a specific datatype
// to use, tack them to the form field's onblur handler.
// document.myForm.phone_number.onblur = phoneFieldBlurHandler	
//   -> this field will now mask for phone numbers onblur
function textFieldBlurHandler() {
	this.value = this.value.trim();
}

function phoneFieldBlurHandler(phone) {
	var temp = phone.value.replace(/\D/g, "");

	if (temp.length > 9 && temp.length < 26) {
		if (temp.length == 10) {
			phone.value = "(" + temp.substring(0,3) + ") "; 
			phone.value += temp.substring(3,6) + "-" + temp.substring(6,10);
		}
	  }
	}

function zipcodeFieldBlurHandler(zip) {
	var temp = zip.value.replace(/\D/g, "");

	if (temp.length == 5 || temp.length == 9) { 
		if (temp.length == 5) {
		  zip.value = temp;
		} else {
		  zip.value = temp.substring(0,5) + "-" + temp.substring(5,9);
		}
	}
}

// like Trim( ) in vbscript. removes trailing and 
// leading whitespace from a string
String.prototype.trim = function() {
	return this.replace(/^\s*|\s*$/g, "");
}


// push is a quite useful method of arrays in newer 
// javascript implementations, but not in ie5-
Array.prototype.push = function(v) {
	this[this.length] = v;
	return v;
}