
var errorList = new Array();
var numErrors = 0;

function addError(err) {
	errorList[numErrors] = "" + err;
	numErrors = numErrors + 1;
}

function resetErrorList() {
	errorList = new Array();
	numErrors = 0;
}

function validateForm(formName) {

	var f = document.getElementById(formName);

	var isValid = true;

	for(var i = 0; i < f.elements.length; i++) {
		var el = f.elements[i];
		if(el.type == "text") { // only interested in text elements

			var isRequired = el.getAttribute("required");
			var validation = el.getAttribute("validation").split(",");

			var elID = trim(validation[0] + "");
			var type = trim(validation[1] + "");
			var desc = trim(validation[2] + "");

			// If this field is required, make sure it's present.
			var obj = document.getElementById("" + elID);
			var content = obj.value;

			if(isRequired && content == "") {
				isValid = false;
				addError(desc + " field is not filled out.");
			} else if(isRequired) {
				// Check content validity
				var curValid = true;
				curValid = validateAs(elID, type, desc);
				if(!curValid) { // if this field isn't good, invalidate the form.
					isValid = false;
				}
			}
		}
	}

	if(!isValid) {
		var errorString = ""; 
		for(i = 0; i < errorList.length; i++) {
			errorString += errorList[i] + "\n";
		}

		alert("Please correct the following problems and submit again:\n\n" + errorString);
		
		resetErrorList();
	}

	return isValid;

}

//Types: name, email, alphanumeric, tel, addressLine, city, state, zip, date
function validateAs(elID, type, desc) {
	//alert("validating: " + elID + " as " + type);

	var obj = document.getElementById("" + elID);
	var val = obj.value;

	var isValid = true;
	if(type == "tel") {
		isValid = validateTel(val);

		if(!isValid) {
			addError(desc + " is not a valid phone number."); 
		}

	} else if(type == "email") {
		isValid = validateEmail(val);

		if(!isValid) {
			addError(desc + " field does not contain a valid email address.");
		}
	}

	return isValid;
}


function validateEmail(addr) {
	var isValid = false;

	apos = addr.indexOf("@");
	dotpos = addr.lastIndexOf(".");
	
	if (apos < 1 || dotpos - apos < 2) {
		isValid = false;
	} else {
		isValid = true;
	}

	return isValid;
}


function validateTel(num) {
	// Valid separators: .-
	// Valid formats: (xxx)-yyy-zzzz, xxx-yyy-zzzz, xxxyyyzzzz
	// Valid lengths: 14, 12, 10
	
	var isValid = false;
	var lengthValid = false;
	var badParens = false;
	var badSeparators = false;
	var digitsValid = false;

	//(xxx)-yyy-zzzz
	//0123456789TJQKA
	if(num.length == 14) { // separated, with parens
		lengthValid = true;

		// Check Paren Validity
		if(num.charAt(0) != '(' || num.charAt(4) != ')') {
			isValid = false;
			badParens = true;
		} else {
			badParens = false;
			// Check Separators
			if(!isSeparator(num.charAt(5)) || !isSeparator(num.charAt(9))) {
				badSeparators = true;
			} else {
				badSeparators = false;
				// Check Digit Groups
				if(!stringIsNumber(num.substring(1, 4)) || !stringIsNumber(num.substring(6, 9)) || !stringIsNumber(num.substring(10, 14))) {
					digitsValid = false;
				} else {
					digitsValid = true;
				}	
			}
		}

	//xxx-yyy-zzzz
	//0123456789TJQ
	} else if(num.length == 12) { // separated, no parens
		lengthValid = true;

		// Check Separators
		if(!isSeparator(num.charAt(3)) || !isSeparator(num.charAt(7))) {
			badSeparators = true;
		} else {
			badSeparators = false;
			// Check Digit Groups
			if(!stringIsNumber(num.substring(0, 3)) || !stringIsNumber(num.substring(4, 7)) || !stringIsNumber(num.substring(8, 12))) {
				digitsValid = false;
			} else {
				digitsValid = true;
			}	
		
		}

	//xxxyyyzzzz
	//0123456789T
	} else if(num.length == 10) { // no sep, no parens 
		lengthValid = true;
	
		// Check Digit Groups
		if(!stringIsNumber(num.substring(0, 3)) || !stringIsNumber(num.substring(3, 6)) || !stringIsNumber(num.substring(6, 10))) {
			digitsValid = false;
		} else {
			digitsValid = true;
		}	

	} else {
		lengthValid = false;
	}

	// Overall Metric Validity Check
	if(lengthValid && digitsValid && !badParens && !badSeparators) {
		isValid = true;
	} else {
		isValid = false;
	}

	return isValid;

}

function isSeparator(c) {
	result = false;

	if(c == '.' || c == '-') {
		result = true;
	}

	return result;
}

function stringIsMoney(str) {
	var result = true;

	var first = str.charAt(0);
	first = "" + first;
	if(!charIsNumber(first) && first != '$') {
		result = false;
	} else {
		var numPeriods = 0;
		for(var i = 1; i < str.length; i++) {
			var curChar = str.charAt(i);
			if(!charIsNumber(curChar) && curChar != ',') {	
				if(curChar == '.') {
					numPeriods++;
					if(numPeriods > 1) {
						result = false;
					}
				} else {
					result = false;
					break;
				}
			}
		}
	}

	return result;
}

function stringIsNumber(str) {
	result = true;

	for(var i = 0; i < str.length; i++) {
		if(!charIsNumber(str.charAt(i))) {
			result = false;
			break;
		}
	}

	return result;
}

function charIsNumber(c) {
	result = false;

	if(c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
		result = true;
	}

	return result;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

