/*****************************
 * Creado por Gabriel Memmel *
 *    gabimem[]gmail.com     *
 *       Junio - 2010        *
 *****************************/
 
 
/*
.obli {
	border-color:red;
}
*/
 
(function($){
	$.extend($.fn, {
		validar: function (){
			var contenedor = this;
			var inco  = false;
			var nopop = false;
			var sel   = Object();
			
			// Asigna el evento onkeyup para sacar el borde rojo al rellenar el campo
			$(contenedor).find('input.requerido, textarea.requerido, select.requerido').each(function(){
				$(this).keyup(function(){
					$(this).removeClass('obli');
				});
				$(this).change(function(){
					$(this).removeClass('obli');
				});
			});
			
			// Recorre el formulario
			$(contenedor).find('.requerido').each(function(){
				var $this_arr = new Array(), thisInd;
				
				$(this).removeClass('obli');
				if(!/input|textarea|select/i.test(this.tagName)){
					$this_arr[++thisInd] = this;
					var $this = $this_arr[thisInd];
					
					$(this).find('input, textarea, select').not('[disabled],.no-req').each(function(){
						// Agrega las funciones para sacar la clase obli
						$(this).keyup(function(){
							$($this).removeClass('obli');
						});
						$(this).change(function(){
							$($this).removeClass('obli');
						});
						if(this.type == 'radio' || this.tagName == 'select'){
							$(this).click(function(){
								$($this).removeClass('obli');
							});
						}
						
						// Verifica los campos
						if(!verificar(this, contenedor)){
							$($this).addClass('obli');
							inco = true;
						}
					});
				}
				else{
					if(!verificar(this)){
						$(this).addClass('obli').focus();
						inco = true;
					}
				}
			});
			
			function verificar(obj, padre){
				if($(obj).attr('type') == 'radio' || $(obj).attr('type') == 'checkbox'){
					if($(padre).find('input[name="'+$(obj).attr('name')+'"]:checked').length > 0){
						return true;
					}
					else{
						return false;
					}
				}
				else if($(obj).attr('value') == ''){
					return false;
				}
				else{
					if($(obj).hasClass('req-email')){
						if(!validarEmail($(obj).attr('value'))){
							if(!nopop) alert('El email ingresado no es válido.');
							nopop = true;
							return false;
						}
					}
					if($(obj).hasClass('req-numero')){
						if(!validarNumero($(obj).attr('value'))){
							if(!nopop) alert('El valor debe ser numérico.');
							nopop = true;
							return false;
						}
					}
					if($(obj).hasClass('req-fecha')){
						if(!validarFecha($(obj).attr('value'))){
							if(!nopop) alert("La fecha ingresada no es válida.\nEl formato debe ser dd/mm/YYYY");
							nopop = true;
							return false;
						}
					}
					if($(obj).hasClass('req-hora')){
						if(!validarHora($(obj).attr('value'))){
							if(!nopop) alert("La hora ingresada no es válida.\nEl formato debe ser HH:mm");
							nopop = true;
							return false;
						}
					}
				}
				return true;
			};
			
			function validarEmail(valor) {
				if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) {
					return true;
				} else {
					return false;
				}
			}
			function validarNumero(valor) {
				if (/^[0-9\.\,]+$/.test(valor)) {
					return true;
				} else {
					return false;
				}
			}
			function validarFecha(valor) {
				if (/^[0-9]{2,4}[\/-][0-9]{1,2}[\/-][0-9]{1,2}$/.test(valor)) {
					return true;
				} else if (/^[0-9]{1,2}[\/-][0-9]{1,2}[\/-][0-9]{2,4}$/.test(valor)) {
					return true;
				} else {
					return false;
				}
			}
			function validarHora(valor) {
				if (/^[0-9]{1,2}:[0-9]{2}(:[0-9]{2})?(\s?(am|pm|hs))?$/i.test(valor)) {
					return true;
				} else {
					return false;
				}
			}
			
			if(inco){
				if(!nopop){
					$(contenedor).find(".requerido[value='']:first").focus();
					alert('Por favor, complete los campos obligatorios,');
				}
				return false;
			}
			else{
				return true;
			}
		}
	})
})(jQuery);
function validador(form) {
	this.formulario = form;
	this.campos = new Array();
	this.compara = new Array();
	this.validar = validar;
	this.valido = valido;
	this.form_campo = form_campo;
	this.agregar = agregar;
	this.c = c;
	this.contrasena = contrasena;
	function validar() {
		/*for (i = 0 ; i < this.formulario.elements.length ; i++) {*/
		for(ii = 0 ; ii < this.campos.length ; ii++) {
			//alert(this.formulario.elements[i].name);
			/*if(mensaje = this.valido(this.formulario.elements[i].name)) {*/
			i = this.form_campo(ii);
			if(i != ''){
				mensaje = this.campos[ii];
				tipo = mensaje[2]||'';
				if(this.formulario.elements[i].type == 'radio') {
					var sel = false;
					var radio = this.formulario.elements[this.formulario.elements[i].name];
					for (j = 0 ; j < radio.length ; j++) {
						if (radio[j].checked == true) {
							sel = true;
							break;
						}
					}
					if (!sel) {
						this.formulario.elements[i].focus();
						alert(mensaje[1]);
						return false;
					}
				} else {
					if(this.formulario.elements[i].value == '' || this.formulario.elements[i].value == mensaje[3]) {
						if(!(/^\w+:0/.test(tipo))){
							this.formulario.elements[i].focus();
							alert(mensaje[1]);
							return false;
						}
					} else {
						regs = '';
						if(res = /^\w+/.exec(tipo)) regs = res[0];
						switch (regs) {
							case 'email':
								if(!validarEmail(this.formulario.elements[i].value)) {
									this.formulario.elements[i].focus();
									alert('El email ingresado no es valido.');
									return false;
								}
								break;
							case 'numero':
								if(!validarNumero(this.formulario.elements[i].value)) {
									this.formulario.elements[i].focus();
									alert('El valor debe ser numerico.');
									return false;
								}
								break;
							case 'fecha':
								if(!validarFecha(this.formulario.elements[i].value)) {
									this.formulario.elements[i].focus();
									alert('La fecha ingresada no es valida.');
									return false;
								}
								break;
							case 'hora':
								if(!validarHora(this.formulario.elements[i].value)) {
									this.formulario.elements[i].focus();
									alert('La hora ingresada no es valida.');
									return false;
								}
								break;
							case 'archivo':
								var expreg = new RegExp('\.(' + tipo.substr(10) + ')$');
								if(!validarExtension(this.formulario.elements[i].value, expreg)) {
									this.formulario.elements[i].focus();
									alert('El formato de archivo no es soportado.');
									return false;
								}
								break;
						}
					}
				}
			}
		}
		for(i = 0 ; i < this.compara.length ; i++){
			if(!comparar(this.formulario.elements[this.compara[i][0]].value, this.formulario.elements[this.compara[i][1]].value)){
				this.formulario.elements[this.compara[i][0]].value = '';
				this.formulario.elements[this.compara[i][1]].value = '';
				this.formulario.elements[this.compara[i][0]].focus();
				alert(this.compara[i][2]);
				return 0;
			}
		}
		this.formulario.submit();
	}
	function valido(nombre) {
		for (k = 0 ; k < this.campos.length ; k++) {
			if(this.campos[k][0] == nombre)
				return this.campos[k];
		}
		return false;
	}
	function form_campo(ind){
		for(k = 0 ; k < this.formulario.elements.length ; k++){
			if(this.formulario.elements[k].name == this.campos[ind][0]){
				return k;
			}
		}
		return '';
	}
	function comparar(valor1, valor2) {
		if(valor1 == valor2)
			return true;
		else
			return false;
	}
	function agregar(nombre, mensaje, tipo, excepcion) {
		this.campos[this.campos.length] = new Array(nombre, mensaje, tipo, excepcion);
	}
	function c(nombre, mensaje, tipo, excepcion) {
		this.campos[this.campos.length] = new Array(nombre, mensaje, tipo, excepcion);
	}
	function validarEmail(valor) {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) {
			return true;
		} else {
			return false;
		}
	}
	function validarNumero(valor) {
		if (/^[0-9]+$/.test(valor)) {
			return true;
		} else {
			return false;
		}
	}
	function validarFecha(valor) {
		if (/^[0-9]{2,4}[\/-][0-9]{1,2}[\/-][0-9]{1,2}$/.test(valor)) {
			return true;
		} else if (/^[0-9]{1,2}[\/-][0-9]{1,2}[\/-][0-9]{2,4}$/.test(valor)) {
			return true;
		} else {
			return false;
		}
	}
	function validarHora(valor) {
		if (/^[0-9]{1,2}:[0-9]{2}(:[0-9]{2})?$/.test(valor)) {
			return true;
		} else {
			return false;
		}
	}
	function validarExtension(valor, expreg) {
		if (valor != '' && expreg.exec(valor)) {
			return true;
		} else {
			return false;
		}
	}
	function contrasena(campo1, campo2, mensaje1, mensaje2, mensaje3, excepcion1, excepcion2){
		this.agregar(campo1, mensaje1, '', excepcion1);
		this.agregar(campo2, mensaje2, '', excepcion2);
		this.compara[this.compara.length] = new Array(campo1, campo2, mensaje3);
	}
}
/******************************************************
Modo de uso:
//Declarar
valida = new validador(document.MyFormulario);

//Agregar los campos a validar
//valida.agregar('NombreCampo', 'Mensaje de error' [,'tipo de validacion(email|mumero)']);
valida.agregar('nombre', 'Ingrese su nombre');
valida.agregar('email', 'Ingrese su email', 'email');
valida.agregar('edad', 'Ingrese su edad', 'numero');

//Al hacer el submit
valida.validar();
*******************************************************/
