// JavaScript Document

sfsValidatorField = new Class ({
	Implements: Options,
	input:'',
	element:null,
	options:{
		message:'',
		error_display:'',
		error_class:'',
	},
	initialize:function(input,options) {
		this.setOptions(options);
		this.input = input;
		element = $(this.options.input);
		this.cleanError();
	},
	setError: function() {
		if(this.options.error_class != '') {
			this.element.addClass(this.options.error_class);
		}
		if(this.options.error_display != '') {
			$(this.options.error_display).innerHTML = this.options.message;
		}
	},
	cleanError: function () {
		if(this.options.error_class != '') {
			this.element.removeClass(this.options.error_class);
		}
		if(this.options.error_display != '') {
			$(this.options.error_display).innerHTML = '';
		}
	}
});

sfsValidator = new Class({
	Implements: Options,
	options:{errorClass:''},
	errors:new Array(),
	hasErrors: false,
	cleanError: function (input,options) {
		
	},
	addError: function(field,default_message) {
		
		if(field.options.message == '') { field.options.message = field.input +': ' + default_message;}
		
		field.setError();
		this.errors.push(field);
	},
	testReg:function (input,regex,options, default_message) {
		var f= new sfsValidatorField(input, options);
		var npt = $(input);
		if( ! regex.test(npt.value) ) {
			this.addError(f,default_message); 
			this.hasErrors = true;
			return false;
		}
		return true;
	},
	testFunc:function (input,func,options, default_message) {
		var f= new sfsValidatorField(input, options);
		var npt = $(input);
		if( ! func() ) {
			this.addError(f,default_message); 
			this.hasErrors = true;
			return false;
		}
		return true;
	},
	required:function(input,options) {
		var regex = /[^.*]/;
		return this.testReg(input, regex, options, "Field is required");
	},
	
	same:function(input,options) {
		var func = function(){ return $(input).value == $(options.compare).value }
		return this.testFunc(input, func, options, "No coindide con " + options.compare);
	},
	
	email:function(input,options) {
		var regex = /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;
		return this.testReg(input, regex, options, "Not a valid email");
	},
	multi:function(name,options) {
		var arr = $$('input[name='+name+'])');
		var func = function () {
			var flg = false;
			arr.each(function(e) {
				if (e.checked) {flg = true;}
			});
			return flg;
		}
		var f= new sfsValidatorField(name, options);
		
		if( ! func() && arr.length > 1) {
			this.addError(f,"Field is required"); 
			this.hasErrors = true;
			return false;
		}
		return true;
	},
	getErrors: function()
	{
		var ret = '';
		this.errors.each ( function(el) {
			ret += el.options.message + '\n';					
		})
		return ret;
	}
	
});