addEvent(window, "load", setupVal, false) ;
function setupVal() {
	var valFields = getElementsByClassName(document, "*", "validate") ;
	for (var i=0; i<valFields.length; i++) {
		var parentForm = climbDom(valFields[i], "form") ;
		if (parentForm && !classContains(parentForm, "requiresValidation")) {
			addEvent (parentForm, "submit", validateForm, false) ;
			addClass(parentForm, "requiresValidation") ;
		}
	}
}

function validateForm(e) {
	var myTarget = getTarget(e) ;
	if (!myTarget) {
		cancelEvent(e) ;
		return false ;
	}
	whatForm = climbDom(myTarget, "form") ;
	var valFields = getElementsByClassName(whatForm, "*", "validate") ;
	var errorText = "" ;
	for (var i=0; i<valFields.length; i++) {
		var allClassNames = valFields[i].className.split(" ") ;
		for (var j=0; j<allClassNames.length; j++) {
			if (allClassNames[j].indexOf("val-") == 0) {
				var validationRule = allClassNames[j].substring(4) ;
				// alert("Testing " + validationRule) ;
				switch (validationRule) {
					case "nonblank" :
						if (valFields[i].options) {
							if (valFields[i].options[valFields[i].selectedIndex].value.length == 0) {
								errorText += " - " + valFields[i].title + "\n" ;
							}
						}
						else if (valFields[i].value.length == 0) {
							errorText += " - " + valFields[i].title + "\n" ;
						}
					break ;
					case "nonzero" :
						if (valFields[i].value== 0) {
							errorText += " - " + valFields[i].title + "\n" ;
						}
					break ;
					case "email" :
						var str = valFields[i].value ;
						var at="@" ;
						var dot="." ; 
						var lat=str.indexOf(at) ; 
						var lstr=str.length ;
						var ldot=str.indexOf(dot) ;
						if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr || str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr || str.indexOf(at,(lat+1))!=-1 || str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot || str.indexOf(dot,(lat+2))==-1 || str.indexOf(" ")!=-1 ) {
							errorText += " - " + valFields[i].title + "\n" ;
						}
					break ;
					case "checked" :
						if (!valFields[i].checked) {
							errorText += " - " + valFields[i].title + "\n" ;
						}
						else {
						}
					break ;
					case "radioselected" :
						var radioChecked = false ;
						var childRadios = valFields[i].getElementsByTagName("input") ;
							for (var k=0; k<childRadios.length; k++) {
								if (childRadios[k].checked) radioChecked = true ;
							}
						if (!radioChecked) errorText += " - " + valFields[i].title + "\n" ;
					break ;
					default :
						continue ;
					break ;
				}
			}
		}
	}
	if (errorText.length) {
		alert("Errors found:\n" + errorText) ;
		cancelEvent(e) ;
		return false ;
	}
	else return true ;
}


function cancelEvent(e) {
	// Cross-browser cancel event
	if (e && e.preventDefault) e.preventDefault(); // DOM style
	else return false; // IE style ;
}