/*
 *	Generic Javascript form validation, similar to .net client-side validation but lacking a few features.
 *  Supplies validation to check that a value has been entered and to check that it conforms to a regular 
 *  expression.  Will automaticlly display all errors in specified location. For usage example see the 
 *  contact us form for monster.co.uk
 */

function validate(validators) {
	var verified = false;
	for (var i=0; i<validators.length; i++) {
		validate_element(form_validators[i]);
	}
	verified = writeErrors(validators);
	
	return verified;
}
function validate_element(validator) {
	var field = document.getElementById(validator.getAttribute('fieldid'));
	validator.setAttribute('isValid', (window[validator.getAttribute('validationtype')](field, validator)));	
}

function writeErrors(validators) {
	var message = document.getElementById("errorMessages").getAttribute('headertext') + "<ol>";
	var errorCount = 0;
	for (j=0; j<validators.length; j++) {
		
		if (validators[j].getAttribute('isValid')=="false" || validators[j].getAttribute('isValid')==false) {
			validators[j].style.visibility = "visible";
			message = message + "<li>" + validators[j].getAttribute("errormessage") + "</li>";
			errorCount+=1;
			
		}
		else {
			validators[j].style.visibility = "hidden";
		}
	}
	message = message + "</ol>";
	
	if (message != document.getElementById("errorMessages").getAttribute('headertext') + "<ol></ol>") {
		document.getElementById("errorMessages").innerHTML = message;
		document.getElementById("errorMessages").style.display = "block";
		return false; 
	}
	else {
		document.getElementById("errorMessages").innerHTML = message;
		document.getElementById("errorMessages").style.display = "none";
		return true;
	}
}

function required(field, validator) {
	var val = trim(field.value);
	if (val == null || val == "") {
		return false;
	}
	else {
		return true;
	}
}

function regular_expression_validate(field, validator) {
	var val = trim(field.value);
	if (val == null || val=="") {
		return true;
	}
	var rx = new RegExp(validator.getAttribute('regularexpression'));
    var matches = rx.exec(val);
    return (matches != null && val == matches[0]);

}

function trim(str) {
	while(str.charAt(0) == (" ") ) {  
		str = str.substring(1);
	  }
	  while(str.charAt(str.length-1) == " " ) {  
	  	str = str.substring(0,str.length-1);
	  }
 	return str;
}