/* 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);
	}
}

function popupPosition(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;
	var retorno = 'width='+ancho+',height='+alto+',top='+yOffset+',left='+xOffset;
	return retorno;
}

/* 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 abrir_ventana(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:    nombrePantalla
   FUNCIONALIDAD: hace el href a la url que indicamos con el parametro nombrePantalla
*/
/* 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 abrirVentanaMenuIzqSinControles(formu){
	var ancho = 460;
	var alto = 300;
	eval('document.' + formu + '.target = "' + formu + 'ventana"');
	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('',formu + 'ventana',param);
}

function abrirVentanaMenuIzq(formu){
	eval('document.' + formu + '.target = "' + formu + 'ventana"');
	setTimeout('document.' + formu + '.submit()',1000);
	window.open('',formu + 'ventana');
}

/* 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.getElementsByTagName("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);
		}
	}
}

function addParameterId(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 == "id"){
					existe = "si";
				}
			}
		}
		if(existe == "no"){
			input1 = document.createElement('INPUT');
			input1.type = "hidden";
			input1.value = valor;
			input1.name = "id";
			input1.id = "id";
			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 getNumericDate2()
{
	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 = day.toString() + "/" + month.toString() + "/" +  year.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( fechaD == "" || fechaH == ""){
	return "OK";
	}
		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"
	        }
	}
}

//**********************************************************************************************************
// * 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(texto1);

      }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=trim(obj.value);
       valorAux='';
       encontradoCero='si';
       //alert(valor);
       //Quito los ceros por delante
       for(a=0;a<valor.length;a++){
       	if(valor.charAt(a)==0 && encontradoCero=='si'){

       	}
	else{
	 encontradoCero='no'
	 valorAux=valorAux+valor.charAt(a);
	}
       }
       //alert(valorAux);
       valorNum = parseInt(trim(valorAux))

      //Compruebo si es un valor num?rico valido.
      if ((isNaN(valorNum)||valorAux!=valorNum || valorNum<0)&&valor!='') {
         //entonces (no es numero) devuelvo el valor cadena vacia
         obj.focus();
	 obj.value='';
         alert(texto2);
         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(texto3);
           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(texto4);
           objmes.focus();
           return false;
       }
       //Si el mes es febrero miramos si est? bien introducido el dia
       if ((mes==2) && ((dia<1) || (dia>febrero)))
       {
           alert(texto5);
           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(texto5);
           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(texto5);
           objdia.focus();
           return false;
       }

       return true;
}

function validarFechaString(fecha){
	if(trim(fecha)=='') return true;
	numGuiones=0;
	numBarras=0;
	numSeparadores=0;
	numCaracAnyo=0;
	var dia = "";
	var mes = "";
	var anyo = "";
	for(a=0;a<fecha.length;a++){
		caracter=fecha.charAt(a);
		if(caracter=='/'){
			numBarras++;
			numSeparadores++;
		}
		if(caracter=='-'){
			numGuiones++;
			numSeparadores++;
		}
		if(caracter!='/' && caracter!='-'){
			if(numSeparadores==0) dia=dia+caracter;
			if(numSeparadores==1) mes=mes+caracter;
			if(numSeparadores==2){ anyo=anyo+caracter;numCaracAnyo++ }
		}
	}
	if(numGuiones!=2 && numBarras!=2){
		 alert(texto6);
		 return false;
	}
	if(!esNumeroValidoSinAlert(dia) || !esNumeroValidoSinAlert(mes) || !esNumeroValidoSinAlert(anyo)){
		 alert(texto6);
		 return false;
	}
	if(numCaracAnyo!=4){
		alert(texto7);
		return false;
	}

       //vemos si la fecha es v?lida
       //Si el a?o no es valido
       if (anyo<0)
       {
           alert(texto3);
           return false;
       }
	if(anyoBisiesto(anyo))
           febrero=29;
       else
           febrero=28;
       //Miramo si el mes introducido es erroneo
       if ((mes<1) || (mes>12))
       {
           alert(texto4);
           return false;
       }
       //Si el mes es febrero miramos si est? bien introducido el dia
       if ((mes==2) && ((dia<1) || (dia>febrero)))
       {
           alert(texto5);
           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(texto5);
           return false;
       }
       //Si el mes tiene 30 d?as
       if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30)))
       {
           alert(texto5);
           return false;
       }
       return true;
}

function validarFechaStringSep(fecha){
	if(trim(fecha)=='') return true;
	numGuiones=0;
	numBarras=0;
	numSeparadores=0;
	numCaracAnyo=0;
	var dia = "";
	var mes = "";
	var anyo = "";
	if ( fecha.length != 10){
		alert(texto8);
		 return false;
	}
	for(a=0;a<fecha.length;a++){
		caracter=fecha.charAt(a);
		if(caracter=='/'){
			numBarras++;
			numSeparadores++;
		}
		if(caracter!='/'){
			if(numSeparadores==0) dia=dia+caracter;
			if(numSeparadores==1) mes=mes+caracter;
			if(numSeparadores==2){ anyo=anyo+caracter;numCaracAnyo++ }
		}
	}
	if( numBarras!=2){
		 alert(texto8);
		 return false;
	}
	if(!esNumeroValidoSinAlert(dia) || !esNumeroValidoSinAlert(mes) || !esNumeroValidoSinAlert(anyo)){
		 alert(texto8);
		 return false;
	}
	if(numCaracAnyo!=4){
		alert(texto7);
		return false;
	}

       //vemos si la fecha es v?lida
       //Si el a?o no es valido
       if (anyo<0)
       {
           alert(texto3);
           return false;
       }
	if(anyoBisiesto(anyo))
           febrero=29;
       else
           febrero=28;
       //Miramo si el mes introducido es erroneo
       if ((mes<1) || (mes>12))
       {
           alert(texto4);
           return false;
       }
       //Si el mes es febrero miramos si est? bien introducido el dia
       if ((mes==2) && ((dia<1) || (dia>febrero)))
       {
           alert(texto5);
           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(texto5);
           return false;
       }
       //Si el mes tiene 30 d?as
       if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30)))
       {
           alert(texto5);
           return false;
       }
       return true;
}

function diaDeFecha(fecha){
	dia='';
	for(a=0;a<fecha.length;a++){
		caracter=fecha.charAt(a);
		if(caracter!='/' && caracter!='-') dia=dia+caracter;
		if(caracter=='/' || caracter=='-') a=fecha.length;
	}
	return dia;
}

function mesDeFecha(fecha){
	mes='';
	numSeparadores=0;
	for(a=0;a<fecha.length;a++){
		caracter=fecha.charAt(a);
		if(numSeparadores==1 && caracter!='/' && caracter!='-') mes=mes+caracter;
		if(caracter=='/' || caracter=='-') numSeparadores++
		if(numSeparadores==2) a=fecha.length;
	}
	return mes;
}

function anyoDeFecha(fecha){
	anyo='';
	numSeparadores=0;
	for(a=0;a<fecha.length;a++){
		caracter=fecha.charAt(a);
		if(numSeparadores==2 && caracter!='/' && caracter!='-') anyo=anyo+caracter;
		if(caracter=='/' || caracter=='-') numSeparadores++
	}
	return anyo;
}

function esNumeroValido (valor){
	noNumero = eval('isNaN("' + valor + '")');
	if (noNumero){
		alert(texto9);
		return false;
	}else{
		return true;
	}
}

function esNumeroValidoSinAlert(valor){
       valorAux='';
       encontradoCero='si';

       //Quito los ceros por delante
       for(a=0;a<valor.length;a++){
       	if(valor.charAt(a)==0 && encontradoCero=='si'){

       	}
	else{
	 encontradoCero='no'
	 valorAux=valorAux+valor.charAt(a);
	}
       }

       valorNum = parseInt(trim(valorAux))
       //Compruebo si es un valor num?rico
        if (isNaN(valorNum)||valor!=valorNum) {
		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(texto4);
           objmes.focus();
           return false;
       }
       //Si el a?o no es valido
       if (anyo<0 || anyo=='')
       {
           alert(texto3);
           objanyo.focus();
           return false;
       }
       //Si el mes es febrero miramos si est? bien introducido el dia
       if ((mes==2) && ((dia<1) || (dia>febrero)))
       {
           alert(texto5);
           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(texto5);
           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(texto5);
           objdia.focus();
           return false;
       }

       if(anyo<anyoHoy){
       		alert(texto10);
       		objanyo.focus();
       		return false;
       }
       else{
		if(anyo==anyoHoy&&mes<mesHoy){
			alert(texto10);
			objmes.focus();
       			return false;
		}
		else{
			if(anyo==anyoHoy && mes==mesHoy && dia<diaHoy){
       				alert(texto10);
       				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 emailStr = nombre.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(emailStr)) return true;
	else{
		alert(texto11);
		return false;
	}
}

/*
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(texto12)
   	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(texto13);
			campo.focus();
			return false;
		}
	}else{
		if ((ultimo != ultimaLetra [num]) && (ultimo != ultimoNumero[num])){
			alert(texto13);
			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(texto14);
		campo.focus();
		return false;
	}
	return true;
}

function validarNumeroConDecimales (valor,mensajeDeError){
	valorAux="";
	for(a=0;a<valor.length;a++){
		if(valor.charAt(a)=='.')
			valorAux=valorAux;
		else
			valorAux=valorAux+valor.charAt(a);
	}

	valor=valorAux;
	valorAux="";
	for(a=0;a<valor.length;a++){
		if(valor.charAt(a)==',')
			valorAux=valorAux+'.';
		else
			valorAux=valorAux+valor.charAt(a);
	}

	miFloat = parseFloat(valorAux);

	noNumero = eval('isNaN("'+miFloat+'")');
	if ( noNumero||miFloat!=valorAux){
		alert(mensajeDeError);
		return false;
	}else{
		return true;
	}
}

function abrir_ventanaSinScroll(url,ancho,alto,nombre) {
	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=no,status=no,toolbar=no,location=no,directories=no,menubar=no,width='+ancho+',height='+alto+',resizable=0,top='+yOffset+',left='+xOffset;
	window.open(url,nombre,parametros);
}

//-----------------

/* **** STRING EXTENSION FOR PUNCTUATION **** */
String.fromKeyCode = function(keyCode,evtType) {
	if (!evtType || !evtType.length)
		evtType = "keyDown";
	else if (evtType.toLowerCase() == "keypress")
		return String.fromCharCode(keyCode);
	var keyDownChars = new Array(16);
		keyDownChars[8] = '[Bksp]';
		keyDownChars[9] = '[Tab]';
		keyDownChars[12] = '[N5+shift]';
		keyDownChars[13] = '[Enter]';
		keyDownChars.push('[Shift]','[Ctrl]','[Alt]','[Pause]','[CapsLock]');
		for (i=11;i;--i) keyDownChars.push('undefined');
		keyDownChars[27] = '[Esc]';
		keyDownChars.push(' ','[PgUp]','[PgDn]','[End]','[Home]','[Left]','[Up]','[Right]','[Down]');
		for (i=7;i;--i) keyDownChars.push('undefined');
		keyDownChars[45] = '[Ins]';
		keyDownChars[46] = '[Del]';
		keyDownChars.push(['0',')'],['1','!'],['2','@'],['3','#'],['4','$'],['5','%'],['6','^'],['7','&'],['8','*'],['9','(']);
		for (i=7;i;--i) keyDownChars.push('undefined');
		keyDownChars.push('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[WinKey]');
		for (i=4;i;--i) keyDownChars.push('undefined');
		keyDownChars.push('0','1','2','3','4','5','6','7','8','9','*','+','undefined','-','.','/','[F1]','[F2]','[F3]','[F4]','[F5]','[F6]','[F7]','[F8]','[F9]','[F10]','[F11]','[F12]');
		for (i=62;i;--i) keyDownChars.push('undefined');
		keyDownChars[144] = '[NumLock]';
		keyDownChars[145] = '[ScrollLock]';
		keyDownChars.push([';',':'],['=','+'],[',','<'],['-','_'],['.','>'],['/','?'],['`','~']);
		for (i=26;i;--i) keyDownChars.push('undefined');
		keyDownChars.push(['[','{'],['\\','|'],[']','}'],["'",'"']);
	return keyDownChars[keyCode];
}

/* **** COMBOBOX CODE **** */
/**************************************************
Original Version (1.0):
Glenn G. Vergara
http://www21.brinkster.com/gver/
glenngv AT yahoo DOT com
Makati City, Philippines

Object-Based Version:
Eric C. Davis
http://www.10mar2001.com/
eric AT 10mar2001 DOT com
Atlanta, GA, US

(Keep the above intact if you want to use it! Thanks.)

Current Version: 2.3
Last Update: 11 September 2003

********
Change Log:
New in version 2.3a:
	- Added accepting of non-existent option

New in version 2.2:
	- Many properties made private
	- Getters and setters for nearly all properties

New in version 2.0:
	- Object-oriented properties and methods using prototype
	- Constructor can accept a select element object or a select element object's ID string
	- Invocation reduced to single line of script: varName = new TypeAheadCombo('selectElementID');

New in version 1.4:
	- Allowable character set ranges use dynamic evaluation
	- Display of typed characters in status bar can be disabled

New in version 1.2:
	- Replaced major if/elseif/.../else statement with switch/case
	- Correction of characters typed on the numpad, reassigning to actual character values
********

********
API:
Constructor:
	new TypeAheadCombo(someSelectElement) // as an object or object reference
	new TypeAheadCombo('someSelectElementID') // as a string
	new TypeAheadCombobox('someSelectElementID', true) // to allow an undefined value

Priviledged Methods: (these interact with private properties and act as helper functions)
	getTyped()
		- returns the string typed by the user since the last timeout
	setTyped(str)
		- argument "str" - string which will replace the value in the type buffer
	type(str)
		- argument "str" - string which will be appended to the type buffer
	resetTyped()
		- clears what has been typed from the buffer
	getIndex()
		- returns the location of the option currently selected
	setIndex(val)
		- stores the location of the option being selected
	getPrev()
		- returns the location of the option previously selected
	setPrev(val)
		- stores the location of the option previously selected
	setResetTime(val)
		- sets the timeout interval for the reset timers
	getResetTime()
		- returns the timeout interval for the reset timers
	setResetTimer()
		- sets the timeout for the reset of the typed buffer
	clearResetTimer()
		- clears the timeout of the reset of the typed buffer
	validChar(charCode)
		- validates that the charCode passed is acceptable to the typed buffer
	setDisplayStatus(bool)
		- set whether to display the typed buffer in the status bar
	getDisplayStatus()
		- returns the current setting for status bar display of the typed buffer

Public Methods:
	detectKey()
		- detects the keyCode, parses whether it is acceptable, and adds it to the typed buffer if so
	selectItem()
		- finds the first option that matches the typed buffer and selects it
	reset()
		- clears the typed buffer and the status display
	updateIndex()
		- handles the onclick and onblur events
	elementFocus()
		- handles the onfocus event
	elementKeydown()
		- handles the onkeydown event
********

***************************************************/
function TypeAheadCombo(anElement,acceptNewValue) {
	// VALIDATION
	if (!anElement) {
		return false;
	}
	if (typeof anElement == "string") { // try for the ID
		anElement = document.getElementById ? document.getElementById(anElement) : document.all ? document.all[anElement] : document.layers ? document.layers[anElement] : anElement;
	}
	if (typeof anElement == "string") { // the grab failed: typeof null yields "object"
		return false;
	}
	// ASSOCIATION
	this.element = anElement;
	this.element.combo = this;
	// ELEMENT EVENT HANDLERS
	this.element.onkeydown = this.elementKeydown;
	this.element.onfocus = this.elementFocus;
	this.element.onclick = this.updateIndex;
	this.element.onblur = this.updateIndex;
	this.element.reset = this.reset;
	// PRIVATE PROPERTIES
	var self = this,	// corrects privatization bug
		typed = "",
		index = prev = 0,
		displayStatus = true,
		resetter, nullStarter, acceptNew,
		resetTime = 1600,
		numberRangeStart = 48,
		numberRangeEnd = 57,
		charRangeStart = 65,
		charRangeEnd = 90,
		punctRangeStart = 146,
		punctRangeEnd = 223;
	if ((this.element.options[0]!=null) && (this.element.options[0].text.length == 0 && (this.element.options[0].value.length == 0) || this.element.options[0].value == 0)){
		nullStarter = true;
	} else {
		nullStarter = false;
	}
	if (typeof acceptNewValue != 'undefined' && acceptNewValue) {
		acceptNew = true;
		resetTime = 2400;
	} else {
		acceptNew = false;
	}
	// PRIVATE METHODS
	var getResetTime = function getResetTime() {
		return resetTime;
	}
	var charInRanges = function charInRanges(charCode) {
		if ((charCode >= numberRangeStart && charCode <= numberRangeEnd) || (charCode >= charRangeStart && charCode <= charRangeEnd) || (charCode >= punctRangeStart && charCode <= punctRangeEnd)) {
			return true;
		} else {
			return false;
		}
	}
	// PRIVILEDGED METHODS
	this.hasNullStarter = function() {
		return nullStarter;
	}
	this.getAcceptsNew = function() {
		return acceptNew;
	}
	this.getTyped = function () {
		return typed;
	}
	this.setTyped = function (str) {
		typed = str;
		return true;
	}
	this.resetTyped = function () {
		typed = "";
		return true;
	}
	this.type = function (str) {
		typed += str;
		return true;
	}
	this.getIndex = function () {
		return index;
	}
	this.setIndex = function (val) {
		if (!isNaN(val)) {
			index = val;
		}
	}
	this.getPrev = function () {
		return prev;
	}
	this.setPrev = function (val) {
		if (!isNaN(val)) {
			prev = val;
		}
	}
	this.setResetTime = function (val) {
		if (!isNaN(val)) {
			prev = val;
		}
	}
	this.setTimer = function () {
		resetter = setTimeout("document.forms['"+self.element.form.name+"'].elements['"+self.element.name+"'].reset();", getResetTime());
	}
	this.clearTimer = function () {
		clearTimeout(resetter);
	}
	this.validChar = function (evt, charCode) {
		if ((evt.ctrlKey) || (evt.altKey)) {
			return false;
		} else if ((evt.shiftKey) && charInRanges(charCode)) {
			return true;
		} else if (evt.shiftKey) {
			return false;
		} else {
			return charInRanges(charCode);
		}
	}
	this.setDisplayStatus = function (bool) {
		if (bool == true || bool == false) {
			displayStatus = bool;
		}
	}
	this.getDisplayStatus = function () {
		return displayStatus;
	}
}

/*
PUBLIC METHODS
*/

TypeAheadCombo.prototype.detectKey = function (evt){
	this.clearTimer();
	var combo_letter = "";
	var combo_code = (document.all) ? window.event.keyCode : evt.which;
	var event = (document.all) ? window.event : evt;
	if (combo_code <= 105 && combo_code >= 96) { // make up for numPad typing
		combo_code = combo_code - 48;
	}
	switch (combo_code) {
		case 27:	//ESC key
			this.reset();
			this.setIndex(this.getPrev());
			// Put a little delay to override NS6/Mozilla's built-in behavior of ESC inside select element
			setTimeout("document.forms['"+this.element.form.name+"'].elements['"+this.element.name+"'].selectedIndex = document.forms['"+this.element.form.name+"'].elements['"+this.element.name+"'].index",0);
			return false;
			break;
		case 13:	//ENTER key
			this.reset();
			if (this.element.onchange) {
				this.element.onchange();
			}
		case 9:		//TAB key	(don't break from ENTER - all TAB needs to do is return true. ENTER needs above and return true.
			return true;
			break;
		case 8:		//BACKSPACE key
			this.setTyped(this.getTyped().substring(0,this.getTyped().length-1));
			if (this.getAcceptsNew()) {
				this.makeNewValue();
			}
			if (this.getTyped() == "") {
				this.reset();
				this.setIndex(this.getPrev());
				this.element.selectedIndex = this.getIndex();
				return false;
			} else {
				this.setTimer();
			}
			break;
		case 33:	//PAGEUP key
		case 34:	//PAGEDOWN key
		case 35:	//END key
		case 36:	//HOME key
		case 38:	//UP arrow
		case 40:	//DOWN arrow
			this.reset();
			return true;
			break;
		case 37:	//LEFT arrow	(translates to %)
		case 39:	//RIGHT arrow	(translates to ')
			this.reset();
			return false;
			break;
		case 32:	//SPACE key	(not in accepted ranges)
			combo_letter = " ";
			this.setTimer();
			break;
		default:
			if (this.validChar(event, combo_code)) {
				combo_letter = String.fromKeyCode(combo_code);
				if (combo_letter.length > 1) {
					if (event.shiftKey) {
						combo_letter = combo_letter[1];
					} else {
						combo_letter = combo_letter[0];
					}
				}
				this.setTimer();
			} else {
				return true;
			}
			break;
	}
	this.type(combo_letter);
	if (this.getDisplayStatus()) {
		window.status = this.getTyped();
	}
	return this.selectItem();
}

TypeAheadCombo.prototype.selectItem = function (){
	for (var i=0; i<this.element.options.length; i++){
		if (this.element.options[i].text.toUpperCase().indexOf(this.getTyped()) == 0){
			this.element.selectedIndex = i;
			this.setIndex(i);	//remember selected index
			return false;
		}
	}
	if (this.getAcceptsNew()) {
		this.makeNewValue();
	} else {
		this.element.selectedIndex = this.getIndex();	//re-select previously selected option even if there's no match
	}
	return false;  //always return false
}

TypeAheadCombo.prototype.makeNewValue = function () {
	this.removeNewValue();
	if (this.hasNullStarter()) {
		newOption = this.element.options[0];
	} else {
		newOption = document.createElement("option");
		this.element.insertBefore(newOption, this.element.firstChild);
		this.newOption = newOption;
	}
	var tmpText = this.getTyped(),tmpStart = tmpEnd = "",tmpArr,i;
	tmpArr = tmpText.split(" ");
	i = tmpArr.length;
	if (tmpText.indexOf(" ") >= 0) {
		do {
			tmpStart = tmpArr[--i].substring(0,1);
			tmpEnd = tmpArr[i].substring(1,tmpArr[i].length);
			tmpArr[i] = tmpStart.toUpperCase() + tmpEnd.toLowerCase();
		} while (i);
		tmpText = tmpArr.join(" ");
	} else {
		tmpStart = tmpText.substring(0,1);
		tmpEnd = tmpText.substring(1,tmpText.length);
		tmpText = tmpStart.toUpperCase() + tmpEnd.toLowerCase();
	}
	newOption.value = tmpText;
	newOption.text = tmpText;
	this.element.selectedIndex = 0;
	this.setIndex(0);
}

TypeAheadCombo.prototype.removeNewValue = function () {
	if (this.hasNullStarter()) {
		this.element.options[0].text = '';
		this.element.options[0].value = '';
	} else if (this.newOption) {
		this.element.remove(this.newOption);
	}
}

TypeAheadCombo.prototype.reset = function () {
	theCombo = this;
	if (this.combo) {
		theCombo = this.combo;
	}
	theCombo.resetTyped();
	if (theCombo.getDisplayStatus()) {
		window.status = window.defaultStatus ? window.defaultStatus : '';
	}
}

TypeAheadCombo.prototype.updateIndex = function (){
	this.combo.setIndex(this.selectedIndex);
	this.combo.setPrev(this.combo.getIndex);
	this.combo.reset();
}

TypeAheadCombo.prototype.elementFocus = function () {
	this.combo.setIndex(this.selectedIndex);
}

TypeAheadCombo.prototype.elementKeydown = function (event) {
	return this.combo.detectKey(event);
}



