/**
 * FUNCIONALIDAD: Clase para validar todo tipo de formularios y así agilizar el proceso.
 * 		   FECHA: Marzo 2008
 *       EMPRESA: VisualNT
 *   PROGRAMADOR: Fernando Pascua García
*/ 


// Declaración de clase "Validador"
var Validador = function(id,obj){
	if(!Validador.Objetos){ 
		Validador.Objetos = new Array();
		this.NumObj = 0;
	} else 	this.NumObj = Validador.Objetos.length;
	Validador.Objetos[this.NumObj] = this;
	this.PuntActual = 0;
	this.PuntFinal = 0;
	this.form = id;
	this.mensajeError = '';
	this.nomObjeto = obj;
	var opciones = arguments[2] || {};
	this.colorError = opciones.colorError || 'red';
	this.fuenteError = opciones.fuenteError || 'Arial';
	this.fuenteSize = opciones.fuenteSize || '12pt';
	this.imgError = (opciones.imgError)? ((opciones.imgError == 'SI')? true : false) : true; //defecto true
	this.imgCorrecto = (opciones.imgCorrecto)? ((opciones.imgCorrecto == 'SI')? true : false) : true;
	this.onBlur = (opciones.onBlur)? ((opciones.onBlur == 'SI')? true : false) : true;
	this.focusEnter = (opciones.focusEnter)? ((opciones.focusEnter == 'SI')? true : false) : true;
	this.onSubmitResp = '';
	this.Gecko = this.ValidaGecko();	
	this.validaForm();
}


Validador.prototype = {
	validaForm: function() {
		var form = document.getElementById(this.form);
		var input = '';
		var tipo = '';
		for (var i=0; i<form.getElementsByTagName('input').length; i++){
			input = form.getElementsByTagName('input')[i];
			if (this.focusEnter) // añadir foco con intro
				if (input.getAttribute('type') != 'button' && input.getAttribute('type') != 'submit')
					this.ponerEvento(input,'onkeypress','return '+ this.nomObjeto + ".Enter(this,event);" );
			input.className="campo";
			tipo = input.getAttribute('tipo');
			if (tipo){
				this.seleccionaTipo(tipo,input);
				this.ponerAtributo(input,'correcto','true');
			}
		}
		for (var i=0; i<form.getElementsByTagName('select').length; i++){
			input = form.getElementsByTagName('select')[i];
			if (this.focusEnter) // añadir foco con intro
					this.ponerEvento(input,'onkeypress','return '+ this.nomObjeto + ".Enter(this,event);" );
			input.className="campo";
			tipo = input.getAttribute('tipo');
			if (tipo){
				this.seleccionaTipo(tipo,input);
				this.ponerAtributo(input,'correcto','true');
			}
		}
		for (var i=0; i<form.getElementsByTagName('textarea').length; i++){
			input = form.getElementsByTagName('textarea')[i];
			if (this.focusEnter) // añadir foco con intro
					this.ponerEvento(input,'onkeypress','return '+ this.nomObjeto + ".Enter(this,event);" );
			input.className="campo";
			tipo = input.getAttribute('tipo');
			if (tipo){
				this.seleccionaTipo(tipo,input);
				this.ponerAtributo(input,'correcto','true');
			}
		}
		this.ponerEvento(form,'onsubmit', 'return ' +this.nomObjeto +'.todoCorrecto();');
	},

	validaInput: function(input){
		var tipo = '';
		if (input.tagName.toLowerCase() == 'input'){
			if (this.focusEnter) // añadir foco con intro
				if (input.getAttribute('type') != 'button' && input.getAttribute('type') != 'submit')
					this.ponerEvento(input,'onkeypress','return '+ this.nomObjeto + ".Enter(this,event);" );
			input.className="campo";
			tipo = input.getAttribute('tipo');
			if (tipo){
				this.seleccionaTipo(tipo,input);
				this.ponerAtributo(input,'correcto','true');
			}
		} else if (input.tagName.toLowerCase() == 'select'){
			if (this.focusEnter) // añadir foco con intro
					this.ponerEvento(input,'onkeypress','return '+ this.nomObjeto + ".Enter(this,event);" );
			input.className="campo";
			tipo = input.getAttribute('tipo');
			if (tipo){
				this.seleccionaTipo(tipo,input);
				this.ponerAtributo(input,'correcto','true');
			}
		} else if (input.tagName.toLowerCase() == 'textarea'){
			if (this.focusEnter) // añadir foco con intro
					this.ponerEvento(input,'onkeypress','return '+ this.nomObjeto + ".Enter(this,event);" );
			input.className="campo";
			tipo = input.getAttribute('tipo');
			if (tipo){
				this.seleccionaTipo(tipo,input);
				this.ponerAtributo(input,'correcto','true');
			}
		}
	},

	seleccionaTipo: function(tipo,input){
		switch(tipo){
			case 'expresion':
				var expr = input.getAttribute('expresion');
				this.completaForm(input, 'onblur', this.nomObjeto + ".validaExpr('"+ input.id + "','" + expr + "');");
			break;
			case 'contraseña':
				var otro_id = input.getAttribute('otro_id');
				this.completaForm(document.getElementById(otro_id), 'onblur', this.nomObjeto + ".validaContra('"+ input.id + "','" + otro_id + "');");
				this.ponerAtributo(document.getElementById(otro_id),'otro_id',input.getAttribute('id'));
				if (input.getAttribute('calidadContra') == 'SI'){
					this.completaForm(input, 'onkeyup', this.nomObjeto + ".validaCalidadContra('"+ input.id + "');");
					this.longitudCalidad = input.getAttribute('longitudCalidad') || '184';
					if (input.getAttribute('divCalidad')){
			 			this.divCalidad = input.getAttribute('divCalidad');
						document.getElementById(this.divCalidad).style.paddingTop = '5px';
						var t = '<div style="visibility:visible; position:relative; overflow:hidden; width:'+ this.longitudCalidad +'px; height:12px; background-color:white; border:1px solid #DDDDDD; text-align:center; vertical-align:center; font-size:8pt;"><span style=" background-color:white;left:0px; width:0%; height:40px; position:absolute; font-size:1px;"></span><span style="left:0px; width:100%; height:100%; position:absolute; text-align:center; font-size:8pt; color:#AAAAAA; font-family: Arial,sans-serif; font-weight:bold;">0%</span></div>';
						document.getElementById(this.divCalidad).innerHTML = t;	
					}
				}
			break;
			default:
				this.completaForm(input, 'onblur', this.nomObjeto + ".valida"+ tipo +"('"+ input.id + "');");
			break;
		}
	}, 

	validafecha: function(id) {
		this.recogerParamComunes(id);
		this.formFecha = this.input.getAttribute('formFecha') || 'aaaa*mm*dd';
		this.sepFecha = this.input.getAttribute('sepFecha') || '-';
		var fecha = this.input.value;
		this.validaLong(fecha);
		this.esFecha(fecha);
		this.muestraResultado(fecha);
	},	

	esFecha: function(fecha) {
		switch (this.formFecha) {
			case 'aaaa*mm*dd':
				var formato_valido = new RegExp('^\\d{4}\\'+ this.sepFecha + '\\d{2}\\' + this.sepFecha + '\\d{2}$');
				var año = fecha.split(this.sepFecha)[0]
				var mes = fecha.split(this.sepFecha)[1]
				var dia = fecha.split(this.sepFecha)[2]
			break;
			case 'dd*mm*aaaa':
				var formato_valido = new RegExp('^\\d{2}\\'+ this.sepFecha + '\\d{2}\\' + this.sepFecha + '\\d{4}$');
				var mes = fecha.split(this.sepFecha)[1]
				var dia = fecha.split(this.sepFecha)[0]
				var año = fecha.split(this.sepFecha)[2]
			break;				
		}
		if (!formato_valido.test(fecha))  // comprobamos el formato de la fecha
			this.mensajeErrorFinal(' ::Formato de fecha inválido');
		else {  // comprobamos si el rango de fechas es válido
			var fecha2 = new Date(año, mes-1, dia)
			if ((fecha2.getMonth()+1!=mes)||(fecha2.getDate()!=dia)||(fecha2.getFullYear()!=año))
				this.mensajeErrorFinal(' ::Fecha no válida');
		}
	},

	validahora: function(id) {
		this.recogerParamComunes(id);
		var hora = this.input.value;
		this.formHora = this.input.getAttribute('formHora') || '24h';
		this.sepHora = this.input.getAttribute('sepHora') || ':';
		this.validaLong(hora);
		this.esHora(hora);
		this.muestraResultado(hora);		
	},

	esHora: function(hora) {
		var er_hora = new RegExp('^\\d{2}\\'+ this.sepHora + '\\d{2}\\' + this.sepHora + '\\d{2}$');
		if(!er_hora.test(hora))
			this.mensajeErrorFinal(' ::Formato no válido');
		else {
			var h = hora.split(this.sepHora)[0];
			var m = hora.split(this.sepHora)[1];
			var s = hora.split(this.sepHora)[2];
			var formHora = 23;
			if (this.formHora == '12h') // si queremos formato de 12 horas
				formHora = 11;
			if (!((h <= formHora && h >= 0) && (m <= 59 && m >= 0) && (s <= 59 && s >= 0)))
				this.mensajeErrorFinal(' ::Hora no válida');							
		}			
	},

	validafechaHora: function(id) {
		this.recogerParamComunes(id);
		var fechaHora = this.input.value;
		this.validaLong(fechaHora);
		this.formFecha = this.input.getAttribute('formFecha') || 'aaaa*mm*dd';
		this.sepFecha = this.input.getAttribute('sepFecha') || '-';
		this.formHora = this.input.getAttribute('formHora') || '24h';
		this.sepHora = this.input.getAttribute('sepHora') || ':';
		var er_fechaHora = new RegExp('^(\\d{4}\\'+ this.sepFecha + '\\d{2}\\' + this.sepFecha + '\\d{2})|(\\d{2}\\' + this.sepFecha + '\\d{2}\\' + this.sepFecha + '\\d{4}) \\d{2}\\'+ this.sepHora + '\\d{2}\\' + this.sepHora + '\\d{2}$');
		if(!er_fechaHora.test(fechaHora))
			this.mensajeErrorFinal(' ::Formato no válido');		
		else {
			this.esFecha(fechaHora.split(' ')[0]);
			this.esHora(fechaHora.split(' ')[1]);
		}
		this.muestraResultado(fechaHora);
	},

	validaentero: function(id) {
		this.recogerParamComunes(id);
		var numero = this.input.value;
		this.validaLong(numero);

		var formato_valido = /^(\+|-)?\d+$/;
		if (!formato_valido.test(numero))
			this.mensajeErrorFinal(' ::Debe introducir un número sin cifras decimales');

		this.muestraResultado(numero);
	},

	validafloat: function(id) {
		this.recogerParamComunes(id);
		var numero = this.input.value;
		this.validaLong(numero);

		var formato_valido = /^(\+|-)?\d+(\.\d+)?$/;
		if (!formato_valido.test(numero))
			this.mensajeErrorFinal(' ::Debe introducir un número');

		this.muestraResultado(numero);
	},

	validaemail: function(id) {
		this.recogerParamComunes(id);
		var email = this.input.value;
		this.validaLong(email);
		var formato_valido = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
		if (!formato_valido.test(email))  // comprobamos el formato del email
			this.mensajeErrorFinal(' ::Formato de email inválido');

		this.muestraResultado(email);
	},

	validaCIF_NIF: function(id) {
		this.recogerParamComunes(id);
		var CIF = this.input.value;
		//this.juridico = this.input.getAttribute('tipoCIF') || '0';
		CIF = CIF.replace(/ /g,''); // quito los espacios en blanco
		this.validaLong(CIF);
		var uno = CIF.substr(0,1);
		var dos	= CIF.substr(1,1);
		var lei = '';
		var num = '';
		var lef = '';
		var flag = true;
		if ((uno + dos) == "ES"){ // es un NIF español.
			CIF = CIF.substr(2); // elimino ES de la cadena
			uno = CIF.substr(0,1);
			dos	= CIF.substr(1,1);				
		}	
		if (uno.length == 0 || dos.length == 0)
			this.mensajeErrorFinal(' :: Formato no válido');			
		else if (/[0-9]/.test(uno)){	 // es un NIF físico español
			num = CIF;
			lef = num.substr(num.length-1,1);
			if (/[0-9]/.test(lef))
				lef = '';
			else 
				num = num.substr(0,num.length-1);
			var nif = '00000000' + num;
			nif = nif.substr(nif.length-8);
			this.esNifFisico(nif + lef);			
		} else if (/[XKLM]/.test(uno)){  // es un NIF físico especial
			num = CIF.substr(1);
			lef = num.substr(num.length-1,1);
			if (/[0-9]/.test(lef))
				lef = '';
			else 
				num = num.substr(0,num.length-1);
			var nif = '00000000' + num;
			nif = nif.substr(nif.length-8);
			this.esNifFisico(nif + lef);			
		} else if (/[0-9]/.test(dos)){   // es un NIF jurídico español
			lei = uno;
			num = CIF.substr(1);
			lef = num.substr(num.length-1,1);
			num = num.substr(0,num.length-1);
			//var nij = '0000000' + num;
			//nij = nij.substr(nij.length-7);
			nij = num;
			this.esNifJuridico(lei + nij + lef);
		} else if (/^([A-Z]{2})[a-zA-Z0-9]*$/.test(CIF)){  // es un NIF jurídico o físico extranjero
		} else {
			this.mensajeErrorFinal(' :: Formato no válido');			
		}
		this.muestraResultado(CIF);	
	},
			
	esNifJuridico: function(CIF) {
		var resul = false;
		CIF = CIF.toUpperCase(); // Pasar a mayúsculas
		if (!/^[A-Za-z0-9]{9}$/.test(CIF)) //Son 9 dígitos
			this.mensajeErrorFinal(' ::Longitud incorrecta, un CIF consta de 9 dígitos');
		else if (!/^[ABCDEFGHNPQS]/.test(CIF)){ //Es una letra de las admitidas
			this.mensajeErrorFinal(' ::El primer dígito del CIF no es correcto');
  		}else{
			resul = true;
		}
		if (resul){
			var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
			var v2 = new Array('J','A','B','C','D','E','F','G','H','I');
			var temp = 0;

			for(var i = 2; i <= 6; i += 2 ){
				temp = temp + v1[parseInt(CIF.substr(i-1,1))];
				temp = temp + parseInt(CIF.substr(i,1));
			}

			temp = temp + v1[ parseInt(CIF.substr(7,1))];
			temp = (10 - ( temp % 10));

			var codigoControl = 0;
			if( temp == 10 )
				codigoControl = 0;
			else
				codigoControl = temp;
			if ((CIF.substr(8,1) != codigoControl) && (CIF.substr(8,1) != v2[codigoControl]))
				this.mensajeErrorFinal(' ::El último dígito no es correcto');		
		}
	},

	esNifFisico: function(NIF) {
		flag = true;
		var patron = "TRWAGMYFPDXBNJZSQVHLCKET";
		NIF = NIF.replace(/ /g,''); // quito los espacios en blanco
		var er_NIF = /^[0-9]+[TRWAGMYFPDXBNJZSQVHLCKET]$/;
		if(!er_NIF.test(NIF)){
			this.mensajeErrorFinal(' ::Formato no válido');
			flag = false;
		}
		if (flag){
			var numeros = NIF.substr(0,NIF.length-1);
			var letra = NIF.substr(NIF.length-1,1);
			if (letra != patron.substr((numeros % 23),1)){
				this.mensajeErrorFinal(' ::La letra no corresponde con ese DNI');
			}
		}		
	},

	validaCIB: function(id) {
		this.recogerParamComunes(id);
		var CIB = this.input.value;
		CIB = CIB.replace(/ /g,''); // quito los espacios en blanco
		this.validaLong(CIB);
		var pais = CIB.substr(0,2);
		if (CIB.length != 14)
			this.mensajeErrorFinal(' :: El CIB debe tener 14 dígitos');		
		else if (pais == 'ES'){
			var digit_aut = CIB.substr(2,1);  // dígito a disposición de la autoridad competente
			var digit_con = CIB.substr(3,1);  // dígito de control
			var cod_INE = CIB.substr(4,2);    // código INE comunidad autónoma
			var num_ser = CIB.substr(6,4);    // número de serie
			var numerac = CIB.substr(10,4);    // numeración
			var oper = cod_INE + num_ser + numerac;
			if (this.esINE(cod_INE)){
				var sum = 0;
				var v = new Array(1,2,3,4,5,6,7,8,9,1);
				for (i=0; i<oper.length; i++)
					sum += oper.substr(i,1) * v[i];
				if (digit_con != (sum % 10))
					this.mensajeErrorFinal(' :: CIB incorrecto');
			}
		} else if (!/^[A-Z]{2}$/.test(pais)){
			this.mensajeErrorFinal(' :: CIB incorrecto');
		}
		this.muestraResultado(CIB);		
	},

	validaCBV: function(id) {
		this.recogerParamComunes(id);
		var CB = this.input.value;
		CB = CB.replace(/ /g,''); // quito los espacios en blanco
		this.validaLong(CB);
		var pais = CB.substr(0,3);
		if (CB.length != 14)
			this.mensajeErrorFinal(' :: El Cód. Barras debe tener 14 dígitos');	
		else if (pais == '084'){
			var cod_INE = CB.substr(3,2);    // código INE comunidad autónoma
			var num_ser = CB.substr(5,4);    // número de serie
			var numerac = CB.substr(9,4);    // numeración
			var oper = cod_INE + num_ser + numerac;
			var digit_con = CB.substr(13,1); // dígito de control
			if (this.esINE(cod_INE)){
				var sum = 0;
				var v = new Array(1,2,3,4,5,6,7,8,9,1);
				for (i=0; i<oper.length; i++)
					sum += oper.substr(i,1) * v[i];
				if (digit_con != (sum % 10))
					this.mensajeErrorFinal(' :: Cód. Barras incorrecto');
			}
		} else {
			this.mensajeErrorFinal(' :: Cód. barras incorrecto');
		}
		this.muestraResultado(CB);	
	},

	esINE: function(INE) {
		if (!/^(0[1-9])|([1][0-7])$/.test(INE)){
			this.mensajeErrorFinal(' :: Cód. comunidad(INE)  incorrecto');
			return false;
		}
		return true;
	},

	validatelefono: function(id) {
		this.recogerParamComunes(id);
		var tlf = this.input.value;
		this.validaLong(tlf);
		var er_tlfono = /^[0-9]{9}$/;
		if(!er_tlfono.test(tlf))
			this.mensajeErrorFinal(' ::Formato no válido');
		this.muestraResultado(tlf);			
	},

	validaExpr: function(id,expr) {
		this.recogerParamComunes(id);
		var valor = this.input.value;
		this.validaLong(valor);

		var formato_valido = new RegExp(expr);

		if (!formato_valido.test(valor)){  // comprobamos el formato de la expresión
			this.mensajeErrorFinal(' ::Formato no válido');
		}
		this.muestraResultado(valor);
	},

	validaContra: function(id,id_r) {
		this.recogerParamComunes(id);
		var contraseña = this.input.value;
		this.validaLong(contraseña);
		var contraseña2 = document.getElementById(id_r).value;

		if (contraseña != contraseña2)  // comprobamos coinciden las dos contraseñas
			this.mensajeErrorFinal(' ::Escriba la misma contraseña');
		this.muestraResultado(contraseña);
	},

	validaCalidadContra: function(id) {
		this.recogerParamComunes(id);
		var contraseña = this.input.value;
		this.PuntFinal = 0;
		var formato_may = /[A-Z]/;
		var formato_minusc = /[a-z]/;
		var formato_numeros = /\d/;
		var formato_espec = /(\s|\\|\/|!|·|\$|%|&|\(|\)|=|\?|¿|\||@|#|¬|€|\^|`|\[|\]|\+|\*|¨|´|\{|\}|\-|_|\.|:|,|;|>|<)/;
		var longitud = contraseña.length;
		if (longitud > 6) 
			longitud = 6;
		if (formato_may.test(contraseña))
			this.PuntFinal += 10;
		if (formato_minusc.test(contraseña))
			this.PuntFinal += 10; 
		if (formato_numeros.test(contraseña))
			this.PuntFinal += 10; 
		if (formato_espec.test(contraseña))
			this.PuntFinal += 10; 
		this.PuntFinal += (longitud * 10);
		if (this.tiempo)
				clearInterval(this.tiempo);
		this.tiempo = window.setInterval ('Validador.Objetos['+this.NumObj+'].dibujarBarra()', 1);
	},

	validaTC :function (id){
		this.recogerParamComunes(id);
		var sepTC = this.input.getAttribute('sepTC') || null;
		var tarjeta = this.input.value;
		this.validaLong(tarjeta);
		if (sepTC != null)
			var er_TC = new RegExp('^\\d{4}\\'+sepTC+'\\d{4}\\'+sepTC+'\\d{4}\\'+sepTC+'\\d{4}$');
		else var er_TC = new RegExp('^\\d{4}\\d{4}\\d{4}\\d{4}$');
		if (!er_TC.test(tarjeta)){
			this.mensajeErrorFinal(' ::Formato de tarjeta no válida');
		} else {
			tarjeta = tarjeta.replace(/[^0-9]/g,''); // elimino todo lo que sea distinto de numero
			var suma = 0;
			var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
			for (var i=1; i<tarjeta.length; i+=2){
				suma += parseInt(tarjeta.substr(i,1));
				suma += v1[parseInt(tarjeta.substr(i-1,1))];
			}
			if ((suma % 10) != 0)
				this.mensajeErrorFinal(' ::Tarjeta no válida');
		}
		this.muestraResultado(tarjeta);
	},

	validaURL: function(id) {
		this.recogerParamComunes(id);
		var URL = this.input.value;
		URL = URL.replace(/ /g,''); // quito los espacios en blanco
		this.validaLong(URL);
		var er_URL = /^(file:\/\/|http:\/\/www.|https:\/\/www.|ftp:\/\/)\S+(\.\w{2,3})+$/;
		if (!er_URL.test(URL))
			this.mensajeErrorFinal(' ::URL no válida');
		this.muestraResultado(URL);		
	},

	validaselecSimple: function(id) {
		this.recogerParamComunes(id);
		this.distintoDe = this.input.getAttribute('distintoDe') || '';
      		var seleccion = this.input.options[this.input.selectedIndex].value;
		if (this.distintoDe != '')
			if (!this.esDistintoDe(this.distintoDe.split('|')))
				this.mensajeErrorFinal(' ::Opción no válida, seleccione otra');	
		if (this.input.selectedIndex == 0)	
			this.muestraResultado('');
		else this.muestraResultado(seleccion);								
	},

	esDistintoDe: function(arr_valores) {
		for (var i=0; i<arr_valores.length; i++)
			if (this.input.selectedIndex == arr_valores[i])
				return false;
		return true;
	},

	validaselecMulti: function(id) {
		this.recogerParamComunes(id);
		this.recogerParamSelec(this.input);
		this.distintoDe = this.input.getAttribute('distintoDe') || '';
        var seleccionados = new Array();
	    var index = 0;
        for (var i=0; i<this.input.options.length; i++)
	    	if (this.input.options[i].selected){
				seleccionados[index] = i;
				index++;
		}

		if (this.distintoDe != ''){
			var arr_distinto = this.distintoDe.split('|');
			for (var i=0; i<arr_distinto.length; i++)
				for (var j=0; j<seleccionados.length; j++)
					if (seleccionados[j] == arr_distinto[i])
						this.mensajeErrorFinal(' ::Opción ' + this.input.options[seleccionados[j]].value + ' no válida, seleccione otra');	
		}
		this.hayAlMenos(seleccionados);
			
		if (seleccionados.length == 0)	
			this.muestraResultado('');
		else this.muestraResultado('hay datos');								
	},

	validacheckBox: function(id) {
		this.recogerParamComunes(id);
		this.recogerParamSelec(this.input);
		var nombre = this.input.getAttribute('name');
        var seleccionados = new Array();
		var index = 0;
		var inputs = document.getElementById(this.form).getElementsByTagName('input');

		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type')=='checkbox'){
				if (inputs[i].getAttribute('name') == nombre)
					if (inputs[i]["checked"]){
						seleccionados[index] = inputs[i].value;
						index++;
					}
			}
		}
		this.hayAlMenos(seleccionados);
			
		if (seleccionados.length == 0)	
			this.muestraResultado('');
		else this.muestraResultado('hay datos');
	},

	recogerParamSelec: function(input){
		this.selecMin = input.getAttribute('selecMin') || '';
		this.selecMax = input.getAttribute('selecMax') || '';
		this.numSelec = input.getAttribute('numSelec') || '';
	},

	hayAlMenos: function(seleccionados){
		if (this.numSelec != '')
			if (seleccionados.length != this.numSelec)
				this.mensajeError = ' ::Ha de seleccionar ' + this.numSelec + ' opciones';
		if (this.selecMin != '')
			if (seleccionados.length < this.selecMin)
				this.mensajeError = ' ::Ha de seleccionar al menos ' + this.selecMin + ' opciones';			
		if (this.selecMax != '')
			if (seleccionados.length > this.selecMax)			
				this.mensajeError = ' ::Ha de seleccionar menos de ' + this.selecMax + ' opciones';
	},

	validaradioB: function(id){
		this.recogerParamComunes(id);
		var nombre = this.input.getAttribute('name');
        	var seleccion = false;
		var inputs = document.getElementById(this.form).getElementsByTagName('input');

		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type')=='radio')
				if (inputs[i].getAttribute('name') == nombre)
					if (inputs[i]["checked"])
						seleccion = true;
		}
			
		if (!seleccion)	
			this.muestraResultado('');
		else this.muestraResultado('hay datos');
	},

	validatextarea: function(id){
		this.recogerParamComunes(id);
		var texto = this.input.value;
		this.validaLong(texto);
		this.muestraResultado(texto);
	},

	validalongitud: function(id) {
		this.recogerParamComunes(id);
		var longitud = this.input.value;
		this.validaLong(longitud);
		this.muestraResultado(longitud);
	},

	validaLong: function(valor){
		if (this.longitud != '')
			if (valor.length != this.longitud)
				this.mensajeError = ' ::La longitud ha de ser de ' + this.longitud;
		if (this.longMin != '')
			if (valor.length < this.longMin)
				this.mensajeError = ' ::La longitud ha de ser mayor de ' + this.longMin;			
		if (this.longMax != '')
			if (valor.length > this.longMax)			
				this.mensajeError = ' ::La longitud ha de ser menor de ' + this.longMax;
	},

	mensajeErrorFinal: function(mensaje){
		if (this.mensajeErrorUsuario != '')
			this.mensajeError = this.mensajeErrorUsuario;
		else this.mensajeError = mensaje;
	},

	muestraResultado: function(valor){
		if (!(this.obligatorio) && valor == ''){
			if (!this.comprobarAntec()){
				this.ponerAtributo(this.input,'correcto','true');
				this.correcto();
			} else {
				this.mensajeError = ' ::Campo Obligatorio';
				this.ponerAtributo(this.input,'correcto','false');
				this.mostrarError();
			}
		}
		if (this.obligatorio && valor == ''){
			this.mensajeError = ' ::Campo Obligatorio';
			this.ponerAtributo(this.input,'correcto','false');
			this.mostrarError();
		}
		if (valor != ''){	
			if (this.mensajeError != ''){
				this.ponerAtributo(this.input,'correcto','false');
				this.mostrarError();
			} else {
				this.ponerAtributo(this.input,'correcto','true');
				this.correcto();
			}
		}
	},

	comprobarAntec: function() {
		this.antec = this.input.getAttribute('obligSi') || '';
		var antecedentes = new Array();
		var obj = '';
		if (this.antec != ''){
			antecedentes = this.antec.split('|');
			for (var j=0; j<antecedentes.length; j++){
				obj = document.getElementById(antecedentes[j]);
				if (obj.getAttribute('tipo') == 'checkBox'){
					var nombre = obj.getAttribute('name');
			        	var seleccionados = new Array();
					var index = 0;
					var inputs = document.getElementById(this.form).getElementsByTagName('input');

					for(var i=0; i<inputs.length; i++){
						if(inputs[i].getAttribute('type')=='checkbox'){
							if (inputs[i].getAttribute('name') == nombre){
								if (inputs[i]["checked"]){
									seleccionados[index] = inputs[i].value;
									index++;
								}
							}
						}
					}
					if (seleccionados.length == 0)
						return false;
				} else if (obj.getAttribute('tipo') == 'radioB'){
					var seleccion = false;
					var nombre = obj.getAttribute('name');
					var inputs = document.getElementById(this.form).getElementsByTagName('input');

					for(var i=0; i<inputs.length; i++){
						if(inputs[i].getAttribute('type')=='radio')
							if (inputs[i].getAttribute('name') == nombre)
								if (inputs[i]["checked"])
									seleccion = true;
					}
			
					if (!seleccion)	
						return false;
				} else if (obj.getAttribute('tipo') == 'selecMulti'){
        				var seleccionadosM = new Array();
				        var index = 0;
			        	for (var i=0; i<obj.options.length; i++)
				            if (obj.options[i].selected){
				                seleccionadosM[index] = i;
				                index++;
				            }
					if (seleccionadosM.length == 0)
						return false;
				} else if (obj.getAttribute('tipo') == 'selecSimple'){
					if (obj.selectedIndex == 0)
						return false;
				} else if (obj.value == '')
					return false;
			} //for
			return true;
		}
		return false;			
	},

	correcto: function() {
		this.input.className="campo_correcto";
		if (this.divError != ''){
			var obj = document.getElementById(this.divError);
			if (this.imgCorrecto){
				obj.className = 'correcto';
				var imagen = document.createElement('img');
				imagen.src = 'ok.jpg';
				obj.appendChild(imagen);
			}
   			for (var i=obj.childNodes.length-1; i>=0; i--)
      			obj.removeChild(obj.childNodes.item(i));
		}else {
			var obj = document.createElement("span");
			obj.setAttribute('tipo', 'span');
			if (this.imgCorrecto){
				obj.className = 'correcto';
				var imagen = document.createElement('img');
				imagen.src = 'ok.jpg';
				obj.appendChild(imagen);
			}
			var hijo_sig = this.sig_hijo(this.input);
			var padre = this.input.parentNode; 
			if (hijo_sig){
				if (hijo_sig.getAttribute('tipo')){
					if (hijo_sig.getAttribute('tipo') == 'span'){
						padre.replaceChild(obj, hijo_sig);
					}else {		
						padre.insertBefore(obj,hijo_sig);			
					}
				}else {		
					padre.insertBefore(obj,hijo_sig);			
				}
			}else {				
				padre.appendChild(obj);
			}
		}
	},

	mostrarError: function() {
		this.input.className="campo_incorrecto";
		if (this.divError != '') {
			var obj = document.getElementById(this.divError);
   			for (var i=obj.childNodes.length-1; i>=0; i--)
      			obj.removeChild(obj.childNodes.item(i));
			if (this.imgError)
				obj.className = 'no_correcto';
			obj.style.color = this.colorError;
			obj.style.fontFamily = this.fuenteError;
			obj.style.fontSize = this.fuenteSize;
			obj.appendChild(document.createTextNode(this.mensajeError)); 
		} else {  // creo el span del error
			var obj = document.createElement("span");
			obj.setAttribute('tipo', 'span');
			if (this.imgError)
				obj.className = 'no_correcto';
			obj.style.color = this.colorError;
			obj.style.fontFamily = this.fuenteError;
			obj.style.fontSize = this.fuenteSize;
			obj.appendChild(document.createTextNode(this.mensajeError));
			var hijo_sig = this.sig_hijo(this.input,this.id);
			var padre = this.input.parentNode; 
			if (hijo_sig){
				if (hijo_sig.getAttribute('tipo')){
					if (hijo_sig.getAttribute('tipo') == 'span'){
						padre.replaceChild(obj, hijo_sig);
					}else {		
						padre.insertBefore(obj,hijo_sig);			
					}
				}else {		
					padre.insertBefore(obj,hijo_sig);			
				}
			}else {				
				padre.appendChild(obj);
			}
		}	
	},

	recogerParamComunes: function(id) {
		this.mensajeError = '';  //inicializo mensajeError
		this.input = document.getElementById(id);
		this.id = id;
		this.mensajeErrorUsuario = this.input.getAttribute('mensajeError') || '';
		this.divError = this.input.getAttribute('divError') || '';
		this.obligatorio = (this.input.getAttribute('obligatorio'))? ((this.input.getAttribute('obligatorio') == 'SI')? true : false) : true; //defecto true
		this.longitud = this.input.getAttribute('longitud') || '';
		this.longMin = this.input.getAttribute('longMin') || '';
		this.longMax = this.input.getAttribute('longMax') || '';
	},

	todoCorrecto: function() {
		eval(this.onSubmitResp); 
		var form = document.getElementById(this.form);
		var flag = true;
		var input = '';
		var correcto = '';
		for ( i=0; i<form.getElementsByTagName('input').length; i++){
			input = form.getElementsByTagName('input')[i];
			correcto = input.getAttribute('correcto');
			if (correcto){
				if (correcto == 'false')
					flag = false;
			}
		}
		for ( i=0; i<form.getElementsByTagName('select').length; i++){
			input = form.getElementsByTagName('select')[i];
			correcto = input.getAttribute('correcto');
			if (correcto){
				if (correcto == 'false')
					flag = false;
			}
		}
		for ( i=0; i<form.getElementsByTagName('textarea').length; i++){
			input = form.getElementsByTagName('textarea')[i];
			correcto = input.getAttribute('correcto');
			if (correcto){
				if (correcto == 'false')
					flag = false;
			}
		}
		return flag;
	},

	sig_hijo: function(obj,id) {
		var padre = obj.parentNode;
		var id_sig = '';
		var id_hijo = obj.getAttribute('id');
		var sig = '';
		var i = 0;
		while (i < padre.childNodes.length){
			if (padre.childNodes[i].nodeType == 1){
				id_sig = padre.childNodes[i].getAttribute('id');
				if (id_sig ==  id_hijo){
					sig = padre.childNodes[i+1];
					break;
				}
			}
			i = i+1;
		}
		if (sig){
			while ((sig.nodeType != 1) && (i <= padre.childNodes.length)){ // esto es porque dependiendo del navegador si me encuentro un espacio en blanco o un tabulador me lo considera como un objeto y yo los quiero descartar.
				i= i+1;
				sig = padre.childNodes[i];
				if (!sig)
					break;
			}
		}
		return sig;
	},

	Enter: function (campo, event) {  
		// Guargamos el código de la tecla presionada en los cuadros de texto  
		var enterCodigo = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;    
		// Si se presionó la tecla Enter se ejecuta 
		if (enterCodigo == 13) {
			var i; 
			for (i = 0; i < campo.form.elements.length; i++){
				//alert(campo.form.elements[i].tagName);
				//alert(i+ '  -  '+campo.getAttribute('id') +'  -  '+ campo.form.elements[i].getAttribute('id'));
				if (campo.getAttribute('id') == campo.form.elements[i].getAttribute('id'))
						break;
			} 
			i += 1; 
			if (i < campo.form.elements.length){
				if (campo.form.elements[i].getAttribute('type') == 'submit')
					i = 0;
				while (campo.form.elements[i].tagName != 'INPUT' && campo.form.elements[i].tagName != 'SELECT' && i < campo.form.elements.length)
					i += 1;
				if (campo.form.elements[i].tagName == 'INPUT' || campo.form.elements[i].tagName == 'SELECT')
					campo.form.elements[i].focus();
			}
			return false;    
		} 
	},

	ValidaGecko: function () {
		var gko = navigator.userAgent.toLowerCase();
		if (gko.indexOf('gecko')!=-1) //soporta gecko (Mozilla, Netscape, Safari ...)
			return true;
		else return false; //es explorer
	},

	completaForm: function (obj, atributo, valor){
		if (this.onBlur)
			this.ponerEvento(obj, atributo, valor);
		this.onSubmitResp = this.onSubmitResp + valor;
	},

	ponerAtributo: function (obj, atributo, valor) {
		if (this.Gecko)
			obj.setAttribute(atributo, valor);
		else eval('obj.'+ atributo +'= \'' +valor+ '\';');		
	},

	ponerEvento: function (obj, atributo, valor){
		if (this.Gecko)
			obj.setAttribute(atributo, valor);
		else obj[atributo]= new Function(valor);
	},

	dibujarBarra: function (){
		var color = 'red';
		var color_fuente = '#AAAAAA';
		if (this.PuntActual == this.PuntFinal){
			clearInterval(this.tiempo);
		}
		if (this.PuntFinal < this.PuntActual){
			this.PuntActual = this.redondear(this.PuntActual - 0.5, 1);
		}
		if (this.PuntFinal > this.PuntActual){
			this.PuntActual = this.redondear(this.PuntActual + 0.5, 1);
		}
		if (this.PuntActual <= 40){
			color = 'red';
			color_fuente = '#AAAAAA';		
		}
		else if (this.PuntActual > 40 && this.PuntActual < 50){
			color_fuente = '#AAAAAA';
			color = 'blue';
		}
		else if (this.PuntActual >= 50 && this.PuntActual <= 60){
			color_fuente = 'white';
			color = 'blue';
		}
		else{
			color_fuente = 'white';
			color = 'green';
		}
		var t = '<div style="visibility:visible; position:relative; overflow:hidden; width:'+ this.longitudCalidad +'px; height:12px; background-color:white; border:1px solid #DDDDDD; text-align:center; vertical-align:center; font-size:8pt;"><span style=" background-color:' + color + ';left:0px; width:' + this.PuntActual+ '%; height:40px; position:absolute; font-size:1px;"></span><span style="left:0px; width:100%; height:100%; position:absolute; text-align:center; font-size:8pt; color:'+color_fuente+'; font-family: Arial,sans-serif; font-weight:bold;">'+ Math.round(this.PuntActual) +'%</span></div>';
		document.getElementById(this.divCalidad).innerHTML = t;
	},

	redondear: function (cantidad, decimales) {
   		var cantidad = parseFloat(cantidad);
		var decimales = parseFloat(decimales);
		decimales = (!decimales ? 2 : decimales);
		return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
	} 
}

