//
// This script is the email form validation routine
//

// define formcheck functions
function isblank(s) {
	for(var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}
	
function verify(f) {
	// set basic variables
	var msg;
	var empty_fields = "";
	var error_fields = "";
	var errors = "";
	
	// validate test fields
	for(var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		if (((e.type == "text") || (e.type == "textarea")) && !e.optional) {
			if ((e.value == null) || (e.value == "") || isblank(e.value)) {
				empty_fields += "\n          " + e.name;
				continue;
				}
			if (e.numeric || (e.min != null) || (e.max != null)) {
				var v = parseFloat(e.value);
				if  (isNaN(v) || ((e.min != null) && (v < e.min)) || ((e.max != null) && (v > e.max))) {
					errors += "- The field " + e.name + " must be a number.";
				if (e.min != null)
					errors += " that is greater than " + e.min;
				if (e.max != null && e.min != null)
					errors +=  " and less than " + e.max;
				else if (e.max != null)
					errors += " that is less than " + e.max;
					errors += ".\n";
				}
			}
		}
	}
	
	// validate actual contents email/age/phone
	for(var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		if ((e.name == "email") && (e.value != '')) {
			var atsgn = e.value.indexOf('@');
			var per = e.value.lastIndexOf('.');
			var spa = e.value.indexOf(' ');
			var lngt = e.value.length - 1;
			if ((atsgn < 1) || (per <= eval(atsgn + 1)) || (per == lngt) || (spa != -1)) {
   				error_fields += "\n          " + "email address invalid";
   			}
			else {
			}
			//if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(f.email.value)) {
			//}
			//else {
			//	error_fields += "\n          " + "email address invalid";
			//}
		}
	}
		
	if (!empty_fields && !errors && !error_fields) {
		return true;
	}
	
	msg  = "______________________________________________________\n\n";
	msg += "The form was not submitted because of the following error(s).\n";
	msg += "Please correct these error(s) and re-submit.\n";
	msg += "______________________________________________________\n\n";

	if (empty_fields) {
		msg += "- The following required fields are empty:"
			+ empty_fields + "\n";
		if (errors) msg += "\n";
	}
	if (error_fields) {
		msg += "\n\n- The following fields are incorrect:"
			+ error_fields + "\n";
	}
	msg += errors;
	alert(msg);
	return false;
}
