/*********************************************************************
	ValidateForm.js
	
	usage example:
	<form name="Form" action="form.cfm" method="post"
	onSubmit="this.FirstName.optional = true;
						this.LastName.optional = true;
						this.Email.email = true;
						this.YOB.min = 1900;
						return verify(this);">

	First Name: <input type="text" name="FirstName" value="" size="20">
	Last Name: <input type="text" name="LastName" value="" size="20">
	User Name: <input type="text" name="UserName" display="User Name" value="" size="20">
	Password: <input type="text" name="Password" value="" size="20">
	Email: <input type="text" name="Email" value="" size="35">
	Year of birth: <input type="text" name="YOB" display="Year of birth" value="" size="4">
	
	</form>

*********************************************************************/

function verify(f) {
	var msg;
	var empty_fields = "";
	var errors = "";
	
	// Loop through the elements of the form, looking for all 
	// text and textarea elements that don't have an "optional" property
	// defined. Then, check for fields that are empty and make a list of them.
	// Also, if any of these elements have a "min" or a "max" property defined,
	// verify that they are numbers and in the right range.
	// If the element has a "numeric" property defined, verify that
	// it is a number, but don't check its range.
	// Put together error messages for fields that are wrong.
	for(var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		var FieldName_require = eval("f." + e.name + "_require");
		var FieldName_writein = eval("f." + e.name + "_writein");
		
		//alert(e.type);

		/***************************
		* TEXT & TEXTAREA
		***************************/
		if (((e.type == "text") || (e.type == "textarea"))) {
			// is the field required
			if (FieldName_require && FieldName_require.value == "true"){
				if ((e.value == null) || (e.value == "") || isblank(e.value)) {
					empty_fields += "\n          " + showName(e);
					continue;
				}
			}

			// Now check for fields that are supposed to be numeric.
			var FieldName_numeric = eval("f." + e.name + "_numeric");
			var FieldName_min = eval("f." + e.name + "_min");
			var FieldName_max = eval("f." + e.name + "_max");
			if (FieldName_numeric){
				var v = parseFloat(e.value);
				if (isNaN(v) ||
						(FieldName_min && v < FieldName_min.value) ||
						(FieldName_max && v > FieldName_max.value)) {
					errors += "- The field " + showName(e) + " must be a number";
					if (FieldName_min){
						errors += " that is greater than " + FieldName_min.value;
					}
					if ((FieldName_min) && (FieldName_max)){
						errors += " and less than " + FieldName_max.value;
					} 
					else if (FieldName_max) {
						errors += " that is less than " + FieldName_max.value;
					}
					errors += ".\n";
				}
			}
			
			//Now check for fields that are supposed to be an email
			var FieldName_email = eval("f." + e.name + "_email");
			if (FieldName_require && FieldName_email) { 
				var v = e.value;
				if (!isEmail(v)) {
					errors += "- The field " + showName(e) + " must be a valid email address.\n";
				}
			}

			//Now check for fields that are supposed to be an date
			var FieldName_date = eval("f." + e.name + "_date");
			var FieldName_noFuture = eval("f." + e.name + "_noFuture");
			if (FieldName_date) { 
				var v = e.value;
				if (!isDate(v)) {
					errors += "- The field " + showName(e) + " must be a valid date.\n";
				}
				if (isDate(v) && FieldName_noFuture) {
					var today = new Date();
					var dateToCheck = new Date(v);
					if (dateToCheck > today) {
						errors += "- " + showName(e) + " can not be a date in the future.\n";
					}
				}
			}

			//Check to see if there is a password verification
			var FieldName_password1 = eval("f." + e.name + "_password");
			var FieldName_password2 = eval("f." + e.name + "_verify");
			if (FieldName_password1) { 
				var v1 = e.value;
				var v2 = FieldName_password2.value;
				if (v1 != v2) {
					errors += "- Passwords do not match. Please correct.\n";
				}
			}

		} // TEXT & TEXTAREA

		/***************************
		* Drop Down
		***************************/
		if ((e.type == "select-one") && FieldName_require) {
			if (!DropDownSelected(e) && !WriteInResponse(FieldName_writein)) {
				empty_fields += "\n          " + showName(e);
			}
		} // Drop Down

		/***************************
		* Radio
		***************************/
		if ((e.type == "radio") && FieldName_require) {
			if (!RadioSelected(eval("e.form." + e.name)) && !WriteInResponse(FieldName_writein)) {
				if (empty_fields.indexOf("\n          " + showName(e)) == -1)
					empty_fields += "\n          " + showName(e);
			}
		} // Radio

		/***************************
		* Checkbox
		***************************/
		if ((e.type == "checkbox") && FieldName_require) {
			if (!RadioSelected(eval("e.form." + e.name)) && !WriteInResponse(FieldName_writein)) {
				if (empty_fields.indexOf("\n          " + showName(e)) == -1)
					empty_fields += "\n          " + showName(e);
			}
		} // Radio

	}

	// Now, if there were any errors, display the messages, and
	// return false to prevent the form from being submitted. 
	// Otherwise return true.
	if (!empty_fields && !errors) return true;
	
	msg  = ""
	msg += "Please correct the errors listed below to continue.\n";
	msg += "______________________________________________________\n\n"
	
	if (empty_fields) {
		msg += "- The following question(s) are required:" 
						+ empty_fields + "\n";
		if (errors) msg += "\n";
	}
	msg += errors;
	alert(msg);
	return false;

	// A utility function to determine which name to show
	function showName(e) {
		var FieldName_displayName = eval("f." + e.name + "_displayName");
		if (FieldName_displayName) {
			return FieldName_displayName.value;
		} else {
			return e.name;
		}
	}
}


/*********************************************************************
*	Utility functions
*********************************************************************/

// A utility function that returns true if a string contains only 
// whitespace characters.
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;
}

// A utility function that returns true if a string is a valid email.
function isEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported){
		if ((str.indexOf(".") == 0) || (str.indexOf("@") == 0)){
			return false;
		} else {
			return true;
		}
	}
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  if (!r1.test(str) && r2.test(str)){
		return true;
	} else {
		return false;
	}
}

// A utility function that returns true if a string is a valid date.
function isDate(str){
  // date can be entered in one of 3 formats
	// 1-1-1900, 1/1/1900, 1.1.1900
	var Day, Month, Year, delimiter
	
	if (str.indexOf('-') > -1) {
		delimiter = '-';
	} else if (str.indexOf('/') > -1) {
		delimiter = '/';
	} else if (str.indexOf('.') > -1) {
		delimiter = '.';
	} else {
		return false;
	}

	Month = str.substring(0,str.indexOf(delimiter));
	Day = str.substring(str.indexOf(delimiter)+1,str.lastIndexOf(delimiter));
	Year = str.substring(str.lastIndexOf(delimiter)+1,str.length);
	
	var var_date = new Date(Year,Month-1,Day);
	if (var_date.getDate() != Day)
  {
    return false;
  } 
 return true;
}
function formatDate(str,format){
	if (isDate(str)) {
		var thisDate = new Date();
		thisDate = thisDate.parse(str);
		return thisDate.format(format);
	}	else {
		return str;
	}
	
}

// A utility function that returns true if a select-one has a option selected
// which is not a empty string
function DropDownSelected(e){
	for (i=0; i < e.length; i++){
		if (e.options[i].selected)
			if (!e.options[e.selectedIndex].value == "")
				return true;
	}
	return false;	
}

function RadioSelected(field){
	for (i=0; i < field.length; i++){
		if (field[i].checked)
			return true;
	}
	return false;
}

function WriteInResponse(e){
	if ((!e) || (e.value == null) || (e.value == "") || isblank(e.value)) {
		return false;
	}
	return true;
}