
// JavaScript is lacking the useful trim function, so we add it here for all string objects to use
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
}

// Validate fields. Sets the input fields to CSS class "invalidate"
// Example:
//     < script language="javascript" type="text/javascript" src="../../scripts/validate.js" >< /script >
//     < form (...) onSubmit="return validate('request', ['yourname', 'email'])" >
//
function validate(formName, fields) {
	var form = document.forms[formName];
	var invalid = [];
	
	for (var i = 0; i < fields.length; i++) {
		var fieldName = fields[i].trim();
		var fieldNode = form[fieldName];
		var value     = form[fieldName].value.trim();

		// reset the class to empty, assume that the field is okay
		fieldNode.className = '';
		
		// "special" email case
		if ((fieldName.substr(0, 5) == 'email')) {
			// supports x@x.co.uk as a minimum
			if (!value.match(/^\w+@\w+\.\w{2,}/)) {
				invalid.push(fieldName);
				fieldNode.className = 'invalid';
			}
		// regular case
		} else if (value == '') {
			invalid.push(fieldName);
			fieldNode.className = 'invalid';
		}
	} // for

	// popup a message anyway
	var lko = invalid.join(', ');
	if (lko) alert("You must enter values for:\n" + lko);
	return (lko) ? false : true;
}
