
//FUNCIÓN PARA COMPROBAR SI EL NAVEGADOR TIENE HABILITADAS LAS VENTANAS FLOTANTES

function compruebaVentanas(){
	pruebaVentana=window.open("nada.htm","pruebaVentana","width=2,height=2, menubars=no, scrollbars=no, resizable=no, left=0, top=0");
			
	if (pruebaVentana){
		pruebaVentana.close();
	}else{	
		alert("Su navegador no acepta ventanas flotantes.\n Por favor habilítelas para el correcto funcionamiento del site.");
		pruebaVentana.close();
	}	

}


//FIN FUNCIÓN PARA COMPROBAR SI EL NAVEGADOR TIENE HABILITADAS LAS VENTANAS FLOTANTES






function esBisiesto(anyo)
    {
        /**
        * si el año introducido es de dos cifras lo pasamos al periodo de 1900. Ejemplo: 25 > 1925
        */
        if (anyo < 100)
            var fin = anyo + 1900;
        else
            var fin = anyo ;

        /*
        * primera condicion: si el resto de dividir el año entre 4 no es cero > el año no es bisiesto
        * es decir, obtenemos año modulo 4, teniendo que cumplirse anyo mod(4)=0 para bisiesto
        */
        if (fin % 4 != 0)
            return false;
        else
        {
            if (fin % 100 == 0)
            {
                /**
                * si el año es divisible por 4 y por 100 y divisible por 400 > es bisiesto
                */
                if (fin % 400 == 0)
                {
                    return true;
                }
                /**
                * si es divisible por 4 y por 100 pero no lo es por 400 > no es bisiesto
                */
                else
                {
                    return false;
                }
            }
            /**
            * si es divisible por 4 y no es divisible por 100 > el año es bisiesto
            */
            else
            {
                return true;
            }
        }
    }

function validarFecha(Cadena){

	var Fecha= new String(Cadena)	// Crea un string
	var RealFecha= new Date()	// Para sacar la fecha de hoy
	var Ano= new String(Fecha.substring(Fecha.lastIndexOf("/")+1,Fecha.length))
	var Mes= new String(Fecha.substring(Fecha.indexOf("/")+1,Fecha.lastIndexOf("/")))
	var Dia= new String(Fecha.substring(0,Fecha.indexOf("/")))
	
	if (isNaN(Ano) || Ano.length<2 || Ano.length>4){
        	
		return false
	}
	//comprobamos q el año no sea inferior a 1900 ni tenga solo 3 cifras, ya q sino da problemas de formato.
	if(Ano.length==4){
		if (Ano<1900){
		return false
		}
	}
	if (Ano.length==3){
		return false
	}
	//fin comprobar año
	
		
	if (isNaN(Mes) || Mes.length>2 || Mes.length<1 || parseFloat(Mes)<1 || parseFloat(Mes)>12){
		
		return false
	}
	if (isNaN(Dia) || Dia.length<1 || Dia.length>2 || parseFloat(Dia)<1 || parseFloat(Dia)>31){
		
		return false
	}
	var bisiesto=esBisiesto(Ano)
	if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {
		if ( ((Mes==2) && (Dia > 28) && !(bisiesto) ) || (Dia>30) || ((bisiesto) && (Mes==2) && (Dia>29))) 																																	{    			
			return false
		}
	}
 	return true	
}


/* Esta función valida si f1 es una fecha menor que f2. En este caso 
 * devolvemos true. En caso contrario devolvemos false. 
 */
function validarFechaMenor(f1,f2) {
	f1 = f1.split("/");
	f2 = f2.split("/");
	if (f2[2]>=f1[2])
		if(f2[2]>f1[2]) return true;
		else if (f2[1]>=f1[1]) 
				if (f2[1]>f1[1]) return true;
				else if (f2[0]>=f1[0]) return true;
						else return false;
}

function validarEmail(email) {
	caracNoValidos = " /:,;";
	if(email == "") return false; 							// debe rellenarse
	for(i = 0; i < caracNoValidos.length; i++) {			// ¿hay algún carácter no válido?
		caracMal = caracNoValidos.charAt(i);
		if(email.indexOf(caracMal,0) > -1) return false;
	}
	posArroba = email.indexOf("@",1); 						// debe haber una @
	if(posArroba == -1) return false;
	if(email.indexOf("@",posArroba+1) != -1) return false;	// y sólo una
	posPunto = email.indexOf(".",posArroba);
	if(posPunto == -1) return false;  						// y al menos un . después de la @
	if(posPunto+3 > email.length) return false; 			// debe haber al menos 2 caracteres tras el .
	return true;
}
//------------------------- FIN Lo puso Diego -------------------------------------------








// --------------- FUNCIONES PARA EL ENVIO DE TEXTAREA A TRAVES DE VARIABLES JAVASCRIPT ------------

//Indicamos la cadena q queremos en vez de /n 
var separador="1122TT2211";


//FUNCION Q REEMPLAZA EN UNA CADENA LOS CARACTERES DESEADOS
function strReplaceAll(str,strFind,strReplace)
{
	var returnStr = str;
	var start = returnStr.indexOf(strFind);
	while (start>=0)
	{
		returnStr = returnStr.substring(0,start) + strReplace + returnStr.substring(start+strFind.length,returnStr.length);
		start = returnStr.indexOf(strFind,start+strReplace.length);
	}
	return returnStr;
}



//Función q quita los \n de un textarea para pasar su contenido en una var. jscript sin cortar la cadena
function quitaBarraN(descripcion){
	aux=descripcion.split("\n");
	var cuenta=aux.length;
	var cadenaDescripcion="";
	for(ind=0; ind<aux.length-1; ind++){
		cadenaDescripcion=cadenaDescripcion+aux[ind].substr(aux[ind],aux[ind].length-1)+separador;
	}
	cadenaDescripcion=cadenaDescripcion+aux[cuenta-1];

return cadenaDescripcion;

}	




// ------------- FIN FUNCIONES PARA EL ENVIO DE TEXTAREA A TRAVES DE VARIABLES JAVASCRIPT ----------


// ------------- FUNCIONES PARA FORMATOS ----------------//

/* Esta funcion valida la hora que se pasa por parametro. Retorna un 0 si hay éxito y
 * -1 si no es correcto el formato(dd:dd:dd) o los rangos(24horas).
 * - Parámetros:
 * @ hora_a_validar-> cadena que contiene la hora a validar.
 */
function ComprobarFormatoHora24(hora_a_validar) {
	var ExpReg=/^\d{2}:\d{2}:\d{2}$/;//formato de la hora en Expresion Regular
	
	if (ExpReg.test(hora_a_validar)) {
		var hora_array = hora_a_validar.split(":");
		var hora = parseInt(hora_array[0]);
		var minutos = parseInt(hora_array[1]);
		var segundos = parseInt(hora_array[2]);
		
		if ( (hora<0) || (hora>23) ) return (-1);
		if ( (minutos<0) || (minutos>59) ) return(-1);
		if ( (segundos<0) || (segundos>59) ) return(-1);
	} else { return (-1); }
	
	//Todo correcto...
	return (0);
}


/* Esta funcion comprueba el formato del numero de documento que se pasa por parámetro
 * Si es un nif comprueba si son 8 dígitos y una letra y si es un cif comprueba que sea
 * una letra y ocho digitos. Luego comprueba si la letra y el numero son correctos.
 * Retorna -1 si es incorrecto y 0 si es correcto y -2 si está vacío.
 * Parámetros:
 * @ documento-> cadena que contiene el número de documento a validar.
 */
function ValidarNifCif(documento) {
	var Vacio=/\S+/;
	var resultado;
	if (!Vacio.test(documento)) return (-2);

	if (documento.length!=9) return (-1);
	documento = documento.toUpperCase(documento);
	if ( !isNaN(documento.charAt(0)) ) {//se trata de un nif.
		resultado = nifValido(documento);
		return (resultado);
	} else {//se trata de un cif o un nie.
		
		if (documento.charAt(0)=="X") {//es un nie.
			documento = "0"+ documento.substring(1);
			resultado = nifValido(documento);
			return (resultado);
		} else {// es un cif.
			resultado = cifValido(documento);
			return (resultado);
		}
	}
}

/* Esta función valida un dni. Devuelve un 0 si es correcto y un -1 en caso contrario
 */
function nifValido(num_doc) {
	//cojo la letra.
	var letraIntroducida = num_doc.toUpperCase().substring(8);
	var letras = "TRWAGMYFPDXBNJZSQVHLCKET"
	var numero = parseInt(num_doc);
	numero = numero % 23;
	
	if ( letraIntroducida == letras.charAt(numero) ) return (0);
		else return (-1);
}

/* Esta función valida un cif. Devuelve un 0 si es correcto y un -1 en caso contrario
 */
function cifValido(numero_doc) {
	var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
    var temp = 0;
	var num = numero_doc.toUpperCase();
	var letra="";

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

    temp = temp + v1[ parseInt(num.substr(7,1)) ];
    temp = (10 - ( temp % 10));
	
	//si es una clave de caracter
	if ( (num.charAt(0)=="P") || (num.charAt(0)=="Q") || (num.charAt(0)=="S") ){
		temp+=40;
	 	letra = unescape("%"+temp);
		if ( letra == num.charAt(8))  return (0);
		else return (-1);
	} 
	//si es una clave numerica
	if (temp ==10) temp =0;
	if ( temp == num.charAt(8))  return (0);
	else return (-1);
}









//funcioin de validacion de DNI. Devuelve un 0 si es correcto y un -1 en caso contrario
function validarDNI(dni)
{
	num=dni.substring(0,dni.length-1);
	let=dni.charAt(dni.length-1);
	if (!isNaN(let)) return false;
	cadena="TRWAGMYFPDXBNJZSQVHLCKET";
  	posicion = num % 23;
  	letra = cadena.substring(posicion,posicion+1);
  	if (letra!=let.toUpperCase()) return (-1);
	return (0);
}
/* Esta funcion comprueba el formato del numero de documento que se pasa por parámetro
 * Si es un nif comprueba si son 8 dígitos y una letra y si es un cif comprueba que sea
 * una letra y ocho digitos. Luego comprueba si la letra y el numero son correctos.
 * Retorna -1 si es incorrecto y 0 si es correcto y -2 si está vacío.
 * Parámetros:
 * @ documento-> cadena que contiene el número de documento a validar.
 */
function ValidarNifCif_mod(documento) {
	var Vacio=/\S+/;
	var resultado;
	if (!Vacio.test(documento)) return (-2);
	//if (documento.length!=9) return (-1);
	documento = documento.toUpperCase(documento);
	if ( !isNaN(documento.charAt(0)) ) {//se trata de un nif.
		resultado = validarDNI(documento);
		return (resultado);
	} else {//se trata de un cif o un nie.
		
		if (documento.charAt(0)=="X") {//es un nie.
			documento = "0"+ documento.substring(1);
			resultado = validarDNI(documento);
			return (resultado);
		} else {// es un cif.
			resultado = cifValido(documento);
			return (resultado);
		}
	}
}
/* Esta función valida un cif. Devuelve un 0 si es correcto y un -1 en caso contrario
 */

function StrReplace(as,as_rex,as_out){
	 // Purpose: To simulate VB replace
	 //////////////////////////////////
	 var ls_rex;
	 ls_rex = new RegExp(as_rex,"g");
	 as = as.replace(ls_rex, as_out);
	 return as;
}

function Right(cad,ai) {return cad.substr(cad.length - ai)}

function Left(cad,ai)  {return cad.substring(0,ai)}

function ValidaMatricula(elem) {
	/*
	Parsear el formato del primer patrón para rellenar huecos en los alfabéticos con espacios en blanco
	- si por la izquierda solo hay un caracter, ponemos caracter + espacio
	- si por la derecha solo hay un caracter, ponemos espacio + caracter
	en vehículos especiales, si al final hay VE se quita la V dejando solo la E.
	*/
	
	pos1 = elem.value.indexOf('-'); 
	//alert(pos1);
	if (pos1!=-1){
		pos = pos1+1;
		pos2 = elem.value.indexOf('-',pos); 
		//alert(pos2);
		if (pos2==-1){
			elem.value = StrReplace(elem.value,'-','0');	
		}
	}
	elem.value = StrReplace(elem.value,'-','');	
	mt = elem.value.toUpperCase();
	mt = StrReplace(mt,' ','');
	
	EsPatron1 = /^[A-Z]{1,2}[0-9]{4}[A-Z]{1,2}$/.test(mt);
	//alert(EsPatron1);
	EsPatron2 = /^[0-9]{4}[A-Z]{3}$/.test(mt);
	//alert(EsPatron2);
	EsPatron3 = /^[A-Z]{1,2}[0-9]{6}$/.test(mt);
	//alert(EsPatron3);
	
	//12M1232
	EsPatron4 = /^[0-9]{2}[A-Z]{1,2}[0-9]{4}$/.test(mt);
	//alert(EsPatron4);
	
	EsPatron5 = /^[0-9]{6}$/.test(mt);
	//alert(EsPatron5);
	//EsPatron3 = /^R{1}[0-9]{4}[A-Z]{3}$/.test(mt);
	//alert(EsPatron3);
	
	EsVehiculoEspecial = /^E[0-9]{4}[A-Z]{3,4}$/.test(mt);
	//alert(EsVehiculoEspecial);	
	EsVehiculoEspecial2 = /^[A-Z]{1,2}[0-9]{5,6}V{0,1}E{1}$/.test(mt);
	//alert(EsVehiculoEspecial2);
	EsVehiculoEspecial_quitarV = /^[A-Z]{1,2}[0-9]{5,6}V{1}E{1}$/.test(mt);
	//alert(EsVehiculoEspecial_quitarV);	
	
	EsCiclomotor = /^C[0-9]{4}[A-Z]{3,4}$/.test(mt);
	//alert(EsCiclomotor);
	EsRemolque = /^R[0-9]{4}[A-Z]{3,4}$/.test(mt);
	//alert(EsRemolque);
	
	if(EsPatron1)
	{
		ini = Left(mt,2);
		fin = Right(mt,2);
		s3 = mt;
		if(!/^[A-Z]{2}$/.test(ini))
			{ 
			//alert('Solo un caracter a la izquierda');
			s2 = Right(ini,1);
			s1 = Left(ini,1);
			s3 = StrReplace(s3, ini, s1+" "+s2);
			elem.value = s3;
			}
		if(!/^[A-Z]{2}$/.test(fin))
			{ 
			//alert('Solo un caracter a la derecha');
			elem.value = StrReplace(s3, fin, Left(fin,1)+" "+Right(fin,1));
			}
	}
	if(EsVehiculoEspecial || EsVehiculoEspecial2)
	{
		ini = Left(mt,2);
		fin = Right(mt,2);
		s3 = mt;
		if(!/^[A-Z]{2}$/.test(ini))
			{ 
			//alert('Solo un caracter a la izquierda');
			s2 = Right(ini,1);
			s1 = Left(ini,1);
			s3 = StrReplace(s3, ini, s1+" "+s2);
			}
		if(EsVehiculoEspecial_quitarV)
		{
			fin = Right(s3,2);
			aux = Left(s3, s3.length - 2);
			s3 = aux+Right(fin,1);
		}
		elem.value = s3
	}
	return (EsPatron1 || EsPatron2 || EsPatron3 || EsPatron4 || EsPatron5 || EsVehiculoEspecial || EsVehiculoEspecial2 || EsCiclomotor || EsRemolque);
}
// ---------------- FIN DE FUNCIONES PARA FORMATOS ----------------//



// ---------------- FIN DE FUNCIONES PARA FORMATOS ----------------//





// ---------------- FUNCIONES AJAX ----------------//
function nuevoAjax(){
var xmlhttp=false;
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}


function novoAjax(){
var xmlhttp=false;
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}

function urlDecode(str){
  	str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}

function getAjax (url, div){
        var contenedor = document.getElementById(div);
        ajax=nuevoAjax(); 
        //peticionamos los datos, le damos la url enviada desde el link
        ajax.open("GET", url, true); 
        ajax.onreadystatechange=function(){
            if(ajax.readyState==1){

            contenedor.innerHTML = "<div align='center'style='float: right; width: 225px; margin: 60px 0;'><img src='images/loading.gif' width='30' height='30' /><br />Cargando...</div>";

            }else if(ajax.readyState==4){
                        if(ajax.status==200){
                                //mostramos los datos dentro del contenedor
                                contenedor.innerHTML = ajax.responseText
                        }else if(ajax.status==404){
                                contenedor.innerHTML = "La página no existe";
                        }else{
                                //mostramos el posible error
                                contenedor.innerHTML = "Error:".ajax.status; 
                        }
                }
        }
        ajax.send(null);
}
function ventana(URL,nombre){	
//URL="index.htm"
//nombre='dani';
	//alert(nombre);
		eval("temp=window.open('"+URL+"','"+nombre+"', 'toolbar=0,scrollbars=no,location=0,statusbar=0,menubar=0,resizable=1,width=1,height=1,left=10,top=10')");
		temp.focus();
		
}
// ---------------- FIN DE FUNCIONES AJAX ----------------//




/* DIEGO : FUNCIONES NIF/CIF */
	  	function cif(cif)
		{
			par = 0
			non = 0
			letras="ABCDEFGHKLMNPQS"
			let=cif.charAt(0)

			if (!isNaN(let))
		    {
				nif=cif
				return validar(nif)
  				//return false
 		 	}

			if (cif.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(cif.charAt(zz))
  			}

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

			parcial = par + non

			control = (10 - ( parcial % 10))

			if (control!=cif.charAt(8))
 	 		{
  				//alert("El Cif no es válido")
  				return false
  			}
			//alert("El Cif es válido")
			return true
		}

		function validar(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 limitarCaracteres(field, count, max) {
			if (field.value.length > max)
			field.value = field.value.substring(0, max);
			else
			document.getElementById(count).innerHTML = max - field.value.length;
		}