/***************************
Setup the Forms
***************************/
$(document).ready(function() {
	prepareForms();
});

function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
    thisform.onsubmit = function() {
      return validateForm(this);
    }
  }
}

function validateForm(whichform) {
	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 < whichform.length; i++) {
		var whichElement = whichform.elements[i];
		toggleRequiredClass(whichElement, 0);

		//Check for any AJAX failure messages
		if (whichElement.failure && whichElement.failure.length > 0) { 
			errors += "- " + whichElement.failure + "\n";
		}

		/***************************
		* TEXT & TEXTAREA
		***************************/
		if ((whichElement.type == "text") || (whichElement.type == "textarea") || (whichElement.type == "hidden") || (whichElement.type == "file")) {

			// REQUIRED
			if (whichElement.className.match(/(\s|^)required(\s|$)/) != null && isBlank(whichElement.value)) {
				toggleRequiredClass(whichElement, 1);
				empty_fields += "\n          " + showName(whichElement);
				continue;
			}

			// NUMERIC
			if ((whichElement.className.match(/(\s|^)numeric(\s|$)/) != null)
				|| (whichElement.className.match(/(\s|^)min(\s|$)/) != null)
				|| (whichElement.className.match(/(\s|^)max(\s|$)/) != null)) {
				
				// TODO: Need to figure out how to handle the min and max stuff
				var whichValue = parseFloat(whichElement.value);
				if (isNaN(whichValue) || 
					((whichElement.min != null) && (whichValue < whichElement.min)) || 
					((whichElement.max != null) && (whichValue > whichElement.max))) {
					errors += "- The field " + showName(whichElement) + " must be a number";
					if (whichElement.min != null)
						errors += " that is greater than " + whichElement.min;
					if (whichElement.max != null && whichElement.min != null)
						errors += " and less than " + whichElement.max;
					else if (whichElement.max != null)
						errors += " that is less than " + whichElement.max;
					errors += ".\n";
				}
			}
			
			// EMAIL
			if (whichElement.className.match(/(\s|^)email(\s|$)/) != null) { 
				var whichValue = whichElement.value;
				if (!isEmail(whichValue)) {
					errors += "- The field " + showName(whichElement) + " must be a valid email address.\n";
				}
			}

			// DATE
			if (whichElement.className.match(/(\s|^)date(\s|$)/) != null) { 
				var whichValue = whichElement.value;
				if (!isDate(whichValue)) {
					errors += "- The field " + showName(whichElement) + " must be a valid date.\n";
				}
			}

		} // TEXT & TEXTAREA

		/***************************
		* Drop Down
		***************************/
		if ((whichElement.type == "select-one") && whichElement.className.match(/(\s|^)required(\s|$)/) != null) {
			if (!DropDownSelected(whichElement)) {
				toggleRequiredClass(whichElement, 1);
				empty_fields += "\n          " + showName(whichElement);
			}
		} // Drop Down

		/***************************
		* Radio
		***************************/
		if ((whichElement.type == "radio") && whichElement.className.match(/(\s|^)required(\s|$)/) != null) {
			if (!RadioSelected(eval("whichElement.form." + whichElement.name))) {
				if (empty_fields.indexOf("\n          " + showName(whichElement)) == -1)
					toggleRequiredClass(whichElement, 1);
					empty_fields += "\n          " + showName(whichElement);
			}
		} // Radio

		/***************************
		* Checkbox
		***************************/
		if ((whichElement.type == "checkbox") && whichElement.className.match(/(\s|^)required(\s|$)/) != null) {
			if (!CheckboxSelected(eval("whichElement.form." + whichElement.name))) {
				if (empty_fields.indexOf("\n          " + showName(whichElement)) == -1)
					// toggleRequiredClass(whichElement, 1);
					empty_fields += "\n          " + showName(whichElement);
			}
		} // Checkbox
	}

	// Now, if there were any errors, display the messages, and
	// return false to prevent the form from being submitted. 
	// Otherwise return truwhichElement.
	if (!empty_fields && !errors) 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 try again.\n";
	msg += "______________________________________________________\n\n"
	
	if (empty_fields) {
		msg += "- The following required field(s) are empty:" 
						+ empty_fields + "\n";
		if (errors) msg += "\n";
	}
	msg += errors;
	alert(msg);
	return false;
}

/*********************************************************************
*	Utility functions
*********************************************************************/
// A utility function to determine which name to show
function showName(whichElement) {
	if (whichElement.title) {
		return whichElement.title;
	} else {
		return whichElement.name.replace(/_/g, ' ');
	}
}

// A utility function that returns true if a string contains only 
// whitespace characters.
function isBlank(str) {
	if ((str == null) || (str == ""))
		return true;

	for(var i = 0; i < str.length; i++) {
			var c = str.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;
}

// A utility function that returns true if a select-one has a option selected
// which is not a empty string
function DropDownSelected(whichElement){
	for (i=0; i < whichElement.length; i++){
		if (whichElement.options[i].selected)
			if (!whichElement.options[whichElement.selectedIndex].value == "")
				return true;
	}
	return false;	
}

function RadioSelected(whichElement)
{
		alert(whichElement.checked);
	for (i=0; i < whichElement.length; i++){
		if (whichElement[i].checked)
			return true;
	}
	return false;
}

function CheckboxSelected(whichElement)
{
	if (whichElement.checked)
			return true;
	return false;
}

function toggleRequiredClass(field, direction){
	var requiredClass_RegExp = new RegExp(/highlight/)
	if (direction == 0 && field.className.match(requiredClass_RegExp)){
		field.className = field.className.replace(requiredClass_RegExp, "");
	} else if (direction == 1 && !field.className.match(requiredClass_RegExp)){
		field.className+=" highlight";
	}
}
