/*
	FormValidator by Karurosu 0.1

	ChangeLog:
	0.1		First Version
*/
var formValidator = new Class({
	Implements: Options,
	options: {
		lang: {
			'error': 'error',
			'empty':"{%fld} can't be empty",
			'minlength':'{%fld} is too small'
		},
		message: function(msj,obj) {console.log(msj);}
	},
	initialize: function(options)
	{
		this.setOptions(options);
	},
	validate: function(form, rules)
	{
		//console.log(rules);
		if($type(form) == false || $type(rules) != 'object')
		{
			console.log('bad parameter');
			return false;
		}
		if($type(form) == 'string')
		{
			form = $(form);
		}
		this.allrules = new Object();
		if($type(rules['*']) != false)
		{
			this.allrules = rules['*'];
		}
		
		this.rules = rules;
		this.result = true;
		input = form.getElements('input');
		input.each(
			function(el)
			{
				if(el.get("type") == "submit")
				{
					return;
				}
				this.allrules.each(
					function(rule){
						this.result = this.applyrule(el,rule) && this.result;
					}.bind(this)
				);
				//console.log('specific rules');
				//console.log(this.rules[el.get('name')]);
				if($type(this.rules[el.get('name')]) != false )
				{
					this.rules[el.get('name')].each(function(rule){
						this.result = this.applyrule(el,rule) && this.result;
					}.bind(this));	
				}
			}.bind(this)
		);
		return this.result;
	},
	applyrule: function(obj, rule)
	{
		pars = null;
		if($type(rule) != "string")
		{
			action = rule[0];
			pars = rule[1];
		}
		else
		{
			action = rule;
		}
		return this[action](obj,rule,pars);
	},
	genMsj: function(obj, msj)
	{
		this.options.message(msj.replace("{%fld}",obj.get('name')),obj);
	},
	notempty: function(obj,rule,pars) {
		//console.log("Applying notempty rule");
		if(obj.value == "")
		{
			this.genMsj(obj, this.options.lang.empty);
			return false;
		}
		return true;
	},
	minlength: function(obj,rule,pars) {
		//console.log("Applying minlength rule");
		if(obj.value.length < pars[0])
		{
			this.genMsj(obj, this.options.lang.minlength);
			return false;
		}
		return true;
	},
	regexp: function(obj, rule, pars)
	{
		r = new RegExp(pars[0],pars[1])
		//console.log(r);
		if(r.test(obj.value) == true)
		{
			return true;
		}
		else
		{
			this.genMsj(obj,pars[2]);
			return false;
		}
		return ;
	},
	trim: function(obj, rule, pars)
	{
		obj.value = obj.value.clean();
		return true;
	},
	addValidation: function(url, form, rules, ajoptions)
	{
		form = $(form);
		form.store('url',url);
		form.store('rules', rules);
		form.store('ajasop', ajoptions);
		form.store('validator',this);
		form.addEvent('submit', function(e) {
			new Event(e).stop();
			if(this.retrieve('validator').validate(this,this.retrieve('rules')) == true)
			{
				document.ajaxer.sendForm(this,this.retrieve('url'),this.retrieve('ajasop'));
			}
		});
	}
});
