/* PARAMETROS:
   FUNCIONALIDAD: Escribe la fecha actual en el formato: Lunes, Marzo 15, 2004
*/
function writeActualDate(){
	// Set an array for the days of the week
	// We add a comma and a space to each for presentation
	// get.day will return 0 through 6 as valid values
	word_day = new Array("Domingo, ","Lunes, ","Martes, ","Mi?rcoles, ","Jueves, ","Viernes, ","S?bado, ")

	// Set an array for the Months of the year
	// We add a space after the month for presentation
	// get.month will return 0 through 11 as valid values
	word_month = new Array("Enero ","Febrero ","Marzo ","Abril ","Mayo ","Junio ","Julio ","Agosto ","Septiembre ", "Octubre ","Noviembre ","Diciembre ")

	// Set right_now to the current date() value
	right_now = new Date();

	// Write the day of the week
	document.write(word_day[right_now.getDay()]);
	// Write the Month of the year
	document.write(word_month[right_now.getMonth()]);

	//Write the date of the month
	document.write(right_now.getDate() + ", ");

	// Write out the Year
	var right_year=right_now.getYear();
	if (right_year < 2000)
	right_year = right_year + 1900;
	document.write( right_year );
}

/*PARAMETROS:   formu es el nombre del formulario al que queramos a?adir el parametro,
		nombre es el nombre del parametro que queramos crear,
		valor es el valor del parametro que estamos creando
FUNCIONALIDAD:	a la hora de a?adir un nuevo parametro al formulario se comprueba si ya
		existe y si es asi se le da el valor que queremos que tenga en este momento
		y si no existe se crea
RETURN:	 	no devuelve nada */
function addNewParameter(formu,nombre,valor){
	var existe = "no";
	for(var i=0; i<eval(formu + '.elements.length'); i++){
		if(eval(formu).elements[i].name == nombre){
			eval(formu).elements[i].disabled = false;
			eval(formu).elements[i].value = valor;
			existe = "si";
		}
	}
	if(existe == "no"){
		var input1 = document.createElement('INPUT');
		input1.type = "hidden";
		input1.value = valor;
		input1.name = nombre;
		eval(formu).appendChild(input1);
	}
}

/* PARAMETROS: 	  url, url que queremos que se cargue en la ventana a la que llamamos
		  ancho, ancho que queremos que tenga la ventana flotante a la cual llamamos
		  alto, altura que queremos que tenga la ventana flotante a la cual llamamos
   FUNCIONALIDAD: llama a una pantalla flotante con los parametros indicados
*/
function abrirVentana(url,ancho,alto) {
	if (document.all) var xMax = screen.width, yMax = screen.height;
	else
		if (document.layers) var xMax = window.outerWidth, yMax = window.outerHeight;
		else var xMax = 640, yMax=480;
	var xOffset = (xMax - ancho)/2, yOffset = (yMax - alto)/2 - 30;
	var parametros = 'scrollbars=yes,status=no,toolbar=no,location=no,directories=no,menubar=no,width='+ancho+',height='+alto+',resizable=0,top='+yOffset+',left='+xOffset;
	window.open(url,"Ventana",parametros);
}

/* PARAMETROS: 	  formu, formulario al que llamamos
		  ancho, ancho que queremos que tenga la ventana flotante a la cual llamamos
		  alto, altura que queremos que tenga la ventana flotante a la cual llamamos
   FUNCIONALIDAD: llama a la flotante enviandole los parametros en el submit
*/
function openWindowWithSetTimeOut(formu, ancho, alto){
	setTimeout('document.' + formu + '.submit()',1000);

	if (document.all) var xMax = screen.width, yMax = screen.height;
	else
	   if (document.layers) var xMax = window.outerWidth, yMax = window.outerHeight;
	   else var xMax = 640, yMax=480;
	var xOffset = (xMax - ancho)/2, yOffset = (yMax - alto)/2;
	var param = 'scrollbars=yes,status=no,toolbar=no,location=no,directories=no,menubar=no,width='+ancho+',height='+alto+',resizable=no,top='+yOffset+',left='+xOffset;

	window.open('','ventana',param);
}

/* PARAMETROS:    nombrePantalla
   FUNCIONALIDAD: hace el href a la url que indicamos con el parametro nombrePantalla
*/
function abrirPantalla(nombrePantalla) {
	window.document.location = nombrePantalla;
}

/* PARAMETROS: 	  formu, es el nombre del formulario que queremos enviar
		  seleccion, es el valor del parametro que vamos a crear en caso necesario
   FUNCIONALIDAD: env?a el formulario formu que pasamos como parametro
   		  con el parametro SELECCION si no est? en el formulario
   NOTA:	  el parametro SELECCION es el que me indica que menu tengo en el
   	 	  menu de la izquierda, asi como su submenu seleccionado correspondiente
*/
function addSeleccion(formu, seleccion){
	addNewParameter(formu,'SELECCION',seleccion);
	eval(formu).submit();
}

/* PARAMETROS: 	  formu, es el nombre del formulario que queremos enviar
		  seleccion, es el valor del parametro que vamos a crear en caso necesario
   FUNCIONALIDAD: env?a el formulario formu que pasamos como parametro
   		  con el parametro SELECCION si no est? en el formulario
   NOTA:	  el parametro SELECCION es el que me indica que menu tengo en el
   	 	  menu de la izquierda, asi como su submenu seleccionado correspondiente
   ADVERTENCIA:   ponerlo en el onload del body para  que a?ada desde el principio el
   		  parametro SELECCION  a cada formulario
*/
function addParameterSeleccion(valor){
	var formu;
	var existe;
	var formu2;
	var i;
	var j;
	var input1;
	var coll = document.all.tags("form");
	for(i=0;i<coll.length;i++){
		existe = "no";

		if(coll[i].elements.length !=0){
			for(j=0;j<coll[i].elements.length;j++){
				if(coll[i].elements[j].name == "SELECCION"){
					existe = "si";
				}
			}
		}
		if(existe == "no"){
			input1 = document.createElement('INPUT');
			input1.type = "hidden";
			input1.value = valor;
			input1.name = "SELECCION";
			input1.id = "SELECCION";
			coll[i].appendChild(input1);
		}
	}
}

/* PARAMETROS:    nombrePantalla
   FUNCIONALIDAD: hace el href a la url que indicamos con el parametro nombrePantalla
*/
function irPantalla(formu, nombrePantalla) {
	formu.action = nombrePantalla;
	formu.submit();
}

function getNumericDate()
{
	var mydate = new Date();
	var year = mydate.getYear();
	var month = mydate.getMonth();
	var day = mydate.getDate();
	if (day < 10)
		day = "0" + day;
	month = month + 1;
	if(month < 10)
		month = '0' + month;
	var now = year.toString() + month.toString() + day.toString();
	return now;
}

function fechas(caja){
   if (caja != "dd/mm/aaaa")
   {
      borrar = caja;
      if ((caja.substr(2,1) == "/") && (caja.substr(5,1) == "/"))
      {
        for (i=0; i<10; i++)
        {
		if (((caja.substr(i,1)<"0") || (caja.substr(i,1)>"9")) && (i != 2) && (i != 5))
		{
			borrar = "";
            		break;
		}
        }
	if (borrar)
	{
		a = caja.substr(6,4);
		m = caja.substr(3,2);

		d = caja.substr(0,2);
		if((a < 1900) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31)){
			borrar = "";
		}
		else
		{
			if((a%4 != 0) && (m == 2) && (d > 28)){
				borrar = "";
			}
			else
			{
				if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29))){
					borrar = "";
				}
				else if(((m == 1) || (m == 3) || (m == 5) || (m==7) || (m==8) || (m==10) || (m==12)) && (d>31)){
					borrar = "";
				}
			// Si las fechas son correctas: ANTES se comprobaba si la fecha era mayor que la actual
			/*	else
				{
					var fechaActual = getNumericDate() + '';
					var fechaCaja = a + m + d;

					if (fechaCaja < fechaActual)
					{
						borrar = "";
					}
				}*/
			}
		}
	}
      }
      else{
		borrar = "";
	}

	if (borrar == "")
		return "NOT_OK";
	else
	{
		return "OK";
	}
   }
	else{
		return "OK"
}
}


function dateCompare(fechaD,fechaH){

if(fechaD != "dd/mm/aaaa" && fechaH != "dd/mm/aaaa"){
	var resultado = "completa";

	if (fechas (fechaD) == "OK" && fechas (fechaH) == "OK"){
		var yearone = fechaD.charAt(6) + fechaD.charAt(7) + fechaD.charAt(8) + fechaD.charAt(9);
		var monthone = fechaD.charAt(3) + fechaD.charAt(4);
		var dayone = fechaD.charAt(0) + fechaD.charAt(1);

		var yeartwo = fechaH.charAt(6) + fechaH.charAt(7) + fechaH.charAt(8) + fechaH.charAt(9);
		var monthtwo = fechaH.charAt(3) + fechaH.charAt(4);
		var daytwo = fechaH.charAt(0) + fechaH.charAt(1);

		var fechaDNumeric = (yearone + monthone + dayone) * 1;
		var fechaHNumeric = (yeartwo + monthtwo + daytwo) * 1;

		if(fechaDNumeric > fechaHNumeric)
			resultado = "";
	}else
		resultado = "";

	if (resultado == "")
		return "NOT_OK";
	else
		return "OK";
	}
else{
	if (fechas (fechaD) == "OK" && fechas (fechaH) == "OK"){
		return "OK"
        }else{
	        return "NOT_OK"
        }
}
}

/* PARAMETROS:    el path de las imagenes
   FUNCIONALIDAD: escribe la parte inferior de las pantallas NO flotantes,
		  donde van las imagenes de privacidad y copyright
*/
function writePiePagina(path){
	var texto = "";
	texto = texto + '<table width="765" border="0" cellspacing="0" cellpadding="0">';
	texto = texto + '     <tr>';
	texto = texto + '       <td bgcolor="#CCCCCC" height="1"><img src="' + path + 'images/px_transp.gif" width="1" height="1"></td>';
	texto = texto + '     </tr>';
	texto = texto + '     <tr>';
	texto = texto + '       <td><table width="100%" cellpadding="0" cellspacing="0">';
	texto = texto + '           <tr>';
	texto = texto + '             <td><img src="' + path + 'images/bot_copyright.gif" width="232" height="15"></td>';
	texto = texto + '             <td align="right"><img src="' + path + 'images/bot_privacidad.gif" width="139" height="15"></td>';
	texto = texto + '           </tr>';
	texto = texto + '         </table></td>';
	texto = texto + '     </tr>';
	texto = texto + '</table>';
	document.write(texto);
}

function changeLanguage(valor){
	formIdioma.IDIOMA.value = valor;
	formIdioma.submit();
}

//**********************************************************************************************************
// * Funci?n: validarEntero ()									   	   *
// * Autor: Alvaro V.S.								                           *
// * Fecha Creaci?n: 1/7/2004									           *
// * Objetivo:   Evalua si el n?mero recibido es un entero, si no lo es lanza un aviso.			   *				*
// * Par?metros: valor - contiene el valor que se quiere comprobar si es un numero entero.		   *
//**********************************************************************************************************//
function validarEntero(obj,valor){
      //intento convertir a entero.
      //si era un entero no le afecta, si no lo era lo intenta convertir

       valorNum = parseInt(valor)

      //Compruebo si es un valor num?rico
      if (isNaN(valorNum)||valor!=valorNum) {
         //entonces (no es numero) devuelvo el valor cadena vacia
         obj.focus();
	 obj.value=valorAnterior;
         alert("Debe introducir un valor numerico entero.");

      }else{
         //En caso contrario (Si era un n?mero) devuelvo el valor
         return valor
      }
}

function validarEnteroABlanco(obj){
      //intento convertir a entero.
      //si era un entero no le afecta, si no lo era lo intenta convertir
       valor=obj.value;
       valorNum = parseInt(obj.value)

      //Compruebo si es un valor num?rico valido.
      if ((isNaN(valorNum)||valor!=valorNum || valorNum<0)&&valor!='') {
         //entonces (no es numero) devuelvo el valor cadena vacia
         obj.focus();
	 obj.value='';
         alert("Debe introducir un valor numerico entero positivo.");
         obj.focus();
         return -1;

      }else{
         //En caso contrario (Si era un n?mero) devuelvo el valor
         return obj.value;
      }
}


var valorAnterior=1;

function validarFecha(objdia, objmes, objanyo){
	var dia = objdia.value;
	var mes = objmes.value;
	var anyo = objanyo.value;


	//vemos si la fecha es v?lida
       //Si el a?o no es valido
       if (anyo<0)
       {
           alert("El a?o introducido no es v?lido");
           objanyo.focus();
           return false;
       }
	if(anyoBisiesto(anyo))
           febrero=29;
       else
           febrero=28;
       //Miramo si el mes introducido es erroneo
       if ((mes<1) || (mes>12))
       {
           alert("El mes introducido no es v?lido");
           objmes.focus();
           return false;
       }
       //Si el mes es febrero miramos si est? bien introducido el dia
       if ((mes==2) && ((dia<1) || (dia>febrero)))
       {
           alert("El dia introducido no es v?lido");
           objdia.focus();
           return false;
       }
       //si es un mes de 31 d?as
       if (((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && ((dia<1) || (dia>31)))
       {
           alert("El dia introducido no es v?lido");
           objdia.focus();
           return false;
       }
       //Si el mes tiene 30 d?as
       if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30)))
       {
           alert("El dia introducido no es v?lido");
           objdia.focus();
           return false;
       }



       return true;

}


function esNumeroValido (valor){
	noNumero = eval('isNaN("'+valor+'")');
	if ( noNumero){
		alert("No es un caracter v?lido");
		return false;
	}else{
	return true;
	}
}



function anyoBisiesto(anyo)
    {

        if (anyo % 4 != 0)
            return false;
        else
        {
            if (anyo % 100 == 0)
            {
                //a?o bisiesto
                if (anyo % 400 == 0)
                {
                    return true;
                }
                //a?o NO bisiesto
                else
                {
                    return false;
                }
            }
            //a?o bisiesto
            else
            {
                return true;
            }
        }
    }


    //Mira si la fecha1 es anterior o igual a la fecha2
 function antes(fecha1, fecha2){
    	if (fecha1.getFullYear() > fecha2.getFullYear()){
    		return false;

    	}else{
    		if (fecha1.getFullYear() < fecha2.getFullYear()){
    			return true;
    		}else{
    			//es el mismo a?o
    			if (fecha1.getMonth() > fecha2.getMonth()){
    				return false;
    			}else{
    				if (fecha1.getMonth()<fecha2.getMonth()){
    					return true;
    				}else{
    				//son el mismo mes
    					if (fecha1.getDate() <=fecha2.getDate()){
    						return true;
    					}else{
    						return false;
    					}
    				}
    			}
    		}

	}
}

function validarFechaConActual(objdia, objmes, objanyo,diaHoy,mesHoy,anyoHoy){
	var dia = objdia.value;
	var mes = objmes.value;
	var anyo = objanyo.value;


	//vemos si la fecha es v?lida

	if(anyoBisiesto(anyo))
           febrero=29;
       else
           febrero=28;
       //Miramo si el mes introducido es erroneo
       if ((mes<1) || (mes>12))
       {
           alert("El mes introducido no es v?lido");
           objmes.focus();
           return false;
       }
       //Si el a?o no es valido
       if (anyo<0 || anyo=='')
       {
           alert("El a?o introducido no es v?lido");
           objanyo.focus();
           return false;
       }
       //Si el mes es febrero miramos si est? bien introducido el dia
       if ((mes==2) && ((dia<1) || (dia>febrero)))
       {
           alert("El dia introducido no es v?lido");
           objdia.focus();
           return false;
       }
       //si es un mes de 31 d?as
       if (((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && ((dia<1) || (dia>31)))
       {
           alert("El dia introducido no es v?lido");
           objdia.focus();
           return false;
       }
       //Si el mes tiene 30 d?as
       if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30)))
       {
           alert("El dia introducido no es v?lido");
           objdia.focus();
           return false;
       }

       if(anyo<anyoHoy){
       		alert("La fecha introducida no puede ser anterior al dia de hoy.");
       		objanyo.focus();
       		return false;
       }
       else{
		if(anyo==anyoHoy&&mes<mesHoy){
			alert("La fecha introducida no puede ser anterior al dia de hoy.");
			objmes.focus();
       			return false;
		}
		else{
			if(anyo==anyoHoy && mes==mesHoy && dia<diaHoy){
       				alert("La fecha introducida no puede ser anterior al dia de hoy.");
       				objdia.focus();
       				return false;
       			}
       			else	{
       				return true;
       			}
		}
       }

       return true;

}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function



/*PARAMETROS: 	 Nombre del formulario.
  FUNCIONALIDAD: Comprueba que el string introducido por el usuario contenga una @ y un punto.
  RETURN: 	 La funci?n no devuelve nada.	
*/
function checkMail(nombre){
	var errores = "";
	if (nombre && nombre.value!='' ) {
		if (nombre.value.indexOf('@',0) == -1 || nombre.value.indexOf('.',0) == -1){
			alert("La direcci?n de E-mail no es correcta.");
			nombre.focus();
			return false;
		}else{
			return true;
		}
	}
}

/*
PARAMETROS:	campo --> Se pasa el campo para coger su value y poder hacer el focus().
FUNCIONALIDAD:	Comprueba que un campo sea o un CIF o un NIF. Para ello llama a las siguientes dos funciones: verificarCIF y verificarNIF.
RETURN:		Devuelve las alertas correspondientes a que no se trata de un CIF o NIF.
RECOMENDABLE:   El uso de esta funci?n se hace sobre el evento onblur()
*/
function checkCIFOrNIF(campo){
   var valor = campo.value.toUpperCase();
   if (valor.length != 9 && valor.length != 0){
   	alert("Introduzca 9 caracteres para el campo CIF/NIF.")
   	campo.focus();
   }else if(valor.length == 9){
	var toWork = new String(valor.substring(0,9));
	var first = toWork.substring(0,1);
	var letraCIF = new String ('ABCDEFGHPQS');
	   
	if (letraCIF.indexOf (first) >=0){
	   var letraOrg = new String('PQS');
	   var isOrg = (letraOrg.indexOf (first) >=0);
	   return verificaCIF(toWork, isOrg,campo);
	}else
	   return verificaNIF(toWork,campo);
   }
}

/*
PARAMETROS:	vienen de la funci?n checkCIFOrNIF.
FUNCIONALIDAD:	Comprueba que un campo sea o un CIF.
RETURN:		Devuelve las alertas correspondientes a que no se trata de un CIF.
*/
function verificaCIF(toWork, isOrg,campo){
	var ultimaLetra  = new Array ('J','A','B','C','D','E','F','G','H','I');
	var ultimoNumero = new Array ('0','1','2','3','4','5','6','7','8','9');
	
	var numValue = new String(toWork.substring(1,8));
	
	var sumaPar = 0;
	for(i=1; i<numValue.length; i+=2){
		sumaPar += parseInt(numValue.substring(i,i+1));
	}
	
	var sumaImpar = 0;
	var stVal = '';
	for(i=0; i<numValue.length; i+=2){
		var val = parseInt(numValue.substring(i,i+1)) * 2;
		if (val > 9)
		    val = val - 9;
		stVal = new String(val);
		for (j=0; j<stVal.length; j++){
		    sumaImpar += parseInt(stVal.substring(j,j+1));
		}
	}
	
	var sumaTotal = sumaImpar + sumaPar;
	var num = (10 - (sumaTotal % 10));
	if (num == 10)
		num = 0;
	
	var ultimo = toWork.substring(8, 9);
	if (isOrg){
		if (ultimo != ultimaLetra[num]){
			alert("No es un CIF v?lido.");	
			campo.focus();
			return false;
		}
	}else{
		if ((ultimo != ultimaLetra [num]) && (ultimo != ultimoNumero[num])){
			alert("No es un CIF v?lido.");	
			campo.focus();
			return false;
		}
	}
	return true;
}

/*
PARAMETROS:	vienen de la funci?n checkCIFOrNIF.
FUNCIONALIDAD:	Comprueba que un campo sea o un NIF.
RETURN:		Devuelve las alertas correspondientes a que no se trata de un NIF.
*/
function verificaNIF(toWork,campo)
{
	var valids  = new Array('T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E');
	var spanish = new Array('0','1','2','3','4','5','6','7','8','9');
	
	var last = toWork.charAt( toWork.length - 1 );
	var ver  = toWork.charAt(0);
	var toConvert = new String('A');
	var tipo = 0;
	for(i=0; i<spanish.length; i++){
		if( ver == spanish[i] ){
		         toConvert = toWork.substring(0,8);
		         break;
		}
	}
	if( ver == 'L' || ver == 'K')
		toConvert = toWork.substring(3,8);
	else if(ver == 'X')
		toConvert = toWork.substring(1,8);
	
	tipo = toConvert;
	var num = tipo % 23;
	if(valids[num] != last){
		alert("No es un NIF v?lido.");	
		campo.focus();
		return false;
	}
	return true;
}