//IMAXES (precarga de imaxes)
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//levantar ventana flotante
function ventana(URL,x,y,posx,posy,resize)
{
 day = new Date();
 id = day.getTime();
 eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=auto,location=0,statusbar=0,menubar=0,resizable="+resize+",width="+x+",height="+y+",left="+posx+",top="+posy+"');");
}
function ventana2(URL,x,y,posx,posy,resize)
{
 day = new Date();
 id = day.getTime();
 eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable="+resize+",width="+x+",height="+y+",left="+posx+",top="+posy+"');");
}

//funciones de fecha, comprueba si el año pasado por parámetro el bisiesto
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;
            }
        }
}

//Funcion de validacion de una Fecha
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<4 || parseFloat(Ano)<1900 || 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	
}

//funcioin de validacion de email
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;
}

//funcioin de validacion de DNI
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 false;
	return true;
}

//funcioin de validacion de CIF
function validarCIF(cif)
{
	par = 0;
	non = 0;
	letras="ABCDEFGHKLMNPQS";
	let=cif.charAt(0);
	if (!isNaN(let)) return false;
	if (cif.length!=9) return false;
	if (letras.indexOf(let.toUpperCase())==-1) 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)) return false;
	return true;
}

// Compara 2 fechas. 
// Si String1>String2 entonces devuelve false.
// Si tipoFecha es true las fechas vienen en formato americano.
function compararFechas(String1,String2,tipoFecha) {
	sFecha1 = new String(String1);
	sFecha2 = new String(String2);
	if (!tipoFecha) {
		ArrayFecha1=sFecha1.split("/");
		ArrayFecha2=sFecha2.split("/");
		sFecha1=ArrayFecha1[1]+"/"+ArrayFecha1[0]+"/"+ArrayFecha1[2];
		sFecha2=ArrayFecha2[1]+"/"+ArrayFecha2[0]+"/"+ArrayFecha2[2];
	} else {
		sFecha1 = String1;
		sFecha2 = String2;
	}
	//date.parse lo que hace es devolverte un numero entero, con lo cual la comparacion es asi de simple
	numFecha1=Date.parse(sFecha1);
	numFecha2=Date.parse(sFecha2);

	if (numFecha1>numFecha2) return false 
	return true;
}


//funcion q comprueba si el valor recibido es un numero y devuelve true i false
//tipo
	//"decimal"
	//"enteiro"
//signo
	//1 -> +
	//0 -> + e -
	//-1 -> -
//nulo -> si vale 1 quere decir non se permite o valor 0, se non se pasa pu pasaselle 0 quere decir q se permite o valor 0
function compruebaNumero(n,tipo,signo,nulo)
{
	var decimal=/^((\d+(\.\d*)?)|((\d*\.)?\d+)|(\d+(\,\d*)?)|((\d*\,)?\d+))$/

	if (n=="") return false;
	if (isNaN(n)) return false;
	if(tipo=="decimal")
	{
		if(!decimal.test(Math.abs(n))) return false;
	}
	else
	{
		if(tipo=="enteiro")
		{
			if (n!=parseInt(n)) return false;
		}
		else
		{
			return false;
		}
	}
	if (isNaN(signo)) return false;
	if(nulo) if (isNaN(nulo)) return false;
	if(!nulo) nulo=0; else if(nulo!=1) nulo=0;
	
	switch(signo)
	{
		case 1://positivo
			if(nulo==0){ if(n<0) return false; }else{  if(n<=0) return false;}
			break;
		case 0://positivo negativo
			
			if(nulo==1){ if(n==0) return false; }
			break;
		case -1://negativo
			if(nulo==0){ if(n>0) return false; }else{  if(n>=0) return false;}
			break;
	}
	return true;
}
/*******Funcion de Daniel Tino*******/
//Funcion que solo permite introducir numeros por teclado
function soloNumero()
{
	var key=window.event.keyCode;//codigo de tecla.

	if (key!=9){
		if (key < 48 || key > 57){
			//si no es numero 
			window.event.keyCode=0;//anula la entrada de texto.
		}
	}
}//soloNumero

function soloNumeroFirefox(evt)
{
	//var key=window.event.keyCode;//codigo de tecla.
	var nav4 = window.Event ? true : false;
	var key = nav4 ? evt.which : evt.keyCode;
	if (key==0 || key==9){
		return;
	}
	else{				
		if (key!=8 && (key < 48 || key > 57)){
			//si no es numero 
			//window.event.keyCode=0;//anula la entrada de texto.
			return ((key>=48 && key<=57));
		}		
	}
}

//-----------------FUNCIONES AJAX-------------------------

function creaAjax(){

	var objetoAjax=false;
	try {

	/*Para navegadores distintos a internet explorer*/
	objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");
	
	} catch (e) {

		try {
		/*Para explorer*/
		objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) {
		objetoAjax = false;
		}
	}

	if (!objetoAjax && typeof XMLHttpRequest!='undefined') {
		objetoAjax = new XMLHttpRequest();
	}

	return objetoAjax;
	
}

function FAjax (url,capa,valores,metodo,cargando,processScripts)
{
	//alert(url);
var ajax=creaAjax();
var capaContenedora = document.getElementById(capa);
/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
if(metodo.toUpperCase()=='POST'){
         ajax.open ('POST', url, true);
         ajax.onreadystatechange = function() {
         if (ajax.readyState==1) {
			 if (cargando=='')
			 	{ capaContenedora.innerHTML="Cargando......."; }
				else
			 	{ capaContenedora.innerHTML=cargando; }         }
         else if (ajax.readyState==4){
                   if(ajax.status==200)
                   {
					   	if(processScripts)
							{ SetContainerHTML(capa, ajax.responseText, true); }
						else
							{ document.getElementById(capa).innerHTML=ajax.responseText; }
 					  
                  } else if(ajax.status==404) {
					   capaContenedora.innerHTML = "La direccion no existe";
                   } else {
                        capaContenedora.innerHTML = "Error: "+ajax.status;
                   }
         }
}
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(valores);
return;
}

/*Creamos y ejecutamos la instancia si el metodo elegido es GET*/
if (metodo.toUpperCase()=='GET'){

         ajax.open ('GET', url, true);
         ajax.onreadystatechange = function() {
         if (ajax.readyState==1) {
			 if (cargando=='')
			 	{ capaContenedora.innerHTML="Cargando......."; }
				else
			 	{ capaContenedora.innerHTML=cargando; }
			}
         else if (ajax.readyState==4){
                   if(ajax.status==200){
					   	if(processScripts)
							{ SetContainerHTML(capa, ajax.responseText, true); }
						else
							{ document.getElementById(capa).innerHTML=ajax.responseText; }
                   }
                   else if(ajax.status==404)
                                             {

                            capaContenedora.innerHTML = "La direccion no existe";
                                             }
                                             else
                                             {
                            capaContenedora.innerHTML = "Error: "+ajax.status;
                                             }
                                    }
                  }
         ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         ajax.send(null);
         return
}
}

function SetContainerHTML(id,html,processScripts)
{
	mydiv = document.getElementById(id);
	mydiv.innerHTML = html;
	if(processScripts!=false)
	{
	var elementos = mydiv.getElementsByTagName('script');
	for(i=0;i<elementos.length;i++) {
	var elemento = elementos[i];
	nuevoScript = document.createElement('script');
	nuevoScript.text = elemento.innerHTML;
	nuevoScript.type = 'text/javascript';
	if(elemento.src!=null && elemento.src.length>0)
	nuevoScript.src = elemento.src;
	elemento.parentNode.replaceChild(nuevoScript,elemento);
	}
	}
}

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 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);
}

//-------------------FIN FUNCIONES AJAX-----------------------------------

