///////////////////////////////////////////////////////////////////////////
//   Fichero GCSWeb.js
///////////////////////////////////////////////////////////////////////////
//   Usuario Internet: /
//   Fichero JavaScript de Programas y Funciones 
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
//   Variables Comunes
///////////////////////////////////////////////////////////////////////////
var TIMEOUT			= 10;								// Numero de segundos de retardo
var	NS4 			= (document.layers)? true:false;	// Booleano indicando Netscape
var	IE4				= (document.all)? true:false;		// Booleano indicando Explorer

var DESTINO			= "CATEGORIA";						// Variable de control del directorio

var browser			= navigator.appName;
var version			= navigator.appVersion;
var br				= "";
var segundosRestantes	= 0;

var LISTDIA	 	= new Item('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
var LISTMES	 	= new Item('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
//   Funciones Comunes
///////////////////////////////////////////////////////////////////////////

function activaEstilo()
{
	br = "UKW";

	if ((browser.indexOf("Netscape") >= 0) && (version.indexOf('5.0') >= 0))
	{
		br		="DOM";
		links	= document.getElementsByTagName('link');
		links[0].disabled	= true;
		links[1].disabled	= true;
		links[2].disabled	= false;
	}
	else if ((browser.indexOf("Explorer") >= 0) && (version.indexOf('5.0') >= 0))
	{
		br		="DOM";
		links	= document.getElementsByTagName('link');
		links[0].disabled	= true;
		links[1].disabled	= true;
		links[2].disabled	= false;
	}
	else if ((browser.indexOf("Explorer") >= 0) && (version.indexOf('4.') >= 0))
	{
		br		= "IE4";
		links	= document.all.tags("link");
		links[0].disabled	= true;
		links[1].disabled	= false;
		links[2].disabled	= true;
	}
	else if ((browser.indexOf("Netscape") >= 0) && (version.indexOf('4.') >= 0))
	{
		br		= "NS4";
		document.links[0].disabled	= false;
		document.links[1].disabled	= true;
		document.links[2].disabled	= true;
	}

	//alert("Navegador detectado: " + br);

}

///////////////////////////////////////////////////////////////////////////
// Funcion que define un elemento tipo array
function Item()
{

	this.length = Item.arguments.length;

	for (var i = 0; i < this.length; i++)
	{
		this[i] = Item.arguments[i]
	}
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion que situa el focus en elemento que se le indique
function setFocus(elemento)
{
	elemento.focus();
	elemento.select();
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion que formatea un campo en un entero de longitud especificada
function formateaCampoEntero(longitud, valor)
{

	var ceros = "";
	var campo = valor;
		
	if (campo == null) { campo = ""; }	

	if (campo.length == longitud) { return campo; }
	else if (campo.length > longitud) { 
		// Si sobrepasa la longitud recortamos por la izquierda
		return campo.substring(campo.length-longitud); 
	}
	else {
		// Si es menor añadimos ceros
		for (var i=0; i<(longitud-campo.length); i++) { ceros = ceros + "0"; }
		
		// Relleno por le izquierda
		campo = ceros + campo;
		return campo;
	}

}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion que devuelve la fecha actual en el formato especificado como 
// argumento: Formatos: 1, 2, 3, 4, 5, 6, 7 o 8
function getFecha(formato) 
{
	var ahora;
	var fecha = new Date();

	var ano   = fecha.getFullYear();
	var mes   = fecha.getMonth();
	var dia   = fecha.getDay();
	var diaM  = fecha.getDate();
	
	var hora  = fecha.getHours();
	var min   = fecha.getMinutes();
	var seg   = fecha.getSeconds();
	
	if (hora <= 9) { hora = "0" + hora; }
	if (min <= 9)  { min  = "0" + min; }
	if (seg <= 9)  { seg  = "0" + seg; }

	//var aux   = "" + fecha;
	//alert("Fecha: " + fecha);

	// Generacion de la cadena de fecha segun el formato
	if (formato == 1)
	{
		// Fecha en formato: Dia, DD de Mes de AAAA
		ahora = LISTDIA[dia] + ", " + diaM + " de " + LISTMES[mes] + " de " + ano;
	}
	else if (formato == 2)
	{
		// Fecha en formato: DD/MM/AAAA
		ahora = diaM + "/" + (mes+1) + "/" + ano;
	}
	else if (formato == 3)
	{
		// Fecha en formato: DD de Mes de AAAA
		ahora = diaM + " de " + LISTMES[mes] + " de " + ano;
	}
	else if (formato == 4)
	{
		// Fecha en formato: DD de Mes de AAAA
		ahora = diaM + " " + LISTMES[mes] + " " + ano;
	}
	else if (formato == 5)
	{
		// Fecha en formato: HH:MM:SS del Dia DD de Mes de AAAA
		ahora = hora + ":" + min + ":" + seg + " del " + LISTDIA[dia] + " " + diaM + " de " + LISTMES[mes] + " de " + ano;

	}
	else if (formato == 6)
	{
		// Fecha en formato: HH:MM:SS DD/MM/AAAA
		ahora = hora + ":" + min + ":" + seg + " " + diaM + "/" + (mes+1) + "/" + ano;

	}
	else if (formato == 7)
	{
		// Fecha en formato: DD/MM/AAAA
		if (diaM <= 9) { ahora = "0" + diaM; }
		else { ahora = "" + diaM; }
		ahora += "/";
		mes = mes + 1;
		if (mes <= 9)  { ahora  += "0" + mes; }
		else { ahora  += "" + mes; }
		ahora += "/" + ano;

	}
	else if (formato == 8)
	{
		// Fecha en formato: AAAAMMDD
		ahora = ano;
		mes = mes + 1;
		if (mes <= 9)  { ahora  += "0" + mes; }
		else { ahora  += "" + mes; }
		if (diaM <= 9) { ahora += "0" + diaM; }
		else { ahora += "" + diaM; }
	}

	//alert("Fecha Formateada: " + ahora);

	return ahora;
}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion que comprueba si un año es bisiesto
function esBisesto (anyo) {
    if (((anyo % 4)==0) && ((anyo % 100)!=0) || ((anyo % 400)==0)) {
        return (true);
    }
    else {
        return (false);
    }
}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion que comprueba si una fecha es válida
function compruebaFecha(dia, mes, ano)
{
	var error  = 0;
	var indice = 0;

	// Año valido
	if ((dia>31) || (dia<0)) 	{ return -1; }
	if ((mes>12) || (mes<0)) 	{ return -1; }
	if ((ano<0))				{ return -1; }
	if (isNaN(ano)) 			{ return -1; }
	
	if ((new String(ano)).length != 4) { return -2; }
	
    // Dias de Febrero validos
    if (mes==2) {
       if (dia>29) { error = -3; }
       else if (dia==29) {
           if (!esBisesto(ano)) { error = -4; }
       }
    }
    
    // Dias de resto de meses validos
    if (mes<8) {
       if (mes%2==0) {
          if (dia>30) { error = -5; }
       }
    }
    else {
       if (mes%2!=0) {
          if (dia>30) { error = -5; }
       }
    }   

	//alert("Fecha Revisada: dia/mes/ano: " + dia + "/" + mes + "/" + ano + "  Error: " + error);
    return error;
}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion generica de inicializacion a un accion especificada
function inicializaAccion(action) {

	// Reloj
	setTime();
	
	// Ubicacion
	setLocation(action);
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion generica de inicializacion a un accion especificada
function inicializa()
{
	// Deteccion del Navegador
	activaEstilo();

	// Mensaje de Arranque
	//alert("Fecha: " + getFecha(6));
}
///////////////////////////////////////////////////////////////////////////




///////////////////////////////////////////////////////////////////////////
// Funcion que arranca un contador que decrementa una variable TIMEOUT
function setTime()
{
 	TIMEOUT = TIMEOUT - 1;

	if (TIMEOUT > 0) { id = setTimeout("setTime()",1000); }
	if (TIMEOUT != -1) { return; }
}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion que cambia la URL de la ventana padre a la especificada
function setLocation(location)
{
	document.location.href = location;
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion que cambia la URL de la ventana padre a la especificada
function setParentLocation(pagina)
{
	parent.document.location.href = pagina;
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion que cambia la URL actual a la especificada
function goLocation(location)
{
	document.location.href = location;
}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion que abre una URL en nueva ventana o en la ventana padre
// en funcion de variables de preferencias NEWWINDOW, MULTIPLEWINDOW
function openLocation(location)
{
	
	if (NEWWINDOW == "si")
	{
		if (MULTIPLEWINDOW == "si") { window.open(location); }
		else {  redbook = window.open(location, "RedBook"); }
	}
	else { parent.document.location.href = location; }

}
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Funcion que hace visible la capa indicada
function seleccion(cat)
{
	if (NS4) { document.layers[cat].visibility = "show"; }
	if (IE4) { document.all[cat].style.display = "block"; }
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion que oculta la capa indicada
function deseleccion(cat)
{
	if (NS4) { document.layers[cat].visibility = "hide"; }
	if (IE4) { document.all[cat].style.display = "none"; }
}
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
// Funcion que escribe en la pagina un enlace HTML
function generaEnlace(direccion)
{
	if (direccion == "") { document.write("-"); return; }

	var enlace = "";
	enlace = "<A HREF=\"javascript:openLocation('" + direccion + "');\"> " + direccion + " </A>";
	document.write(enlace);
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// Funcion que escribe en la pagina un enlace a cuenta de e-mail
function generaEnlaceMail(direccion)
{
	if (direccion == "") { document.write("-"); return; }

	var enlace = "";
	enlace = "<A HREF=\"mailto:" + direccion + "\"> " + direccion + " </A>";
	document.write(enlace);
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
//   Funciones Especificas de Paginas
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
//   CAB  Plantilla de Cabecera
///////////////////////////////////////////////////////////////////////////
// Variable auxiliar para periodo de refresco de la pagina
// Variable a 0 indica que no hay refresco de la pagina
var CABperiodoAux = 0;


function CABinicio() {

	// Inicio de Aplicacion
	parent.document.location.href = ALIAS_BASE;
}

function CABinicioAplicacion(inicio) {

	// Inicio de Aplicacion
	parent.document.location.href = inicio;
}

function CABinicioUsuario(home) {

	parent.directorio.DIRsetPagina();

	// Inicio de Usuario
	parent.aplicacion.document.location.href = home;
}

function CABinicializa() {

	// Fijamos el periodo de refresco del frame
	var per = parseInt(CABperiodo, 10);
	if (isNaN(per)) { TIMEOUT = CABperiodoAux; }
	else { TIMEOUT = per; }
		
    CABsetTime();
}

function CABgeneracionCabecera() {

	// Generamos el frame de cabecera
	document.location.href = ACTION;
	
}

function CABsetTime()
{
 	TIMEOUT = TIMEOUT - 1;

	if (TIMEOUT > 0) { id = setTimeout("CABsetTime()",1000); }
	if (TIMEOUT == 0) { document.location.href = ACTION; }
	if (TIMEOUT == -1) { return; }
	
}

function CABsetLocation(location)
{
	DESTINO = "PAGINA";

	parent.aplicacion.document.location.href = location;
}

function CABseleccionCategoria(categoria)
{
	//alert("Destino: " + categoria);
	
	// Inicializacion del frame de aplicacion
	if (categoria == "")
	{
		parent.document.location.href= ALIAS_BASE;
		return;
	}
	
	if (categoria == "home")
	{
		parent.directorio.document.location.href = DIRECTORIO;
	}
	else
	{ 
		parent.directorio.document.location.href = "directorio." + categoria + ".html";
	}

	if (categoria != "expand")
	{
		parent.aplicacion.document.location.href = categoria + ".html";
	}
	
	DESTINO = "CATEGORIA";
}
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
//   DIR  Plantilla de Directorio
///////////////////////////////////////////////////////////////////////////
var DIRlayer_actual = "CARGA";

function DIRinicializa ()
{
    DESTINO = "CATEGORIA";

}

function DIRsetLocation(location)
{
	DESTINO = "PAGINA";

	parent.aplicacion.document.location.href = location;
}

function inicializacionCategoria(categoria)
{
	if (categoria == "") { return; }
	else { DIRseleccionCategoria(categoria); }
}


function DIRseleccionCategoria(categoria)
{
	//alert("Destino: " + categoria);
	
	// Inicializacion del frame de aplicacion
	if (categoria == "")
	{
		parent.document.location.href= ALIAS_BASE;
		return;
	}
	
	if (categoria == "home")
	{
		document.location.href = DIRECTORIO;
	}
	else
	{ 
		document.location.href = "directorio." + categoria + ".html";
	}

	if (categoria != "expand")
	{
		parent.aplicacion.document.location.href = categoria + ".html";
	}
	
	DESTINO = "CATEGORIA";
}

function DIRsetPagina()
{
	DESTINO = "PAGINA";
}
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// 
//  Funciones para la gestión de un árbol de menús.
//  Llevan todas el prefijo 'menu'.
//  La estructura del array bidimensional de elementos debe ser:
//    El primer índice corresponde al indice de elemento (0,1,2,...)
//    El array interior contiene:
//      posicion 0: flag de visibilidad (0 ó 1)
//      posicion 1: flag de expandido, inicialmente 0
//      posicion 2: identificador propio, por ejemplo 'CONTA'
//      posicion 3: identificador del padre, por ejemplo 'APP'
//      posicion 4: nivel en el árbol, 0 para los de nivel más alto, 1, 2, ...
//      posicion 5: texto del elemento
//      posicion 6: url destino
//      posicion 7: icono a mostrar cuando el elemento se pueda desplegar
//      posicion 8: icono a mostrar cuando el elemento se pueda replegar
//      posicion 9: icono a mostrar cuando el elemento sea una hoja no desplegable
//
///////////////////////////////////////////////////////////////////////////

function menuDibujaPagina(indice, expandir, elementos, modo, anchoTabla, anchoCelda)
{
	
	var desplegable = menuGeneraMenu(indice, expandir, elementos, modo, anchoTabla, anchoCelda);
	
	var codigoElementos = menuGeneraElementos(elementos);
	
	var pagina=	menuGeneraPagina(desplegable, codigoElementos);
	
	document.clear();
	document.write(pagina);
	document.close()

}

function menuGeneraPagina(desplegable, codigoElementos)
{
	var pagina = "";

	pagina += "<HTML> \n";
	pagina += "<HEAD> \n";
	pagina += "<SCRIPT SRC=\"/configuracion/GCSWeb.js\"></SCRIPT> \n"
	pagina += codigoElementos;
	pagina += "</HEAD> \n";

	pagina += "<BODY> \n";

	pagina += "<CENTER> \n";
	pagina += desplegable;
	pagina += "</CENTER> \n";
	
	pagina += "</BODY> \n";
	pagina += "</HTML> \n";
	
	return pagina;
}


function menuGeneraMenu(indice, expandir, elementos, modo, anchoTabla, anchoCelda)
{
	var idPadre	= "";
	var nPadre;
	var desplegable = "";

	if (modo == "multiple") // multiples submenus pueden mostrarse a la vez
	{
		// Enciende o apaga el flag "expandido" del elemento pulsado
		menuModificaExpandido(elementos[indice], expandir);
	}
	else // modo sencillo: sólo se muestra un submenú cada vez
	{
		for (var i=0; i<elementos.length; i++)
		{
			// primero apaga el flag "expandido" de todos los elementos
			menuModificaExpandido(elementos[i],0);
		}
		// ahora enciende o apaga el flag del indice seleccionado...
		menuModificaExpandido(elementos[indice], expandir);
		// ... y enciende el de sus antepasados
		var i = indice;
		while (menuNivel(elementos[i]) > 0)
		{
			i = menuIndicePadre(i, elementos);
			menuModificaExpandido(elementos[i], 1);
		}
	}
	
	//calcula el número máximo de niveles
	var numNiveles = menuNiveles(elementos);
	
	desplegable += "<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\" WIDTH=\"" + anchoTabla + "\"> \n";

	for (var n=0; n<elementos.length; n++)
	{
		if (!menuEsVisible(n, elementos))
		{
			continue;
		}

		if (menuNivel(elementos[n]) > 0)
		{
			continue;
		}

		desplegable += menuGeneraEntrada(n, elementos, modo, numNiveles, anchoTabla, anchoCelda);
				
		desplegable += menuGeneraNodo(menuIdPropio(elementos[n]), elementos, modo, numNiveles, anchoTabla, anchoCelda);
	}

	desplegable += "</TABLE> \n";

	return desplegable;
}

function menuGeneraNodo(id, elementos, modo, numNiveles, anchoTabla, anchoCelda)
{
	var idPadre	= "";
	var desplegable 	= "";
	
	for (var n=0; n<elementos.length; n++)
	{	
		if (!menuEsVisible(n, elementos))
		{
			continue;
		}

		// Calculo del ID del padre
		idPadre = menuPadre(elementos[n]);
		
		if (idPadre != id)
		{
			continue;
		}

		if (!menuEstaExpandido(idPadre, elementos))
		{
			continue;
		}

		desplegable += menuGeneraEntrada(n, elementos, modo, numNiveles, anchoTabla, anchoCelda);
		
		desplegable += menuGeneraNodo(menuIdPropio(elementos[n]), elementos, modo, numNiveles, anchoTabla, anchoCelda);
	}

	return desplegable;
}

function menuGeneraEntrada(n, elementos, modo, numNiveles, anchoTabla, anchoCelda)
{
		var entrada = "";
		
		entrada += "<TR> \n";
		for(var i=0; i<(menuNivel(elementos[n])); i++)
		{
			entrada += "<TD></TD> \n";
		}

		entrada += "<TD WIDTH='" + anchoCelda + "' ALIGN='CENTER'> <P> ";

		if (!menuTieneHijos(menuIdPropio(elementos[n]), elementos)) //si no tiene hijos, dibuja un icono hoja
		{
			if (menuIconoHoja(elementos[n]) != "")
			{
				entrada += "<img src='" + menuIconoHoja(elementos[n]) +"' border=0>";
			}
		}
		else if (menuExpandido(elementos[n]) == 0) //si el elemento no está expandido, dibuja un icono desplegable
		{
			entrada += "<A HREF=\"javascript:menuDibujaPagina(" + n + ", " + (1-menuExpandido(elementos[n])) + ", elementos, '" + modo + "', " + anchoTabla + ", " + anchoCelda + ");\"> ";
			if (menuIconoDesplegable(elementos[n]) != "")
			{
				entrada += "<img src='" + menuIconoDesplegable(elementos[n]) +"' border=0> ";
			}
			else
			{
				entrada += "o";
			}
			entrada += "</A>";
		}
		else //si el elemento está expandido, dibuja un icono replegable
		{
			entrada += "<A HREF=\"javascript:menuDibujaPagina(" + n + ", " + (1-menuExpandido(elementos[n])) + ", elementos, '" + modo + "', " + anchoTabla + ", " + anchoCelda + ");\"> ";
			if (menuIconoReplegable(elementos[n]) != "")
			{
				entrada += "<img src='" + menuIconoReplegable(elementos[n]) +"' border=0> ";
			}
			else
			{
				entrada += "o";
			}
			entrada += "</A>";
		}
		
		entrada += " </TD> </P> \n";
		entrada += "<TD WIDTH=\"" + (anchoTabla - anchoCelda - anchoCelda*(menuNivel(elementos[n]))) + "\" COLSPAN=\"" + (numNiveles - menuNivel(elementos[n])) + "\"> <P> <A HREF=\"" + menuDestino(elementos[n]) +"\"> " + menuDescripcion(elementos[n]) + " </A> </P> </TD> \n";

		entrada += "</TR> \n";
		
		return entrada;
	
}

function menuVisible(elemento)
{
	return parseInt(elemento[0]);
}

function menuExpandido(elemento)
{
	return parseInt(elemento[1]);
}

function menuIdPropio(elemento)
{
	return elemento[2];
}

function menuPadre(elemento)
{
	return elemento[3];
}

function menuNivel(elemento)
{
	return parseInt(elemento[4]);
}

function menuDescripcion(elemento)
{
	return elemento[5];
}

function menuDestino(elemento)
{
	return elemento[6];
}

function menuIconoDesplegable(elemento)
{
	return elemento[7];
}

function menuIconoReplegable(elemento)
{
	return elemento[8];
}

function menuIconoHoja(elemento)
{
	return elemento[9];
}

function menuModificaExpandido(elemento, expandido)
{
	elemento[1] = expandido;
}

function menuIndicePadre(indice, elementos)
{
	var idPadre;
	idPadre = menuPadre(elementos[indice]);
	return menuBuscaElemento(idPadre, elementos);
}

function menuNiveles(elementos)
{
	var nivelMaximo = 0;
	
	for (var i=0; i<elementos.length; i++)
	{
		if (menuNivel(elementos[i]) > nivelMaximo)
		{
			nivelMaximo = menuNivel(elementos[i]);
		}
	}
	
	return parseInt(nivelMaximo) + 1;
}

function menuTieneHijos(id, elementos)
{
	for (var i=0; i<elementos.length; i++)
	{
		if ((menuPadre(elementos[i]) == id) && ( menuEsVisible(i, elementos) ))
		{
			return true;
		}
	}
	return false;
}

function menuBuscaElemento(id, elementos)
{
	for (var i=0; i<elementos.length; i++)
	{
		if (menuIdPropio(elementos[i]) == id)
		{
			return (i);
		}
	}
	return -1;
}
	

function menuEstaExpandido(id, elementos)
{
	var i = menuBuscaElemento(id, elementos);
	if ((i >= 0) && (i < elementos.length))
	{
		return (menuExpandido(elementos[i])==1);
	}
	return false;
}

function menuEsVisible(indice, elementos)
{
	return (menuVisible(elementos[indice])==1);
}

function menuGeneraElementos(elementos)
{
	var codigo = '';
	
	codigo += "<SCRIPT LANGUAGE=\"JavaScript1.2\">\n";
	codigo += "<!-- \n";
	codigo += "var elementos = new Array();\n";
	for (var i=0; i<elementos.length; i++)
	{
		codigo += "elementos[" + i + "] = new Array(";
		for (var j=0; j<elementos[i].length; j++)
		{
			codigo += "\"" + elementos[i][j] + "\",";
		}
		codigo = codigo.substring(0,codigo.length-1) + ");\n";
	}
	codigo += "//-->\n";
	codigo += "</SCRIPT>\n";
	
	return codigo;
}

function loadMenus (raiz, elementos, estilos, direccion, x, y, separacion) 
{
	var ejecutable;
	var hijos = new Array();
	var	xCelda = 0;
	var yCelda = 0;
	
	hijos = generaHijos(null, raiz, true, elementos);
	
	ejecutable = "window." + raiz + " = new Menu(\"" + raiz + "\")"; eval(ejecutable);
	for (var n=0; n<hijos.length; n++)
	{
		if (direccion == "vertical") 
		{ 
			xCelda = x;
			yCelda = y + separacion*n;
		}
		else
		{
			xCelda = x + separacion*n;
			yCelda = y
		}
		
		if (hijos[n][0] == "MENU")
		{
			ejecutable = raiz + ".addMenuItem(" + hijos[n][2] + ", " + xCelda + ", " + yCelda + ")";
		}
		else
		{
			ejecutable = raiz + ".addMenuItem(\"" + hijos[n][1] + "\", \"" + hijos[n][3] + "\")";
		}
		eval(ejecutable);
	}
	for (var i=0; i<estilos.length; i++)
	{
    	ejecutable = raiz + "." + estilos[i][0] + "	= estilos[" + i + "][1]";	eval(ejecutable);
    }
    ejecutable = raiz + ".prototypeStyles	= " + raiz;		eval(ejecutable);
	ejecutable = raiz + ".writeMenus()";					eval(ejecutable);
}

function generaHijos(id, raiz, esRaiz, elementos)
{
	var ejecutable;
	var hijos = new Array();
	var nietos = new Array();
	var numHijos = 0;

	for (var i=0; i<elementos.length; i++)
	{
		if ( menuEsVisible(i, elementos) )
		{
			if ( (menuPadre(elementos[i]) == id) 
			|| ( (menuNivel(elementos[i]) == 0) && (esRaiz) )) 
			{ 
				if (menuTieneHijos(menuIdPropio(elementos[i]),elementos))
				{
					nietos = generaHijos(menuIdPropio(elementos[i]), raiz, false, elementos);
					
					ejecutable = "window.menu" + raiz + menuIdPropio(elementos[i]) + " = new Menu(\"" + menuDescripcion(elementos[i]) + "\")";
					eval(ejecutable);
					
					for (var n=0; n<nietos.length; n++)
					{
						if (nietos[n][0] == "MENU")
						{
							ejecutable = "menu" + raiz + menuIdPropio(elementos[i]) + ".addMenuItem(" + nietos[n][2] + ")";
						}
						else
						{
							ejecutable = "menu" + raiz + menuIdPropio(elementos[i]) + ".addMenuItem(\"" + nietos[n][1] + "\", \"" + nietos[n][3] + "\")";
						}
						eval(ejecutable);
					}
					
					hijos[numHijos] = new Array("MENU", menuDescripcion(elementos[i]), "menu" + raiz + menuIdPropio(elementos[i]), "//\" onMouseOver=\"window.showMenu(menu" + raiz + menuIdPropio(elementos[i]) + ");" );
					numHijos++;
				}
				else
				{
					hijos[numHijos] = new Array("OPCION", menuDescripcion(elementos[i]), null, menuDestino(elementos[i]));
					numHijos++;
				}
			}
		}
	}
	return hijos;
}

/**
 * Menu 990702
 * by gary smith, July 1997
 * Copyright (c) 1997-1999 Netscape Communications Corp.
 *
 * Menu 020903
 * by doron rosenberg, September 2002
 * Copyright (c) 1997-2002 Netscape Communications Corp.
 *
 * Netscape grants you a royalty free license to use or modify this
 * software provided that this copyright notice appears on all copies.
 * This software is provided "AS IS," without a warranty of any kind.
 */

function Menu(label) {
    this.version = "020903 [Menu; menu.js]";
    this.type = "Menu";
    this.fontSize = "2.7mm";
    this.fontWeight = "bold";
    this.fontFamily = "Verdana,Arial, Helvetica,Sans-serif";
    this.fontColor = "#FF2222";
    this.fontColorHilite = "#FFFF00";
    this.bgColor = "#7F7F7F";
    this.menuBorder = 1;
    this.menuItemBorder = 1;
    this.menuItemBgColor = "#E0E0E0";
    this.menuLiteBgColor = "#ffffff";
    this.menuBorderBgColor = "#777777";
    this.menuHiliteBgColor = "#E0E0E0";
    this.menuContainerBgColor = "#cccccc";
    this.childMenuIcon = "images/arrows.gif";
    this.childMenuIconHilite = "images/arrows2.gif";
    this.items = new Array();
    this.actions = new Array();
    this.colors = new Array();
    this.mouseovers = new Array();
    this.mouseouts = new Array();
    this.childMenus = new Array();

    this.addMenuItem = addMenuItem;
    this.addMenuSeparator = addMenuSeparator;
    this.writeMenus = writeMenus;
    this.showMenu = showMenu;
    this.onMenuItemOver = onMenuItemOver;
    this.onMenuItemOut = onMenuItemOut;
    this.onMenuItemDown = onMenuItemDown;
    this.onMenuItemAction = onMenuItemAction;
    this.hideMenu = hideMenu;
    this.hideChildMenu = hideChildMenu;
    this.mouseTracker = mouseTracker;
    this.setMouseTracker = setMouseTracker;

    if (!window.menus) window.menus = new Array();
    this.label = label || "menuLabel" + window.menus.length;
    window.menus[this.label] = this;
    window.menus[window.menus.length] = this;
    if (!window.activeMenus) window.activeMenus = new Array();
    if (!window.menuContainers) window.menuContainers = new Array();
    if (!window.mDrag) {
        window.mDrag    = new Object();
        mDrag.startMenuDrag = startMenuDrag;
        mDrag.doMenuDrag    = doMenuDrag;
        this.setMouseTracker();
    }
    if (window.MenuAPI) MenuAPI(this);
}

function addMenuItem(label, action, color, mouseover, mouseout) {
    this.items[this.items.length] = label;
    this.actions[this.actions.length] = action;
    this.colors[this.colors.length] = color;
    this.mouseovers[this.mouseovers.length] = mouseover;
    this.mouseouts[this.mouseouts.length] = mouseout;
}

function addMenuSeparator() {
    this.items[this.items.length] = "separator";
    this.actions[this.actions.length] = "";
    this.menuItemBorder = 0;
}

function writeMenus(container) {
    if (!container && document.layers) {
        if (eval("document.width")) 
            container = new Layer(1000);
    } else if (!container && document.all) {
        if (!document.all["menuContainer"]) 
            document.writeln('<SPAN ID="menuContainer"></SPAN>');
        container = document.all["menuContainer"];
    }else if (!container && document.getElementById) {
      if (!document.getElementById("menuContainer")){ 
        container = document.createElement("span");
		container.id="menuContainer"
	    document.body.appendChild(container);
	  }
    }
		
    if (!container && !window.delayWriteMenus) {
        window.delayWriteMenus = this.writeMenus;
        window.menuContainerBgColor = this.menuContainerBgColor;
        setTimeout('delayWriteMenus()', 3000);
        return;
    }
    container.isContainer = "menuContainer" + menuContainers.length;
    menuContainers[menuContainers.length] = container;
    container.menus = new Array();
    for (var i=0; i<window.menus.length; i++) 
        container.menus[i] = window.menus[i];
    window.menus.length = 0;
    var countMenus = 0;
    var countItems = 0;
    var top = 0;
    var content = '';
    var proto;
    for (var i=0; i<container.menus.length; i++, countMenus++) {
        var menu = container.menus[i];
        proto = menu.prototypeStyles || this.prototypeStyles || menu;
        content += ''+
        '<DIV ID="menuLayer'+ countMenus +'" STYLE="position:absolute;left:10;top:'+ (i * 100) +';visibility:hidden;">\n'+
        '  <DIV ID="menuLite'+ countMenus +'" STYLE="position:absolute;left:'+ proto.menuBorder +';top:'+ proto.menuBorder +';visibility:hide;" onMouseOut="hideMenu(event);">\n'+
        '    <DIV ID="menuFg'+ countMenus +'" STYLE="position:absolute;left:1;top:1;visibility:hide;">\n'+
        '';
        var x=i;
        for (var i=0; i<menu.items.length; i++) {
            var item = menu.items[i];
            var childMenu = false;
            var defaultHeight = 20;
            var defaultIndent = 15;
            if (item.label) {
                item = item.label;
                childMenu = true;
            } else if (item.indexOf(".gif") != -1 && item.indexOf("<IMG") == -1) {
                item = '<IMG SRC="' + item + '" NAME="menuItem'+ countItems +'Img">';
                defaultIndent = 0;
                if (document.layers) {
                    defaultHeight = null;
                }
            }
            proto.menuItemHeight = proto.menuItemHeight || defaultHeight;
            proto.menuItemIndent = proto.menuItemIndent || defaultIndent;
            var itemProps = 'visibility:hide;font-Family:' + proto.fontFamily +';font-Weight:' + proto.fontWeight + ';fontSize:' + proto.fontSize + ';';
            if (document.getElementById || document.all) 
                itemProps += 'font-size:' + proto.fontSize + ';" onMouseOver="onMenuItemOver(event,this);" onMouseOut="onMenuItemOut(event,this);" onClick="onMenuItemAction(event,this);';
            var dTag    = '<DIV  class="menuItemText" ID="menuItem'+ countItems +'" STYLE="position:absolute;left:0;top:'+ (i * proto.menuItemHeight) +';'+ itemProps +'">';
            var dText   = '<DIV ID="menuItemText'+ countItems +'" STYLE="position:absolute;left:' + proto.menuItemIndent + ';top:0;color:'+ proto.fontColor +';">'+ item +'</DIV>\n<DIV ID="menuItemHilite'+ countItems +'" STYLE="position:absolute;left:' + proto.menuItemIndent + ';top:0;color:'+ proto.fontColorHilite +';visibility:hidden;">'+ item +'</DIV>';
            if (item == "separator") {
                content += ( dTag + '<DIV ID="menuSeparator'+ countItems +'" STYLE="position:absolute;left:1;top:2;"></DIV>\n<DIV ID="menuSeparatorLite'+ countItems +'" STYLE="position:absolute;left:1;top:2;"></DIV>\n</DIV>');
            } else if (childMenu) {
                content += ( dTag + dText + '<DIV ID="childMenu'+ countItems +'" STYLE="position:absolute;left:0;top:3;'+ itemProps +'"><IMG SRC="'+ proto.childMenuIcon +'"></DIV>\n</DIV>');
            } else {
                content += ( dTag + dText + '</DIV>');
            }
            countItems++;
        }
        content += '      <DIV ID="focusItem'+ countMenus +'" STYLE="position:absolute;left:0;top:0;visibility:hide;" onClick="onMenuItemAction(null,this);">&nbsp;</DIV>\n';
        content += '   </DIV>\n  </DIV>\n</DIV>\n';
        i=x;
    }
    if (!container) return;
    if (container.innerHTML) {
        container.innerHTML=content;
    } else {
        if (document.getElementById && !document.all)
          container.innerHTML=content;		
		else{
          container.document.open("text/html");
          container.document.writeln(content);
          container.document.close();
		}  
    }
    proto = null;
    if (document.layers) {
        container.clip.width = window.innerWidth;
        container.clip.height = window.innerHeight;
        container.onmouseout = this.hideMenu;
        container.menuContainerBgColor = this.menuContainerBgColor;
        for (var i=0; i<container.document.layers.length; i++) {
            proto = container.menus[i].prototypeStyles || this.prototypeStyles || container.menus[i];
            var menu = container.document.layers[i];
            container.menus[i].menuLayer = menu;
            container.menus[i].menuLayer.Menu = container.menus[i];
            container.menus[i].menuLayer.Menu.container = container;
            var body = menu.document.layers[0].document.layers[0];
            body.clip.width = proto.menuWidth || body.clip.width;
            body.clip.height = proto.menuHeight || body.clip.height;
            for (var n=0; n<body.document.layers.length-1; n++) {
                var l = body.document.layers[n];
                l.Menu = container.menus[i];
                l.menuHiliteBgColor = proto.menuHiliteBgColor;
                l.document.bgColor = proto.menuItemBgColor;
                l.saveColor = proto.menuItemBgColor;
                l.mouseout  = l.Menu.mouseouts[n];
                l.mouseover = l.Menu.mouseovers[n];
                l.onmouseover = proto.onMenuItemOver;
                l.onclick = proto.onMenuItemAction;
                l.action = container.menus[i].actions[n];
                l.focusItem = body.document.layers[body.document.layers.length-1];
                l.clip.width = proto.menuItemWidth || body.clip.width + proto.menuItemIndent;
                l.clip.height = proto.menuItemHeight || l.clip.height;
                if (n>0) l.top = body.document.layers[n-1].top + body.document.layers[n-1].clip.height + proto.menuItemBorder;
                l.hilite = l.document.layers[1];
                l.document.layers[1].isHilite = true;
                if (l.document.layers[0].id.indexOf("menuSeparator") != -1) {
                    l.hilite = null;
                    l.clip.height -= l.clip.height / 2;
                    l.document.layers[0].document.bgColor = proto.bgColor;
                    l.document.layers[0].clip.width = l.clip.width -2;
                    l.document.layers[0].clip.height = 1;
                    l.document.layers[1].document.bgColor = proto.menuLiteBgColor;
                    l.document.layers[1].clip.width = l.clip.width -2;
                    l.document.layers[1].clip.height = 1;
                    l.document.layers[1].top = l.document.layers[0].top + 1;
                } else if (l.document.layers.length > 2) {
                    l.childMenu = container.menus[i].items[n].menuLayer;
                    l.icon = proto.childMenuIcon;
                    l.iconHilite = proto.childMenuIconHilite;
                    l.document.layers[2].left = l.clip.width -13;
                    l.document.layers[2].top = (l.clip.height / 2) -4;
                    l.document.layers[2].clip.left += 3;
                    l.Menu.childMenus[l.Menu.childMenus.length] = l.childMenu;
                }
            }
            body.document.bgColor = proto.bgColor;
            body.clip.width  = l.clip.width +1;
            body.clip.height = l.top + l.clip.height +1;
            body.document.layers[n].clip.width = body.clip.width;
            body.document.layers[n].captureEvents(Event.MOUSEDOWN);
            body.document.layers[n].onmousedown = proto.onMenuItemDown;
            //body.document.layers[n].onfocus = proto.onMenuItemDown;
            body.document.layers[n].onmouseout = proto.onMenuItemOut;
            body.document.layers[n].Menu = l.Menu;
            body.document.layers[n].top = -30;
            menu.document.bgColor = proto.menuBorderBgColor;
            menu.document.layers[0].document.bgColor = proto.menuLiteBgColor;
            menu.document.layers[0].clip.width = body.clip.width +1;
            menu.document.layers[0].clip.height = body.clip.height +1;
            menu.clip.width = body.clip.width + (proto.menuBorder * 2) +1;
            menu.clip.height = body.clip.height + (proto.menuBorder * 2) +1;
            if (menu.Menu.enableTracker) {
                menu.Menu.disableHide = true;
                setMenuTracker(menu.Menu);
            }
        }
    } else if (document.all) {
        var menuCount = 0;
        for (var x=0; x<container.menus.length; x++) {
            var menu = container.document.all("menuLayer" + x);
            container.menus[x].menuLayer = menu;
            container.menus[x].menuLayer.Menu = container.menus[x];
            container.menus[x].menuLayer.Menu.container = menu;
            proto = container.menus[x].prototypeStyles || this.prototypeStyles || container.menus[x];
            proto.menuItemWidth = proto.menuItemWidth || 200;
            menu.style.backgroundColor = proto.menuBorderBgColor;
            for (var i=0; i<container.menus[x].items.length; i++) {
                var l = container.document.all["menuItem" + menuCount];
                l.Menu = container.menus[x];
                proto = container.menus[x].prototypeStyles || this.prototypeStyles || container.menus[x];
                l.style.pixelWidth = proto.menuItemWidth;
                l.style.pixelHeight = proto.menuItemHeight;
                if (i>0) l.style.pixelTop = container.document.all["menuItem" + (menuCount -1)].style.pixelTop + container.document.all["menuItem" + (menuCount -1)].style.pixelHeight + proto.menuItemBorder;
                l.style.fontSize = proto.fontSize;
                l.style.backgroundColor = proto.menuItemBgColor;
                l.style.visibility = "inherit";
                l.saveColor = proto.menuItemBgColor;
                l.menuHiliteBgColor = proto.menuHiliteBgColor;
                l.action = container.menus[x].actions[i];
                l.hilite = container.document.all["menuItemHilite" + menuCount];
                l.focusItem = container.document.all["focusItem" + x];
                l.focusItem.style.pixelTop = -30;
                l.mouseover = l.Menu.mouseovers[x];
                l.mouseout  = l.Menu.mouseouts[x];
                var childItem = container.document.all["childMenu" + menuCount];
                if (childItem) {
                    l.childMenu = container.menus[x].items[i].menuLayer;
                    childItem.style.pixelLeft = l.style.pixelWidth -11;
                    childItem.style.pixelTop = (l.style.pixelHeight /2) -4;
                    childItem.style.pixelWidth = 30 || 7;
                    childItem.style.clip = "rect(0 7 7 3)";
                    l.Menu.childMenus[l.Menu.childMenus.length] = l.childMenu;
                }
                var sep = container.document.all["menuSeparator" + menuCount];
                if (sep) {
                    sep.style.clip = "rect(0 " + (proto.menuItemWidth - 3) + " 1 0)";
                    sep.style.backgroundColor = proto.bgColor;
                    sep = container.document.all["menuSeparatorLite" + menuCount];
                    sep.style.clip = "rect(1 " + (proto.menuItemWidth - 3) + " 2 0)";
                    sep.style.backgroundColor = proto.menuLiteBgColor;
                    l.style.pixelHeight = proto.menuItemHeight/2;
                    l.isSeparator = true
                }
                menuCount++;
            }
            proto.menuHeight = (l.style.pixelTop + l.style.pixelHeight);
            var lite = container.document.all["menuLite" + x];
            lite.style.pixelHeight = proto.menuHeight +2;
            lite.style.pixelWidth = proto.menuItemWidth + 2;
            lite.style.backgroundColor = proto.menuLiteBgColor;
            var body = container.document.all["menuFg" + x];
            body.style.pixelHeight = proto.menuHeight + 1;
            body.style.pixelWidth = proto.menuItemWidth + 1;
            body.style.backgroundColor = proto.bgColor;
            container.menus[x].menuLayer.style.pixelWidth  = proto.menuWidth || proto.menuItemWidth + (proto.menuBorder * 2) +2;
            container.menus[x].menuLayer.style.pixelHeight = proto.menuHeight + (proto.menuBorder * 2) +2;
            if (menu.Menu.enableTracker) {
                menu.Menu.disableHide = true;
                setMenuTracker(menu.Menu);
            }
        }
        container.document.all("menuContainer").style.backgroundColor = container.menus[0].menuContainerBgColor;
        container.document.saveBgColor = container.document.bgColor;
    }else if (document.getElementById) {
        var menuCount = 0;
        for (var x=0; x<container.menus.length; x++) {
            var menu = document.getElementById("menuLayer" + x);
            container.menus[x].menuLayer = menu;
            container.menus[x].menuLayer.Menu = container.menus[x];
            container.menus[x].menuLayer.Menu.container = menu;
            proto = container.menus[x].prototypeStyles || this.prototypeStyles || container.menus[x];
            proto.menuItemWidth = proto.menuItemWidth || 200;
            menu.style.backgroundColor = proto.menuBorderBgColor;
            var l = document.getElementById("menuItem" + menuCount)

            for (var i=0; i<container.menus[x].items.length; i++) {
                l = document.getElementById("menuItem" + menuCount);
                l.Menu = container.menus[x];
                proto = container.menus[x].prototypeStyles || this.prototypeStyles || container.menus[x];		
                l.style.width = proto.menuItemWidth;
                l.style.height = proto.menuItemHeight;
                if (i>0) l.style.top = parseInt(document.getElementById("menuItem" + (menuCount -1)).style.top,10) + parseInt(document.getElementById("menuItem" + (menuCount -1)).style.height,10) + proto.menuItemBorder;
                l.style.fontSize = proto.fontSize;
                l.style.backgroundColor = proto.menuItemBgColor;
                l.style.visibility = "inherit";
                l.saveColor = proto.menuItemBgColor;
                l.menuHiliteBgColor = proto.menuHiliteBgColor;
                l.action = container.menus[x].actions[i];
                l.hilite = document.getElementById("menuItemHilite" + menuCount);
                l.focusItem = document.getElementById("focusItem" + x);
                l.focusItem.style.top = -30;
				
                l.mouseover = l.Menu.mouseovers[x];
                l.mouseout  = l.Menu.mouseouts[x];
                var childItem = document.getElementById("childMenu" + menuCount);
                if (childItem) {
                    l.childMenu = container.menus[x].items[i].menuLayer;
                    childItem.style.left = l.style.width -11;
                    childItem.style.top = (l.style.height /2) -4;
                    childItem.style.width = 30 || 7;
                    childItem.style.clip = "rect(0 7 7 3)";
                    l.Menu.childMenus[l.Menu.childMenus.length] = l.childMenu;
                }
                var sep = document.getElementById("menuSeparator" + menuCount);
                if (sep) {
                    sep.style.clip = "rect(0 " + (proto.menuItemWidth - 3) + " 1 0)";
                    sep.style.backgroundColor = proto.bgColor;
                    sep = document.getElementById("menuSeparatorLite" + menuCount);
                    sep.style.clip = "rect(1 " + (proto.menuItemWidth - 3) + " 2 0)";
                    sep.style.backgroundColor = proto.menuLiteBgColor;
                    l.style.height = proto.menuItemHeight/2;
                    l.isSeparator = true
                }
                menuCount++;
            }
            proto.menuHeight = (parseInt(l.style.top,10) + parseInt(l.style.height,10));
            var lite = document.getElementById("menuLite" + x);
            lite.style.height = proto.menuHeight +2;
            lite.style.width = proto.menuItemWidth + 2;
            lite.style.backgroundColor = proto.menuLiteBgColor;
            var body = document.getElementById("menuFg" + x);
            body.style.height = proto.menuHeight + 1;
            body.style.width = proto.menuItemWidth + 1;
            body.style.backgroundColor = proto.bgColor;
            container.menus[x].menuLayer.style.width  = proto.menuWidth || proto.menuItemWidth + (proto.menuBorder * 2) +2;
            container.menus[x].menuLayer.style.height = proto.menuHeight + (proto.menuBorder * 2) +2;
            if (menu.Menu.enableTracker) {
                menu.Menu.disableHide = true;
                setMenuTracker(menu.Menu);
            }
        }
        document.getElementById("menuContainer").style.backgroundColor = container.menus[0].menuContainerBgColor;
        container.saveBgColor = container.bgColor;
    }	
    window.wroteMenu = true;
}

function onMenuItemOver(e, l, a) { l.style.cursor = 'pointer';
    l = l || this;
    a = a || window.ActiveMenuItem;
    var esImagen = (l.id.substring(0,5) == "child"); 
    if (document.layers) {
        if (a) {
            a.document.bgColor = a.saveColor;
            if (a.hilite) a.hilite.visibility = "hidden";
            if (a.childMenu) a.document.layers[1].document.images[0].src = a.icon;
        } else {
            a = new Object();
        }
        if (this.mouseover && this.id != a.id) {
            if (this.mouseover.length > 4) {
                var ext = this.mouseover.substring(this.mouseover.length-4);
                if (ext == ".gif" || ext == ".jpg") {
                    this.document.layers[1].document.images[0].src = this.mouseover;
                } else {
                    eval("" + this.mouseover);
                }
            }
        }
        if (l.hilite) {
            l.document.bgColor = l.menuHiliteBgColor;
            l.zIndex = 1;
            l.hilite.visibility = "inherit";
            l.hilite.zIndex = 2;
            l.document.layers[1].zIndex = 1;
            l.focusItem.zIndex = this.zIndex +2;
        }
        l.focusItem.top = this.top;
        l.Menu.hideChildMenu(l);
    } else if (document.all && l.style && l.Menu) {
        if (!esImagen) { document.onmousedown=l.Menu.onMenuItemDown; }
        if (a) {
            a.style.backgroundColor = a.saveColor;
            if (a.hilite) a.hilite.style.visibility = "hidden";
        } else {
            a = new Object();
		}
        if (l.mouseover && l.id != a.id) {
            if (l.mouseover.length > 4) {
                var ext = l.mouseover.substring(l.mouseover.length-4);
                if (ext == ".gif" || ext == ".jpg") {
                    l.document.images[l.id + "Img"].src = l.mouseover;
                } else {
                    eval("" + l.mouseover);
                }
            }
        }
		if (l.isSeparator) return;
        l.style.backgroundColor = l.menuHiliteBgColor;
        if (l.hilite) {
            l.style.backgroundColor = l.menuHiliteBgColor;
            l.hilite.style.visibility = "inherit";
        }
        if (!esImagen)
        {
	        l.focusItem.style.pixelTop = l.style.pixelTop;
	        l.focusItem.style.zIndex = l.zIndex +1;
	    }
        l.zIndex = 1;
        l.Menu.hideChildMenu(l);
    } else if (document.getElementById){ 
        if (!esImagen) { document.onmousedown=l.Menu.onMenuItemDown; }
        if (a) {
	        a.style.backgroundColor = a.saveColor;
    	    if (a.hilite) a.hilite.style.visibility = "hidden";
        } else {
            a = new Object();
        }
        if (this.mouseover && this.id != a.id) {
            if (this.mouseover.length > 4) {
                var ext = this.mouseover.substring(this.mouseover.length-4);
                if (ext == ".gif" || ext == ".jpg") {
                    document.images[l.id + "Img"].src = this.mouseover;
                } else {
                    eval("" + this.mouseover);
                }
            }
        }
        if (l.hilite) {
	        l.style.backgroundColor = l.menuHiliteBgColor;
            l.hilite.style.visibility = "inherit";
        }
        if (!esImagen)
        {
	        l.focusItem.style.top = l.style.top;
	        l.focusItem.style.zIndex = l.zIndex +1;
	    }
        l.zIndex = 1;
        if (!esImagen) { l.Menu.hideChildMenu(l); }
	}		
    window.ActiveMenuItem = l;
}

function onMenuItemOut(e, l, a) {
    if (!document.all && !document.layers && e.currentTarget.nodeType == 1 && e.currentTarget.tagName == 'DIV')
      return true;
    l = l || this;
	a = a || window.ActiveMenuItem;
    if (l.id.indexOf("focusItem")) {
        if (a && l.top) {
            l.top = -30;
			if (a.mouseout && a.id != l.id) {
				if (a.mouseout.length > 4) {
					var ext = a.mouseout.substring(a.mouseout.length-4);
					if (ext == ".gif" || ext == ".jpg") {
						a.document.layers[1].document.images[0].src = a.mouseout;
					} else {
						eval("" + a.mouseout);
					}
				}
			}
        } else if (a && l.style) {
            document.onmousedown=null;
			if(window.event)
              window.event.cancelBubble=true;
			else
			  e.cancelBubble=true;
	        if (l.mouseout) {
				if (l.mouseout.length > 4) {
					var ext = l.mouseout.substring(l.mouseout.length-4);
					if (ext == ".gif" || ext == ".jpg") {
						l.document.images[l.id + "Img"].src = l.mouseout;
					} else {
						eval("" + l.mouseout);
					}
				}
			}
        }
    }
}

function onMenuItemAction(e, l) {
    l = window.ActiveMenuItem;
    if (!l) return;
//    if (!ActiveMenu.Menu.disableHide) hideActiveMenus(ActiveMenu.menuLayer);
    if (l.action) {
        eval("" + l.action);
    }
}

function showMenu(menu, x, y, child) {
    if (!window.wroteMenu) return;
    if (document.layers) {
        if (menu) {
            var l = menu.menuLayer || menu;
            if (typeof(menu) == "string") {
                for (var n=0; n < menuContainers.length; n++) {
                    l = menuContainers[n].menus[menu];
                    for (var i=0; i<menuContainers[n].menus.length; i++) {
                        if (menu == menuContainers[n].menus[i].label) l = menuContainers[n].menus[i].menuLayer;
                        if (l) break;
                    }
                }
				if (!l) return;
            }
            l.Menu.container.document.bgColor = null;
            l.left = 1;
            l.top = 1;
            hideActiveMenus(l);
            if (this.visibility) l = this;
            window.ActiveMenu = l;
            window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP);
            setTimeout('if(window.ActiveMenu)window.ActiveMenu.Menu.setMouseTracker();', 300);
        } else {
            var l = child;
        }
        if (!l) return;
        for (var i=0; i<l.layers.length; i++) {                
            if (!l.layers[i].isHilite) 
                l.layers[i].visibility = "inherit";
            if (l.layers[i].document.layers.length > 0) 
                showMenu(null, "relative", "relative", l.layers[i]);
        }
        if (l.parentLayer) {
            if (x != "relative") 
                l.parentLayer.left = x || window.pageX || 0;
            if (l.parentLayer.left + l.clip.width > window.innerWidth) 
                l.parentLayer.left -= (l.parentLayer.left + l.clip.width - window.innerWidth);
            if (y != "relative") 
                l.parentLayer.top = y || window.pageY || 0;
            if (l.parentLayer.isContainer) {
                l.Menu.xOffset = window.pageXOffset;
                l.Menu.yOffset = window.pageYOffset;
                l.parentLayer.clip.width = window.ActiveMenu.clip.width +2;
                l.parentLayer.clip.height = window.ActiveMenu.clip.height +2;
                if (l.parentLayer.menuContainerBgColor) l.parentLayer.document.bgColor = l.parentLayer.menuContainerBgColor;
            }
        }
        l.visibility = "inherit";
        if (l.Menu) l.Menu.container.visibility = "inherit";
    } else if (document.all) {
        var l = menu.menuLayer || menu;
        hideActiveMenus(l);
        if (typeof(menu) == "string") {
            l = document.all[menu];
            for (var n=0; n < menuContainers.length; n++) {
                l = menuContainers[n].menus[menu];
                for (var i=0; i<menuContainers[n].menus.length; i++) {
                    if (menu == menuContainers[n].menus[i].label) l = menuContainers[n].menus[i].menuLayer;
                    if (l) break;
                }
            }
        }
        window.ActiveMenu = l;
        l.style.visibility = "inherit";
        if (x != "relative") 
            l.style.pixelLeft = x || (window.pageX + document.body.scrollLeft) || 0;
        if (y != "relative") 
            l.style.pixelTop = y || (window.pageY + document.body.scrollTop) || 0;
        l.Menu.xOffset = document.body.scrollLeft;
        l.Menu.yOffset = document.body.scrollTop;
    } else if (document.getElementById) {
        var l = menu.menuLayer || menu;
        hideActiveMenus(l);
        if (typeof(menu) == "string") {
            l = document.getElementById(menu);
            for (var n=0; n < menuContainers.length; n++) {
                l = menuContainers[n].menus[menu];
                for (var i=0; i<menuContainers[n].menus.length; i++) {
                    if (menu == menuContainers[n].menus[i].label) l = menuContainers[n].menus[i].menuLayer;
                    if (l) break;
                }
            }
        }
        window.ActiveMenu = l;
        l.style.visibility = "inherit";
        if (x != "relative") 
            l.style.left = x || (window.pageX) || 0;
        if (y != "relative") 
            l.style.top = y || (window.pageY) || 0;
        l.Menu.xOffset = document.body.scrollLeft;
        l.Menu.yOffset = document.body.scrollTop;
    }
	
    if (menu) {
        window.activeMenus[window.activeMenus.length] = l;
    }
}

function hideMenu(e) {
    if (!document.all && e.currentTarget && e.currentTarget.tagName && e.currentTarget.tagName == 'DIV')
      return true;
	  
    var l = e || window.ActiveMenu;
    if (!l) return true;
    if (l.menuLayer) {
        l = l.menuLayer;
    } else if (this.visibility) {
        l = this;
    }
    if (l.menuLayer) {
        l = l.menuLayer;
    }
    var a = window.ActiveMenuItem;
    document.saveMousemove = document.onmousemove;
    document.onmousemove = mouseTracker;
    if (a && document.layers) {
        a.document.bgColor = a.saveColor;
        a.focusItem.top = -30;
        if (a.hilite) a.hilite.visibility = "hidden";
        if (a.childMenu) a.document.layers[1].document.images[0].src = a.icon;
        if (mDrag.oldX <= e.pageX+3 && mDrag.oldX >= e.pageX-3 && mDrag.oldY <= e.pageY+3 && mDrag.oldY >= e.pageY-3) {
            if (a.action && window.ActiveMenu) setTimeout('window.ActiveMenu.Menu.onMenuItemAction();', 2);
        } else if (document.saveMousemove == mDrag.doMenuDrag) {
            if (window.ActiveMenu) return true;
        }
    } else if (window.ActiveMenu && document.all) {
        document.onmousedown=null;
        if (a) {
            a.style.backgroundColor = a.saveColor;
            if (a.hilite) a.hilite.style.visibility = "hidden";
        }
        if (document.saveMousemove == mDrag.doMenuDrag) {
            return true;
        }
    } else if (window.ActiveMenu && document.getElementById) {
        document.onmousedown=null;
        if (a) {
            a.style.backgroundColor = a.saveColor;
            if (a.hilite) a.hilite.style.visibility = "hidden";
        }
        if (document.saveMousemove == mDrag.doMenuDrag) {
            return true;
        }
	}		
    if (window.ActiveMenu) {
        if (window.ActiveMenu.Menu) {
            if (window.ActiveMenu.Menu.disableHide) return true;
            e = window.event || e;
            if (!window.ActiveMenu.Menu.enableHideOnMouseOut && e.type == "mouseout") return true;
        }
    }
    hideActiveMenus(l);
    return true;
}

function hideChildMenu(menuLayer) {
    var l = menuLayer || this;
    for (var i=0; i < l.Menu.childMenus.length; i++) {
        if (document.getElementById || document.all) {
            l.Menu.childMenus[i].style.visibility = "hidden";
        } else if (document.layers) {
            l.Menu.childMenus[i].visibility = "hidden";
        }
        l.Menu.childMenus[i].Menu.hideChildMenu(l.Menu.childMenus[i]);
    }
    if (l.childMenu) {
        if (document.layers) {
            l.Menu.container.document.bgColor = null;
            l.Menu.showMenu(null,null,null,l.childMenu.layers[0]);
            l.childMenu.zIndex = l.parentLayer.zIndex +1;
            l.childMenu.top = l.top + l.parentLayer.top + l.Menu.menuLayer.top;
            if (l.childMenu.left + l.childMenu.clip.width > window.innerWidth) {
                l.childMenu.left = l.parentLayer.left - l.childMenu.clip.width + l.Menu.menuLayer.top + 15;
                l.Menu.container.clip.left -= l.childMenu.clip.width;
            } else if (l.Menu.childMenuDirection == "left") {
                l.childMenu.left = l.parentLayer.left - l.parentLayer.clip.width;
                l.Menu.container.clip.left -= l.childMenu.clip.width;
            } else {
                l.childMenu.left = l.parentLayer.left + l.parentLayer.clip.width  + l.Menu.menuLayer.left -5;
            }
            l.Menu.container.clip.width += l.childMenu.clip.width +100;
            l.Menu.container.clip.height += l.childMenu.clip.height;
            l.document.layers[1].zIndex = 0;
            l.document.layers[1].document.images[0].src = l.iconHilite;
            l.childMenu.visibility = "inherit";
        } else if (document.all) {
            l.childMenu.style.zIndex = l.Menu.menuLayer.style.zIndex +1;
            l.childMenu.style.pixelTop = l.style.pixelTop + l.Menu.menuLayer.style.pixelTop;
            if (l.childMenu.style.pixelLeft + l.childMenu.style.pixelWidth > document.width) {
                l.childMenu.style.pixelLeft = l.childMenu.style.pixelWidth + l.Menu.menuLayer.style.pixelTop + 15;
            } else if (l.Menu.childMenuDirection == "left") {
                //l.childMenu.style.pixelLeft = l.parentLayer.left - l.parentLayer.clip.width;
            } else {
                l.childMenu.style.pixelLeft = l.Menu.menuLayer.style.pixelWidth + l.Menu.menuLayer.style.pixelLeft -5;
            }
            l.childMenu.style.visibility = "inherit";
        } else if (document.getElementById) {
            l.childMenu.style.zIndex = l.Menu.menuLayer.style.zIndex +1;
            l.childMenu.style.top = parseInt(l.style.top,10) + parseInt(l.Menu.menuLayer.style.top, 10);
            if ( parseInt(l.childMenu.style.left) + parseInt(l.childMenu.style.width) > document.width) {
                l.childMenu.style.left = parseInt(l.childMenu.style.width,10) + parseInt(l.Menu.menuLayer.style.top,10) + 15;
            } else if (l.Menu.childMenuDirection == "left") {
                //l.childMenu.style.pixelLeft = l.parentLayer.left - l.parentLayer.clip.width;
            } else {
                l.childMenu.style.left = parseInt(l.Menu.menuLayer.style.width,10) + parseInt(l.Menu.menuLayer.style.left,10) -5;
            }
            l.childMenu.style.visibility = "inherit";
        }		
		
        if (!l.childMenu.disableHide) 
            window.activeMenus[window.activeMenus.length] = l.childMenu;
    }
}

function hideActiveMenus(l) {
    if (!window.activeMenus) return;
    for (var i=0; i < window.activeMenus.length; i++) {
    if (!activeMenus[i]) return;
   	    if (document.layers && activeMenus[i].visibility && activeMenus[i].Menu) {
            activeMenus[i].visibility = "hidden";
            activeMenus[i].Menu.container.visibility = "hidden";
            activeMenus[i].Menu.container.clip.left = 0;
        } else if (activeMenus[i].style) {
            activeMenus[i].style.visibility = "hidden";
        }
    }
    document.onmousemove = mouseTracker;
    window.activeMenus.length = 0;
}

function mouseTracker(e) {
    e = e || window.Event || window.event;
    window.pageX = e.pageX || e.clientX;
    window.pageY = e.pageY || e.clientY;
}

function setMouseTracker() {
    if (document.captureEvents) {
        document.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
    }
    document.onmousemove = this.mouseTracker;
    document.onmouseup = this.hideMenu;
}

function setMenuTracker(menu) {
    if (!window.menuTrackers) window.menuTrackers = new Array();
    menuTrackers[menuTrackers.length] = menu;
    window.menuTrackerID = setInterval('menuTracker()',10);
}

function menuTracker() {
    for (var i=0; i < menuTrackers.length; i++) {
        if (!isNaN(menuTrackers[i].xOffset) && document.layers) {
            var off = parseInt((menuTrackers[i].xOffset - window.pageXOffset) / 10);
            if (isNaN(off)) off = 0;
            if (off < 0) {
                menuTrackers[i].container.left += -off;
                menuTrackers[i].xOffset += -off;
            } else if (off > 0) {
                menuTrackers[i].container.left += -off;
                menuTrackers[i].xOffset += -off;
            }
        }
        if (!isNaN(menuTrackers[i].yOffset) && document.layers) {
            var off = parseInt((menuTrackers[i].yOffset - window.pageYOffset) / 10);
            if (isNaN(off)) off = 0;
            if (off < 0) {
                menuTrackers[i].container.top += -off;
                menuTrackers[i].yOffset += -off;
            } else if (off > 0) {
                menuTrackers[i].container.top += -off;
                menuTrackers[i].yOffset += -off;
            }
        }
        if (!isNaN(menuTrackers[i].xOffset) && document.body) {
            var off = parseInt((menuTrackers[i].xOffset - document.body.scrollLeft) / 10);
            if (isNaN(off)) off = 0;
            if (off < 0) {
                menuTrackers[i].menuLayer.style.pixelLeft += -off;
                menuTrackers[i].xOffset += -off;
            } else if (off > 0) {
                menuTrackers[i].menuLayer.style.pixelLeft += -off;
                menuTrackers[i].xOffset += -off;
            }
        }
        if (!isNaN(menuTrackers[i].yOffset) && document.body) {
            var off = parseInt((menuTrackers[i].yOffset - document.body.scrollTop) / 10);
            if (isNaN(off)) off = 0;
            if (off < 0) {
                menuTrackers[i].menuLayer.style.pixelTop += -off;
                menuTrackers[i].yOffset += -off;
            } else if (off > 0) {
                menuTrackers[i].menuLayer.style.pixelTop += -off;
                menuTrackers[i].yOffset += -off;
            }
        }
    }
}

function onMenuItemDown(e, l) {
    l = l || window.ActiveMenuItem || this;
    if (!l.Menu) {
    } else {
        if (document.layers) {
            mDrag.dragLayer = l.Menu.container;
            mDrag.startMenuDrag(e);
            document.captureEvents(Event.MOUSEMOVE);			
        } else if (document.all) {
            mDrag.dragLayer = l.Menu.container.style;
            mDrag.startMenuDrag(e);
            window.event.cancelBubble=true;
        } else if (document.getElementById) {
            mDrag.dragLayer = l.Menu.container.style;
            mDrag.startMenuDrag(e);
            document.captureEvents(Event.MOUSEMOVE);			
        }
        var x = !document.all? e.pageX : window.event.clientX;
        var y = !document.all? e.pageY : window.event.clientY;
    
    }
}

function startMenuDrag(e) {
    if (document.layers) {
        if (e.which > 1) {
            if (window.ActiveMenu) ActiveMenu.Menu.container.visibility = "hidden";
            window.ActiveMenu = null;
            return true;
        }
        document.captureEvents(Event.MOUSEMOVE);
        var x = e.pageX;
        var y = e.pageY;
    } else if (document.all) {
        var x = window.event.clientX;
        var y = window.event.clientY;
    } else if (document.getElementById) {
        if (e.which > 1) {
            if (window.ActiveMenu) ActiveMenu.Menu.container.visibility = "hidden";
            window.ActiveMenu = null;
            return true;
        }
        document.captureEvents(Event.MOUSEMOVE);
        var x = e.pageX;
        var y = e.pageY;
    }
	
    mDrag.offX = x;
    mDrag.offY = y;
    mDrag.oldX = x;
    mDrag.oldY = y;
    if (!ActiveMenu.Menu.disableDrag) document.onmousemove = mDrag.doMenuDrag;
    return false;
}

function doMenuDrag(e) {
    if (document.layers) {
        mDrag.dragLayer.moveBy(e.pageX-mDrag.offX,e.pageY-mDrag.offY);
        mDrag.offX = e.pageX;
        mDrag.offY = e.pageY;
    } else if(document.all) {
        mDrag.dragLayer.pixelLeft = window.event.offsetX;
        mDrag.dragLayer.pixelTop  = window.event.offsetY;
        return false; //for IE
    } else if (document.getElementById){
        mDrag.dragLayer.left = e.pageX;
        mDrag.dragLayer.top  = e.pageY;	
	}
}
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////



// 
//  Funciones para la validación de campos mediante expresiones regulares.
//  Llevan todas el prefijo 'valida'.
//
///////////////////////////////////////////////////////////////////////////

function validaTelefono(elemento)
{
	//expresión regular para telefonos
	//permite cifras, campos vacios, signo mas, guiones, puntos, barras, barras invertidas y parentesis

	var expRegTelefono = /^[0-9\s\+\-\.\/\\\()]+$/;
	if (!expRegTelefono.test(elemento.value))
	{
		//alert(elemento.value + ' no es un teléfono válido.')
		return false;
	}
	return true;
}

function validaEmail(elemento)
{
	//expresión regular para emails
	//la primera parte (antes de la @) compuesta por alfanumericos, guiones y puntos
	//la segunda parte (entre la @ y el .) empieza con alfanumerico seguido de alfanumericos, guiones y puntos.
	//la tercera parte (despues del .) solo compuesta por cifras y numeros
	//en las dos últimas partes no se permiten subguiones (underscores)
	//   Otra opción es:  /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/
	//   Sample Matches:  joe.tillis@unit.army.mil / jack_rabbit@slims.com / foo99@foo.co.uk  
	//   Sample Non-Matches:  find_the_mistake.@foo.org / .prefix.@some.net  
	//   Description:  Matches 99.99% of e-mail addresses (excludes IP e-mails, which are rarely used). 
	//   The {2,7} at the end leaves space for top level domains as short as .ca but leaves room for 
	//   new ones like .museum, etc. The ?: notation is a perl non-capturing notation, and can be 
	//   removed safely for non-perl-compatible languages.

	var expRegEmail = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
	if (!expRegEmail.test(elemento.value))
	{ 
		//alert(elemento.value + ' no es un e-mail válido.');
		return false;
	}
	return true;
}

function validaEntero(elemento)
{
	//expresión regular para numeros enteros
	//signo (más o menos) opcional
	//seguido de una o más cifras
	
	var expRegNumeroEntero = /^[\+|-]?\d+$/
	if (!expRegNumeroEntero.test(elemento.value))
	{
		//alert(elemento.value + ' no es un entero válido.');
		return false;
	}
	return true;
}

function validaDosDecimales(elemento)
{
	//expresión regular para numeros con un máximo de dos decimales significativos
	//signo (más o menos) opcional (\+|-)?
	//seguido de un número sin parte decimal \d+
	//o de un número decimal compuesto por
	//   parte entera opcional \d*
	//   punto decimal \.
	//   uno o dos decimales significativos \d{1,2}
	//   ceros opcionales a la derecha no significativos 0*
	//ejemplos válidos: +166.38, 0.07, .75, 9.90, -12.5, 25, 6.250
	//ejemplos no válidos: +166.386, -12., 6.251, .
	
	var expRegNumeroDosDecimales = /^(\+|-)?((\d+)|(\d*\.\d{1,2}0*))$/
	if (!expRegNumeroDosDecimales.test(elemento.value))
	{
		//alert(elemento.value + ' no es un número de dos decimales válido.');
		return false;
	}
	return true;
}

function validaFecha(elemento)
{
	//expresión regular para fechas en formato dd/mm/aaaa
	//valida fechas en formato d/m/y desde 1/1/1600 - 31/12/9999
	//29/02/00 no se acepta ya que no se puede saber si corresponde a un año bisiesto (utilizar las 4 cifras aquí)
	//dias y meses se pueden expresar con 1 ó 2 cifras, o un 0 y una cifra. Los años con 2 ó 4 cifras
	//el separaror puede ser una barra /, un guión - o un punto . y debe coincidir.
	//formato USA MMDDAAAA: /^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1[0-2])(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/
	
	var expRegFechaDDMMAAAA = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:0?[1-9]|1[0-2])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
	if(!expRegFechaDDMMAAAA.test(elemento.value))
	{
		//alert(elemento.value + ' no es una fecha válida');
		return false;
	}
	return true;
}

function validaCodigoPostal(elemento)
{
	//expresion regular para códigos postales españoles
	//acepta códigos de cinco cifras entre 01001 y 52999 que no acaben en 000
	//la primera parte (0[1-9]|[1234]\d|5[012]) valida el código de provincia
	//   0[1-9]   acepta 01 a 09
	//   [1234]\d acepta 10 a 49
	//   5[012]   acepta 50 a 52
	//la segunda parte ([1-9]\d{2}|\d[1-9]\d|\d{2}[1-9]) valida tres dígitos que no sean 000
	//   [1-9]\d{2} tiene al menos un dígito distinto de 0 en la 1ª posición
	//   \d[1-9]\d  tiene al menos un dígito distinto de 0 en la 2ª posición
	//   \d{2}[1-9] tiene al menos un dígito distinto de 0 en la 3ª posición
	
	var expRegCodigoPostal = /^(0[1-9]|[1234]\d|5[012])([1-9]\d{2}|\d[1-9]\d|\d{2}[1-9])$/
	if(!expRegCodigoPostal.test(elemento.value)) 
	{
		//alert(elemento.value + ' no es un código postal válido.');
		return false;
	}
	return true;
}

function validaNss(elemento)
{
	//expresión regular para números de la seguridad social
	//Se trata de una cifra de 11 dígitos para el caso de las cuentas de cotización de empresas, 
	//y de 12 dígitos en el caso del número de un trabajador. 
	//Los dos últimos dígitos constituyen los dígitos de control. 
	//Estas dos ultimas cifras del número completo, debe ser el resto de dividir 
	//todo el número exceptuando los dos ultimos digitos (que son los de control) entre 97
	//La expresión regular acepta 11 ó 12 cifras separadas (o no) por una barra, un guión, un punto o un espacio
	//La comprobación de los dígitos de control tendrá que hacerse a posteriori
	
	var expRegNSS = /^\d((\/|-|\.|\s)?\d){10}((\/|-|\.|\s)?\d)?$/;
	if(!expRegNSS.test(elemento.value)) 
	{
		//alert(elemento.value + ' no es un número de la Seguridad Social válido.');
		return false;
	}
	else
	{
		var nss = elemento.value;
		for (var i = nss.length-1; i >= 0; i--)
		{
			if ("0123456789".indexOf(nss.charAt(i)) == -1)
			{
				nss = nss.substring(0,i) + nss.substring(i+1);
			}
		}
		if ((nss.length == 12) && (nss.charAt(2) == 0))
		{
			nss = nss.substring(0,2) + nss.substring(3);
		}
		if ((nss.substring(0,nss.length-2)%97) != (nss.substring(nss.length-2)))
		{
			//alert(elemento.value + ' no es un número de la Seguridad Social válido.');
			return false;
		}
	}
	return true;
}

function validaDni(elemento)
{
	//expresión regular para DNI
	
	var expRegDNI= /^(\d){8}$/
	if(!expRegDNI.test(elemento.value))
	{
		//alert(elemento.value + ' no es un DNI válido');
		return false;
	}
	return true;
}

function validaNif(elemento)
{
	//expresión regular para NIF normal
	var expRegNIFBasico = /^(\d){8}[TRWAGMYFPDXBNJZSQVHLCKE]$/
	
	//este NIF permite una barra, guión, punto o espacio detrás de cada cifra
	var expRegNIF= /^(\d(\/|-|\.|\s)?){8}[TRWAGMYFPDXBNJZSQVHLCKE]$/
	if(!expRegNIF.test(elemento.value))
	{
		//alert(elemento.value + ' no es un NIF válido');
		return false;
	}
	else
	{
		var nif = elemento.value;
		for (var i = nif.length-2; i >= 0; i--)
		{
			if ("0123456789".indexOf(nif.charAt(i)) == -1)
			{
				nif = nif.substring(0,i) + nif.substring(i+1);
			}
		}
		if ("TRWAGMYFPDXBNJZSQVHLCKE".charAt(nif.substring(0,8)%23) != nif.substring(8))
		{
			//alert(elemento.value + ' no es un NIF válido');
			return false;
		}
	}
	return true;
}

function validaUrl(elemento) 
{
	//expresión regular para direcciones URL de Internet básicas
	//	hostname	([A-Za-z](\w|\$|-|@|\.|&|\+|!|\*|"|'|\(|\)|\,|(%[A-Fa-f\d]{2}))+([A-Za-z](\w|\$|-|@|\.|&|\+|!|\*|"|'|\(|\)|\,|(%[A-Fa-f\d]{2}))+)*)
	//	hostnumber	(\d+\.\d+\.\d+\.\d+)
	//	var expRegURL = /^(([A-Za-z](\w|\$|-|@|\.|&|\+|!|\*|"|'|\(|\)|\,|(%[A-Fa-f\d]{2}))+([A-Za-z](\w|\$|-|@|\.|&|\+|!|\*|"|'|\(|\)|\,|(%[A-Fa-f\d]{2}))+)*)|(\d+\.\d+\.\d+\.\d+))$/
	var expRegURL = /^((((http|ftp|https):(\/\/)?)|mailto:)[^ >"\t]*|www\.[-a-z0-9.]+)[^ .,;\t>">]$/
	if(!expRegURL.test(elemento.value))
	{
		//alert(elemento.value + ' no es una URL válida');
		return false;
	}
	return true;
}

///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
// 
//  Funciones para la gestión de eventos.
//  Llevan todas el prefijo 'eventos'.
//
///////////////////////////////////////////////////////////////////////////

function eventosKeyPress(elemento, e, formulario) 
{
	var teclaIntro = 13;
	var numeroTecla;
	var nombreElemento;
	var siguienteElemento;
	var ordenReturn;
	
	if (window.event)							// para Internet Explorer
	{
		numeroTecla = window.event.keyCode;
	}
	else if (e)									// para Netscape y DOM
	{
		numeroTecla = e.which;
	}
	if (numeroTecla == teclaIntro)
	{
		if (formulario == null)
		{
			formulario = elemento.form;
		}
		ordenReturn = formulario.ordenReturn.value;
		
		nombreElemento = elemento.name;
		
		// recorrer el ordenReturn mientras el elemento no exista o sea un hidden
		do
		{
			nombreElemento = eventosNextElement(nombreElemento, ordenReturn);
			siguienteElemento = eventosGetElement(nombreElemento, formulario);
		}
		while ((siguienteElemento == null) || (siguienteElemento.type == "hidden"))
		
		siguienteElemento.focus();
		if ('[checkbox][file][image][password][radio][text][textarea]'.indexOf('[' + siguienteElemento.type + ']') != -1)
		{
			siguienteElemento.select();
		}
		return false;
	}
	else
	{
		return true;
	}
}

function eventosNextElement(nombreElemento, ordenReturn)
{
	var arrayElementos = ordenReturn.split(',');
	var i = 0;
	while (i < arrayElementos.length)
	{
		if (arrayElementos[i] == nombreElemento)
		{
			if (i == (arrayElementos.length - 1))
			{
				return arrayElementos[0];
			}
			else
			{
				return arrayElementos[i+1];
			}
		}
		i++;
	}
	return arrayElementos[0];

}

function eventosGetElement(nombreElemento, formulario)
{
	var fieldlist=formulario.getElementsByTagName("*");
	
	for (i=0; i<fieldlist.length; i++)
	{
	    if (fieldlist[i].name == nombreElemento)
	    {
	    	return fieldlist[i];
	    }
	}
	return null;
}	

///////////////////////////////////////////////////////////////////////////
// 
//  Funciones para la gestión de ventanas modales.
//  Llevan todas el prefijo 'modal'.
//
///////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
// Deteccion de Navegador
////////////////////////////////////////////////////////////////////////////////////
function detectaBrowser()
{
	NS4 = (document.layers)? true:false;			// Booleano indicando Netscape
	IE4 = (document.all)? true:false;
	DOM = ((document.getElementById)&&(!IE4))? true:false;	// Booleano indicando Netscape 6
}

////////////////////////////////////////////////////////////////////////////////////
// CAMPOS Y FUNCIONES DE LA APLICACION DE VENTANA MODAL
////////////////////////////////////////////////////////////////////////////////////
function modalInicializaOpener(campoModal)
{
	detectaBrowser();
	campoModal.value	= 0;
	window.modal		= campoModal;
	ventanaModal		= new Object();	// Definición del nombre que recibirá la ventana en Netscape
}

function modalInicializaModal()
{
	detectaBrowser();
	if (NS4)
	{
		modal   		= opener.modal;		// Variable de control modal de la pagin principal
	}
}
////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
// Funciones Propias
////////////////////////////////////////////////////////////////////////////////////
function modalMuestraModal(htmlModal, ancho, alto, returnFunc, returnParam)
{
	var DIMENSIONES;
	var WIDTH	= ancho;
	var HEIGHT	= alto;
	var XPOS	= (screen.width - WIDTH)/2;
	var YPOS	= (screen.height- HEIGHT)/2;
	
	if (IE4)
	{
		DIMENSIONES =	"dialogWidth="	+ WIDTH		+ "px;" + 
						"dialogHeight="	+ HEIGHT	+ "px;" +
						"dialogLeft="	+ XPOS		+ "px;" +
						"dialogTop="	+ YPOS		+ "px";
						
		var returnedValue = window.showModalDialog(htmlModal,'ventanaModal',DIMENSIONES);
		if ((returnedValue != undefined) && (returnParam != undefined))
		{
			returnParam.value = returnedValue;
		}
	}
    else
    {
	    if (!ventanaModal.win || (ventanaModal.win && ventanaModal.win.closed))
	    {
			DIMENSIONES =	"left="		+ XPOS + 
							",top="		+ YPOS + 
							",width="	+ WIDTH + 
							",height="	+ HEIGHT + 
							",modal=yes";
			
			ventanaModal.returnFunc = returnFunc;
			ventanaModal.returnParam = returnParam;
			ventanaModal.win = window.open(htmlModal,'ventanaModal',DIMENSIONES);
			ventanaModal.win.focus();
		} 
		else {
			ventanaModal.win.focus()
		}
	}
    
}

////////////////////////////////////////////////////////////////////////////////////
// Funciones de la ventana modal para salir
////////////////////////////////////////////////////////////////////////////////////
function modalCancelar()
{
	if (NS4)
	{
		modal.value = 0;
	}
	window.close();
	return false;
}

function modalDevolverValor(valor)
{
	if (IE4)
	{
		window.returnValue = valor;
		window.close();
		return false;
	}
	else
	{
		if (NS4)
		{
			modal.value = 0;
		}
		if (opener && !opener.closed)
		{
			if (top.opener && !top.opener.closed)
			{
				top.opener.ventanaModal.returnedValue = valor;
			}
			if (opener.ventanaModal.returnFunc != undefined)
			{
				opener.ventanaModal.returnFunc(opener.ventanaModal.returnParam);
			}
			window.close();
			return false;
		} 
		return valor;
	}
}

//Función que sirve para meter el resultado en el campo apropiado
function modalMeterResultado(campo){
	if (!IE4)
	{
		if (campo != undefined)
		{
			campo.value = ventanaModal.returnedValue;
		}
	}
}
////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
// Funciones que se ejecutan en el body para la gestión del foco en NS4
////////////////////////////////////////////////////////////////////////////////////
function modalGestionFocus()
{
	if ((NS4) && (modal.value != 1)) 
	{
		window.opener.focus();
	}
}

function modalGestionBlur()
{
	if (NS4)
	{
		modal.value = -1;
	}
}

function modalCerrar()
{
	if (NS4)
	{
		modal.value = 0;
	}
}
////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
// Funciones que gestionan las operaciones del body en NS4
////////////////////////////////////////////////////////////////////////////////////
function modalGestionModal(campoModal)
{
	if ((NS4) && (campoModal.value == -1))
	{
		campoModal.value = 1;
		ventanaModal.win.focus();
	}
	
}