var currentPage;

/*
* Esta funcion es para setear variables generales para el funcionamiento del curso
*/
var globalSym ;
var canGoToNext=false;
var hasText = false;
var currentMax = 0 ; 
var amPages = 35;
var initPage = 1;
function setProperties(sym,page ){
	if(typeof window.parent.initCourse !== "undefined"){
	console.log("aca2")
	window.parent.initCourse()
	}
	currentPage = page; 
	globalSym = sym;
	checkBookmark();
	console.log("Pagina actual-->"+currentPage);
	sym.$("close-button").bind( "click",closePage).css("cursor","pointer");
	sym.$("next-button").bind( "click",nextPage).css("cursor","pointer");
	jQuery(sym.$("next-button")).css("opacity","0.5","cursor","pointer")
	jQuery(sym.$("back-button")).css("opacity","0.5","cursor","pointer")
	sym.$("back-button").bind( "click",prevPage).css("cursor","pointer");
	sym.$("home-button").bind( "click",backToHome).css("cursor","pointer");
	jQuery(".hide").hide();
	//jQuery(globalSym.$("help-button")).hide(); //Se puso esta linea para desactivar las intrucciones	
	jQuery(".direction-button, .download-button").css("cursor","pointer");
	jQuery(".direction-button, .download-button").hide();
	canGoToNext=false;
	configureInstructions();
	jQuery(".direction-button").bind( "click", handleDirection); 
	
}



function getVal(obj)
{
	return obj.id.split("-")[1]; 
}

function blinkIns(){
	$(globalSym.$("instman")).css({"opacity":0.5}).animate({opacity:'1'}, 900, 
		function(){
			$(globalSym.$("instman")).animate({opacity:0.5}, 900, blinkIns);
		});
}

function blinkObj(){
	jQuery(blinkable).each(function(){
		if(!jQuery(this).hasClass("noblink"))
		jQuery(this).animate({opacity:'0.5'}, 265).delay(265).animate({opacity:1}, 265);
	})
	setTimeout(blinkObj,1800)
}

var blinkable
function addBlink(obj){
	jQuery(obj).removeClass("noblink")
	blinkable = obj
	blinkObj();
}


function blinkObj2(){
	jQuery(blinkable2).each(function(){
		if(!jQuery(this).hasClass("noblink"))
		jQuery(this).animate({opacity:'0.5'}, 265).delay(265).animate({opacity:'0.8'}, 265);
	})
	setTimeout(blinkObj2,1800)
}

var blinkable2
function addBlink2(obj2){
	jQuery(obj2).removeClass("noblink")
	blinkable2 = obj2
	blinkObj2();
}

function removeBlink2(){
	jQuery(blinkable2).addClass("noblink")
	jQuery(blinkable2).clearQueue().stop().css({"opacity":1});
}

function removeBlink(){
	jQuery(blinkable).addClass("noblink")
	jQuery(blinkable).clearQueue().stop().css({"opacity":1});
}


function bindAsTooltip(the_parent,the_child,hideParent){
	jQuery(globalSym.$(the_child)[0]).hide();

	globalSym.$(the_parent).mouseenter( function () {
		if(hideParent)
			jQuery(globalSym.$(the_parent)[0]).stop().animate({opacity: 0}, 100);
		jQuery(globalSym.$(the_child)[0]).stop().fadeIn(500);
	 }).mouseleave( function () {
	 	if(hideParent)
	 		jQuery(globalSym.$(the_parent)[0]).stop().animate({opacity: 1}, 100);
		jQuery(globalSym.$(the_child)[0]).stop().fadeOut();
	 });
}


function configureInstructions(){
	jQuery(globalSym.$("down")).hide();
	if(globalSym.$("instruction")[0]){
		jQuery(globalSym.$("instruction")).hide();
		addBlink(globalSym.$("help-button")[0])
		jQuery(globalSym.$("help-button")[0]).css("cursor","pointer").click(function(){
			//removeBlink(globalSym.$("help-button")[0]) -- Al quitar esta línea se resuelve el problema de quoitar blink en menu cuando se presiona help-button
			jQuery(globalSym.$("instruction")[0]).fadeToggle();
			jQuery(globalSym.$("down")[0]).fadeToggle();
		})
	}
}



var currentAmDrag=0;
var callbackGoodDrag= function(){}
var callbackBadDrag= function(){}
var callbackAllDrags= function(){}
var justDrag=false;
var goodDragRevert = false;
var the_draggable, the_dropabble;
var a, q, s; // Declaré estas vriables como globales
var position={left:0,top:0}
function dragAndDropActivity(){
	var amountToDrag = jQuery(".draggable").length
	jQuery( ".draggable" ).css("cursor","pointer").draggable({
		revertDuration: 200,
		revert:true,
		 start: function(event, ui) {
	        position.left = parseInt(ui.helper[0].style.left.split("px")[0]);
	        position.top = parseInt(ui.helper[0].style.top.split("px")[0]);
	        ui.originalPosition.top = position.top;
        	ui.originalPosition.left = position.left;
	    },
		drag:function(event, ui ){
			removeBlink(jQuery(this))
			var strsc = $("#Stage")[0].style.transform;
			var zoomScale=1
			if(strsc!==null && strsc!="")
				zoomScale = parseFloat((strsc.split("scale(")[1]).substr(0,6))
	        ui.position.left =  ui.position.left/zoomScale;
	        ui.position.top = ui.position.top/zoomScale;
		}
	});
	jQuery( ".droppable" ).droppable({
		drop: function( event, ui ) {
		the_dropabble = this;
		the_draggable = ui.draggable[0];
		 q = getVal(this); //Modifique esta linea a variables globales para poder utilizarlas en animate
		 a =  getVal(ui.draggable[0]) ; //Modifique esta linea a variables globales para poder utilizarlas en animate
		//console.log(q,"=", a)
		if(parseInt(q)==parseInt(a) || justDrag){
				callbackGoodDrag();
				//console.log(">>aca",the_draggable)
				jQuery(ui.draggable[0]).draggable( 'option', 'revert', goodDragRevert );
				jQuery(ui.draggable[0]).draggable( "disable" );
				jQuery(ui.draggable[0]).hide();//agregué esta linea para ocultar el dragable
				//jQuery(sym.$("txt-"+ a)).fadeIn();//agregué esta linea para mostrar la respuesta
				currentAmDrag++;
				if(!justDrag)
					playSound("correcto")
				if(currentAmDrag==amountToDrag){
					callbackAllDrags();
				}
		  }else{
		  		callbackBadDrag();
		  		if(!justDrag)
					playSound("incorrecto")
		  }
		  tempY="";
		}
	});
}

function dragFix(event, ui) {
    var contWidth = containmentArea.width(), contHeight = containmentArea.height();
    ui.position.left = Math.max(0, Math.min(ui.position.left / percent , contWidth - ui.helper.width()));
    ui.position.top = Math.max(0, Math.min(ui.position.top  / percent,  contHeight- ui.helper.height()));
}

var currentQuestion=1;
var arrAnswers = new Array();
var callbackGoodQuestion= function(){}
var callbackBadQuestion= function(){}
var callbackAllQuestions= function(){}
var lockQuestion=false
function questionActivity(){
	
	jQuery(".btn").css("cursor","pointer").on("click",function(){
		if(lockQuestion) return false;
		lockQuestion=true;
		if(getVal(this)==arrAnswers[currentQuestion-1]){
			
			playSound("correcto")
			jQuery(".item").delay(500).fadeOut();
			callbackGoodQuestion()
			if(currentQuestion==arrAnswers.length){
				jQuery(".btn").off("click");
				callbackAllQuestions()
			}
			else{
				
				currentQuestion++;
				jQuery(globalSym.$("question-"+currentQuestion)).delay(1000).fadeIn(function(){lockQuestion=false;});
			}
		}else{
			callbackBadQuestion();
			setTimeout(function(){lockQuestion=false;},1000)
			playSound("incorrecto")
		}

	});
}

var hideCurrent = false;
var animateReveal = false;//este se puede automatizar por una decision que mire cuantos items hay para mostrar 
var animateSlide= false;
var typeOpacity  = 0;
var inOrder = false;
var currentActivityStep =1;
var effect =0;
var showNextFromActivity=true;
//currentActivityStep++
var callbackReveal=function(){};
function revealActivity(){
	var amount = jQuery(".btn").length
	addBlink(globalSym.$("btn-"+currentActivityStep))
	jQuery(".btn").css("cursor","pointer").click(function(){
		//console.log(jQuery(this)[0],jQuery(globalSym.$("btn-"+currentActivityStep))[0] )
		console.log(inOrder , jQuery(this)[0],jQuery(globalSym.$("btn-"+currentActivityStep))[0])
		if(inOrder && jQuery(this)[0]!=jQuery(globalSym.$("btn-"+currentActivityStep))[0]  ){
			return false;
		}

		jQuery(this).addClass("noblink")
		jQuery(this).clearQueue().stop().css({"opacity":1});		

		if(hideCurrent)
			jQuery(".item").hide();

		if(currentActivityStep==amount){
			if(showNextFromActivity)
				setTimeout(enableNext,1500) 
			console.log("callback")
			if(inOrder)
				inOrder=false;
			callbackReveal();
		}
		currentActivityStep++;
		addBlink(globalSym.$("btn-"+currentActivityStep))
		if(typeOpacity>0){
			if(typeOpacity==2){
				jQuery(".btn").css("opacity",1);
				jQuery(this).css("opacity",0.5);
			}else if(typeOpacity==3){
				jQuery(".btn").css("opacity",1);
				jQuery(this).css("opacity",0);
			}else if(typeOpacity==4){
				jQuery(this).css("opacity",0);
			}else if(typeOpacity==5){
				globalSym.getSymbol("btn-"+getVal(this)).play();

			}
			else{
				jQuery(".btn").css("opacity",0.5);
				jQuery(this).css("opacity",1);
			} 
		}

		var opt = this.id.split("-")[1];
		if(animateReveal){   
			var timeTo = 200;
			console.log("vino "+timeTo) 
			jQuery(".item-"+opt).each(function(){
				if(animateSlide)
					jQuery(this).slideDown(200);
				else{
					jQuery(this).fadeIn(timeTo);	
				}
				timeTo+=500;
			})
		}else{
			if(animateSlide){
				jQuery(globalSym.$("ans-"+opt)).slideDown();			
			}
			else
				jQuery(globalSym.$("ans-"+opt)).fadeIn();
				jQuery(globalSym.$("btn-closeAns")).fadeIn(); //Declarar un botón llamado btn-closeAns
		}
		
	});
}

function revealActivity2(){
	var amount = jQuery(".btn").length
	addBlink(globalSym.$("btn-"+currentActivityStep))
	jQuery(".btn").css("cursor","pointer").click(function(){
		//console.log(jQuery(this)[0],jQuery(globalSym.$("btn-"+currentActivityStep))[0] )
		console.log(inOrder , jQuery(this)[0],jQuery(globalSym.$("btn-"+currentActivityStep))[0])
		if(inOrder && jQuery(this)[0]!=jQuery(globalSym.$("btn-"+currentActivityStep))[0]  ){
			return false;
		}

		jQuery(this).addClass("noblink")
		jQuery(this).clearQueue().stop().css({"opacity":1});		

		if(hideCurrent)
			jQuery(".item").hide();

		if(currentActivityStep==amount){
			if(showNextFromActivity)
				setTimeout(enableNext,1500) 
			console.log("callback")
			if(inOrder)
				inOrder=false;
			callbackReveal();
		}
		currentActivityStep++;
		//addBlink(globalSym.$("btn-"+currentActivityStep))
		if(typeOpacity>0){
			if(typeOpacity==2){
				jQuery(".btn").css("opacity",1);
				jQuery(this).css("opacity",0.5);
			}else if(typeOpacity==3){
				jQuery(".btn").css("opacity",1);
				jQuery(this).css("opacity",0);
			}else if(typeOpacity==4){
				jQuery(this).css("opacity",0);
			}else if(typeOpacity==5){
				globalSym.getSymbol("btn-"+getVal(this)).play();

			}
			else{
				jQuery(".btn").css("opacity",0.5);
				jQuery(this).css("opacity",1);
			} 
		}

		var opt = this.id.split("-")[1];
		if(animateReveal){   
			var timeTo = 200;
			console.log("vino "+timeTo) 
			jQuery(".item-"+opt).each(function(){
				if(animateSlide)
					jQuery(this).slideDown(200);
				else{
					jQuery(this).fadeIn(timeTo);	
				}
				timeTo+=500;
			})
		}else{
			if(animateSlide){
				jQuery(globalSym.$("ans-"+opt)).slideDown();			
			}
			else
				jQuery(globalSym.$("ans-"+opt)).fadeIn();
				jQuery(globalSym.$("btn-closeAns")).fadeIn(); //Declarar un botón llamado btn-closeAns
		}
		
	});
}

function getSymbol(symbol){
	return globalSym.getSymbol(symbol);
}

function bindObjects(the_parent,the_child){
	jQuery(globalSym.$(the_parent)[0]).click(function(){
		if(_class!=null)
			jQuery("."+_class).hide();
		jQuery(globalSym.$(the_child)[0]).fadeIn();
	});
}

function setTextArea( obj ){
	$(obj).html( "<textarea style='width:"+$(obj).width()+ "px;height:"+$(obj).height()+ "px; resize: none;border:none; '></textarea>" );
	hasText=true;
	
	if(arrPageTexts!=null && arrPageTexts["Pagina"+currentPage]!=undefined && arrPageTexts["Pagina"+currentPage]!='' ){
		var arrTextToFill = arrPageTexts["Pagina"+currentPage].split(",")
		jQuery(obj).find("textarea").val(arrTextToFill[getVal(obj[0])-1 ])
	}
}

function saveTexts(arrTexts){
	var arrPos = localGetBookmark().split("-");
	var dataChunk = arrPos[2]||"";

	console.log(dataChunk);
	if(dataChunk=="")
		dataChunk= new Object();
	else
		dataChunk= jQuery.parseJSON(arrPos[2]);

	dataChunk["Pagina"+currentPage] = arrTexts.join(",");
	localSetData(arrPos[0]+"-"+arrPos[1] +"-"+ JSON.stringify(dataChunk));
	
}

function localGetData(){
	if(typeof window.parent.GetDataChunk == 'function'){
		return window.parent.GetDataChunk();
	}else{
		return localStorage.getItem("bookmark-sigma-I"); 
	}
}

function localSetData(dataChunk){
	if(typeof window.parent.setBookmark == 'function'){
		 window.parent.setBookmark(dataChunk);
	}else{
		 localStorage.setItem("bookmark-sigma-I",dataChunk); 
	}
}

function localGetBookmark(){
	if(typeof window.parent.getBookmark == 'function'){
		return window.parent.getBookmark();
	}else{
		return localStorage.getItem("bookmark-sigma-I"); 
	}
}

function localSetBookmark(bookmark){
	if(typeof window.parent.setBookmark == 'function'){
		 window.parent.setBookmark(bookmark);
	}else{
		 localStorage.setItem("bookmark-sigma-I",bookmark); 
	}
}

function checkBookmark(){
	console.log(localGetBookmark())
	if(localGetBookmark()!=null ){
		var arrPos = localGetBookmark().split("-");
		//currentPage = parseInt(arrPos[0]);
		currentMax=parseInt(arrPos[1]);
	}else{
		currentPage=1;
		currentMax=1;
		localSetBookmark(currentPage+"-"+currentMax);
	}

	if(currentPage==0 && arrPos!=null && arrPos[0]>1){
		gotoPage(arrPos[0]); 
	}else{

		//var max = currentMax/*(currentPage==5 || currentPage==7)?currentMax+1:*/;

		if(currentPage>currentMax)
			currentMax=currentPage;
		
		localSetBookmark(currentPage+"-"+currentMax);
	}
}

// function checkBookmark(){
// 	var bookmark = localGetBookmark()
// 	console.log("localGetBookmark ----->",bookmark)
// 	if(bookmark!=null && bookmark!='' ){
// 		var arrPos = localGetBookmark().split("-");
// 		var dataChunk = arrPos[2]||"";

// 		currentMax=parseInt(arrPos[1]);
// 		if(currentPage>currentMax)
// 			currentMax=currentPage;

// 		if(currentPage==1 && arrPos[0]>initPage){
// 			gotoPage(arrPos[0]); 
// 		}
// 		else{
// 			dataChunk = dataChunk==""?dataChunk:"-"+dataChunk
// 			localSetBookmark(currentPage+"-"+currentMax+dataChunk);

// 			if(arrPos[2]!=undefined && arrPos[2]!=''){
// 				arrPageTexts = jQuery.parseJSON(arrPos[2])
// 			}
// 		}
// 	}else{
// 		currentPage=1,currentMax=1;
// 		localSetBookmark(currentPage+"-"+currentMax);
// 	}
// }

var arrPageTexts

function finishCourse(){
	window.parent.SetReachedEnd();
}

function enableNext(){
	jQuery(".direction-button, .download-button").fadeIn();

	jQuery(globalSym.$("next-button")).css("opacity","1","cursor","pointer");
	jQuery(globalSym.$("back-button")).css("opacity","0.8","cursor","pointer");;
	//jQuery(globalSym.$("back-button")).css("opacity","1","cursor","pointer");
	jQuery(globalSym.$("home-button")).css("opacity","1","cursor","pointer");
	jQuery(globalSym.$("txt_next")).css("opacity","1","cursor","pointer");
	jQuery(globalSym.$("txt_back")).css("opacity","1","cursor","pointer");
	addBlink(globalSym.$("next-button"));
	canGoToNext=true;
}
	
function playSound(name, pos){
	//console.log("cino aca") 
	pos =  pos | 0.1;
	globalSym.$(name)[0].currentTime = pos;  
    globalSym.$(name)[0].play();
}

function pauseSound(name){
	 globalSym.$(name)[0].pause();
}

function resumeSound(name){
	 globalSym.$(name)[0].play();
}

var myNext 
function nextPage(){
	console.log("pagina siguiente ",currentPage,canGoToNext)
	if(currentPage>amPages-1) return false;

	myNext = myNext|currentPage+1;
	if(currentPage<amPages && canGoToNext){ 
		gotoPage(currentPage+1); 
	}
}

var myBack;
function prevPage(){  
	console.log("pagina anterior ",currentPage)
	
	if(currentPage<initPage+1) return false;

	myBack = myBack|currentPage-1;
	gotoPage(myBack); 
}

function backToHome(){
	if(canGoToNext)
		gotoPage(2);
}

function handleDirection(){
	var p = this.id.split("-");
	if(currentPage<amPages && canGoToNext) 
		gotoPage(p[p.length-1]);
}

var checkAllTexts=true
function gotoPage(pos){
	var canGo = true 
	if(hasText && pos>currentPage){ //la segunda condicion es para dejar regresar asi los campos esten vacios
		var arrTexts = new Array();
		jQuery("textarea").each(function(){
			if(jQuery(this).val()=="" &&  checkAllTexts){

				alert("No has escrito en todos los campos");
				canGo = false;
				return false;
			}else{
				console.log(jQuery(this).val())
				arrTexts.push(jQuery(this).val());

			}
			
		})

		if(canGo){
			console.log(arrTexts)
			saveTexts(arrTexts); 
		} 
	}

	var max = currentMax+1; 
	console.log("vino aca-> "+pos,canGo,max,pos<=max)
	if(canGo && pos<=max)
	{   
		window.open("P"+pos+".html","_self");  
		//window.open("../P"+pos+"/P"+pos+".html","_self");   
	}
} 

function download(){
	window.open("downloads/P"+currentPage+".pdf","_blank"); 
	//window.open("../downloads/P"+currentPage+".pdf","_blank"); 
} 

function closePage(){
	console.log("cerrar pagina")
	 top.close();
}

function getRandom(min,max){
	return Math.floor(Math.random() * (max - min + 1)) + min;
}
