// Clases Validacion de formularios v 0.9 CR1

/*
Documentaci├│n Clase Validaci├│n v 0.9 CR1 13/11/2009

:validar , Parametros (Reglas, idForm, {Parametros JSON} )
	Reglas: Objeto JSon con la definici├│n de cada Relaga
	idForm: Id del contenedor o Formulario de campos
	JSON:
		funcion (string): nombre de la funci├│n a ejecutar si todo fue correcto
		submit (boolean): Hecemos submit del formulario
	Nota submi tiene prioridad
*/

var classValidar = new Class ({

  // -----------------------------------------------------
  // ----------- Validar ------------ Aplicamos las reglas
  // -----------------------------------------------------
  validar: function(reglas, id, Json){

		// -- Comprobamos parametros
		this.parametros(Json);
		// -- Comprobamos los campos definidos
		for (var campo in reglas ){

			var oCampo 	= $(campo);
			var oReglas	= reglas[campo];
			var sTipo	= oCampo.type.replace('-','');
			$bResultado = eval ("this."+sTipo+"(oCampo,oReglas);");
			if ( $bResultado == false ) return false;
		} // for

		// -- Si se especifico submit lo hacemos (Tiene prioridad)
		if ( this.submit ) {$(id).submit();}
		// -- Si se especifico la funci├│n la ejecutamos
		if ( !esVacio(this.funcion) ) {eval(this.funcion);}

		return true;
  },

  text: function (oCampo, oReglas) {

        oCampo.value = trim(oCampo.value);
	return this.aplicarReglas(oCampo, oReglas);

  },

  password: function (oCampo, oReglas) {

	return this.aplicarReglas(oCampo, oReglas);

  },

  checkbox: function (oCampo, oReglas) {

        if (oCampo.checked){
            return true;
        }
        else {
            oCampo.focus();
            $('span_'+oCampo.id).style.color='#FF0000';
   
            pf = new PulseFade('span_'+oCampo.id,{
		min: 0,
		max: 1,
		duration: 500,
                times: 0
                })
            pf.start();

            return false;
        }

  },


  textarea: function (oCampo, oReglas) {

	oCampo.value = trim(oCampo.value)
	return this.aplicarReglas(oCampo, oReglas);

  },

  selectone: function (oCampo, oReglas) {

	return this.aplicarReglas(oCampo, oReglas);

  },

  aplicarReglas: function (oElemento, oReglas) {

	var iControl = true;
	// -- Comprobamos si el campos es requerido
	iControl = this.requerido(oElemento, oReglas);
	/* Nivel de control de campo requerido
	1.- Requerido y Comprobamos
	2.- Requerido estaba vacio asi que ya hemos avisado
	3.- No era requerido	*/
	if ( iControl == 1 ) {
		// -- Comprobamos si el campos tiene un tipo a validar
		if ( !this.comprobar(oElemento, oReglas) ) {return false;}
		// -- Comprobamos si el campos sigue las siguentes reglas
		if ( !this.restricciones(oElemento, oReglas) ) {return false;}
		// -- Comprobamos si el campos tiene que ser igual a otro
		if ( !this.igualA(oElemento, oReglas) ) {return false;}
	}
	else if ( iControl == 2 ) {return false;}
	else if ( iControl == 3 ) {null}

  },

  // -----------------------------------------------------------------------
  // ----------- Parametros ------- Aplicamos los parametros si es requerido
  // -----------------------------------------------------------------------
  parametros: function(Json) {

		if ( !esVacio(Json) ) {
			if (Json.funcion) 	this.funcion = Json.funcion;
			if (Json.submit)	this.submit = Json.submit;
		}else { /*alert('Parametros incorrectos');*/ } //

  },

  // -----------------------------------------------------------------------
  // ----------- Requerido ------------ Aplicamos las reglas si es requerido
  // -----------------------------------------------------------------------
  requerido: function(oElemento, oReglas){
  	 // -- Comprobamos el mensaje si es campo es requerido
  	 var sMensaje = oReglas.mensaje;
  	 // -- Si es requerido comprobamos
	   if (oReglas.requerido == true) {
		// -- Si esta vacio
		if (oElemento.value == '' || oElemento.value==sMensaje) {
			// -- Si no hay mensaje definido mensaje por defecto
			if (oReglas.resaltar) this.resaltar(oElemento, oReglas);
			if (sMensaje == '' || sMensaje == undefined) {marcar(oElemento,'Compruebe campos','');return 2;}
			else {marcar(oElemento,sMensaje,'');return 2;}
		// -- Si hay mensaje mostramos
		} else {return 1;} // if (oElemento.value == '')
	   }else {return 3;} // if (oReglas.requerido)

   },

   // ------------------------------------------------------------------
   // ----------- Comprobar ------------ Aplicamos las reglas de tipos
   // ------------------------------------------------------------------
   comprobar: function(oElemento, oCampo) {

		// -- Obtenemos el Tipo
		var sTipo = oCampo.tipo;
		// -- Mostraos mensaje por defecto
		// -- Obtenemos valor del campo
		var sValorCampo = oElemento.value;
		var resultado = true;
		// -- Comprobamos que el valor cumpla el filtro de su tipo
                
		if ( existeTipo(sTipo) ) 	{ eval("resultado = "+sTipo+"('"+(str_replace("'",'"',sValorCampo))+"');"); }
		else 						{ /*alert('El tipo '+sTipo+' no est├í disponible.');*/ }
		if ( resultado == false) {
			if (oCampo.resaltar) this.resaltar(oElemento, oCampo);
			if (oCampo.mensajeValido == false || oCampo.mensajeValido == undefined) { marcar(oElemento,oCampo.mensajeValido,''); return false;}
			else {marcar(oElemento,oCampo.mensajeValido,'');return false;}
			return false;
		}else {return true;}
   },


   // ------------------------------------------------------------------
   // ----------- igualA ------------ comparamos 2 campos
   // ------------------------------------------------------------------
   igualA: function(oElemento, oCampo) {
		// -- Obtenemos el Tipo
		var sIgualA = $(oCampo.igualA);


                if (sIgualA && (sIgualA.value != oElemento.value)){
                    marcar(sIgualA,sIgualA.value,'');
                    marcar(oElemento,oCampo.mensajeDistinto,sIgualA.id);
                    return false;
                }
                return true;
   },
   // ------------------------------------------------------------------
   // ----------- Restriccion -------- Resticciones de campo
   // ------------------------------------------------------------------
   restricciones: function (oElemento, oCampo) {

		var sRestriccion = oCampo.restriccion;
		var sMsgRestriccion = oCampo.msgRestriccion;
		// -- Obtenemos valor del campo
		var sValorCampo = oElemento.value;
		var iOpcion = '';

		if ( strpos(sRestriccion,"mayor") 	!== false ) iOpcion = 0;
		if ( strpos(sRestriccion,"entre") 	!== false ) iOpcion = 1;
		if ( strpos(sRestriccion,"lmaximo") !== false ) iOpcion = 2;
		if ( strpos(sRestriccion,"lentre") 	!== false ) iOpcion = 3;
		if ( strpos(sRestriccion,"ligual") 	!== false ) iOpcion = 4;

		var bDenegado = false;

		switch ( iOpcion ) {
			case 0:
					if ( !Numero(sValorCampo) ) { /*alert('Restricci├│n imposible el campo no es de tipo n├║mero.');*/return false;}
					var iMayor = sRestriccion.substr(6,7);
					if ( parseInt(sValorCampo) <= parseInt(iMayor) ) bDenegado = true;
				break;
			case 1:
					if ( !Numero(sValorCampo) ) {/* alert('Restricci├│n imposible el campo no es de tipo n├║mero.');*/return false;}
					var iMayor = sRestriccion.substr(6,sRestriccion.length);
					var aDatos = iMayor.split(':');
					if ( parseInt(sValorCampo) <= parseInt(aDatos[0]) && parseInt(sValorCampo) >= parseInt(aDatos[1]) ) bDenegado = true;
				break;
			case 4:
					var longitud = sRestriccion.substr(6,sRestriccion.length);
                                        if (oElemento.value.length==longitud)
                                             bDenegado = false;
                                        else
                                             bDenegado = true;

				break;
		} // switch

		if ( bDenegado ) {
			if ( sMsgRestriccion == '' || sMsgRestriccion == undefined )/* alert('Compruebe Campo');*/
                            marcar(oElemento,oCampo.sMsgRestriccion,'');
                        //else {/*alert(sMsgRestriccion);*/}
			return false;
		}else {return true;}

   },

   // ------------------------------------------------------------------
   // ----------- Resaltar ------------ Si hay problemas resaltamos el campo
   // ------------------------------------------------------------------
   resaltar: function (oElemento, oCampo) {
   oElemento.focus();
   },

   // ------------------------------------------------------------------
   // ----------- Enviar ------------ Enviamos formualrio
   // ------------------------------------------------------------------
   enviar: function (id) {$(id).submit();}

} );

// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Funciones de dependecia de classValidar ----------------------------------------
// --------------------------------------------------------------------------------

function texto 		(sValorCompo)	{if ( sValorCompo == '' ) {resultado = false;}}
function email 		(sValorCompo)	{return isValidEmail(sValorCompo);}
function cif 		(sValorCompo)	{return isValidCif(sValorCompo);}
function nif 		(sValorCompo)	{return isValidNif(sValorCompo);}
function nifcifnie 	(sValorCompo) 	{return (valida_nif_cif_nie(sValorCompo)>0); }
function telefono 	(sValorCompo) 	{return isValidTelef(sValorCompo);}
function movil 		(sValorCompo)	{return isValidTelefMovil(sValorCompo);}
function fecha 		(sValorCompo)	{return isValidDateFormat(sValorCompo);}
function numero 	(sValorCompo)	{return Numero(sValorCompo);}

function existeTipo (function_name) {

	// Checks if the function exists
	// version: 909.322
	// discuss at: http://phpjs.org/functions/function_exists
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Steve Clay
	// +   improved by: Legaev Andrey
	// *     example 1: function_exists('isFinite');
	// *     returns 1: true
	if (typeof function_name == 'string'){return (typeof this.window[function_name] == 'function');}
	else {return (function_name instanceof Function);}

}

// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Funciones de Validacion --------------------------------------------------------
// --------------------------------------------------------------------------------

function strpos( haystack, needle, offset){

    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman
    // +   bugfixed by: Daniel Esteban
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14

    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

function trim (str, charlist) {
    var whitespace, l = 0, i = 0;
    str += '';
    if (!charlist) {
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    l = str.length;
    for (i = 0; i < l; i++) {if (whitespace.indexOf(str.charAt(i)) === -1) {str = str.substring(i);break;}}
    l = str.length;
    for (i = l - 1; i >= 0; i--) {if (whitespace.indexOf(str.charAt(i)) === -1) {str = str.substring(0, i + 1);break;}}
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}


function esVacio (valor) {
	if (valor == '' || valor == undefined) 	return true;
	else									return false;
}

function isValidCif(abc){
    par = 0;
    non = 0;
    letras = "ABCDEFGHKLMNPQS";
    let = abc.charAt(0);

    if (abc.length!=9) {
        //alert('El Cif debe tener 9 d├¡gitos');
        return false;
    }

    if (letras.indexOf(let.toUpperCase())==-1) {
        //alert("El comienzo del Cif no es v├ílido");
        return false;
    }

    for (zz=2;zz<8;zz+=2) {
        par = par+parseInt(abc.charAt(zz));
    }

    for (zz=1;zz<9;zz+=2) {
        nn = 2*parseInt(abc.charAt(zz));
        if (nn > 9) nn = 1+(nn-10);
        non = non+nn;
    }

    parcial = par + non;
    control = (10 - ( parcial % 10));
    if (control==10) control=0;

    if (control!=abc.charAt(8)) {
        //alert("El Cif no es v├ílido");
        return false;
    }
    //alert("El Cif es v├ílido");
    return true;
}


function isValidNif(abc){
    dni=abc.substring(0,abc.length-1);
    let=abc.charAt(abc.length-1);
    if (!isNaN(let)) {
        //alert('Falta la letra');
        return false;
    }else{
        cadena = "TRWAGMYFPDXBNJZSQVHLCKET";
        posicion = dni % 23;
        letra = cadena.substring(posicion,posicion+1);
        if (letra!=let.toUpperCase()){
            //alert("Nif no v├ílido");
            return false;
        }
    }
    //alert("Nif v├ílido")
    return true;
}



function isValidEmail(str){
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return (filter.test(str));
}

function isValidTelef(num){
    if(num.length < 9){
        return false;
    }else if(isNaN( num )){
        return false;
    }else{
        return true;
    }
}

function isValidTelefMovil (num) {
    if(num.length < 9){
        return false;
    }else if(isNaN( num )){
        return false;
    }else if (num[0] != '6'){
        return false;
    }else{
        return true;
    }
}

function isValidDateFormat(str){
    var filter=/^(\d{1,2}\/\d{1,2}\/\d{2})$/i;
    return (filter.test(str));
}


function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };

    return sa ? s : s[0];
}

//Retorna: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF error, -2 = CIF error, -3 = NIE error, 0 = ??? error
function valida_nif_cif_nie(a)
{
    var temp=a.toUpperCase();
    var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";

    if (temp!==''){
        //si no tiene un formato valido devuelve error
        if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
        {
            return 0;
        }

        //comprobacion de NIFs estandar
        if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
        {
            posicion = a.substring(8,0) % 23;
            letra = cadenadni.charAt(posicion);
            var letradni=temp.charAt(8);
            if (letra == letradni)
            {
                   return 1;
            }
            else
            {
                return -1;
            }
        }

        //algoritmo para comprobacion de codigos tipo CIF
        suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
        for (i = 1; i < 8; i += 2)
        {
            temp1 = 2 * parseInt(a[i]);
            temp1 += '';
            temp1 = temp1.substring(0,1);
            temp2 = 2 * parseInt(a[i]);
            temp2 += '';
            temp2 = temp2.substring(1,2);
            if (temp2 == '')
            {
                temp2 = '0';
            }

            suma += (parseInt(temp1) + parseInt(temp2));
        }
        suma += '';
        n = 10 - parseInt(suma.substring(suma.length-1, suma.length));

        //comprobacion de NIFs especiales (se calculan como CIFs)
        if (/^[KLM]{1}/.test(temp))
        {
            if (a[8] == String.fromCharCode(64 + n))
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }

        //comprobacion de CIFs
        if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
        {
            temp = n + '';
            if (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
            {
                return 2;
            }
            else
            {
                return -2;
            }
        }

        //comprobacion de NIEs
        //T
        if (/^[T]{1}/.test(temp))
        {
            if (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
            {
                return 3;
            }
            else
            {
                return -3;
            }
        }

        //XYZ
        if (/^[XYZ]{1}/.test(temp))
        {
            pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
            if (a[8] == cadenadni.substring(pos, pos + 1))
            {
                return 3;
            }
            else
            {
                return -3;
            }
        }
    }

    return 0;
}

function Numero(v){
	var ok=1, i;
	var check=".0123456789";
	for(i=0;i<v.length && ok==1;i++){
		ok=0;
		for(j=0;j<check.length && ok==0;j++){
			if (check.charAt(j) == v.charAt(i))
				ok=1;
		}
	}
	if (ok==0) return false;
	return true;
}



function marcar(elemento,mensaje,igualA){
        elemento.addEvent('focus', function(){
                        if ($('span_'+this.id) && $('span_'+this.id).style.color!='rgb(0, 0, 0)') {
                            $('span_'+this.id).style.color='#000000';
                            this.style.backgroundColor='#FFFFFF';
                            this.value=this.title;
                            if (igualA!=''){
                                $(igualA).style.backgroundColor='#FFFFFF';
                                $('span_'+igualA).style.color='#000000';
                            }
                        }
                        });
                       elemento.title=elemento.value;
                       elemento.value=mensaje;
                       if ($('seguro'))
                            $('seguro').focus();
                       $('span_'+elemento.id).tween('color', ['#000000', '#FF0000']);
                       elemento.tween('background-color', ['#FFFFFF', '#fd9696']);
    }


window.addEvent('load',function () {

	oValidator = new classValidar();


});




var PulseFade = new Class({

	//implements
	Implements: [Options,Events],

	//options
	options: {
		min: 0,
		max: 1,
		duration: 200,
		times: 5
	},

	//initialization
	initialize: function(el,options) {
		//set options
		this.setOptions(options);
		this.element = $(el);
		this.times = 0;
	},

	//starts the pulse fade
	start: function(times) {
		if(!times) times = this.options.times * 2;
		this.running = 1;
		this.fireEvent('start').run(times -1);
	},

	//stops the pulse fade
	stop: function() {
		this.running = 0;
		this.fireEvent('stop');
	},

	//runs the shizzle
	run: function(times) {
		//make it happen
		var self = this;
		var to = self.element.get('opacity') == self.options.min ? self.options.max : self.options.min;
		self.fx = new Fx.Tween(self.element,{
			duration: self.options.duration / 2,
			onComplete: function() {
				self.fireEvent('tick');
				if(self.running && times)
				{
					self.run(times-1);
				}
				else
				{
					self.fireEvent('complete');
				}
			}
		}).start('opacity',to);
	}
});

function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
