////////////////////////////////////////////////////////////////////////////////////////////////////
// JavaScript Document
// Gonzalo Monjard�n
// 26/mayo/2014
// gonzalomonjardin@adams.es / gonzalo@alabusa.com
// Cliente: Adams
////////////////////////////////////////////////////////////////////////////////////////////////////
//**************************************************************************************************//
var commonJs = true;
var exType;
var letrasArr = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z");
var browser;
var videoTestObject;
var localVideos= false;
var carpetaVideos = '../videos/';
var videoPercent = 0;
var cuentaAtrasTimer;

function openGlosario(_p){
	window.open("../tools/glosario.html?p="+_p, "_blank", "status=no,toolbar=no, scrollbars=yes, resizable=no, top=100, left=100, width=600, height=400");	
}
function openPdf(_file){
	var pdfWin = window.open(_file,'','status=no,scrollbars=yes,top=0,left=0,resizable=yes,width=800, height=600"');
	pdfWin.focus();
}
function openUrl(_file){
	var urlWin = window.open(_file,'','status=yes,scrollbars=yes,top=0,left=0,resizable=yes,width=800, height=600"');
	urlWin.focus();
}
function showError(txt){	
	if($('#error').length<=0){
	$('body').append('<div id="error"><div class="left" style="float:left">'+txt+'</div><div class="close" style="float:right;font-weight:bold;"><a style="color:#fff;text-decoration:none;" href="javascript:void(0)" onclick="$(this).parent().parent().slideUp();">X</div></div>');
	}else{
		$('#error .left').html($('#error .left').html() + '<br/>'+txt);
	}
}
////////////////////////////////////////////////////////////////////////////////////////
// MANEJO DE LAS PRACTICAS EN CAPTIVATE ////////////////////////////////////////////////
var checkSWFLoading = function (e){
	addControl('checkSWFLoading');
	if(!e.success || !e.ref){swfBlocked();return false;}
	 var initialTimeout = setTimeout(function (){       
			if(typeof e.ref.PercentLoaded !== "undefined" && e.ref.PercentLoaded()){
				var loadCheckInterval = setInterval(function (){
					var percent = e.ref.PercentLoaded();
					addControl('percent swf = ' + percent);
					if(percent === 100){
						clearInterval(loadCheckInterval);
						addControl('SWF LOADED ');						
						if(typeof captivate != 'undefined'){captivateGoToAndStop();}
					}
				}, 1500);
			}else{/*alert( 'SWF no encontrado.')*/}
		}, 200);
 };

function captivateGoToAndStop(){
	addControl('captivateGoToAndStop');	
	document.getElementById('myContent').style.margin = 'auto';
	var swf = CaptivateController('myContent');
	swf.gotoSlideAndStop(captivate);
	setTimeout(function (){  
		swf = CaptivateController('myContent');
		swf.pause();
		document.getElementById('myContent').style.display = 'block';
	}, 1000);
	/*swf.SetVariable('cpSkinLoader_mc.rdcmndPause', 1);
	swf.SetVariable('cpSkinLoader_mc.rdcmndGotoFrame', captivate);
	swf.style.display = 'block';*/
}

function swfBlocked(){
	addControl('FLASH BLOCKED');
	var myContent = document.getElementById('myContent');
	myContent.innerHTML = ERROR_FLASH_PLAYER;
	myContent.style.width='50%';
	myContent.style.margin='auto';
	myContent.style.border='solid 1px #ccc';
}

var _swfPractica;
function loadPractica(_url,_swf){
	_swfPractica = _swf;
	var miWin = window.open(_url,"Practica");
	miWin._swfPractica = _swfPractica;
	miWin.focus();
}

function llamadajs(notaFinal){
	alert(notaFinal);
} 

function setNumTries(){		
	if(exType=="check"){
		addControl("Mostrar Justificacion");
		showResultDiv('pregunta');
		showResultDiv('J');
	}
	if(exType=="list"){}
}


var startTime = 0
var start = 0
var end = 0
var diff = 0
var timerID = 0
function chrono(){
		end = new Date()
		diff = end - start
		diff = new Date(diff)
		var msec = diff.getMilliseconds()
		var sec = diff.getSeconds()
		var min = diff.getMinutes()
		var hr = diff.getHours()-1
		if (min < 10){
			min = "0" + min
		}
		if (sec < 10){
			sec = "0" + sec
		}
		if(msec < 10){
			msec = "00" +msec
		}
		else if(msec < 100){
			msec = "0" +msec
		}
		document.getElementById("crono").innerHTML = hr + ":" + min + ":" + sec;//+ ":" + msec
		timerID = setTimeout("chrono()", 1000);
}


function cuentaAtras(){
	var cuentaNumTxt = cuentaNum;
	addControl('## : ' + cuentaNum)
	if(cuentaNum > 0){		
		if(cuentaNumTxt<10){
			cuentaNumTxt = "0" + cuentaNum;
		}	
		var cuentaBarLeft = (parseInt(cuentaNum*100))/totalCuentaNum;
		var bgColor = "#009900";
		if(cuentaBarLeft<50){
			bgColor = "#FF6600";
		}
		if(cuentaBarLeft<25){
			bgColor = "#FF3300";
		}
		if(cuentaBarLeft<10){
			bgColor = "#FF0000";
		}
		$('#timeBar').css({
			width : cuentaBarLeft+'%',
			'background-color':bgColor
		});
		$("#cronoTxt").html(cuentaNumTxt + ' secs');		
		//setTimeout('cuentaAtras()',1000);
		cuentaNum--;
	}else{
		addControl('##2 : ' + cuentaNum);
		showPreloader('Corrigiendo...');
		$('#timeBar').css({
			width : '2px',
			'background-color':bgColor
		});
		clearInterval(cuentaAtrasTimer);
		$("#cronoTxt").html('0 secs');
		corregirEval();
	}
}	

var totalCuentaNum;
function createCrono(){
	totalCuentaNum = cuentaNum;
	$('body').append('<div id="crono" style="position:fixed;top:100px; right:20px;z-index:10;background-color:#fff;padding:3px;font-size:1.2em"><img src="../images/recursos/crono.jpg" style="vertical-align:middle"/><span id="cronoTxt">'+cuentaNum + ' secs</span><div style="width:100%;height:10px;border:1px solid #ccc;background-color:#eee"><div id="timeBar" style="width:100%;height:10px;background-color:#009900;float:right;"></div></div></div>');	 
}


function resetExercise(){
	numTries = 0;
	showSolution = false;
	hacorregido = false;
	resOk = 0;
	resKo = 0;
	resNo = 0;
	if(document.forms[0]!=undefined){
		document.forms[0].reset();
	}
}

function repeatExButton(div){
	div.append('<div class="centrado"><input name="corrige" id="botRepetir" value="Repetir" class="bot"type="button"/></div>');
	$("#botRepetir").live("click", function(){location.reload() });	
	return $('#botRepetir');
}

function markSolution(){	
	addControl("# markSolution #");	
	if(typeof exType !='undefined'){
		if(exType=="check"){
			for(i=1;i<=res.length;i++){					
				for(j=0;j<=letrasArr.length;j++){			
					var theCheck = eval('document.EF.r'+i+'['+j+']');			
					if(theCheck!= undefined){
						//addControl(theCheck.value);
						if(theCheck.value == res[(i-1)]){
							theCheck.checked = true;
						}else{
							theCheck.checked = false;
						}
					}
				}
			}
		}		
		if(exType=="list"){
			addControl("list");
			for(i=0;i<=res.length;i++){
				if(res[i]){
					document.EF["r"+(i+1)].selectedIndex = res[i];
				}			
			}
		}
	}
	//ejerType = 'sopa'; // frase, checkbox, relAll, relOne, bloques, sopa, nomina
	if(typeof ejerType !='undefined'){
		addControl('Ejercicio : ' + ejerType);
		if(ejerType=="checkbox"){	fillCheckSolution();	}
		if(ejerType=="frase")	{	fillFraseSolution();	}
		if(ejerType=="relAll")	{	fillRelAllSolution();	}
		if(ejerType=="relOne")	{	fillRelOneSolution();	}
		if(ejerType=="bloques")	{	fillBloquesSolution();	}
		if(ejerType=="sopa")	{	fillSopaSolution();		}
		if(ejerType=="nomina")	{	fillNomina();			}
	}
}	
	
////////////////////////////////////////////////////////////////////////////////////////////////
//FUNCIONES V�DEOS THINKING HEADS y PROPIOS  ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
var token;
var usuarioVideo;
var videoFile;
function getToken(_file,_id){
	token=CryptoJS.HmacSHA1('63'+_file,_id);
	token=token.toString();
	token=token.substr(0,20);
	videoFile = _file;
	var traza="";
	traza += '<ul><li>Crypto Token : ' + token + "</li>";	
	traza += '<li>Real : 6fc7357451c5c6030be6';
	traza += '</li></ul>';
	var head= document.getElementsByTagName('head')[0];
  	var script= document.createElement('script');
  	script.type= 'text/javascript';
    var videoUrl = 'http://digital.thinkingheads.com/ext/token.php?video='+videoFile+'&id_cliente=63&data='+token+'&onlydata=true&protocolo=http';
	script.src= videoUrl;
   	head.appendChild(script);
	addControl('getToken: ' + videoUrl);
	setTimeout(showThumb,1000);		
	return true;
}

var subtitlesFile;
function showThumb(){
	addControl('showThumb')
	var thumbTxt="";
	var txtFiles = "";
	try{	
		var thumbTxt = '<p style="width:100%;float:left;margin-left:20px;"><img src="'+avz_thumb+'" align="left"/></p>';
		thumbTxt +="<ul style='list-style-type:none;padding:0;margin:0;margin-left:10px;'>";
		thumbTxt += '</li><li><i>T&iacute;tulo: </i><br/><b>' + avz_titulo + '</b>';
		thumbTxt += '</li><li><i>Autor : </i><br/><b>' +avz_autor+ '</b>';
		thumbTxt += '</li><li><i>Duraci&oacute;n :</i><br/> ' + avz_duracion;
		thumbTxt += '</li><li><i>Descripci&oacute;n :</i><br/> ' + avz_descripcion;
		thumbTxt += '</li><li><a href="#" onclick="loadVideo()">Ver v&iacute;deo</a>';
		thumbTxt += '</li></ul>';
		thumbTxt += '<div id="subtitulos"></div>';
		//thumbTxt += avz_subtitulos;
		txtFiles = avz_subtitulos.split(';');		
		for(i=0;i<txtFiles.length;i++){
			var txtParams = txtFiles[i].split(',');
			if(txtParams[1] == 'es'){
				subtitlesFile = txtParams[2]
			}
		}
		$('#playerDiv').append('<img src="'+avz_imagen_video+'" controls width="100%" height="auto"></img>');
	
	}catch(err){
		thumbTxt+="<br/>Ha ocurrido un error: " + err.message +"</p>" ;
	}	
	$('#thumbs').append(thumbTxt);
	$('#video').append('<div id="subtitulos"></div><div id="subtitulos1"></div><div id="subtitulos2"></div>');
	
	//subtitlesFile = "../prueba.txt"
	/*$('#subtitulos').load(subtitlesFile, function() {		
	 	//window.open(subtitlesFile,"_blank", "status=no,toolbar=no, scrollbars=yes, resizable=no, top=100, left=100, width=600, height=400");	
	});*/
	/*$.ajax({
            url : subtitlesFile,
            dataType: "text",
            success : function (data) {
                $("#subtitulos1").html("SUBTITULOS01: " + data);
            }
        }); */ 
	  $.get(subtitlesFile, function(data) {
		data = data.split('-->');
		// $("#subtitulos2").append('<ul></ul>')
     	for(i=0;i<=data.length;i++){
			// $("#subtitulos2 ul").append('<li>'+data[i] + '</li>')
		}
		 
		 //$("#subtitulos2").html("SUBTITULOS02: " + data.length);
		 
   	 }, 'text');
}

function loadVideo(){	
	usuarioVideo = studentId();
	addControl("loadVideo : " + usuarioVideo)
	var head= document.getElementsByTagName('head')[0];
  	var script= document.createElement('script');
  	script.type= 'text/javascript';
  	script.src= 'http://digital.thinkingheads.com/ext/token.php?video='+videoFile+'&id_cliente=63&data='+token+'&protocolo=http&id_usuario=' + usuarioVideo;
	head.appendChild(script);
	setTimeout(loadVideoContent,1000);
}

function loadVideoContent(videoURL,_dest){
	addControl("loadVideoContent : " + videoURL + "   :  " + _dest);	
	if(!videoURL){
		videoURL = avz_file;
	}else{
		//comprobamos si es local o no para empaquetado terceros.
		if(localVideos){
			var urlCheck = videoURL.split('/');
			urlCheck = urlCheck[urlCheck.length-1];
			videoURL = carpetaVideos + urlCheck;
		}
	}
	if(!_dest){	_dest = 'playerDiv';}	
	var bgImage = '../js/flowplayer/videoBg.jpg';	
	var playerName = 'player'+_dest;
	
	if(typeof(iframeEx)!='undefined'){//videoTest
		bgImage = '../js/flowplayer/videoTestBg.jpg';
		playerName = _dest+'VideoTest';
	}
	
	if(detectflash()){  
		addControl('VIDEO FLASH');
		videoPlayer = '<div id="videoWrapper" style="width:100%;max-width:640px;height:0px;padding-bottom:62.5%;position:relative;margin:auto;">';
		videoPlayer  += '<a class="'+playerName+'" style="max-height:400px;width:100%;height:100%;position:absolute;left:0px;top:0px;background-image:url('+bgImage+');background-position:center"><img src="../js/flowplayer/videoPlay.png" style="margin:25% 50%;height:20%;width:auto;min-height:50px;"/></a>';
		videoPlayer  +=  '</div>';		
		$('#'+_dest).html(videoPlayer);			
		if(typeof(iframeEx)!='undefined'){//videoTest
			$('#'+_dest).css({visibility:'hidden'});
		}	
		setTimeout(function() {	
			flowplayer("."+playerName,{src:"../js/flowplayer/flowplayer-3.2.16.swf", wmode: "transparent"},{
				clip: {
					url:videoURL,
					autoPlay: true,
					autoBuffering: true
				},
				plugins: {
					//controls: null //// Pendiente de ocultar los controles en el videoTest
				},
				onStart:function(){
					getActiveMediaCurrTime();
				},
				onResume: function(){				
					$('#videoPlay').val('Pausar');
					
				},			
				onPause: function(){
					$('#videoPlay').val('Continuar');
				},
				onBeforeFinish:function(){
					//videoPercent = 100;
				}
			});			
			videoTestObject = flowplayer();
		}, 1000);
				
	} else{
		addControl('VIDEO MP4');
		if(typeof(iframeEx)!='undefined'){//videoTest
			videoPlayer = '<video id ="'+playerName+'" width="640" height="400"><source src="'+videoURL+'" type="video/mp4"></video>';
			$('#'+_dest).html(videoPlayer);
			videoTestObject = document.getElementById(playerName);
		}else{
			videoPlayer = '<video id="scorm'+playerName+'" width="100%" height="auto"style="max-width:640px" controls><source src="'+videoURL+'" type="video/mp4"></video>';
			$('#'+_dest).html(videoPlayer);
			videoTestObject = document.getElementById("scorm"+playerName);
			getActiveMediaCurrTime();
		}
		
			
	}	
	if(typeof(iframeEx)!='undefined'){//videoTest
		manageVideoTest();
	}else{
			
	}
}


// AUDIO SLIDESHOW CONTROLS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function loadAudios(soundFile,playerName,audioImg){
	addControl('LOAD AUDIOS');	
	if(detectflash()){  
		addControl('Flash');
		setTimeout(function() {				
			flowplayer('.'+playerName,{src:"../js/flowplayer/flowplayer-3.2.18.swf"},{
				clip: {
				debug:true,
				url: soundFile,
				autoPlay: false,
				autoBuffering: true,
				coverImage: { url: audioImg,
					scaling: 'orig' }
				}
			});
		}, 1000);		
	}else{
		$('.'+playerName).html('<p class="centrado" style="border:1px #ccc solid;padding-bottom:5px;"><img src="'+audioImg+'"/><br/>' +NO_FLASH_AUDIO_MSN + '</p>')
		$('.'+playerName).css({height : 'auto',width:'auto'});	
	}
}

function getActiveMediaCurrTime(){
	var percent = 0;
	if(detectflash()){ 
		startVideoProgressChecking();
	}else{
		videoTestObject.addEventListener('timeupdate', function() {
			videoPos = Math.round(videoTestObject.currentTime);
			var videoDuration = Math.round(videoTestObject.duration);
			$('#time').html(videoPos +' de ' +videoDuration+ ' secs');
			videoPercent = (videoPos*100)/videoDuration;			
			$('#percent').css({
				width : videoPercent + '%'			  
			})		
			
		});		
	}
	return true;
}

/* flowplayer(): control de reproducción /////////////////////////////////////////////////////////////////////////////////////////////////////*/
var videoProgressInterval;
function startVideoProgressChecking() {
    videoProgressInterval = setInterval(checkVideoProgress, 1000);
}
function stopVideoProgressChecking() {
    clearInterval(videoProgressInterval);  
}
function checkVideoProgress() {
    var time_completed = flowplayer().getTime();
    var total_time = flowplayer().getClip().fullDuration;
    var percent_done = Math.floor((time_completed / total_time) * 100);
	$('#percent').css({	width : percent_done + '%'});
	videoPercent = percent_done;
	var videoPos = Math.round(flowplayer().getTime());
	$('#time').html(videoPos +' de ' + Math.round(total_time)+ ' secs');	
	
	if(typeof(iframeEx)!='undefined'){//videoTest
		var nextStep = pregLaunchTime[pregPos];
		$('#time').html(videoPos +' de ' +Math.round(total_time)+ ' secs');		
		if(videoPos == nextStep){
			launchIframeEx(videoTestObject);
		}
	}
}



var nextTxtAudioPos = 0;
function manageAudio(){	
	for(i=0;i<audioFiles;i++){		
		if(!audioPermitted){ // si no admite HTML5
			$('.imgAudio'+(i+1)).remove();
			$('audio').remove();
			startAudioProgressChecking();
		}else{
			$('.audioDiv'+(i+1)).remove();
			$('.imgAudio'+(i+1)).attr('src',eval('audioImg'+(i+1)));
			$('.imgAudio'+(i+1)).css({clear : 'both',display:'block'});				
			//html5 audio ....
			//setTimeout(function() {	
			var audioObject = document.getElementById('sonido'+(i+1));	
			nextTxtAudioPos = 0;				
			audioObject.addEventListener('timeupdate', function() {
				audioPos = Math.round(audioObject.currentTime);
				addControl('audioPos : ' + audioPos);
				var audioDuration = Math.round(audioObject.duration);
				$('#time').html(audioPos +' de ' +audioDuration+ ' secs');
				var percent = (audioPos*100)/audioDuration;
				$('#percent').css({
					width : percent + '%'			  
				})
				var nextStep = eval('audioTextChangeTime')[nextTxtAudioPos];
				if(audioPos == nextStep){					
					launchAudioEvent();
				}
			});
		//}, 1000);
		}
	}
	return true;
}

/* flowplayer(): control de reproducción /////////////////////////////////////////////////////////////////////////////////////////////////////*/
var audioProgressInterval;
function startAudioProgressChecking() {
    audioProgressInterval = setInterval(checkAudioProgress, 1000);
}
function stopAudioProgressChecking() {
    clearInterval(audioProgressInterval);  
}
function checkAudioProgress() {	
    var time_completed = flowplayer().getTime();
   	var audioPos = Math.round(flowplayer().getTime());
	var nextStep = eval('audioTextChangeTime')[nextTxtAudioPos];
	if(audioPos == nextStep){					
		launchAudioEvent();
	}
}
function launchAudioEvent(){	
	if(typeof audioTextChangeTime !='undefined'){
		if($('#botNextAudioText').length<=0){
			var addBot = $('.listNext').clone().appendTo('.controls');
			addBot.attr('id','botNextAudioText');
			$('#botNextAudioText').removeClass('listNext')
			$('#botNextAudioText').unbind('click').click();
			nextTxtAudioPos++;						
			setTimeout(function(){
				$('#botNextAudioText').remove();		 
				}, 1000);
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// pop up ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var numPops = 0;

function createAlert(_txt,_title){
	showPreloader('Ampliando info...');
	if(!_title){_title="";}	
	var popup = '<div id="pop'+numPops+'" class="popUp" style="visibility:hidden"> <div id="popBar'+numPops+'" class="popBar degraded"><span class="popTitle">'+_title+'</span><a title="cerrar"><img src="../images/recursos/botClose.png" style="float:right;vertical-align:middle;cursor:pointer;" alt="cerrar"/></a></div> <div id="popContent" class="popTxt"></div> </div>';
	$('body').append(popup);	
	
	$('#pop'+numPops + ' #popBar'+numPops+ ' a').on("click", function(e){
				hideObj($(this).parent().parent(),true);
				hideObj($('#preloader'),true);
				if(typeof cuentaNum != 'undefined'){
					cuentaAtrasTimer = setInterval("cuentaAtras()", 1000);
				}
	});	
	
	var _objPopDiv = $('#pop'+numPops);	
	var _objPopDivContent = $('#pop'+numPops +' #popContent');
	if(typeof _txt == 'object'){
		_txt.show();
	}
	_objPopDivContent.append(_txt);
	
	_objPopDivContent.find('img').each(function(item){
		//alert(item)											
	});
	
	managePopDrag(_objPopDiv,_objPopDivContent,$("#pop"+numPops+" .popBar"));
	$('#preloaderSmall').hide();
	centerDiv(_objPopDiv);
	

}

// Funcionalidad del drag de las ventanas flotantes ///////////////////////////////////////////////////////////////////////
function managePopDrag(_obj,_cancel,_handle){
	//addControl("## managePopDrag ##" + _obj.attr("id") + " - " + _handle.attr('class'));		
		_handle.unbind("click");
		_handle.css('cursor','move');
		//$(function() {
			_obj.draggable({
				revert: false,
				cancel: _cancel,
				handle: _handle,
				opacity: 0.35
				
				//start: function(){/*managePopLevels(_obj);*/},
				//drag: function(){},
				//stop: function(){} 
			});
		//});
};


var screenW;
var screenH;
function getSpaceDimensions(){	
  if (typeof window.innerWidth != 'undefined') {
    screenW =  window.innerWidth;
    screenH = window.innerHeight;
   
  }else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth !=
      'undefined' && document.documentElement.clientWidth != 0)
  {
	  screenW = document.documentElement.clientWidth;
	  screenH = document.documentElement.clientHeight;
  }else{
    screenW = document.getElementsByTagName('body')[0].clientWidth;
    screenH = document.getElementsByTagName('body')[0].clientHeight;
  }
	return true;
}



function showObj(obj){
	obj.css({display:'block',opacity:0});
	obj.animate({
		opacity: 1
		}, 500, function() {
		
	});
}
function hideObj(obj,del){
	obj.animate({
		opacity: 0
		}, 500, function() {
			if(del){
				obj.remove();
			}
	});
}


function centerDiv(_div){	
	getSpaceDimensions();
	_div.css("position","fixed");
	_div.css("opacity",0);
	_div.css("visibility","visible");
	var OH = _div.outerHeight(true);
	var OW = _div.outerWidth(true);
	if(OH > screenH){OH = screenH - 50;}	
	_div.animate({
		top:((((screenH - OH)*100)/screenH)/2 )+"%",
		left: ((((screenW - OW)*100)/screenW)/2 )+"%"
	})
	_div.css("z-index", 50);	
	showObj(_div);
	return true;	 
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MANEJO DE PRECARGAS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function showPreloader(_txt){
	addControl('showPreloader()');
	if(_txt == undefined){_txt='loading content...'};
	if(!$("#preloader").length){
		var preloader = '<div id="preloader" class="preloader"><div id="preloaderSmall" class="preloaderSmall"><span class="Texto" style="margin-left:60px;margin-top:15px;margin-right:10px; float:left">'+_txt+'</span></div></div>';
		$("body").append(preloader);
	}else{
		$("#preloader #preloaderSmall .Texto").html(_txt);
	}
	$('#preloader').css("display","block");
	$('#preloader').css("position","fixed");
	$('#preloader').css('opacity','0.6');
	centerDiv($("#preloader #preloaderSmall"));
}

function hidePreloader(){
	if($("#preloader").length>0) {	
		addControl('hidePreloader()');
		$('#preloader').fadeTo('slow',0, function() {
			$('#preloader').hide();
		});	
	}
}

function roundCorners(){	//Reemplazado por css
	addControl("CSS ROUNDED");
	return true;
	/*if(browser !='ie'){
		try{
			$(".rounded").corner("10px"); 
			$(".roundedTop").corner("top"); 
			$(".roundedBottom").corner("bottom");
			$(".roundedRight").corner("right");
			$(".roundedLeft").corner("left");	
		}catch(e){
			//alert(e)
		}
	}*/
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MANEJO DE CAPAS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function showDiv(_div){	
	$( "div[id^='bloque']" ).slideUp( "fast", function() {});
	$("div[class|='listEscalablecont']").slideUp( "fast", function() {});
	if($('#'+_div).is(":visible")){
			$('#'+_div).slideUp( "slow", function() {});
		}else{
			$('#'+_div).slideDown( "slow", function() {});
		}
	showSubDiv("_div");
	showSubSubDiv("_div");
}

function showSubDiv(_div){	
	$( "div[id^='bloqueB']" ).slideUp( "fast", function() {});
	if($('#'+_div)!=null){
		if($('#'+_div).is(":visible")){
			$('#'+_div).slideUp( "slow", function() {});
			
		}else{
			$('#'+_div).slideDown( "slow", function() {});
		}
		showSubSubDiv("_div");
	}
}

function showSubSubDiv(_div){	
	$("div[id^='bloqueC']" ).slideUp( "fast", function() {});
	if($('#'+_div)!=null){
		if($('#'+_div).is(":visible")){
			$('#'+_div).slideUp( "slow", function() {});			
		}else{
			$('#'+_div).slideDown( "slow", function() {});
		}
	}
}

function showDivMulti(_div1,_div2,_bot){	
	visto = false;
	if(document.getElementById(_div1)!=null){
		if(document.getElementById(_div1).style.display==''){
			visto=true;
		}
	}
	if(document.getElementById(_div2)!=null){
		if(document.getElementById(_div2).style.display==''){
			visto=true;
		}
	}
	for(i=0;i<50;i++){
		if(document.getElementById("bloque"+i)!=null){
			document.getElementById("bloque"+i).style.display = 'none';
		}
		if(document.getElementById("b"+i)!=null){
			document.getElementById("b"+i).className="inactiveDiv";
		}
	}
		{
		if(document.getElementById(_bot)!=null){
			document.getElementById(_bot).className="activeDiv";
		}
		if(visto){
			if(document.getElementById(_div1)!=null)
			document.getElementById(_div1).style.display="none";
			if(document.getElementById(_div2)!=null)
			document.getElementById(_div2).style.display="none";
		}else{
			if(document.getElementById(_div1)!=null)
			document.getElementById(_div1).style.display="";
			if(document.getElementById(_div2)!=null)
			document.getElementById(_div2).style.display="";
		}		
	}	
}

function hideDiv(_clp){
	_clp.empty();
	_clp.hide();
}

function isDefined(variable) {
    return (typeof(window[variable]) == "undefined")?false: true;
}

function pageName(){	
	var a = location.href;
	s = a.lastIndexOf(".html");
	p = a.lastIndexOf("unidad");
	nombrepag = a.substring((s+5), p);
	return nombrepag;
}

function roundNumber(num){
   return (num.toString().indexOf(".") !== -1) ? num.toFixed(2) : num;
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// DETECCIÓN DEL BROWSER ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function detectBrowser(){	
	var objappVersion = navigator.appVersion;
	var objAgent = navigator.userAgent;
	var objbrowserName  = navigator.appName;
	var objfullVersion  = ''+parseFloat(navigator.appVersion); 

	// In Chrome 
		if ((objOffsetVersion=objAgent.indexOf("Chrome"))!=-1) {
		 objbrowserName = "Chrome";
		 objfullVersion = objAgent.substring(objOffsetVersion+7);
		}
		// In Microsoft internet explorer
		else if ((objOffsetVersion=objAgent.indexOf("MSIE"))!=-1) {
		 objbrowserName = "ie";
		 objfullVersion = objAgent.substring(objOffsetVersion+5);
		}
		// In Firefox
		else if ((objOffsetVersion=objAgent.indexOf("Firefox"))!=-1) {
		 objbrowserName = "Firefox";
		}
		// In Safari 
		else if ((objOffsetVersion=objAgent.indexOf("Safari"))!=-1) {
		 objbrowserName = "Safari";
		 objfullVersion = objAgent.substring(objOffsetVersion+7);
		 if ((objOffsetVersion=objAgent.indexOf("Version"))!=-1) 
		   objfullVersion = objAgent.substring(objOffsetVersion+8);
		}
		addControl("BROWSER : "+ objbrowserName);
		//showBrowserInfo()
		return objbrowserName;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DETECTOR DE FLASH PLAYER //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function detectflash(){
    if (navigator.plugins != null && navigator.plugins.length > 0){
        return navigator.plugins["Shockwave Flash"] && true;
    }
    if(~navigator.userAgent.toLowerCase().indexOf("webtv")){
        return true;
    }
    if(~navigator.appVersion.indexOf("MSIE") && !~navigator.userAgent.indexOf("Opera")){
        try{
            return new ActiveXObject("ShockwaveFlash.ShockwaveFlash") && true;
        } catch(e){}
    }
    return false;
}


/* TABLA RESULTADOS EJERCICIOS ///////////////////////////////////////////////////////////////////////////////////////////////////////*/
function showResultsList(Arr,nota){	
	addControl('### showResultsList')
	 var resultadosList = '<div class="tituloSim degraded"><strong>RESULTADOS:</strong></div><span class="resultTxt"></span><div style="padding:1%;" class="padS">Estos son tus resultados de las situaciones planteadas:<ul class="resultadosUl"><li><b>Situación</b></li> <li><b>Intentos</b><li><b>Calificación</b></li></li></ul><ul id="resultsLi" class="resultadosUl"></ul></div>';
	$('#resultados').append(resultadosList);	
	var txt = "";
	var sinContestar = 0;
	var totalSteps = Arr.length;
	for(i=0;i<totalSteps;i++){
		
		var result = "";			
		if(Arr[i]==0){	result = '<img src="../images/check_false.gif" style="vertical-align:middle"/>Incorrecta'; 	}			
		if(Arr[i]==1){	result = '<img src="../images/check_true.gif" style="vertical-align:middle"/>Correcta';	;	}
		if(Arr[i]==2){	result = '<img src="../images/check_true_m.gif" style="vertical-align:middle"/>Mejorable'; 	}
		if(Arr[i]==3){	result = '<img src="../images/check_nulo.gif" style="vertical-align:middle"/>Sin Contestar';sinContestar++;}
		
		var numResps = 1;
		
		if(typeof Arr[i] !='undefined'){				
				txt += '<li>'+stepsTitlesArr[i]+'</li><li>'+ numResps + '</li><li> '+result + '</li>';
			}else{				
				txt += '<li>'+stepsTitlesArr[i]+':</li><li>0</li><li>'+result+'</li>';
		}
	}	
	var notaTxt=""; 
	if(nota >= NotaCorte){
		notaTxt += '<img style="vertical-align:middle;margin-right:5px" src="../images/correcionOk.jpg"/><span class="notaOk">Muy bien!!!.</span> Has superado el ejercicio. ';
		nota = '<span class="notaOk">'+nota+'</span>';			
		};
	if(nota < NotaCorte){
		notaTxt += '<img style="vertical-align:middle;margin-right:5px;" src="../images/correcionKo.jpg"/><span class="notaKo">No lo has hecho bien!!!.</span> Te recomendamos que repases los contenidos. ';
		nota = '<span class="notaKo">'+nota+'</span>';
	}
	
	notaTxt += "<br/>Has conseguido <b>" + nota + "</b> puntos sobre <b>" + scoreMax + '</b>.';
	//alert(sinContestar +' - ' +totalSteps)
	if(sinContestar>=totalSteps){
		notaTxt = '<img style="vertical-align:middle;margin-right:5px" src="../images/check_nulo.gif"/><b>No has contestado al ejercicio.</b> ';
		notaTxt += "";
	}	
	$('#resultsLi').append(txt);
	$('.resultTxt').append(notaTxt);	
	$('#resultados').show();
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
/* OBJETIVOS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
var totObjs;
function showObjetives(){	
	addControl('## showObjetives')
	totObjs =  $('#objetivos > li').length;
	var counter = 0;	
	replaceObjImg(counter);	
}

function replaceObjImg(num){
	var imagen = '../images/recursos/objetivos/personaje'+num+'.gif';
	//addControl('replaceObjImg : ' + imagen);
	var newObj = $('.objImg').clone();

	newObj.css({
		'z-index': parseInt(num+1),
		position:'absolute',
		left:0
	})
	newObj.attr('data-x',newObj.css('left'))
	newObj.css({opacity:0,left:-500});
	newObj.attr('data-pos',num)
	$('#objetivos li:eq('+(num)+')').attr('data-pos',num);	
	
	$('<img class="objImg" data-pos="'+num+'" style="display:none"/>').one("load", function() {
  		var obj = $(this);		
		obj.css({
			'z-index': parseInt($(this).attr('data-pos')+1),
			display:'block',
			position:'absolute',
			top:0,
			opacity:0,
			left:-500
		})
		
		obj.animate({
			opacity: 1,
			left : 0
		}, 1000, function() {
			var liObj = $('#objetivos li:eq('+obj.attr('data-pos')+')');			
			liObj.animate({
					opacity: 1,
					top : $(this).attr('data-y')
				}, 1000, function() {	
					var pos = parseInt($(this).attr('data-pos'))+1;
					if(pos < totObjs) {
						replaceObjImg(pos);	
					}
				});
			});
	}).attr('src', imagen).appendTo("#objBg");
}




