EscribirObjetoFlash();
var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
var tiempo = 0
var intervalo 
///////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////FUNCIONES VARIAS/////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////

//función que se utiliza para mostrar mensajes a javascript
function MostrarMensaje (Mensaje){
	alert(Mensaje)	
}

// Hook for Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
	document.write('<script language=\"VBScript\"\>\n');
	document.write('On Error Resume Next\n');
	document.write('Sub FlashLoad_FSCommand(ByVal command, ByVal args)\n');
	document.write('Call FlashLoad_DoFSCommand(command, args)\n');
	document.write('End Sub\n');
	document.write('</script\>\n');
}
//funcion que comprueba la URL que se lanza y si contiene el ID del bloque donde se ejecuta 
function ComprobarURLJS (){	
	var URLSergio
	//se obtiene la URL que habre el teacher 
	URLSergio= String(document.location);	
	var arVar = new Array();	
	arVar = URLSergio.split("?");		
	if (arVar.length>1)
	{		
		var Variables =  arVar[1];
		var arID= new Array();
		arID = Variables.split("=");	
		//comprobamos que la variable que  se le ha pasado sea correcta
		var NomVal = String(arID[0])
		if (NomVal.toUpperCase()=="ID") {
			var ID = Number(arID[1]);
			if (ID>0)
			{				
				return ID	
			}else{
				//si el ID no es mayor que 0, se devuelve 0 o sea fallido				
				return 0
			}
		} else {						
			//si la variable no se llama ID se devuelve fallido				
			return 0
		}	
    }else{			
		//si no hay una variable en la URL se devuelve fallido			
		return 0
    }
}
//función que reemplaza en el texto que se le pasa un cartácter por otro o varios caracteres
function replace(texto,word,changed)
{	
	var indice = texto.indexOf(word);
	var textoaux  = texto
	while(indice!=-1)
	{		
		var fin  = indice + word.length;
		var part1= textoaux.substring(0,indice)
		var part2= textoaux.substring(fin,textoaux.length)	
		var textoaux= part1.concat(changed,part2);
		indice = textoaux.indexOf(word);
	}
	return textoaux	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////FUNCIONES PARA CALCULAR EL TIEMPO DE CONEXION DENTRO DEL TEACHER//////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////

//funcion que inicia el intervalo de tiempo para contabiliar los segundos que el alumno pasa dentro de la lección
function cronotiempo (){
	intervalo = window.setInterval(cuentaT,1000);	
}

//función que se lanza el intervalo que contabiliza los segundos
function cuentaT(){
	tiempo++;
}

//esta función obtiene los segundos totales que ha pasado el alumno en la lección y calcula sus horas, minutos y segundos
function calculartiempo() {	
	var nhoras = 0;
	var nminutos= Math.floor(tiempo/60);
	if (nminutos>=60 ) {
		nhoras = Math.floor(nminutos/60);
		var nminutos = nminutos-(60*nhoras);
	}
	var nresto = tiempo-(60*nminutos);	
	var sttiempo = comprobarceros(String(nhoras),"horas")+":"+comprobarceros(String(nminutos),"minutos")+":"+comprobarceros(String(nresto),"segundos");	
	return sttiempo;	
}


//según sea  hora, minutos o segundos  colocará tantos ceros
function comprobarceros (num,tipo) {	
	switch (tipo)
	{
		case "horas":	
			var result = rellenarceros(num,4-num.length);	 	
			return result ;
			break;
		case "minutos":
		case "segundos":
			var result = rellenarceros(num,2-num.length);			
			return result;
			break;		
	}		
}

//rellena de ceros a la izquierda un número que se le pasa por parametro y el númeor de ceros a rellenar
function rellenarceros (numero,numceros){
	switch(numceros)
	{
		case 1:
			return "0"+numero;
			break;
		case 2:
			return "00"+numero;
			break;
		case 3:
			return "000"+numero;
			break;
		case 4:
			return "0000"+numero;		
			break;
		case 0:
			return numero;
			break;
	}	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////FUNCIONES NECESARIAS PARA CERRAR EL TEACHER CORRECTAMENTE/////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
function CerramosTeacher(){	
	ComprobarCierre();	
	return false;                 
}
function ComprobarCierre() {	
	var Respuesta = document.FlashLoad.CerramosTeacherFlash();	
}
//comprueba el estado de la ventana
function comprobarestadoventana(){		
	var Modo = document.FlashLoad.ObtenerModoTeacher();		
	if (Modo != "API")	{	
	   var ventana = window.self;
	   ventana.opener = window.self;
       ventana.close();
	}else{			   
	   parent.self.close();
	}
}

//cierra la ventana de la lección preguntando primero si se desea cerrar
function cerrarventana () {
	if (confirm("¿Está seguro que desea salir de Teacher?"))		
	{	
		CerramosTeacher();
		comprobarestadoventana();		
	}	
}

//cerramos el teacher comprobando en que modo estamos y actuando en consecuencia
function cerramos(Modo) {			
		if (Modo=="API")
		{
			var settime = calculartiempo();		
			mm_adl_API.LMSSetValue("cmi.core.session_time",settime);			
			ColocarEstadoExit("suspend");			
			mm_adlOnunload();
		}
}

function ColocarEstadoExit(Estado) {	
	if (Estado=="null"){
		Estado=""
	}
	var  resultadoExit = mm_adl_API.LMSSetValue("cmi.core.exit",Estado);		
	return resultadoExit 
}

//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////FUNCIONES QUE UTILIZA FLASH PARA PODER OBTENER DATOS///////////////////
////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////ERRORES///////////////
//Obtiene el último error que se ha producido dentro de scorm
function ObtenerError(){
	var diagnostic = mm_adl_API.LMSGetLastError();
	return diagnostic;
}
//funcion que devuelve el error que se ha producido en una cadena pasandole el id de error 
function ObtenerCadenaError(error){	
	var sterror = mm_adl_API.LMSGetErrorString(error);
	return sterror
}
function ObtenerDiagnostico(){
	var diac = mm_adl_API.LMSGetDiagnostic("");
	return diac
}
///////////////////TRAZA////////////////
//devuelve la traza del curso actual, almacenada dentro de la variable scorm cmi.suspend_data
function obtenerTraza (){
	var traza= mm_adl_API.LMSGetValue("cmi.suspend_data"); 							
	return traza
}
//funcion que guarda la traza del teacher dentro de la plataforma
function GuardarTraza (Traza){
	var guardar = replace(Traza,"\"","'");			
	if (guardar=="null"){
		guardar =""
	}
	var resultado = mm_adl_API.LMSSetValue("cmi.suspend_data",guardar);						
	return resultado
}
///////////////////POSTIT////////////////
//funcion que guarda el xml con los datos de los comentarios del alumno a los distintos elementos del teacher
function GuardarComentariosPostit(TrazaP){	
	if (TrazaP=="null"){
		TrazaP=""
	}		
	var estado= mm_adl_API.LMSSetValue("cmi.comments",TrazaP);				
	var resultado
}
//funcion que obtiene los comentarios que ha realizado el alumno al profesor mediante el posit de cada uno de los elementos del teacher

function ObtenerComentariosPostit(){

	var resultado= mm_adl_API.LMSGetValue("cmi.comments");					
	return resultado
}

////////////////////FUNCIONES PARA ENCOTRAR LA TRAZA EN MODO PROFESOR
//funcion para comprobar si se esta abriendo el teacher en modo profesor
function comprobarprofesor() {
 	if (window.opener.document.forms["TeacherProfesor"].suspend_data.value!= "null" && window.opener.document.forms["TeacherProfesor"].suspend_data.value!="" && window.opener.document.forms["TeacherProfesor"].suspend_data.value!="undefined")
	{
		return window.opener.document.forms["TeacherProfesor"].suspend_data.value;
	}else{
		return false;		
	}
} 
//funcion que encuentra  dentro del parent una variable dentro de un form para cargar el xml de los postit dentro del profesor
function EncontrarPostitProfesor(){
	if (window.opener.document.forms["TeacherProfesor"].comments.value!= "null" && window.opener.document.forms["TeacherProfesor"].comments.value!="" && window.opener.document.forms["TeacherProfesor"].comments.value!="undefined")
	{		
		return window.opener.document.forms["TeacherProfesor"].comments.value;
	}else{
		return false;		
	}
	
}

/////////////////LECCION/////////////////////////////
//obtiene el contenido de la variable cmi.core.lesson_status donde se encuentra el estado de la lección
function ObtenerEstadoLeccion() {
	var estado= mm_adl_API.LMSGetValue("cmi.core.lesson_status");			
	return estado
}
//Coloca el estado de la lección dentro de la variable cmi.core.lesson_status que se le pasa por parámetros
function ColocarEstadoLeccion(Estado) {		
	var  resp = mm_adl_API.LMSSetValue("cmi.core.lesson_status",Estado);	
}
////////////////////ALUMNO/////////////////////////////
//Obtiene el Nombre del ALumno
function obtenerNombreAlumno()
{	
	var nom= mm_adl_API.LMSGetValue("cmi.core.student_name"); 			
	return nom
	
}
//Obtiene el ID del alumno
function obtenerIDAlumno()
{	
	var idalumno = mm_adl_API.LMSGetValue("cmi.core.student_id"); 		
	return idalumno	
}


/////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////FUNCIONES PARA OBTENER EL API DE SCORM///////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

//Obtine el API de scorm
function obtenAPI()
{	
	var  resultadoAPI = mm_getAPI();
	return resultadoAPI
}

// define global var as handle to API object
var mm_adl_API = null;


// returns LMS API object (or null if not found)
function findAPI(win)
{
  // look in this window
  if (typeof(win) != 'undefined' ? typeof(win.API) != 'undefined' : false)
  {
    if (win.API != null )  return win.API;
  }
  // look in this window's frameset kin (except opener)
  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;

}

// mm_getAPI, which calls findAPI as needed
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 || myAPI == 'undefined')
  {
    window.status = 'API not found';      
    return false
  }
  else
  {
    mm_adl_API = myAPI;               
    estado = mm_adl_API.LMSInitialize("");        
    window.status = 'API found'     
    return true
  }
}

// call LMSInitialize()
function mm_adlOnload()
{
  if (mm_adl_API != null)
  {
    mm_adl_API.LMSInitialize("");    
  }
}

// call LMSFinish()
function mm_adlOnunload()
{
  if (mm_adl_API != null)
  {          
    var resultadoCommit =  mm_adl_API.LMSCommit("");
    var resultadoFinnish = mm_adl_API.LMSFinish("");
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////FUNCION QUE ESCRIBE EL OBJETO FALSH ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function EscribirObjetoFlash(){	
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="100%" height="100%" id="FlashLoad" align="middle">')
	document.write('<param name="allowScriptAccess" value="sameDomain" />')
	document.write('<param name="movie" value="Flash/Preloadteacher.swf" />')
	document.write('<param name="quality" value="high" />')
	document.write('<param name="bgcolor" value="#ffffff" />')
	document.write('<embed src="Flash/Preloadteacher.swf" quality="high" bgcolor="#ffffff" width="100%" height="100%" name="FlashLoad" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />')
	document.write('</object>')
}












