


// a generic, configurable form validator. Each field listed in the validationConfig gets tested 
// against any number of validation functions, defined in Validator. Additional functions can be added to the Validator class, 
// or attached to an instance after creation
var Validator = function(validationConfigArg) {

	var form;
	var validationConfig = validationConfigArg;
	var thisObj = this;
	var errorDivs = [];
	var errorElems = [];

	this.run = function(formArg) {
		var isValid = true;
		form = formArg;
		this.removeErrors();
		validationConfig.fields.each(function(fieldConfig) {
			var field = eval("form['" + fieldConfig.fieldName + "']");

			for (var requirement in fieldConfig.requirements) {
				if(!eval("thisObj." + requirement)(field)) {
					isValid = false;
					thisObj.tellUserAboutError(field, fieldConfig.requirements[requirement]);
					break;
				}
			}
		})
		
		// concatenate phone number into a single field
		if(isValid) {
			$('DayPhone').value = $('DayPhone1').value + $('DayPhone2').value + $('DayPhone3').value;
		}
		
		return isValid;
	}

	this.tellUserAboutError = function(field, message) {
		$('validationErrors').style.display = 'block';
		
		div = new Element("div");
		div.update(message);
		Insertion.Bottom($('validationErrors'), div);
		errorDivs.push(div);
		
		field.style.border = 'solid 1px #ff0000';
		field.style.color = '#ff0000';
		errorElems[errorElems.length] = field;
	}

	this.removeErrors = function(){
		errorDivs.each(function(div){
			div.remove();
		});	
		errorDivs.clear();
		
		for(i = 0; i < errorElems.length; i++) {
			if(errorElems[i] != null) {
				errorElems[i].style.border = '1px solid #d6d6d6';
				errorElems[i].style.color = '#666666';
			}
		}
	}
	
	// VALIDATION FUNCTIONS
	
	/* This function makes sure the email address has one (@), atleast one (.).
	 * It also makes sure that there are no spaces, extra '@'s or a (.) just before or after the @.
	 * It also makes sure that there is atleast one (.) after the @.
	*/
	this.validEmail =  function(elem) {
		try {
			var str = elem.value;
			var at = "@";
			var dot = ".";
			var lat = str.indexOf(at);
			var lstr = str.length;
			var ldot = str.indexOf(dot);
			
			if(str.indexOf(at) == -1) return false;
			if(str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) return false;
			if(str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) return false;
			if(str.indexOf(at, (lat + 1)) != -1) return false;
			if(str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) return false;
			if(str.indexOf(dot, (lat + 2)) == -1) return false;
			if(str.indexOf(" ") != -1) return false;
			
			return true;
		}
		catch(err) {
			return false;
		}
	}

	this.notBlank = function(elem) {
		if(elem.value == ""){
			return false;
		}else{
			return true;
		}
	}
}
