form_validation = {
	validate: function(form,rules,msg) {
		this.form = form;
		this.rules = rules;
		this.errors = [];
		this.msg = document.getElementById(msg);
		// check for error
		for(var i=0; i<this.rules.length; i++){
			var rls = this.rules[i][2].split('|');
			for(var j=0; j<rls.length; j++) {
				var label = rules[i][0];
				this[rls[j]](rules[i][1],label);
			}
		}
		
		if(this.errors.length >0){
			this.show_error();
			return false;
		}else{
			return true;
		}
	},
	
	trim: function(s) {
		while (s.substring(0,1) == ' '){
			s = s.substring(1, s.length);
		}
		while (s.substring(s.length-1, s.length) == ' '){
			s = s.substring(0,s.length-1);
		}
		return s;
	},
	
	required: function(id,label) {
		var el = this.form[id];
		var v = el.value;
		// if the passed in 'id' is a reference to a radio group name
		// el will be a collection in which case we need to loop thru 
		// and find the checked one set
		// if it has a length property and not a nodeName (because 'select's have length)
		if(typeof(el.length) != 'undefined' && typeof(el.nodeName)=='undefined') {
			v = '';
			for(var i=0,c=el.length; i<c; i++){
				if(el[i].type=='radio' && el[i].checked){
					v = el[i].value;
				}
			}
		}
		if(this.trim(v)==''){
			var error = [id,label+' is Required'];
			this.errors.push(error);
			return false;
		}else{
			return true;
		}
	},
	
	email: function(id,label) {
			if(!this.trim(this.form[id].value)==''){
				var re = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
				if (! this.trim(this.form[id].value).match(re)) {
					var error = [id,this.form[id].value+' is not a valid email address'];
					this.errors.push(error);
					return false;
				}else{
					return true;
				}
			}else{
				return true;
			}
	},
	
	show_error: function() {
		this.msg.innerHTML = '';
		var wrapper = document.createElement('div');
		var txt = document.createTextNode('The form has the following errors');
		var p = document.createElement('p');
		p.appendChild(txt);
		var ul = document.createElement('ul');
		for(var i=0; i<this.errors.length; i++){
			var txt = document.createTextNode(this.errors[i][1]);
			var li = document.createElement('li');
			li.appendChild(txt);
			ul.appendChild(li);
			this.form[this.errors[i][0]].className = 'error';
		}
		wrapper.appendChild(p);
		wrapper.appendChild(ul);
		//this.msg.appendChild(p);
		//this.msg.appendChild(ul);
		this.msg.appendChild(wrapper);
		
		self.scrollTo(0,this.msg.offsetTop);
	}
}