function UtilV() {};

function check(id,tipo,strAlert)
	{
		var result = false;
		var obj = UtilV.setCampoParaValidacion(id);
		var value = UtilV.getValueTrim(obj);
		if (value=='' && tipo!='nulo') return true;
		if (typeof tipo == 'function') 
			result = tipo(value);
		else 
		switch (tipo)
		{
			case 'nulo': { result = (value!='') ; break; }
			
			case 'numero': { result = UtilV.validarNumero(value); break; }
			case 'decimal': { result = UtilV.validarDecimal(value,",",2); break; }
			case 'alfanumerico': { result = UtilV.validarAlfanumerico(value); break; }
			case 'email': { result = UtilV.validarEmail(value); break; }			
			case 'nif': { result = UtilV.validarNIF(value); break; }
			case 'cif': { result = UtilV.validarCIF(value); break; }
			case 'nie': { result = UtilV.validarNIE(value); break; }
			case 'nifnie': { result = UtilV.validarDocumento(value); result = (result==1 || result==3); break; }
			case 'nifcifnie': { result = UtilV.validarDocumento(value)>0; break; }
			case 'checkbox': { result = obj.checked; break; }
			case 'radio': { result = UtilV.getRadioValue(obj); break; }
			case 'nombre': { result = UtilV.validarNombre(value); break; }
			case 'descripcion': { result = UtilV.validarDescripcion(value); break; }
			case 'telefono': { result = UtilV.validarTelefono(value, true); break; }
			case 'año': { result = UtilV.validarAnio(value); break; }
			case 'porcentaje': { result = UtilV.validarPorcentaje(value); break; }
			case 'fecha': { result = UtilV.parseDate(value,2)!=false; break; }
			case 'fechanac': { result = UtilV.getAge(value,2)>=0; break; }
			case 'mayordeedad': { result = UtilV.getAge(value,2)>17; break; }
			case 'cp': {result = UtilV.validarCodigoPostal(value); break; }
			case 'matricula': {result = UtilV.validarMatricula(value); break; }
			
			case 'false': { result = false; break; }
		}	
		
		if (!result) 
		{
			if (strAlert!=null && strAlert!= '') {
				alert(strAlert, obj);
				UtilV.fijarAtencion(obj);
			}
		}
		return result;
	}

/*****************************/
function checkArray(arrayIds,tipo,strAlert)
	{
		var result = false;
		var arrayCampos = [];
		var arrayValues = [];
 		var vacios = true;
 
		var f = function(id) {
				var obj = UtilV.setCampoParaValidacion(id, arrayIds);
				var value = UtilV.getValueTrim(obj);
				if (value!='') vacios = false;
				arrayCampos.push(obj);
				arrayValues.push(value);
		}
		iter(arrayIds,f);
		if (vacios) return true;

		if (typeof tipo == 'function') 
			result = tipo(arrayValues);
		else 
			switch (tipo)
			{
				case 'ccc': { result = UtilV.validarCCC(arrayValues[0],arrayValues[1],arrayValues[2],arrayValues[3]); break; }
				case 'mayor': { result = UtilV.validarMayor(arrayValues[0],arrayValues[1]); break; }
				case 'mayorfecha': { result = UtilV.validarMayorFecha(arrayValues[0],arrayValues[1]); break; }
				case 'false': { result = false; break; }
			}	
		
		if (!result) 
		{
			if (strAlert!=null && strAlert!= '') {
				alert(strAlert, arrayCampos[0]);
				iter(arrayCampos,UtilV.fijarAtencion);
			}
		}
		return result;
	}
	
	function iter(arr,func) {
			for (var i=0,l=arr.length;i<l;i++) {
					func(arr[i],i);
			}
	}
/*****************************/
	function checkOperacion(id,tipo,strOperacion,strAlert)
	{
		var result = false;
		var obj = UtilV.setCampoParaValidacion(id);
		var value = UtilV.getValueTrim(obj);
		if (value=='' && tipo!='nulo') return true;		
		switch (tipo)
		{
			case 'value': { result = eval(value+strOperacion); break; }
			case 'edad': { result = eval(UtilV.getAge(value,2)+strOperacion); break; }
			case 'fecha': { result = eval(UtilV.parseDate(value,2)+strOperacion); break; }
		}

		if (!result) 
		{
			if (strAlert!=null && strAlert!= '') {
				alert(strAlert, obj);
				UtilV.fijarAtencion(obj);
			}
		}
		return result;
	}
	
/*****************************/	

function getTipoNIF(documento)
{
		if (/^[KLM0-9]{1}[0-9]{7}[A-Z]{1}$/i.test(documento))	return 1;
		if (/^[ABCDEFGHJPQRSUVNW]{1}[0-9]{7}[A-Z0-9]{1}$/i.test(documento))	return 2;
		if (/^[XYZ]{1}[0-9]{7}[A-Z]{1}$/i.test(documento))	return 3;

		return 0;
}

/*
 * Mediante este metodo se validan todos los tipos de document (NIF,CIF,NIE)
 * Paramentros  
 * - documento a validar
 * Devuelve 1,2,3 para NIF,CIF,NIE correctos, -1,-2,-3 para NIF,CIF,NIE incorrectos o 0 si no es de ningún tipo
 */
function validarDocumento(documento) {
		var tipo = getTipoNIF(documento);
		var res = false;
		switch(tipo) {
				case 1: res = UtilV.validarNIF(documento);break;
				case 2: res = UtilV.validarCIF(documento);break;
				case 3: res = UtilV.validarNIE(documento);break;
		}
		var resultado = parseInt(tipo * (res?1:-1),10);	
		switch (resultado){
				case -1: alert ("Por favor, introduzca un NIF correcto");break;
				case -2: alert ("Por favor, introduzca un CIF correcto");break;
				case -3: alert ("Por favor, introduzca un NIE correcto");break;
				case 0: alert ("Por favor, introduzca un NIF correcto"); break;				
		}
		return resultado;
}
/*****************************/	


UtilV.fijarAtencion = function(campo){
	campo.focus();
	campo.style.backgroundColor = 'lightsteelblue';
	                        
}
UtilV.setCampoParaValidacion = function(id, arrayIds) 
{
		var theFormtxtNombre = document.forms[0][id];
		if (!theFormtxtNombre) theFormtxtNombre = document.getElementById(id);
		if (!theFormtxtNombre) alert("Error: no existe el campo "+id);
		
		if (arrayIds) 
			theFormtxtNombre.onblur = function () 
				{ 
					for (var x=0;x<arrayIds.length;x++) {
						document.forms[0][arrayIds[x]].style.backgroundColor = ''; 
					}
				} 
		else
			theFormtxtNombre.onblur = function () { this.style.backgroundColor = ''; }
				
	return theFormtxtNombre;
}	
UtilV.getValueTrim = function(obj) {
	obj.value = (""+obj.value).replace(/^[ \t\r\n]+|[ \t\r\n]+$/,'');
	return obj.value;
}
/*****************************/
UtilV.validaRegExp = function(exp,value) 
{
	var reg = new RegExp(exp);
	var result = reg.test(value);
	return result;
}



/*****************************/
UtilV.validarAlfanumerico = function(value) {
	return UtilV.validaRegExp("^[a-zA-Z0-9]+$",value);
}
UtilV.validarNumero = function(value) {
	return UtilV.validaRegExp("^[0-9]+$",value);
}	
UtilV.validarPorcentaje = function(value) {
	if (!UtilV.validarNumero(value)) return false;
	return (value >-1 && value <101);
}
UtilV.validarDecimal = function(value, sep, decs) {
	return UtilV.validaRegExp("^[0-9]+["+sep+"]?[0-9]{0,"+decs+"}$",value);
}
UtilV.validarEmail = function(value) {
	return UtilV.validaRegExp(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+(?:[A-Z]{2,3}|info|mobi|name|aero|asia|coop|jobs|post|travel|museum)\b/i,value);
}
UtilV.validarNombre = function(value) {
	return UtilV.validaRegExp("^[a-zA-ZáéíóúÁÉÍÓÚñÑäëïöüÄËÏÖÜàèìòùÀÈÌÒÙ]+(([- ])*[a-zA-ZáéíóúÁÉÍÓÚñÑäëïöüÄËÏÖÜàèìòùÀÈÌÒÙ]+)*$",value);
}
UtilV.validarDescripcion = function(value) {
	return UtilV.validaRegExp(/^[0-9a-záéíóúñäëïöüàèìòù\t\r\n\f\s.,_ºª&{}%@#()¿?¡!:\-\[\<\>\]]*$/i,value);  
}
UtilV.validarTelefono = function(value, espaciado)	{
	var val = ( espaciado ) ? (""+value).replace(/ /gi,"") : ( value );
	return UtilV.validaRegExp("^[69]{1}[0-9]{8}$",val);
}
UtilV.validarAnio = function(value) {
	if (!UtilV.validaRegExp("^[12]{1}[0-9]{3}$",value)) return false;
	var now = new Date();
	var anioIni = 1500;
	var anioFin = UtilV.y2k(now.getFullYear());
	return (value<=anioFin && value > anioIni);
}
UtilV.y2k = function(dateYear) { return (dateYear < 1000) ? dateYear + 1900 : dateYear; }

/*****************************/
UtilV.validarCodigoPostal = function (value)
{
	value+='';
	if (!UtilV.validaRegExp("^[0-9]{5}$",value)) return false;
	var codProvincia = parseFloat(value.substring(0,2));
	return ((codProvincia>0)  && (codProvincia<53));
}

/*****************************/
UtilV.validarCIF = function(documento){
 	var temp=documento.toUpperCase();
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if (!/^[ABCDEFGHJPQRSUVNW]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp))	{
			return false;
		}
 
		//algoritmo para comprobacion de codigos tipo CIF
		var suma = parseInt(documento.charAt(2))+parseInt(documento.charAt(4))+parseInt(documento.charAt(6));
		for (var i=1; i < 8; i += 2)
		{
				var n = 2 * parseInt(documento.charAt(i));
				suma += Math.floor(n/10)+n%10;
		}

		var n = 10 - suma%10;

		//comprobacion de CIFs con codigo de control de tipo numerico
		if (/^[ABCDEFGHJNUV]{1}/.test(temp)){
			return(documento.charAt(8) == n%10);
		}
		
		//comprobacion de CIFs con codigo de control de tipo letra
		if (/^[PQRSNW]{1}/.test(temp)){
			return (documento.charAt(8) == String.fromCharCode(64 + n));
		}		
	}
	return false;
}

UtilV.validarNIF = function(documento){

 	var temp=documento.toUpperCase();
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if (!/^[KLM0-9]{1}[0-9]{7}[A-Z]{1}$/.test(temp))	{
			return false;
		}
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
 
		//NIF especiales
		if (/^[KLM]{1}/.test(temp))
		{
			temp = temp.replace(/\S/,"0");
		}
 		var posicion = temp.substring(0,8) % 23;

		return (temp.charAt(8) == cadenadni.charAt(posicion));
	}

}

UtilV.validarNIE = function(documento){

 	var temp=documento.toUpperCase();
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if (!/^[XYZ]{1}[0-9]{7}[A-Z]{1}$/.test(temp))	{
			return false;
		}
		var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
	 
		var ch = "0";
		switch (temp.charAt(0)) {
				case "Y": ch = "1"; break;
				case "Z": ch = "2"; break;
		}
		temp = temp.replace(/\S/,ch);

 		var posicion = temp.substring(0,8) % 23;

		return (temp.charAt(8) == cadenadni.charAt(posicion));
	}

}


UtilV.getTipoNIF = function(documento)
{
		if (/^[KLM0-9]{1}[0-9]{7}[A-Z]{1}$/i.test(documento))	return 1;
		if (/^[ABCDEFGHJPQRSUVNW]{1}[0-9]{7}[A-Z0-9]{1}$/i.test(documento))	return 2;
		if (/^[XYZ]{1}[0-9]{7}[A-Z]{1}$/i.test(documento))	return 3;

		return 0;
}

UtilV.validarDocumento = function(documento) {
		var tipo = UtilV.getTipoNIF(documento);
		var res = false;
		switch(tipo) {
				case 1: res = UtilV.validarNIF(documento);break;
				case 2: res = UtilV.validarCIF(documento);break;
				case 3: res = UtilV.validarNIE(documento);break;
		}
		return tipo * (res?1:-1);
}

/*****************************/
UtilV.validarCCC = function(entidad,sucursal,dc,cuenta) {
	if (!entidad || !sucursal || !dc || !cuenta) return false;
	return (UtilV.digitoControlCCC(entidad+sucursal) == dc.charAt(0) &&
					UtilV.digitoControlCCC(cuenta) == dc.charAt(1));
}
UtilV.digitoControlCCC = function(cadena) {
	   	
		var pesos = new Array(6,3,7,9,10,5,8,4,2,1);
   	var res = 0;	
   	var cadenaint = 1*cadena;
		for (var i=0, l=pesos.length; i < l; i++){
			var r = cadenaint%10;
			res += r * pesos[i];
			cadenaint = (cadenaint-r)/10;
		}
		res = 11 - (res % 11);
		if (res == 11) {res = 0;}
		else if (res == 10) {res = 1;}
		return res;
}
/*****************************/

UtilV.validarMayor = function(valorComparar,valorRef) {
	if (valorComparar=='') return true;
	return valorComparar>valorRef;
}	
UtilV.validarMayorFecha = function(strFechaComparar,strFechaRef) {
	if (strFechaComparar=='') return true;
	return UtilV.parseDate(strFechaComparar,2)>UtilV.parseDate(strFechaRef,2);
}	

/*****************************/

UtilV.getAge = function(dateString,dateType) 
{
		var now = new Date();
		var myDate = UtilV.parseDate(dateString, dateType);
		if (!myDate) return -1;
		
		var millisDate = myDate.getTime();
		var millisToday = now.getTime(); 
		  
		var minutes = 1000 * 60;
		var hours = minutes * 60;
		var days = hours * 24;
		var years = days * 365.256363;
		
		return Math.floor((millisToday-millisDate)/years); 
}
UtilV.parseDate = function(str, type) {
		var year,mon,day;
		switch(type) {
				case 1: day = str.substring(6,8);
								mon = str.substring(4,6)-1; 
				case 3: year = str.substring(0,4); break;
				case 2: str = str.replace(/-/g,"/");
								var campos = str.split("/");
								day = campos[0];
								mon = campos[1]-1;
								year = campos[2]; break;
		}
		
		var d = new Date(year,mon,day);
		if ( 	(d.getDate()==parseInt(day)) &&
					(d.getMonth()==parseInt(mon)) &&
					(UtilV.y2k(d.getFullYear())==parseInt(year))  ) return d;
		else return false;
}
	
/*****************************/
UtilV.getRadioValue = function(radioObject) { 
	if (radioObject+"" == "undefined" || radioObject == null)
		return null;

	for (var i=0; i < radioObject.length; i++) { 
		if (radioObject[i].checked) return radioObject[i].value;
	} // end for loop 
	
	return null;
}


UtilV.getSelectText = function( selectObject ) 
{
    if (selectObject == null)
            return null;
		var index = selectObject.selectedIndex;
    if (index+"" == "undefined" || index == null || index < 0) return null;

    return selectObject.options[index].text;
}

UtilV.validarMatricula = function (valor)
{
	var auxMat = "";
	
	//No se debe introducir una E al principio. DMFVIRE 24/08/2004.
	if (valor.substring(0, 1) =="E"){
		alert("La matricula introducida no es correcta");
		return(false);
	}
	axMod = valor.split("-");
	if (axMod.length > 1){
		alert("La matrícula debe ser introducida sin guiones.");
		return(false);
//		valor="";
//		for (var x=0; x < axMod.length;x++) {
//			auxMat = axMod[x];
//			axMod[x] = (auxMat.replace(/^\s+/,'')).replace(/\s+$/,'');
//			valor = valor + axMod[x];
//		}//end del for
	}
	auxMat = "";
	for (x=0; x< valor.length;x++){
		if (valor.charAt(x) != " ") auxMat += valor.charAt(x);
	}
	valor = auxMat;			
	if ( compruebaNumero(valor.substring(0,4)) ){
		if (valor.substring(4).length ==3){
			if ( !validaLetraMatricula(valor.substring(4)) ){
				alert("La matrícula introducida no es correcta.");
				return(false);
			}
		}else{
			alert("La matrícula introducida no es correcta.");
			return(false);
		}
	}else{
		if ( vehiculoTuristico(valor)){
			return(true);
		}
		if ( validaLetraMatricula(valor.substring(0,1)) ){
			if ( validaLetraMatricula(valor.substring(1,2)) ){
				if (vehiculoEstado(valor)) {
					return(true);
				}
				var auxRD="";
				auxRD = auxRD+regimenDiplomatico(valor);
				//se valida que la matricula sea del tipo D (regimen diplomático)
				if (auxRD == 1){
					return(true);
				}else{
					if(auxRD == 0){
						if (valor.substring(0,2)!= "CC"){
							alert("El formato de una matrícula en Régimen Diplomático debe tener el formato: "+valor.substring(0,2)+"-000000. Completando con ceros cada bloque de tres cifras.");	
							return(false);
						}
					}
				}	
				//las dos primeras posiciones son letras	
				if (!validaLetrasIniMat(valor.substring(0,2))){
					//Se comprueba si seguido de la 1ª letra esta el literal ITV
					if (valor.substring(1,4) == "ITV"){
						if (vehiculoPruebasITV(valor.substring(1))){
							return(true);
						}
					}
					alert("La matrícula introducida no es correcta, la provincia no es correcta.");
					return(false);
				}else{
					if (valor.substring(2,5) == "ITV"){
						if (vehiculoPruebasITV(valor.substring(2))){
							return(true);
						}
					}
					if (validaLetrasIniMat(valor.substring(0,1))){
						if (vehiculoPruebasITV(valor.substring(1))){
							return(true);
						}
					}
				}	
				if ( compruebaNumero(valor.substring(2,6))){
					if (valor.substring(6).length > 2){
						// a las 2 primeras posiciones, que son letras, les siguen 4 números, 
						//pero hay más de 2 posiciones despues, es decir, ni tiene 6 números
						//despues de las 2 letras, ni tiene 4 numeros y como máximo 2 letras.
						if (vehiculoEspecial(valor.substring(6))){
							return(true);
						}
						alert("La matrícula introducida no es correcta.");
						return(false);
					}else{
						//se compruba el valor de las 2 últimas posiciones
						if (!compruebaNumero(valor.substring(6)) ){
							//si estas 2 ultimas no son números.
							if (!validaLetraMatricula(valor.substring(6))){
								alert("La matrícula introducida no es correcta.");
								return(false);							
							}
						}else{
							//si estas 2 ultimas son números.
							if (valor.substring(6).length != 2){
								alert("La matrícula introducida no es correcta.");
								return(false);
							}
						}
					}
				}else{
					// a las 2 primeras posiciones, que son letras, no les siguen 4 números.
					alert("La matrícula introducida no es correcta.");
					return(false);
				}
			}else{
				//la primera posicion es una letra
				if (!validaLetrasIniMat(valor.substring(0,1))){
					if (vehiculoEspecial2(valor)){
						return(true);
					}
					alert("La matrícula introducida no es correcta, la provincia no es correcta.");
					return(false);
				}	
				if ( compruebaNumero(valor.substring(1,5))){
					if (valor.substring(5).length > 2){
						// a la primera posicion, que es una letra, le sigue 4 números, 
						//pero hay más de 2 posiciones despues, es decir, ni tiene 6 números
						//despues de la letra, ni tiene 4 numeros y como máximo 2 letras.
						if (vehiculoEspecial(valor.substring(5))){
							return(true);
						}
						if (vehiculoEspecial2(valor)){
							//se valida que la matricula sea del tipo E1 ó R1 ó C (ciclomotores) ó T1 (turística) ó TT .
							return(true);
						}
						alert("La matrícula introducida no es correcta.");
						return(false);
					}else{
						//se comprueba el valor de las 2 últimas posiciones
						if (!compruebaNumero(valor.substring(5)) ){
							//si estas 2 ultimas no son números.
							if (!validaLetraMatricula(valor.substring(5))){
								alert("La matrícula introducida no es correcta.");
								return(false);							
							}
						}else{
							if (valor.substring(5).length != 2){
								alert("La matrícula introducida no es correcta.");
								return(false);
							}
						}
					}
				}else{
					// a la primera posicion, que es una letra, no le sigue 4 números.
					alert("La matrícula introducida no es correcta.");
					return(false);
				}
			}		
		}else{
			alert("La matrícula introducida no es correcta.");
			return(false);
		}
	}
	return(true);
}//fin del validaMatricula

/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/***********************      es una matrícula de tipo turística T         ***********************/
/***********************************************************************************/

function vehiculoTuristico(matr)
{
  var mesRomano= new Array("I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII");
	if (matr.length>=7){
		if ( compruebaNumero(matr.substring(0,2)) ){
			if ( validaLetraMatricula(matr.substring(2,3)) ){
				if ( validaLetraMatricula(matr.substring(3,4)) ){
					//es una posible provincia de 2 letras
					if (validaLetrasIniMat(matr.substring(2,4))){
						if (compruebaNumero(matr.substring(4,8))){
							if ( (matr.substring(8).length == 4) || (matr.substring(8).length==0) ){
								if ( matr.substring(8).length==4){
									for (var y = 0;  y <mesRomano.length;  y++){
  										if (matr.substring(8,10) == mesRomano[y]) break;
									}
									if (y == mesRomano.length){
										return(false);
									}
									if (compruebaNumero(matr.substring(10,12))){
										return(true);
									}else{
										return(false);
									}
								}
							}
						}
					}else{
						return(false);
					}
				}else{
					//es una posible provincia de 1 letra
					if (validaLetrasIniMat(matr.substring(2,3))){
						if (compruebaNumero(matr.substring(3,7))){
							if ( (matr.substring(7).length==4) || (matr.substring(7).length==0) ){
								if ( matr.substring(7).length==4){
									for (y = 0;  y <mesRomano.length;  y++){
  										if (matr.substring(7,9) == mesRomano[y]) break;
									}
									if (y == mesRomano.length){
										return(false);
									}
									if (compruebaNumero(matr.substring(9,11))){
										return(true);
									}else{
										return(false);
									}
								}							
							}
						}						
					}else{
						return(false);
					}
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		return(false);
	}
}


/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/******************      es un vehículo del estado (tipo M o M1)         ******************/
/***********************************************************************************/

function vehiculoEstado(matr)
{
	var matEstado = new Array("A","DGP","EA","ET","FN","MF","MMA","MOP","PGC","PME","PMM");	
	var mat1 = matr.substring(0,1);
	var mat2 = matr.substring(0,2);
	var mat3 = matr.substring(0,3);
	var rest = "";
	for (var q = 0;  q <matEstado.length;  q++){
		if (mat1 == matEstado[q]) break;
	}
	for (var y = 0;  y <matEstado.length;  y++){
		if (mat2 == matEstado[y]) break;
	}
	for (var t = 0;  t <matEstado.length;  t++){
		if (mat3 == matEstado[t]) break;
	}
	if (q != matEstado.length){
		rest = matr.substring(1);
	}else{
		if (y != matEstado.length){
			rest = matr.substring(2);
		}else{
			if (t != matEstado.length){
				rest = matr.substring(3);
			}else{
				return(false);
			}
		}
	}
	if (compruebaNumero(rest.substring(0,4))){
		if (rest.substring(4).length==2){
			if (compruebaNumero(rest.substring(4,6))){
				return(true);
			}
			if (validaLetras(rest.substring(4,6))){
				return(true);
			}
			return(false);
		}else{
			return(false);
		}
	}else{
		if (rest.substring(0,2) == "VE"){
			if (rest.substring(2).length==6){	
				if (compruebaNumero(rest.substring(2,8))){
					return(true);
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}
}

/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/**************      es un vehículo de pruebas (tipo P) o de la ITV (tipo I)          ***************/
/***********************************************************************************/

function vehiculoPruebasITV(matr)
{
	if ( compruebaNumero(matr.substring(0,2))){
		if ( (matr.substring(2,3) == "P") || (matr.substring(2,3) == "T")){
			if ( compruebaNumero(matr.substring(3,7)) ){
				if ( (matr.substring(7,8) =="1") || (matr.substring(7,8) =="2") ){
					if ( (matr.substring(8).length == "0") || (matr.substring(8).length == "2") ){
						if (matr.substring(8).length =="2") {
							if ( compruebaNumero(matr.substring(8,10)) ){
								return(true);
							}else{
								return(false);
							}
						}else{
							return(true);
						}
					}else{
						return(false);
					}
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		if (matr.substring(0,3) == "ITV"){
			if (matr.substring(3).length == 4){
				if ( compruebaNumero(matr.substring(3,7)) ){
					return(true);
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}
}

/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/********************      es un vehículo especial tipo E o R  o TE      ***********************/
/***********************************************************************************/

function vehiculoEspecial(matr)
{
	if (matr.length==4){
		// vehiculos del tipo E
 		if (compruebaNumero(matr.substring(0,2))){
			if(matr.substring(2)=="VE"){
				return(true);
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		if (matr.length==3){
			// vehiculos del tipo R
 			if (compruebaNumero(matr.substring(0,2))){
				if(matr.substring(2)=="R"){
					return(true);
				}else{
					return(false);
				}
			}else{
				if ( ( matr.substring(0,1) == "T" ) || ( matr.substring(0,1) == "R" ) ){
					if ( compruebaNumero(matr.substring(1,3)) ){
						return(true);
					}else{
						return(false);
					}
				}else{
					return(false);
				}
			}
		}else{
			return(false);
		}
	}
}

/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/******************      es un vehículo especial tipo E1 o R1 o C o T1          ******************/
/***********************************************************************************/

function vehiculoEspecial2(matr)
{
	if (matr.length==8){
		if ( (matr.substring(0,1)=="E") ||  (matr.substring(0,1)=="R")  ||  (matr.substring(0,1)=="T")  ||  (matr.substring(0,1)=="H")  ||  (matr.substring(0,1)=="P") ||  (matr.substring(0,1)=="V") ||  (matr.substring(0,1)=="S") ) {
			if (compruebaNumero(matr.substring(1,5))){
				if ( validaLetraMatricula(matr.substring(5)) ){			
					return(true);
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		return(false);
	}
}

/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/************************      es un vehículo de regimen diplomático           ************************/
/***********************************************************************************/

function regimenDiplomatico(matr)
{
	if ( (matr.substring(0,2)=="CD") ||  (matr.substring(0,2)=="OI")  ||  (matr.substring(0,2)=="TA") ||  (matr.substring(0,2)=="CC") ) {
		if (matr.length==8){
			if (validaNumero2(matr.substring(2,8))){
				return(1);
			}else{
				return(0);
			}
		}else{
			return(0);
		}
	}else{
		return(2);
	}
}

/***********************************************************************************/
/******************             Función que me valida si la/s  letra/s             ********************/
/******************      del principio una matricula con provincia es correcta        ********************/
/***********************************************************************************/

function validaLetrasIniMat(letras)
{
  var inicialProv = new Array("A","AB","AL","AV","B","BA","BI","BU","C","CA","CC","CE","CO","CR","CS","CU","GC","GI","GE","GR","GU","H","HU","J","L","LE","LO","LU","M","MA","ML","MU","NA","O","OU","OR","P","IB","PM","PO","S","SA","SE","SG","SO","SS","T","TE","TF","TO","V","VA","VI","Z","ZA");
  var checkStr = letras;
  var allValid = true;
  for (y = 0;  y < inicialProv.length;  y++){
  	if (checkStr == inicialProv[y]) break;
  }
  if (y == inicialProv.length){
      allValid = false;
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}


UtilV.validarMatriculaNueva = function (matricula)
{
	var numeros = matricula.substring(0,4);
	var letras = matricula.substring(4,7);
	if (compruebaNumero(numeros)){
		if (validaLetraMatricula(letras)){
			return true;
		}
		else return false;
	}
	else{
		return false;
	}
}

function compruebaNumero(value) {
	return validaRegExp("^[0-9]+$",value);
}

function validaLetraMatricula(letras)
{
  var checkOK = "BCDFGHJKLMNPRSTVWXYZbcdfghjklmnprstvwxyz";
  var checkStr = letras;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}

function validaRegExp(exp,value) {
	var reg = new RegExp(exp);
	var result = reg.test(value);
	return result;
}


// -------------------------------------------------------------------------------------
function UtilF(){}	

UtilF.formatearNIFparaValidacion = function(value) {
		while (value.length<9) value = '0'+value;				
		if (value.length==10 && value.charAt(0)=='0')value = value.substring(1,value.length);
		return value;
	}
UtilF.formatearNIFparaBaseDatos = function(objnif) {
		if (objnif.value.length==9)objnif.value='0'+objnif.value.toUpperCase();
}
UtilF.formatearCantidadParaVisualizacion = function(valor,numDecimales) 
{
	var valor = new Number(valor).toFixed(numDecimales);
	if (isNaN(valor)) return false;
	var numero = (valor+'').split(".");
	var entera = numero[0];
	var result = '';
	var i= entera.length-1;
	for (;i>2;i=i-3) {
			result = "."+entera.charAt(i-2) + entera.charAt(i-1) + entera.charAt(i) + result;
	}
	return entera.substring(0,i+1)+result+","+numero[1];
}


/*******************************************************************************/
/******************  Función que quita el color del campo   ********************/
/******************  pasado									********************/
/*******************************************************************************/
function ponBlanco(campo){
	campo.style.backgroundColor = '';
}

// Funcion que comprueba que un campo no es nulo o vacio
function validaNoNulo(theFormtxtNombre){
 if (theFormtxtNombre.value == "") {
	 return (false);
 }
 else{
	 return(true);
 }
}


// Funcion que quita los caracteres en blanco de un campo
function quitaBlancos(campo) {
	if(campo.value)
	{
		var contenido = campo.value;
		campo.value = (contenido.replace(/^\s+/,'')).replace(/\s+$/,'');
		return(campo)
	}
	return(campo)
}

/*********************************************************************************/
/******************        Función que introduce un cero      ********************/
/******************           al principio del NIF            ********************/
/*********************************************************************************/

function rellenaCeros (numeroDoc){
	if((numeroDoc.value.length < 10) ){
		var re = "";
		for(i=0;i<10-numeroDoc.value.length;i++){
			re="0"+re;
		}
		numeroDoc.value=re+numeroDoc.value.toUpperCase(); 
		 		
	}
	return (numeroDoc);
}


function quitarCeros (numero){
	if (numero.length == 10){
		var primerCaracter = numero.substring (0,1);
		if (primerCaracter == "0"){
			numero = numero.substring(1,numero.length); 
		}
		else {
			var segundoCaracter = numero.substring (1,2);
			if (segundoCaracter == "0"){
				numero = primerCaracter+numero.substring(2,numero.length); 	
			}
		}
	}
	return (numero);
}
								


