/**

Validate.js, from Javascrpt: The Definitive Reference

**/

(function() { // Do everything in one anonymous function

	// When the document finishes loading, call init()
	if (window.addEventListener) window.addEventListener("load", init, false);
	else if (window.attachEvent) window.attachEvent("onload", init);


	// Define event handlers for any forms and form elements that need them
	function init() {
		// Loop through all forms in the document
		for (var i=0; i<document.forms.length; i++ ) {
			var f = document.forms[i];
			
			// Assume for now that this form doesn't need validation
			var needsValidation = false;
			
			// Now loop through elements in the form
			for ( var j = 0; j<f.elements.length; j++ ) {
				var e = f.elements[j];
				
				if (e.type!="text") continue;
				
				var pattern = e.getAttribute("pattern");
				var required = e.getAttribute("required") != null;

				// Required is just a shortcut for a simple pattern
				if (required && !pattern) {
					pattern = "\\S";
					e.setAttribute("pattern", pattern);
				}
				
				if (pattern) {
					e.onchange = validateOnChange;
					needsValidation = true;
				}
			}
			
			if (needsValidation) {

				f.onsubmit = validateOnSubmit;
			}
		}
	
	}
	
	// This is the onchange event handler for text fields that
	// require validation.
	function validateOnChange() {

		var textfield = this;
		var pattern = textfield.getAttribute("pattern");
		var value = this.value;
		
		// if the value does not match the pattern, set the class to "invaid."
		if (value.search(pattern)==-1) textfield.className = "invalid";
		else textfield.className = "valid";
	}
	
	// This is the onsubmit event handler for any form that requires validation
	function validateOnSubmit() {
		var invalid = false;

		for (var i=0; i<this.elements.length; i++ ) {
			var e = this.elements[i];
			if (e.type=="text" && e.onchange==validateOnChange) {
				e.onchange();
				if (e.className=="invalid") invalid = true;
			}
		}
		
		if (invalid) {
			alert("One or more fields are incomplete or incorrect.\n"+
				"Please correct the highlighted fields and try again.");
			return false;
		}
	
	}

})();