// JavaScript Document

SimpleValidator = Class.create();
SimpleValidator.prototype = {
	initialize:function(errorClass) {
		this.errors = new Array();
		this.errorClass = errorClass;
	},
	reset: function() {
		this.errors.clear();
	},
	hasErrors:function() {return this.errors.length > 0},
	getErrors:function() {return this.errors.join("\n")},
	setCss:function(obj) {obj.addClassName(this.errorClass)},
	resetCss:function(obj) {obj.removeClassName(this.errorClass)},
	isEmpty: function(v) {
		return  ((v == null) || (v.length == 0));
	},
	test: function(func, npt, message) {
		var obj = $(npt);
		this.resetCss(obj);
		if(func()) {
			this.setCss(obj);
			this.errors.push(message ? message : "El campo " + obj.id + " es un valor requerido");
		}		
		
			
	},
	required:function(npt,message) {
		var obj = $(npt);
		this.resetCss(obj);
		if(this.isEmpty(obj.value)) {
			this.setCss(obj);
			this.errors.push(message ? message : "El campo " + obj.id + " es un valor requerido");
		}
	},
	numbers:function(npt, message) {
		var obj = $(npt);
		this.resetCss(obj);
		if(this.isEmpty(obj.value) || isNaN(obj.value) || /^\s+$/.test(obj.value)) {
			this.setCss(obj);
			this.errors.push(message ? message : "El campo " + obj.id + " debe contener números");
		}
	},
	email:function(npt, message) {
		var obj = $(npt);
		this.resetCss(obj);
		if(this.isEmpty(obj.value) || !/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(obj.value)) {
			this.setCss(obj);
			this.errors.push(message ? message : "El campo " + obj.id + " debe contener un email válido");
		}		
	},
	extension:function(npt, exts, message) {
		var obj = $(npt);
		var ext = obj.value.slice(obj.value.indexOf(".")).toLowerCase();
		var flag = false;
		for(var i=0; i < exts.length; i ++) {
			if(ext == exts[i]) {flag=true; break}
		}
		if(!flag) {
			this.setCss(obj);
			this.errors.push(message ? message : "El campo " + obj.id + " no tiene una extensión válida");
		}					
	}
}
var sv = new SimpleValidator('npt_error');