/*
| Script: validator
| Version 0.4
| Author: Bryan English
| Description: Easy way to check forms.
| Date: April 21, 2004
| Notes:
add tests..
SSn, phone, zip, money, date, creditcard, 

*/
function Validator(){
	//--------------------------------------------//
	// properties //
	//--------------------------------------------//

	this.tests = new Array();
	this.defmsg = {
		"not null": " is a required field.",
		"email": " is not a valid e-mail address.",
		"numeric": " is a number.",
		"password": "s don't match."
		};		

	
	//--------------------------------------------//
	// methods //
	//--------------------------------------------//

	/*
	This adds a new test to the filters object.
	f = form element,t = type,m = error message
	*/
	this.add = function(f,t,m){
		t = (t)?t:"not null";
		m = (m)?m:f+this.defmsg[t];
		this.tests[this.tests.length] = new Array(f,t,m);
		};

	/*
	This gets a form element value
	*/
	this.get_value = function(e){
		if(e.type!=null)
			switch(e.type){
				case "text": case "hidden": case "password": case "textarea":return(e.value);break;
				case "checkbox":return(((e.checked)?e.value:''));break;
				case "select-one":var o = e.options[e.selectedIndex];
					return(((o.value==null)?o.text:o.value));break;
				}
		else
			for(var cnt=0;cnt<e.length;cnt++)
				if(e[cnt].checked)return(e[cnt].value);

		return(false);
		};

	/*
	This performs the validation tests on the fields
	*/
   this.test = function(form,opttype,filter){
		var errors = '';
		var start = (filter!=null?filter:0);
		var end = (filter!=null?filter+1:this.tests.length);

		for(var fi=start;fi<end;fi++){
			var field = this.tests[fi][0];
			var type = ((opttype)?opttype:this.tests[fi][1]).split(/\s?\&\&\s?/); 
			var msg = this.tests[fi][2];
			var value = this.get_value(form.elements[field]);
			var passed = true; 

			for(var cnt=0;cnt<type.length;cnt++){
				var cmds = type[cnt].split(' ');
				switch(cmds[0]){
					case 'not':
						if(this.test(form,type[cnt].replace('not ',''),fi)=='')
							passed = false;
					break;
					case 'null':
						if(!(value == null || value == ''))
							passed = false;
					break;
					case 'numeric':
						if(isNaN(value))
							passed = false;				
					break;
					case 'range':
						if(!(value > cmds[1] && value <cmds[2]))
							passed = false;				
					break;
					case 'email':
						if(!/^.+\@..+\..+/.test(value))
							passed = false;				
					break;
					case 'password':
						if(value != this.get_value(form.elements[field+"_verify"]))
							passed = false;				
					break;
					}
				}
			errors += (passed?'':'\n- '+msg);
			}

		return errors;
      };		 

	/*
	validate the form
	*/
	this.validate = function(form){
		var errors = '';
		errors = this.test(form);
		if(errors!=''){
			alert("There is a problem with your submission:\n"+errors);
			return false;
			}
		return true;
		}	
	}


var validator = new Validator();