var Pattern = new Object();

Pattern.word = /[\w\d]+/;
Pattern.number = /^[,\d\s]+$/;
Pattern.email = /^[-.\w\d]{1,20}[@][-.\w\d]{1,30}$/;

function isThere(stuff)
{
	
	if (stuff == "" || stuff == null)
		return false;
	return true;
}

function isChar(word)
{
	if (Pattern.word.test(word))
		return true;
	return false;
}

function isNum(number)
{
	if (Pattern.number.test(number))
		return true;
	return false;
}

function isEmail(email)
{
	if (Pattern.email.test(email))
		return true;
	return false;
}

function setIfEmpty(value, replacement){
	if (value == "" || value == null)
		return replacement;
	return value;
}

function errorEffect(elem){
	elem.style.background = '#ffeeee';
}

function unErrorEffect(elem){
	elem.style.background = '#ffffff';
}

function validateForm(form)
{
	s = '';
	errorCount = 0;
	errorMessage = "An error has occured in the following fields: \n\n";
	var currentValue = form.elements;
	for (i = 0; i < currentValue.length; i++) {
		var theValue = currentValue[i].value;
        var theValidator = currentValue[i].getAttribute("validator");
        var theMessage = currentValue[i].getAttribute("message");
        var theName = currentValue[i].getAttribute("name");
		var required = currentValue[i].getAttribute("required");
		
		if (theValidator == null && required == null) continue; //don't touch elems lacking the custom attribs
		
		unErrorEffect(currentValue[i]);
		
		if (isThere(theValue)) { //then do type checking, if we were asked to.
			s += theName + ' is there. ';
			if ((theValidator == "word" || theValidator == "string") && !isChar(theValue)){
				errorMessage += setIfEmpty(theMessage, theName + " must contain only numbers or letters.\n\n");
				errorCount++;
				errorEffect(currentValue[i]);
			} else if (theValidator == "number" && !isNum(theValue)) {
				errorMessage += setIfEmpty(theMessage, theName + " must contain only numbers, and optionally a decimal point, eg. 1.223\n\n");
				errorCount++;
				errorEffect(currentValue[i]);
			} else if (theValidator == "email" && !isEmail(theValue)) {
				errorMessage += setIfEmpty(theMessage, theName + " must be a valid email address eg. john@somewhere.com\n\n");
				errorCount++;
				errorEffect(currentValue[i]);
			}
		} else { //not there, so do existance checking
			s += theName + ' NOT there. ';
			if (theValidator == "exist" || required != null){
				s += theName + ' is required. ';
				errorMessage += setIfEmpty(theMessage, theName + " is a required field.\n\n");
				errorCount++;
				errorEffect(currentValue[i]);
			}
		}
	}
	
	if (errorCount){
		alert(errorMessage);
        return false;
	}
	return true;
}



