/*
 * Script: validation.js
 * License: comercial
 * Author: Catalin Prescure
 * Credits: mootools, Valerio Proietti, <http://mad4milk.net>
*/

var J_local_validation = new Class({
	
	initialize: function(options) {
		this.setOptions(options);
	},
	
	// Local validation
	check: function(field, vars) {
			
			var error = "";

			if ( ! field) {
				return error;
			}

			this.el = $(field);
			this.rules = vars.rules;
			this.errors = vars.errors;

			var arr = this.rules[field].split(' : ');

			for (i=0; i<arr.length; i++) {

				var rule = "";
				var param = "";
				
				var matches = arr[i].match(/([^[]*)(\[(.*)\])?/i);
				
				if (matches[1] != null) {
					rule = matches[1];
				}

				if (matches[3] != null) {
					param = matches[3];
				}

				error =  eval('this.' + rule + '("' + param + '")');

				if (error != '') {
					return error;
				}
			}

			return error;
	},

	valid_email: function(param) {
		return /^[\w\-]+(\.[\w\-]+)*@[\w\-]+\.([\w\-]+\.)*[a-z]{2,}$/i.test(this.el.value) ? "" : this.errors['invalid'];
	},

	required: function(param) {
		if (this.el.value) {
			if (param) {
				return $(param).value ? "" : this.errors['empty'];
			}
		} else {
			return this.errors['empty'];
		}

		return "";
	},

	min_length: function(param) {
		return this.el.value.length < parseInt(param) ? this.errors['min_length'].replace("%s", param) : "";
	},

	max_length: function(param) {
		return this.el.value.length > parseInt(param) ? this.errors['max_length'].replace("%s", param) : "";
	},

	matches: function(param) {
		return this.el.value != $(param).value ? this.errors['not_match'] : "";
	}

});

J_local_validation.implement(new Options, new Events);