/**
 * validate.js:  Unobtrusive HTML form validation
 */
 
function validate() {
	
		// loop through forms
		for (var i=0; i<document.forms.length; i++) {
			var f= document.forms[i];		// current form
			
			// Assume form doesn't need validation atm
			var needsValidation = false;
			
			// loop through elements in form
			for (j=0; j<f.elements.length; j++) {
				var e = f.elements[j]; 		// current element
				
				// we're only interested in textfields
				if (e.type != "text" && e.type != "textarea" && e.type != "password") continue;
				
				// see if it has attributes that require validation
				var pattern =  e.getAttribute("pattern");
				var ipattern = e.getAttribute("ipattern");
				var required = e.getAttribute("required") != null;
				
				if (required && !pattern) {
					pattern = "[a-zA-Z0-9]";
					e.setAttribute("pattern", pattern);
				}
				
				// if element requires validation
				if (pattern || ipattern) {
					alert('validating');
					// validate element each time it changes
					e.onchange = validateOnChange;
					e.onblur   = validateOnChange;
					needsValidation = true;
				}
			}
			
		}
};
	
	/**
	 * Handles validation for text fields onChange
	 */
	 function validateOnChange(e) {
	 	var textfield = e;
	 	var pattern = textfield.getAttribute("pattern");
	 	var ipattern = textfield.getAttribute("ipattern");
	 	var value = e.value;
	 	
	 	if (pattern != null && value.search(pattern) == -1) textfield.className = "invalid";
	 	//else if (pattern != null && value.search(ipattern) != -1) textfield.className = "invalid";
	 	else if (value == '') textfield.className = "invalid";
	 	else textfield.className = "valid";
	 } // end validateOnChange
	 
	 /** 
	  * Handles validation onsubmit
	  */
	  function validateOnSubmit(form) {
	  	var invalid = false;
	  	// loop through all form elements
	  	for (var i=0; i<form.elements.length; i++) {
	  		var e = form.elements[i];
	  		if (e.getAttribute("required") != null) {
	  			if (e.type == "text" || e.type == "textarea" || e.type=="password") {
	  				validateOnChange(e); 		// invoke validateOnChange to revalidate
	  				if (e.className == "invalid") invalid = true;	  			
	  			}
  			}
	  	}
	  	
	  // if the form is invalid, alter user and block submission
	  if (invalid) {
	  	alert("The form is incompletely or incorrectly filled out.\n" +
	  		  "Please correct the highlighted fields.");
	  	return false;
	  } else {
		return true;	  
	  }
	}