
// Este script solo añade a jquery el metodo validar. 

/************
*  $(jqueryString).validar(arrayDeConfiguracion)
*
*  Ejemplo:
*    	$("form").validar([
*			nombre : { validar : "soloTexto,obligatorio" , msg : "El nombre"}
*			email : { validar : "email,obligatorio" , msg : "El e-mail"}
*		])
*
*		nombre e email ---> son los names del os campos del formulario que estamos validando
*        validar : "XXXX" ---> son las validaciones que hacemos. Podemos poner las que queramos separadas por comas.
*        msg : "XXXX" ----> Cuando una validación falla se guarda un mensaje de que es lo que falla. msg: para ponerle un nombre al campo que falla.
*		 
*		Valores que puede haber dentro de validar:
* 			- obligatorio
* 			- seleccionado (= que obligatorio pero para selects)
* 			- checked (para checkboxes y ratios)
* 			- sinRepeticiones (no admitirá más de 4 elementos seguidos iguales)
* 			- soloTexto
* 			- email
* 			- telefonoEspana
* 			- telefono
* 			- cp
* 			- (hay que crear más)
*
*  Uso para ver si se hace o no un envio de formulario:
*	$(document).ready(function() {
*  		$("form").submit(function() {
*			return $(this).validar(arrayDeConfiguracion);
*		});
*	});
*
************/

function calcularNIE(nie)
{
  if ((!/^[Yy]{1}\d{1,8}[A-Za-z]{1}$/.test(nie)) && (!/^[Xx]{1}\d{1,8}[A-Za-z]{1}$/.test(nie)) && (!/^[Zz]{1}\d{1,8}[A-Za-z]{1}$/.test(nie))) { 
    return false;
  }else{
		var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
		var letra_inicial = nie.substr(0,1);
		var numero = nie.substr(1,nie.length-1);
		while (numero.substr(0,1) == '0') {
			numero = numero.substr(1,numero.length);
		}
		if (letra_inicial == 'Y'){
			numero = (parseInt(numero)-9)%23;
		}else{
			numero = parseInt(numero)%23;
		}		
		if (letras.substring(numero,numero+1) != nie.substring(nie.length-1).toUpperCase()) {return false;}
		else {return true;}
  }
}

jQuery.extend({
  validador : {
	form : $(), 
	msgs : [], 
	er : { 
		obligatorio : [ 
			new RegExp("(.)+") ,
			"Debes introducir [X]."
		],
		seleccionado : [ 
			new RegExp("(.)+") ,
			"Debes seleccionar [X]."
		],
		sinRepeticiones : [ 
			{ test : function( val ) {
				numRepeticionesPermitidas = 4;
				ret = true;
				var lc = val.charAt(0);
				var c = 1;
				for(i=1; i<val.length; i++){
					if ( val.charAt(i) == lc ){
						c++;
						if ( c >= numRepeticionesPermitidas ){
							ret = false;
							break;
						}
					} else {
					c = 1;
					lc = val.charAt(i);
					}
				}
				return ret;	}
			}, 
			"[X] no puede contener 4 caracteres iguales seguidos." 
		],
		soloTexto : [ 
			new RegExp("[A-Za-z]") ,
			"[X] s\xf3lo debe contener texto."
		],
		email : [ 
			new RegExp("^([a-zA-Z0-9_'+*$%\^&!\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$") ,
			"[X] debe ser una direcci\xf3n de e-mail correcta." 
		],
		telefonoEspana : [
			new RegExp("^(((6|8)[0-9]{8})|((9)[0-8][0-9]{7}))?$") ,
			//new RegExp("^((6|8|9)[0-9]{8})?$") ,
			//new RegExp("^((6|8|9)[0-8][0-9]{7})?$") ,
			"[X] debe ser un n\xfamero de 9 cifras y comenzar por 6, 8 o 9." 
		],
		telefono : [
			new RegExp("^([0-9]{4,})?$") , 
			"[X] debe ser un n\xfamero de al menos 4 cifras."
		],
		cp : [ 
			new RegExp("([0-4][0-9]{4})|(5[0-2][0-9]{3})") ,
			"[X] debe ser un c\xf3digo postal correcto." 
		],
		nif : [
			{ test : function( nif ) {
				if (nif == "") {
					return true;
				}
				if ( (!/^[YyXx]?\d{1,8}[A-Za-z]$/.test(nif)) ) {
					return false;
				}
				var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
				if ( (/^[YyXx]/.test(nif)) ) {
					var numero = nif.substr(1,nif.length-1);
				} else {
					var numero = nif.substr(0,nif.length-1);
				}
				numero = parseInt(numero)%23;
				if (letras.substring(numero,numero+1) != nif.substring(nif.length-1).toUpperCase()) {
					return false;
				}
				return true; }
			},
			"[X] debe ser un NIF correcto."
		],
		nie : [
			{ test : function( nie ) {
				if (nie == "") {
					return true;
				}
				if(!calcularNIE(nie)){
					return false;				
				}
				/*if ( (!/^[YyXx]\d{1,8}[A-Za-z]$/.test(nie)) ) {
					return false;
				}
				var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
				var numero = nie.substr(1,nie.length-1);
				numero = parseInt(numero)%23;
				if (letras.substring(numero,numero+1) != nie.substring(nie.length-1).toUpperCase()) {
					return false;
				}*/
				return true; }
			},
			"[X] debe ser un NIE correcto."
		]
	},
	run : function ( jqueryString , obj) { // Ejecuta la validación
		this.form = $(jqueryString);
		jQuery.each(obj, function(i, val) {
      		$.validador.test( val.validar , i , val.msg)
    	});
		if ( this.msgs.length > 0){
			this.printMsgs()
			return false;
		}
	},
	get : function (name){
		return this.form.find("[@name="+name+"]").val();
	},
	test : function ( ers , name , msg ) {
			if (ers != "checked") {
				var r= true;
				ers=ers.split(",");
				var value = this.get(name)
				for (i=0; i<ers.length; i++){
					er_obj = eval("jQuery.validador.er."+ers[i])
					if ( !er_obj[0].test(value) ){
						msg = er_obj[1].replace("[X]",msg);
						r = false;
						break;
					}
				}
			} else {
				if ( this.form.find("[@name="+name+"]").is(":checked") )
					var r = true;
				else
					var r =false;
			}
			if (!r) {
				this.msgs.push(msg);
			}
	},
	printMsgs : function (){
		var txt = "Se han encontrado errores en el formulario:\n";
		for (i=0; i<this.msgs.length; i++){
			txt += "\n - " + this.msgs[i];
		}
		alert(txt);
		this.msgs = [];
	}
	
  }
});

jQuery.fn.extend({
  validar: function( objVal ) {
	 return $.validador.run( this, objVal );
  }
});


