var Validator = {
	prepare:function( form, onsubmit ){
		form = DOM.$(form);
		form.onsubmit = function(e){
			Validator.clean( form );
			var errors = [ ];
			List.each( form.elements, function( field ){
				var rules = field.name && field.className.match( Validator.regex ), index = 0;
				if( rules )
					List.each( rules, function( rule ){
						var vtor = Validator.rules[rule],
							condition = rule.slice(0,2) == 'if';

						var error = vtor.test && !vtor.test(field.value) || vtor.call && !vtor.call(field,field.value);
						if( condition ){
							if( error )//condition not fulfilled
								return false;
						}else{
							if( error )
								errors.push({ field:field, index:index, rule:rule });
							++index;
						}
					});
			});
			if( errors.length )
				Validator.errors( form, errors );
			else
				onsubmit.call( form, e );
		};
	},
	rules:{
		required:/\S/,
		rate:/^[0-4]$/,//possible values for the comment (star) rating.
		email:/^[^@\s]+@[^@.\s]+(?:\.\w{2,8}){1,4}$/,//up to 4 subdomains, with 2-8 characters
		integer:/^\d+$/,//integer number
		address:/^\d+(?:[-.]\d+|\s\d+\/\d+)?\s\w/i, //11(.5| 1/2|-222) street name
		citystate:/^[\w\s]+, [\w\s]+/, //name of city, name of state
		zip:/^[0-9]{5}(?:-[0-9]{4})?$/,//matches 33333 and 33333-4444
		phone:function( p ){
			return p.replace(/^\+?1|\D/g,'').length > 6;//must have at least 7 numbers
		},
		ifVisible:function( v ){
			var node = this, form = this.form;
			do{
				if( node.style.display == 'none' )
					return false;
			}while( (node = node.parentNode) && node != form );
			return true;
		},
		ifUSA:function(){
			var field = DOM.$('otherCityCountry');
			return field && US(field.value);
		}
	},
	compile:function(){//will generate the regex to match the rules inside the className
		var rules = [ ];
		List.each( this.rules, function( r, name ){
			rules.push( name );
		});
		this.regex = new RegExp('(?:^|\\b)('+rules.join('|')+')(?:$|\\b)', 'g');
	},
	clean:function( form ){},//must clean the previous errors every new valdidation check
	errors:function( form, errors ){//in case there're errors, will get the form with an array of errors
		var err = errors.shift();//errors have: field, index, rule
		alert( err.field.title.split(';')[err.index] );
	}
};

Validator.compile();