﻿function validarDOC(valor){
	var dni = /^([0-9]{8,8}[a-zA-Z])$/;
	var cif = /^([ABCDEFGHKLMNPQSabcdefghklmnpqs][0-9]{7,7}[0-9A-J])$/;
	var nie = /^([Xx][0-9]{7,7}[a-zA-Z])$/;

 if(cif.test(valor)) {
		return validarCIF(valor);
	}else if(nie.test(valor)){
		return validarNIE(valor.substr(1));
	}else if(dni.test(valor)){
		return validarDNI(valor);
	}
	return false;
	//return true;
}
function esTres(valor,capa,tipo){
	if (tipo==1){
	var nie = /^([Xx][0-9]{7,7}[a-zA-Z])$/;
	if(nie.test(valor) && validarNIE(valor.substr(1)) ) {
		//alert($(capa).style.display);
		document.getElementById(capa).style.display='block';
	}
	}
//	else{
//		alert(valor);
//		document.getElementById(capa).style.display='none';
//	}
}
function validarDNI(valor){
	var letras = 'T,R,W,A,G,M,Y,F,P,D,X,B,N,J,Z,S,Q,V,H,L,C,K,E,T'.split(',');
	var pos = valor.substr(0,valor.length-1) % 23
	var letra = valor.substr(valor.length-1,valor.length);
	if (letra.toUpperCase() == letras[pos]) 
	{
		return true;
	}
	return false;
}
function validarNIE(valor){
	var letras = 'T,R,W,A,G,M,Y,F,P,D,X,B,N,J,Z,S,Q,V,H,L,C,K,E,T'.split(',');
	var pos = valor.substr(0,valor.length-1) % 23
	var letra = valor.substr(valor.length-1,valor.length);
	if (letra.toUpperCase() == letras[pos]) 
	{
		return true;
	}
	return false;
}
 function validarCIF(texto){
        var pares = 0;
        var impares = 0;
        var suma;
        var ultima;
        var unumero;
        var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
        var xxx;
        texto = texto.toUpperCase();
        var regular = new RegExp(/^[ABCDEFGHJKLMNPRQSUVWabcdefghjklmnprqsuvw]\d\d\d\d\d\d\d[0-9,A-J]$/g);
         if (!regular.exec(texto)) return false;
         ultima = texto.substr(8,1);
         for (var cont = 1 ; cont < 7 ; cont ++){
             xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0";
             impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
             pares += parseInt(texto.substr(cont,1));
         }
         xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0";
         impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
         
         suma = (pares + impares).toString();
         unumero = parseInt(suma.substr(suma.length - 1, 1));
         unumero = (10 - unumero).toString();
         if(unumero == 10) unumero = 0;
         
         if ((ultima == unumero) || (ultima == uletra[unumero]))
             return true;
         else
             return false;

 }
function validarEMAIL(valor)
{
	var regexp = /^([\w-\.]+)@([\w-\.]+)\.[a-zA-Z]{2,4}$/;
	return regexp.test(valor)
}
function validarTFN(valor,tipo)
{
	var regexp = /^[689]{1}[0-9]{8}$/;
	return regexp.test(valor)
}
function validarDATE(valor)
{
	var regexp = /^([0-9]{2}\/[0-9]{2}\/[0-9]{4})$/;
	return regexp.test(valor)
}
function validarHORA(valor)
{
	var regexp = /^([0-2][0-9]\:[0-5][0-9])$/;
	return regexp.test(valor)
}
var Validator = {
	formID:'',
	Version: 'V0.1_r0'
	, Libname: 'Validate Form'
	, Owner: '------'
	, Author: '-----'
	, error: false
	, error2: false
	, resalt:false
	, foco: false
	, rMSG:''
	,  load: function(form) {
/*		if((typeof Prototype=='undefined') || 
		(typeof Element == 'undefined') || 
		(typeof Element.Methods=='undefined') ||
		parseFloat(Prototype.Version.split(".")[0] + "." +
		Prototype.Version.split(".")[1]) < 1.5)
			throw("Validator requires the Prototype JavaScript framework >= 1.5.0");*/
		Validator.formID=form;
	},
	Info:function(){
		alert(Validator.Version);
	}
	, Inspect: function(){
		var form=document.getElementById(Validator.formID);
		for(i=0;i<form.length;i++){
			Validator.error2=false;
			Validator.resalt=false;
			var anchor = form.elements[i];
			if(anchor.type.toLowerCase()=='radio'){
				var anchor2;
				end=true;
				for(l=1;end;){
					anchor2=form.elements[i];
					if((anchor2 == undefined) || (anchor.name!=anchor2.name) || (anchor2.type.toLowerCase()!='radio')){
						end=false;
						i--;
						l--;
					}else{
						i++;
						l++;
					}						
				}
				var classAttribute = String(anchor.className);
				if (classAttribute!='null'){
					classAttribute=classAttribute.split(' ');
				}
				for(j=0;j<classAttribute.length;j++){
					if(classAttribute[j]=='RADIO'){
						if(!anchor.disabled)							
							Validator.ValCHK(anchor.name,l);
					}			
				}
			}else{
				var classAttribute = String(anchor.className);
				if (classAttribute!='null'){
					classAttribute=classAttribute.split(' ');
					if(!anchor.disabled){
						j = 0;
						while (!Validator.error2 && (j < classAttribute.length)) {
							validation=classAttribute[j];
							Validator.ValField(anchor,validation);
							j++;
						}
					}
				}
			}
		}
		if(!Validator.error){
			return true;
		}else if(Validator.error){
			alert('Se han producido los siguientes errores:\n'+Validator.rMSG+'\nPor favor, revise los campos resaltados.');
			Validator.error=false;
			Validator.error2=false;
			Validator.resalt=false;
			Validator.foco=false;
			Validator.rMSG='';
			return false;
		}else{
			return false;
		}
	}
	, preInspect: function(array){
		for(i=0;i<array.length;i++){
			Validator.error2=false;
			Validator.resalt=false;
			var anchor = array[i];
			if(anchor.type.toLowerCase()=='radio'){
				var anchor2;
				end=true;
				for(l=1;end;){
					anchor2=array[i];
					if(!(anchor.name==anchor2.name) || anchor2.type.toLowerCase()!='radio'){
						end=false;
						i--;
						l--;
					}else{
						i++;
						l++;
					}						
				}
				var classAttribute = String(anchor.className);
				if (classAttribute!='null'){
					classAttribute=classAttribute.split(' ');
				}
				for(j=0;j<classAttribute.length;j++){
					if(classAttribute[j]=='RADIO'){
						if(!anchor.disabled)
							Validator.ValCHK(anchor.name,l);
					}			
				}
			}else{
				var classAttribute = String(anchor.className);
				if (classAttribute!='null'){
					classAttribute=classAttribute.split(' ');
					if(!anchor.disabled){
						for(j=0;j<classAttribute.length;j++){
							validation=classAttribute[j];
							Validator.ValField(anchor,validation);
						}
					}
				}
			}
		}
		if(!Validator.error){
			return true;
		}else if(Validator.error){
			alert('Los siguientes campos son requeridos:\n'+Validator.rMSG+'\nPor favor, revise los campos resaltados.');
			Validator.error=false;
			Validator.error2=false;
			Validator.resalt=false;
			Validator.foco=false;
			Validator.rMSG='';
			return false;
		}else{
			return false;
		}
		
	}
	, ValField: function(anchor,validation){
		if(validation=='R'){
			if ((anchor.value=='') || ((anchor.type.toUpperCase() == "CHECKBOX") && (!anchor.checked))) {
				Validator.rMSG+='- '+anchor.title+ '\n';
				Validator.resalt=true;
				Validator.error=true;
				Validator.error2=true;
			}
			if(Validator.error&&!Validator.foco&&anchor.type.toUpperCase()!="HIDDEN"){
				Validator.foco=true;
				anchor.focus();
			}
		}

		if(validation=='RCheck'){
			var campocheck = anchor.campoRCheck || anchor.getAttribute("campoRCheck");
			if(document.getElementById(campocheck).checked){
				if(anchor.value==''){
					Validator.rMSG+='- '+anchor.title+ '\n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}

		if(validation=='RNoCheck'){
			var campocheck = anchor.RNoCheck || anchor.getAttribute("RNoCheck");
			if(!document.getElementById(campocheck).checked){
				if(anchor.value==''){
					Validator.rMSG+='- '+anchor.title+ '\n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
			else
				Validator.error2=true;

		}
		if(validation=='RConValor'){
			var campovalor = anchor.RConValor || anchor.getAttribute("RConValor");
			if(document.getElementById(campovalor).value != ''){
				if(anchor.value==''){
					Validator.rMSG+='- '+anchor.title+ '\n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		if(validation=='RSinValor'){
			var campovalor = anchor.RConValor || anchor.getAttribute("RSinValor");
			if(document.getElementById(campovalor).value == ''){
				if(anchor.value==''){
					Validator.rMSG+='- '+anchor.title+ '\n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}

		if(validation=='RCSEL'){
			var camposel = anchor.camposel || anchor.getAttribute("camposel");
			var valorsel = anchor.valorsel || anchor.getAttribute("valorsel");
			if(document.getElementById(camposel).options[document.getElementById(camposel).selectedIndex].value == valorsel){
				if(anchor.value==''){
					Validator.rMSG+='- '+anchor.title+ '\n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}

		if(validation=='DNI'){
			if(anchor.value!='') {
				if(!validarDOC(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': La letra no es correcta \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		if(validation=='EMAIL'){
			if(anchor.value!=''){
				if(!validarEMAIL(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No es una dirección de correo válida. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		if(validation=='SELECT'){
			var valorsel = anchor.valorsel || anchor.getAttribute("valorsel");
			if(anchor.value==valorsel){
				Validator.rMSG+='- El valor elegido para '+anchor.title.toLowerCase()+ ' no es válido \n';
				Validator.resalt=true;
				Validator.error=true;
				Validator.error2=true;
			}
			if(Validator.error&&!Validator.foco){
				Validator.foco=true;
				anchor.focus();
			}
		}

		if(validation=='FICHERO'){
			var formatoValido = false;
			var formatos = anchor.lang.split("|");
			var extension = anchor.value.substr(anchor.value.lastIndexOf(".")+1);
			extension = extension.toUpperCase();
			var q = 0;
			while ((formatoValido == false) && (q < formatos.length)) {
				if (formatos[q] == extension)
					formatoValido = true;
				q++;
			}
			if (!formatoValido) {
				Validator.rMSG+='- '+anchor.title+ ' no tiene un formato de fichero válido \n';
				Validator.resalt=true;
				Validator.error=true;
				Validator.error2=true;
			}
			if(Validator.error&&!Validator.foco){
				Validator.foco=true;
				anchor.focus();
			}
		}

		if(validation=='TFN'){
			if(anchor.value!=''){
				if(!validarTFN(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No es un teléfono válido. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		if(validation=='DATE'){
			if(anchor.value!=''){
				if(!validarDATE(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No es una fecha válida.(dd/mm/aaaa) \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		if(validation=='HORA'){
			if(anchor.value!=''){
				if(!validarHORA(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No es una hora válida.(HH:MM) \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		
		if(validation=='LENMAXN'){
			if(anchor.value!=''){
				var regexp = /^([0-9]+)$/;
				if(!regexp.test(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No es un valor numérico. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}else if(anchor.value.length!=anchor.maxLength){
					Validator.rMSG+='- '+anchor.title+ ': No tiene la longitud adecuada. Escriba '+anchor.maxLength+' caracteres. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				//alert(anchor);
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}

		if(validation.match(/NUM/)){
			if(anchor.value!=''){
				var max=validation.split('#')[1];
				if(max){
					eval('compare='+anchor.value+max.substr(0,1)+'='+max.substr(1)+'?false:true');
				}
				var regexp = /^([0-9]+)$/;
				if(!regexp.test(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No es un valor numérico. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}else if(compare){
					parsea=max.substr(0,1)=='<'?'superior':'inferior';
					Validator.rMSG+='- '+anchor.title+ ': No puede ser '+parsea+' a '+max.substr(1)+' meses. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}else if(anchor.length!=anchor.maxlength){
					Validator.rMSG+='- '+anchor.title+ ': No tiene la longitud adecuada. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}
		if(validation.match(/IMPORTE/)){
			var compare=false;
			if(anchor.value!=''){
				var max=validation.split('#')[1];
				if(max){
					eval('compare='+anchor.value+max.substr(0,1)+'='+max.substr(1)+'?false:true');
				}
				var regexp = /^\d+(\,\d+)?$/;
				if(!regexp.test(anchor.value)){
					Validator.rMSG+='- '+anchor.title+ ': No tiene un formato adecuado. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}else if(compare){
					parsea=max.substr(0,1)=='<'?'mayor':'menor';
					Validator.rMSG+='- '+anchor.title+ ': Su valor no puede ser '+parsea+' de '+max.substr(1)+'€. \n';
					Validator.resalt=true;
					Validator.error=true;
					Validator.error2=true;
				}
				if(Validator.error&&!Validator.foco){
					Validator.foco=true;
					anchor.focus();
				}
			}
		}

		if(validation=='CHK'){
			if(!anchor.checked){
				Validator.rMSG+='- '+anchor.title+ ': No es un teléfono válido. \n';
				Validator.resalt=true;
				Validator.error=true;
				Validator.error2=true;
			}
			if(Validator.error&&!Validator.foco){
				Validator.foco=true;
				anchor.focus();
			}
		}

		if(Validator.resalt){
			anchor.style.border='1px #DA251C solid';
		}else{
			anchor.style.border='1px #888888 solid';
		}
	}
	, ValCHK: function(campo,ncampos){
		var onechk=false,val,reference;
		
		for(p=1;p<=ncampos;p++){
			reference=campo+"_"+p;
			val=document.getElementById(reference);
			if(val.checked && !onechk)
				onechk=true;
		}
		if(!onechk){
			val=document.getElementById(campo+"_1");
			Validator.rMSG+='- '+val.title+ '\n';
			Validator.error=true;
			if(Validator.error&&!Validator.foco){
				Validator.foco=true;
				val.focus();
			}
		}
	}
}
