// JavaScript Document

// **************************************************************************************************
// Validation script adapted from "Form Validation with JavaScript" at www.devshed.com,
// by Nariman K, Melonfire (http://www.devshed.com/c/a/JavaScript/Form-Validation-with-JavaScript/)
// **************************************************************************************************

// Create form validator object ---------------------------------------------------------------------
function formValidator() {
	// set up array to hold error messages
	this.errorList = new Array;

	// set up object methods
	this.isEmpty = isEmpty; 
	this.isNumeric = isNumeric; 
	this.isAlphabetic = isAlphabetic; 
	this.isAlphaNumeric = isAlphaNumeric; 
	this.isWithinRange = isWithinRange; 
	this.isEmailAddress = isEmailAddress; 
	this.isChecked = isChecked; 
	this.isValidTime = isValidTime;
	this.raiseError = raiseError; 
	this.numErrors = numErrors; 
	this.displayErrors = displayErrors;
}

// Form validator methods ---------------------------------------------------------------------------
// Check if input is whitespace or empty
function isEmpty(val) {
	if (val.match(/^s+$/) || val == "") {
		return true;
	}
	else { return false; } 
}

// Check if input is numeric
function isNumeric(val) {
	if (isNaN(val)) { return false; }
	else { return true; } 
}

// Check if input is alphabetic
function isAlphabetic(val) {
	if (val.match(/^[a-zA-Z]+$/)) {
		return true;
	}
	else { return false; } 
}

// Check if input is alphanumeric
function isAlphaNumeric(val) {
	if (val.match(/^[a-zA-Z0-9]+$/)) {
		return true;
	}
	else { return false; } 
}

// Check if value is within range
function isWithinRange(val, min, max) {
	if (val >= min && val <= max) {
		return true;
	}
	else { return false; } 
}

// Check if input is valid email address
function isEmailAddress(val) {
	if (val.match(/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/)) {
		return true;
	}
	else { return false; } 
}

// Check if value is checked
function isChecked(obj) {
	if (obj.checked) { return true; }
	else { return false; } 
}

// Check if time is valid (HH:MM)
function isValidTime(val) {
	timePat = /^(\d{1,2}):(\d{2})$/;
	matchArray = val.match(timePat);
	if (matchArray == null) { return false; }
	hour = matchArray[1];
	minute = matchArray[2];
	if (hour < 1  || hour > 12) { return false; }
	if (minute < 0 || minute > 59) { return false; }
	return true;
}

// Display all errors
// iterate through error array and print each item
function displayErrors() {
	var errorMsg = "Please correct the following error(s):\n\n";
	for (i=0; i<this.errorList.length; i++) {
		errorMsg += this.errorList[i] + "\n";
	}
	alert(errorMsg);
}

// Add an error to error list
function raiseError(msg) {
	this.errorList[this.errorList.length] = msg;
}

// return number of errors in error array
function numErrors() {
	return this.errorList.length;
}

// end object
