//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];}
}

//funciones de fecha
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<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;
}

// Compara 2 fechas. 
// Si String1>String2 entonces devuelve false.
// Si tipoFecha es true las fechas vienen en formato americano.
function Comparar_Fecha(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(n)) return false;
	if(tipo=="enteiro") if (n!=parseInt(n)) 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;
}

//levantar ventana flotante
function ventanaMA(URL)
{
 day = new Date();
 id = day.getTime();
 eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=1,width=820,height=620,left=10,top=10');");
}

//levantar ventana flotante
function ventanaMA2(URL)
{
 day = new Date();
 id = day.getTime();
 eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=600,left=200,top=100');");
}


//levantar ventana flotante
function ventanaMA3(URL)
{
 day = new Date();
 id = day.getTime();
 eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=1,width=300,height=300,left=100,top=100');");
}

//AJAX (Añadido por DLopez pa Javi)
	function urlDecode(str){
  		str=str.replace(new RegExp('\\+','g'),' ');
    	return unescape(str);
	}
	function urlEncode(str){
    	return escape(str);
	}
		
	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;
	}



//-----------------FUNCIONES AJAX-------------------------
// 20080121 - Jose García para modificaciones en el administrador.

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);
	}
	}
}

//-------------------FIN FUNCIONES AJAX-----------------------------------


//-------------------Abrir ventana centrada-----------------------------------
function openCenteredWindow(url, height, width, name, parms)
{
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	var winParms = "resize=true,scrollbars=yes,top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
	if (parms) { winParms += "," + parms; }
	var win = window.open(url, name, winParms);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
	return win;
}		
//-------------------Fin de abrir ventana centrada-----------------------------------
