// JavaScript Document
//Autor: USO-PC (CINDETEC-UNED)
//daparicio@pas.uned.es Enero 2008
//Actualizaciones daparicio@pas.uned.es Junio 2008
//Actualizaciones daparicio@pas.uned.es Octubre/Noviembre 2008

var mm_adl_API = null; // Variable global que contiene la API
var debugActivado = true; //Si está a true, genera un informe de errores en sScormDebug
var sScormDebug =""; //Variable donde se almacena el informe de errores si debugActivado es igual a true
var aObjetivos = new Array(); //Array con string de situación de las visitas de las pestañas de cada ficha
var aPuntuaciones = new Array(); //Array con la puntuación de cada ficha
var aEstado = new Array(); //Array con el estado de cada ficha
var s_data = ""; //Variable que almacena el contenido de suspend_data, en esta se guarda el estado de las pestañas de cada ficha
var implObjetivos = false; //Se pone a true si la plataforma permite el uso de objetivos
var bugObjetivos = true; //Poner a true si la plataforma donde se va a subir tiene algun bug en los objetivos
var fichaActual = -1; //Ficha en la que se está actualmente
var fechaInicial = new Date(); //Fecha a la que se enta al SCO
var localizacion=""; //Última ficha visitada, se usa para las cookies
var curso_completo =""; //Variable donde se guarda si se ha completado el curso completo
var nombreCurso = ""; //Nombre que se le da al curso en una meta de la página principal, para darle nombre a la  cookie. Es importante para que no se machaquen cookies entre cursos

var estaConectado = false; //Variable global que indica si se está conectado
var xmlDoc; //Variable global que contiene el XML de las fichas
var xmlGlosario; //Variable global que contiene el XML del glosario

//*********************//
//**** Obtener API ****//
//*********************//
function mm_getAPI()
{
  var myAPI = null;
  var tries = 0, triesMax = 500;

  while (tries < triesMax && myAPI == null)
  {
    myAPI = findAPI(window);
    if (myAPI == null && typeof(window.parent) != 'undefined') myAPI = findAPI(window.parent)
    if (myAPI == null && typeof(window.top) != 'undefined') myAPI = findAPI(window.top);
    if (myAPI == null && typeof(window.opener) != 'undefined') if (window.opener != null && !window.opener.closed) myAPI = findAPI(window.opener);
    tries++;
  }
  if (myAPI == null)
  {
    window.status = 'Modo no conectado';
    //alert('JavaScript Warning: API object not found in window or opener. (' + tries + ')');
  }
  else
  {
    mm_adl_API = myAPI;
  }
  

}
// Devuelve la API LMS o null si no la encuentra
function findAPI(win)
{
  if (typeof(win) != 'undefined' ? typeof(win.API) != 'undefined' : false)
  {
    if (win.API != null )  return win.API;
  }

  if (win.frames.length > 0)  for (var i = 0 ; i < win.frames.length ; i++);
  {
    if (typeof(win.frames[i]) != 'undefined' ? typeof(win.frames[i].API) != 'undefined' : false)
    {
	     if (win.frames[i].API != null)  return win.frames[i].API;
    }
  }
  return null;
}


//***************************//
//**** LLamadas a la API ****//
//***************************//

function iniciarComunicacion()
{
	mm_getAPI();
	conectarse('');
	iniciarVariables();
	}

// Conectarse al LMS
function conectarse(argumentos)
{
	var conectado = false;
	if(mm_adl_API!=null) //Si encontró la API
	{
		conectado = mm_adl_API.LMSInitialize(argumentos);
		if(debugActivado) setScormDebug("LMSInitialize","",conectado.toString());
		if(conectado) 
			{
				estaConectado=true;
				if(leerDato("cmi.core.student_id").toUpperCase() != "GUEST")
				{
					var objChildren = leerDato("cmi.objectives._children");
					
					if(!bugObjetivos && objChildren.indexOf("id") != -1 && objChildren.indexOf("status") != -1 && objChildren.indexOf("score") != -1) implObjetivos = true; 
					window.status = leerDato("cmi.core.student_name");
				}
				else
				{
					estaConectado=false;
					window.status = leerDato("Modo invitado. No conectado");
					}
				
				
			}
	}
}
	
//Desconectarse del LMS
function desconectarse(argumentos)
{
	var desconectado = false;

	if(mm_adl_API!=null && estaConectado) //Si se mencontró la API y está conectado
	{
		hacerCommit("");
		desconectado = mm_adl_API.LMSFinish(argumentos);
		if(debugActivado) setScormDebug("LMSFinish","",desconectado.toString());
		if(desconectado) {
			window.status = "Modo no conectado";
			estaConectado=false;
		}
	}
}	

//Función que guarda datos en el LMS (LMSSetValue)
function guardarDato(dato, valor)
{
	if(mm_adl_API!=null && estaConectado) //Si se mencontró la API y está conectado
	{
		var resultado = mm_adl_API.LMSSetValue(dato, valor);
		var pp = dato + "," + valor;
		if(debugActivado) setScormDebug("LMSSetValue",pp,resultado.toString());
	}
}	

//Si se mencontró la API y está conectado devuelve el valor, si no devuelve null
function leerDato(dato)
{
	if(mm_adl_API!=null && estaConectado) return (mm_adl_API.LMSGetValue(dato));
	else return null
}	

//Hacer commit de los datos guardados
function hacerCommit(argumentos)
{
	if(mm_adl_API!=null && estaConectado){
		guardarTiempoConectado();
		var resultado = mm_adl_API.LMSCommit(argumentos);
		if(debugActivado) setScormDebug("LMSCommit","",resultado.toString());
	}
}

//Guardar en el informe de errores
function setScormDebug(pCallFunction, pParam, pReturnValue) {
	
	sScormDebug += "Llamada: " + pCallFunction + "('" + pParam+ "') <br> ";
	sScormDebug += "Valor Retorno: " + pReturnValue + " <br> ";
	sScormDebug += "Código de Error: " + mm_adl_API.LMSGetLastError() + " <br> ";
	sScormDebug += "<br>---------------------------------------------------------<br> ";
}


//*******************************//
//**** Seguimiento del curso ****//
//*******************************//

//Inicializa las variables necesarias al entrar en el SCO
function iniciarVariables()
{
	if(mm_adl_API!=null && estaConectado)
	{
		if(leerDato("cmi.core.lesson_location")=="") //Si es la primera vez que se entra, se inicializa suspend_data y los objetivos necesarios
		{
			guardarDato("cmi.core.lesson_status","incomplete")
			s_data = ""
			for(i=0;i<xmlDoc.getElementsByTagName('FICHA').length;i++)//Recorre las fichas y crea un objetivo porficha
			{
				var iObjetivos = i;
				var idOjetivos = obtenerIdObjetivos(i);
				
				nuevoObjetivo(iObjetivos, idOjetivos);

				//Inicializa suspend_data
				nuevoElementoS_DATA (i)
				guardarDato("cmi.suspend_data",s_data);
			}
			//Guarda algo en lesson_location para que no volver a iniciar suspend_data y los objetivos la proxima vez que se entre
			guardarDato("cmi.core.lesson_location","N");
		}
		else s_data = leerDato("cmi.suspend_data");
		
	}
	else
	{	//Si no está en una plataforma con SCORM 1.2, los datos del alumno se guardan en su equipo (cookies)	
		if(document.getElementById("cookie")) nombreCurso = document.getElementById("cookie").content;
		
		if (document.cookie.indexOf(nombreCurso+"_ultima_ficha",0)!=-1) { // propiedad encontrada
			localizacion = obtenerPropiedadCookie(nombreCurso+"_ultima_ficha");
			s_data = obtenerPropiedadCookie(nombreCurso+"_estado_pestanas");
			curso_completo = obtenerPropiedadCookie(nombreCurso+"_curso_completo");
		
		}
		else
		{	//Es la primera vez que entra
			s_data = "";
			for(i=0;i<xmlDoc.getElementsByTagName('FICHA').length;i++)
			{
				nuevoElementoS_DATA (i);
			}
			localizacion = "N";
			curso_completo="incomplete";
			guardarDatoCookie(nombreCurso+'_ultima_ficha=', localizacion);
			guardarDatoCookie(nombreCurso+'_estado_pestanas=', s_data);
			guardarDatoCookie(nombreCurso+'_curso_completo=', curso_completo);
		}
		
	}
		
	aObjetivos = s_data.split("-");
	if(!implObjetivos)//Si la plataforma no permite objetivos
	{
		//Inicializar los Array
		for(iPe=0;iPe<aObjetivos.length;iPe++) 
		{
			var miArrayTemp = new Array();
			miArrayTemp = aObjetivos[iPe].split("1");
			var numUno = miArrayTemp.length-1;
			aPuntuaciones[iPe] = Math.round((numUno*100)/aObjetivos[iPe].length);
			if(aPuntuaciones[iPe]>=100) aEstado[iPe] = "completed";
			else aEstado[iPe] = "incomplete";
		}
	}

	verificarCompletado();
	hacerCommit("");

}

//Devuelve el ID del Objetivo correspondiente

function obtenerIdObjetivos(indice)
{
	var idOjetivos = xmlDoc.getElementsByTagName('FICHA')[indice].attributes.getNamedItem('TITULO').nodeValue;
	//alert(idOjetivos.indexOf(" "));
	do
	{
		idOjetivos = idOjetivos.replace(" ", "_");
		}
	while(idOjetivos.indexOf(" ")>=0);
	return idOjetivos;
}

//Añade un nuevo elemnto del menú a s_data

function nuevoElementoS_DATA (i)
{
	if(i!=0) s_data+="-";
	for(iPe=0;iPe<xmlDoc.getElementsByTagName('FICHA')[i].attributes.getNamedItem('PESTANAS').nodeValue;iPe++) s_data+="0";
	}


//Añade un nuevo objetivo al LMS

function nuevoObjetivo(iObjetivos, idOjetivos)
{				
	if(implObjetivos) //Si la plataforma permite objetivos
	{
		guardarDato("cmi.objectives." + iObjetivos + ".id", idOjetivos);
		guardarDato("cmi.objectives." + iObjetivos + ".score.max","100");				
		guardarDato("cmi.objectives." + iObjetivos + ".score.min","0");
		guardarDato("cmi.objectives." + iObjetivos + ".score.raw","0");
		guardarDato("cmi.objectives." + iObjetivos + ".status","incomplete");
	}
}

//Guardar la última ficha que se ha visitado  en lesson_location, y se actualiza fichaActual
function marcarFicha(indice)
{
	fichaActual = indice;
	guardarDato("cmi.core.lesson_location",indice);

	if(mm_adl_API==null || !estaConectado) {
		localizacion=indice;
		guardarDatoCookie(nombreCurso+'_ultima_ficha=', localizacion);
	}
	hacerCommit("");
	}

//Guardar una ficha como terminada
function actualizarSegFicha(indice)
{
	if(aObjetivos[indice].indexOf("0")==-1) 
	{
		if(implObjetivos) //Si la plataforma permite objetivos
		{
			guardarDato("cmi.objectives." + indice + ".score.raw","100");
			guardarDato("cmi.objectives." + indice + ".status","completed");
		}
		
		aPuntuaciones[indice] = 100;
		aEstado[indice] = "completed";
		verificarCompletado();
	}
}

//Actualizar el seguimiento de las pestañas de una ficha
function actualizarSegPestana(indice)	
{	if(fichaActual>=0)
	{
		if(aObjetivos[fichaActual].substring(indice-1,indice)!="1") //Si no se han completado todas las pestañas de la ficha
		{
			aObjetivos[fichaActual]=aObjetivos[fichaActual].substring(0,indice-1) + "1" + aObjetivos[fichaActual].substring(indice);
			var miArrayTemp = new Array();
			miArrayTemp = aObjetivos[fichaActual].split("1");
			var numUno = miArrayTemp.length-1;
			//Si la plataforma permite objetivos
			if(implObjetivos) guardarDato("cmi.objectives." + fichaActual + ".score.raw",Math.round((numUno*100)/aObjetivos[fichaActual].length)); //Porcentaje de pestañas terminadas de la ficha
			aPuntuaciones[fichaActual] = Math.round((numUno*100)/aObjetivos[fichaActual].length); //Porcentaje de pestañas terminadas de la ficha
			s_data = aObjetivos.join("-")
			guardarDato("cmi.suspend_data",s_data);
			if(mm_adl_API==null || !estaConectado) guardarDatoCookie(nombreCurso+'_estado_pestanas=', s_data);
			actualizarSegFicha(fichaActual)
			hacerCommit("");
		}
	}
}

//Verificar si se ha completado todo el SCO
function verificarCompletado()
{
	var nObjetivos = 0;
	//Si la plataforma permite objetivos
	if(implObjetivos) nObjetivos = leerDato("cmi.objectives._count");
	else nObjetivos = aObjetivos.length;
	var oCompleto = true;
	var nCompletos = 0;
	
	//Recorre los objetivos buscando uno que no esté completo
	for(iObj=0; iObj<nObjetivos; iObj++)
	{
		//Si la plataforma permite objetivos
		if(implObjetivos) aEstado[iObj] = leerDato("cmi.objectives." + iObj + ".status");
		if(aEstado[iObj] !="completed" && aEstado[iObj]!="") oCompleto=false;	
		else nCompletos++;
	}
	if(oCompleto==true) {
		guardarDato("cmi.core.lesson_status", "completed");
		if(mm_adl_API==null || !estaConectado) {
			curso_completo="completed";
			guardarDatoCookie(nombreCurso+'_curso_completo=', curso_completo);
		}
	}
	var porcSCO = Math.round((nCompletos*100)/nObjetivos);
	guardarDato("cmi.core.score.raw", porcSCO); //Guardar porcentaje del curso completado
}


//Marcar una pestaña como completada
function marcarPestanas(documento, marcadores, pestanaActual)
{
	
	for (i=1;i<=marcadores.length;i++)
	{
		var idPestana = i;
		if (documento.getElementById("p"+i)) idPestana="p"+i;
		if (documento.getElementById(idPestana) && i==pestanaActual) documento.getElementById(idPestana).className = 'current';
		else if(documento.getElementById(idPestana) && marcadores.substring(i-1,i)=="1") documento.getElementById(idPestana).className = 'visitado';
		
	}
}

//Alimentar la página de progresos
function paginaProgreso(capa)
{
	var iFichas = 0;
	var textoHTML=""
	for(i=0;i<xmlDoc.getElementsByTagName('MODULO').length;i++)
	{
		var xmlFichas = xmlDoc.getElementsByTagName('MODULO')[i].getElementsByTagName('FICHA');
		textoHTML += '<H3>' + xmlDoc.getElementsByTagName('MODULO')[i].attributes.getNamedItem('TITULO').nodeValue + '</h3>';
		textoHTML += '<ul>';
		for(j=0;j<xmlFichas.length;j++)
		{
			//Si la plataforma permite objetivos
			if(implObjetivos) aPuntuaciones[iFichas] = leerDato("cmi.objectives." + iFichas + ".score.raw");
			textoHTML+='<li>' + xmlFichas[j].attributes.getNamedItem('TITULO').nodeValue + '(' + aPuntuaciones[iFichas] + '%)';
			textoHTML+='<div style="border:1px #000000 solid;  width:100px; height:20px; "><div style="background-color:#0000FF; width:' + aPuntuaciones[iFichas] + '%; height:20px"></div></div>';
			textoHTML+='</li>';
			iFichas++;
		}
		textoHTML += '</ul>';
	}
	capa.innerHTML=textoHTML;
}

//Guardar el tiempo que se lleva conectado
function guardarTiempoConectado()
{
	var fechaFin = new Date();
	var nuevaFecha = new Date(fechaFin-fechaInicial);
	var horas = (nuevaFecha.getHours()-1) + ((nuevaFecha.getDate()-1)*24);

	guardarDato("cmi.core.session_time", formatearNumero(horas, 4) + ":" + formatearNumero(nuevaFecha.getMinutes(), 2) + ":" + formatearNumero(nuevaFecha.getSeconds(), 2));

}

//************************//
//**** Tratar cookie ****//
//***********************//

function guardarDatoCookie(dato, valor)
{
	var fechaCaducidad=new Date (fechaInicial.getFullYear()+2, 12, 31);
	document.cookie=dato+valor+"; expires=" + fechaCaducidad.toGMTString();
	}

//Obtiene el valor de una variable guardada en las cookies
function obtenerPropiedadCookie(variable)
{
	var docCookie = document.cookie;
	var posLoc = docCookie.indexOf(variable,0); 
	var iniProp = docCookie.indexOf("=",posLoc)+1;
	var finProp = docCookie.indexOf(";",posLoc);
	if(finProp<0) finProp=docCookie.length;
	return docCookie.substring(iniProp,finProp);
}

function salir_curso()
{
	window.close();
	}


//************************//
//**** Carga del XML *****//
//************************//

//Cuando carga el XML
function cargado()
{
}

function loadXML(archivo)
{

var xmlDocm;

var navegador = navigator.userAgent.toLowerCase();

if (window.ActiveXObject) //IE
{
	
	xmlDocm=new ActiveXObject("Microsoft.XMLDOM");
  xmlDocm.async=false;
  xmlDocm.load(archivo);
  cargado();	
}
else if (document.implementation && document.implementation.createDocument && (navegador.indexOf('firefox')>=0 || (navegador.indexOf('opera')>=0))) //Firefox y Opera
{//alert("'"+archivo+"'ss");

	xmlDocm=document.implementation.createDocument("","",null);
	xmlDocm.async=false;
	xmlDocm.load(archivo);
	xmlDocm.onload=cargado;
	
}
else if (window.XMLHttpRequest) //Demás navegadores
{
	var xmlHttp;  
	try {
		xmlhttp = new window.XMLHttpRequest();
		xmlhttp.open("GET",archivo,false);
		xmlhttp.send(null);
		xmlDocm = xmlhttp.responseXML.documentElement;
	}
	 catch(e) {
		 alert(e);
        alert("Estás plantillas no son compatibles con el navegador que está utilizando para su uso en local. Use otro navegador o suba los contenidos a un servidor.");
    }
	cargado();
}
else //El navegador no lo soporta
{
	alert('Su navegador no soporta esta funcion de carga XML');
}

  return xmlDocm;
}

function getXMLObject() {
    // create an array with the XML ActiveX versions
    var aVersions = new Array("Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0");

    // loop through the array until we can create an activeX control
    for (var i=0; i<aVersions.length; i++) {
        // return when we can create the activeX control
        try {
            var oXML = new ActiveXObject(aVersions[i]);
            return oXML;
        } 
        catch(e) {
        }
    }
    // could not create an activeX, return a null
    return null;
}


//*****************************//
//********* GLOSARIO **********//
//*****************************//

var iGls; //Contador de tértmino
var intervaloGlosario; //Código del intervalo de búsqueda de términos en el documento
var documentoGlosario = document; //Objeto document del elemento que que solicita el glosario
var eventoR; //Objeto event del documento que solicita el glosario
var wIndow; //Objeto window del documento que solicita el glosario
var swEncima = false; //Indica si el ratón esta sobre un término


//Inicializa el glosario:
//	inicializa documentoGlosario, eventoR ywIndow
//	crea el bocadillo
//	crea un intervalo para buscar los span que contengan elementos de  glosario
function iniciarGlosario(documento,windowD,objetoXMLGlosario)
{
	iGls = 0
	if (documento) documentoGlosario=documento;
	wIndow = windowD;
	xmlGlosario = objetoXMLGlosario;
	
	if(documentoGlosario.getElementsByTagName("span").length>0)	
	{
		documentoGlosario.getElementsByTagName("body")[0].innerHTML += '<div id="bocadillo" style="left:100px; top:100px"></div>';
		documentoGlosario.getElementsByTagName("body")[0].onmousemove = posicionarBocadillo;
		intervaloGlosario = setInterval("generarEventoGlosario()",1);
	}
}

//Prepara los span que contienen un termino del glosario
//	Configura los spam: título del término, descripción del término ...
//	Genera los eventos para mostrar el bocadillo de cada término
function generarEventoGlosario()
{
	if(documentoGlosario.getElementsByTagName("span")[iGls].attributes.getNamedItem("id"))
		{
			if(documentoGlosario.getElementsByTagName("span")[iGls].attributes.getNamedItem("id").nodeValue == "glosario")
			{
				var existeTitulo =false;
				if(documentoGlosario.getElementsByTagName("span")[iGls].attributes.getNamedItem("title"))
				{
					if(documentoGlosario.getElementsByTagName("span")[iGls].attributes.getNamedItem("title").nodeValue) existeTitulo = true;
				}
				
				
				//Función que carga el termino en elemento del glosario
				documentoGlosario.getElementsByTagName("span")[iGls].cargarTermino = function()
				{
					var terminoXML = xmlGlosario.getElementsByTagName("TERMINO")[this.contador].attributes.getNamedItem("ID").nodeValue;

					if(terminoXML.toUpperCase()==this.tituloTermino.toUpperCase() || terminoXML.toUpperCase()==this.textoTermino.toUpperCase()) 
					{
						clearInterval(this.intervalo);
						this.textoTermino=xmlGlosario.getElementsByTagName("TERMINO")[this.contador].childNodes[0].nodeValue;
						this.tituloTermino=terminoXML;
					}
					
					
					this.contador++;
					if(this.contador>=xmlGlosario.getElementsByTagName("TERMINO").length) 
					{
						
						clearInterval(this.intervalo);
					}
				};

					
			if(existeTitulo)
			{
				documentoGlosario.getElementsByTagName("span")[iGls].tituloTermino = documentoGlosario.getElementsByTagName("span")[iGls].innerHTML;
				documentoGlosario.getElementsByTagName("span")[iGls].textoTermino = documentoGlosario.getElementsByTagName("span")[iGls].attributes.getNamedItem("title").nodeValue;
				documentoGlosario.getElementsByTagName("span")[iGls].attributes.getNamedItem("title").nodeValue = "";

			}
			else
			{
				documentoGlosario.getElementsByTagName("span")[iGls].tituloTermino = documentoGlosario.getElementsByTagName("span")[iGls].innerHTML;
				documentoGlosario.getElementsByTagName("span")[iGls].textoTermino="";

			}
			documentoGlosario.getElementsByTagName("span")[iGls].terminosXML = xmlGlosario.getElementsByTagName("TERMINO");
			documentoGlosario.getElementsByTagName("span")[iGls].contador = 0;
			documentoGlosario.getElementsByTagName("span")[iGls].intervalo = setInterval('documentoGlosario.getElementsByTagName("span")['+iGls+'].cargarTermino()',1);
			
			documentoGlosario.getElementsByTagName("span")[iGls].onmouseover = toolTipMouseOver;
			documentoGlosario.getElementsByTagName("span")[iGls].onmouseout = toolTipMouseOut;
		}
	}
	iGls++;
	if(documentoGlosario.getElementsByTagName("span").length == iGls) clearInterval(intervaloGlosario);


}

//Evento onmouseover que muestra el bocadillo del término
function toolTipMouseOver()
{
	swEncima=true;
	documentoGlosario.getElementById("bocadillo").innerHTML = "<b>" + this.tituloTermino + "</b><br/>" + this.textoTermino;
	documentoGlosario.getElementById("bocadillo").style.visibility = "visible";
}

//Evento onmouseout que oculta el bocadillo del término
function toolTipMouseOut()
{
	documentoGlosario.getElementById("bocadillo").style.visibility = "hidden";
	swEncima=false;
}

//Función que detecta el navegador que se está utilizando
function Browser() {
	this.isIE = false; // Internet Explorer
	this.isNS = false; // Netscape
	this.isOpera = false; // Opera
	if (navigator.userAgent.indexOf("Netscape6/") >= 0) {
		this.isNS = true;
		return;
	}
	if (navigator.userAgent.indexOf("Gecko") >= 0) {
		this.isNS = true;
		return;
	}
	if (navigator.userAgent.indexOf("MSIE") >=0 && navigator.userAgent.indexOf("Opera") <0) {
		this.isIE = true;
		return;
	}
	if (navigator.userAgent.indexOf("Opera") >=0) {
		this.isOpera = true;
		return;
	}
}

//Detecta el navegador
var browser = new Browser();

//Función que posiciona el bocadillo con respecto a la posición del ratón
function posicionarBocadillo(evento)
{

	if(swEncima)
	{
		if (browser.isIE) {
			x = wIndow.event.clientX + documentoGlosario.documentElement.scrollLeft
			+ documentoGlosario.body.scrollLeft;
			y = wIndow.event.clientY + documentoGlosario.documentElement.scrollTop
			+ documentoGlosario.body.scrollTop;
		}
		if (browser.isNS) {
			x = evento.clientX + wIndow.scrollX;
			y = evento.clientY + wIndow.scrollY;
		}
		if (browser.isOpera) {
			x = wIndow.event.clientX + documentoGlosario.documentElement.scrollLeft;
			y = wIndow.event.clientY + documentoGlosario.documentElement.scrollTop;
		}
		
		documentoGlosario.getElementById("bocadillo").style.left= (x + 15) +"px";
		documentoGlosario.getElementById("bocadillo").style.top = y + 10 +"px";
	}
	else
	{
		documentoGlosario.getElementById("bocadillo").style.left = 0;
		documentoGlosario.getElementById("bocadillo").style.top = 0;
		}
}



//*****************************//
//**** Funciones en general ****//
//*****************************//

//Formatear un número a un ceirto número de cifras, rellenando con 0 los que faltan
function formatearNumero(numero, numDigitos)
{
	var numTratado = numero.toString();
	var numCeros = numDigitos-numTratado.length;
	for(i=0;i<numCeros;i++) numTratado = "0" + numTratado;
	return numTratado;
	}
