/* Required Field Managment for Forms 
 *
 * requires: prototype.js
 * 
 * to meet spec, inputs should:
 * 1. be of class 'required_field'
 * 2. have an attribute called validate with supported values : notnull, email, phone (comma separated, eg: notnull,email)
 * 3. have a fieldname attribute -- what the field is called in error messages
 */

function FormManager(){
	this.initRequiredFields();
}

FormManager.prototype={
	initRequiredFields:function(){
		this.fields = document.getElementsByClassName('required_field');
		
		for(var i=0; i< this.fields.length; i++){
			var container = document.createElement("span");
			container.className = "required_error";
			container.appendChild(document.createTextNode("*"));
			this.fields[i].error = container;
			
			var fieldName = this.fields[i].getAttribute("fieldname");
			this.fields[i].fieldName = (fieldName == null ? "This" : fieldName);
			this.fields[i].onfocus = this.hideRequiredField;
			this.fields[i].onchange = this.hideRequiredField;
			this.fields[i].parentNode.appendChild(container);
		}
	},
	
	checkRequiredFields:function(){
		var formIsGood = true;
		
		for(var i=0; i< this.fields.length; i++){
			var vTypes = this.fields[i].getAttribute("validate")
			if (vTypes){
				vTypes = vTypes.split(',');
				if (!this.checkByValidationTypes(this.fields[i], vTypes)) formIsGood = false;
			}
		}
		return (formIsGood)
	},
	checkByValidationTypes:function(element, types){
		for (var j=0; j< types.length; j++){
			if (types[j] == 'notnull'){
				if (!this.checkNotNull(element)) return (false);
			}else if(types[j] == 'email'){
				if (!this.checkIsEmail(element)) return (false);
			}else if(types[j] == 'phone'){
				if (!this.checkIsPhone(element)) return (false);
			}
		}
		return (true);
	},
	checkNotNull:function(element){
		var value = element.value;
		if (element.value ==""){
			element.error.firstChild.nodeValue = element.fieldName + "is a required field";
			return false;
		}
		return true;
	},
	
	checkIsEmail:function(element){
		var value = element.value;
		var re = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', 'i');
		
		if (value.match(re) == null){
			element.error.firstChild.nodeValue = "This does not appear to be a valid email";
			return false;
		}
		return true;
	},
	
	checkIsPhone:function(element){
		var value = element.value;
		if (value.indexOf("(")>-1){
			value = value.replace(/\(/g, "");
			value = value.replace(/\)/g, "");
			value = value.replace(/\s/, "-");
		}
		value = value.replace(/\s/g, "");
		
		var re = new RegExp("^[0-9]{10}|([0-9]{3})-([0-9]{3})-([0-9]{4})$");
		if (value.match(re) == null){
			element.error.firstChild.nodeValue =  "This does not appear to be a valid phone number";
			return false;
		}
		return true;
		
	},
	
	hideRequiredField:function(){
		this.error.firstChild.nodeValue ="*";
	}
}
