// JavaScript Document
var dragElements = new Array();
var dropElements = new Array();
var dragTxtWidth = 300;
var dropTxtWidth = 300;
var space = 500;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var solDrag;
var dropWidth = 0;
var dragWidth = 0;
var dragItems = new Array();
var dropItems = new Array();
var dragImgs = new Array();
var dropImgs = new Array();
var dragTxtItems = new Array();
var dropTxtItems = new Array();
var responsesArr = new Array();
var responsesDrags = new Array();
var numElements
var img;
var enunciado;
var instrucciones;	
var feedbackOk;
var feedbackKo;
var feedback1;
var feedback2;
var feedBackNotTried;
var maxConn = 10;
var triesUsed = 0;
var dropped = false;
var one= false;
var exampleColor = "rgba(244,121,32,0.5)";	

$(window).resize(function(){});

$.fn.extend({
selectOff : function(){
this.attr('unselectable', 'on').css({
'KhtmlUserSelect' : 'none',
'MozUserSelect' : 'none'
}).each(function(i,o){
o["onselectstart"] = o['onmousedown'] = function(){return false;}
});
}
});
//Aqu� a�adimos los contenidos a los que queremos aplicar esta limitaci�n
$("#ejercicio").selectOff();
 
function relacionaAllEx(_one){
	addControl('RELACIONA ALL');
	resetRelacionaAll();
	numElements = 0;	
	one = _one
	img = relAllXML.attr('img');
	enunciado = relAllXML.attr('enunciado');	
	instrucciones = relAllXML.attr('instrucciones') + '<span style="text-align:center;display:block;">';
	dragTxtWidth = relAllXML.attr('anchoDrag');
	dropTxtWidth = relAllXML.attr('anchoDrop');
	
	if(img!=undefined){instrucciones += '<img class="imgPpal" src="'+img+'"/>';}
	instrucciones += '</span>';		
	$('#enunciadoEjer').append(enunciado);
	$('#instruccionesEjer').append(instrucciones);
	$('#instruccionesEjer').show();		

	feedbackOk = relAllXML.find("FEEDBACKOK").text();
	feedbackKo = relAllXML.find("FEEDBACK0").text();
	feedback1 = relAllXML.find("FEEDBACK1").text();
	feedback2 = relAllXML.find("FEEDBACK2").text();
	feedBackNotTried = relAllXML.find("NOTRIED").text();		 
	 
	 relAllXML.find("DRAG").each(function(){
		dragElements[numElements] = $(this).text();	
		var dragImg = $(this).attr('img');		
		if(dragImg != undefined){
			dragImgs[numElements] = $(this).attr('img');	
		}
		numElements++;		
	});
	 numElements = 0;	 
	 solDrag = relAllXML.attr('sol').split(",");
	 relAllXML.find("DROP").each(function(){
		dropElements[numElements] = $(this).text();	
		var dropImg = $(this).attr('img');		
		if(dropImg != undefined){
			dropImgs[numElements] = $(this).attr('img');	
		}
		numElements++;		
	});	
	 if(one == true){
		maxConn = dragElements.length;
	}
	var imgsLoaded = 0;
	var instImgsNum = $("#instruccionesEjer").find('img');
	instImgsNum.each(function() {
		$(this).load(function() {
	 		imgsLoaded ++;
			if(imgsLoaded>=instImgsNum.length){
				createDragAndDrop();
			}
	  	});
		
	});	
	if(instImgsNum.length<=0){createDragAndDrop();}
}
 
 function createDragAndDrop(){	
 	addControl('createDragAndDrop');
 	$('#ejercicio').empty();
	$('#corregir').empty();
	$('#ejercicio').css('visibility','hidden');	
	if(one==true){
		var botCorregir = 'onclick="javascript:corrigeDragAndDropOne()"';
	}else{
		var botCorregir = 'onclick="javascript:corrigeDragAndDrop()"';
	}	
	$('#ejercicio').append('<div id="ejercicioBase"><div id="drags" class="drags"></div><div id="drops" class="drops"></div></div>');
	$('#corregir').append('<input name="corrige" id="botCorregir" value="Corregir" class="bot" type="button" '+botCorregir+'"/>');
	
	for(i=0;i<dropElements.length;i++){			
		var items = '<div id="drop'+i+'" class="droppable" rel="'+i+'"></div>';
		if(dropImgs[i] != undefined){
			items += '<div id="dropTxt'+i+'" class="boxDrop" rel="'+i+'"><img id="imgDrop'+i+'" src="'+dropImgs[i]+'" class="dragImg"/>'+dropElements[i]+'</div>';
		}else{
			items += '<div id="dropTxt'+i+'" class="boxDrop" rel="'+i+'">'+dropElements[i]+'</div>';
		}		
		$("#drops").append(items);
		dropTxtItems.push($("#dropTxt"+i));
		dropItems.push($("#drop"+i));		
	}
	for(i=0;i<dragElements.length;i++){	
		var items = '<div id="dragTxt'+i+'" class="boxDrag" rel="'+i+'">'+dragElements[i]+'</div>';
		if(dragImgs[i] != undefined){
			items = '<div id="dragTxt'+i+'" class="boxDrag" rel="'+i+'"><img id ="imgDrag'+i+'" class="dragImg"/>'+dragElements[i]+'</div>';
		}		
		items += '<div id="drag'+i+'" class="draggable" rel="'+i+'"></div>';		
		$("#drags").append(items);
		dragItems.push($("#drag"+i));
		dragTxtItems.push($("#dragTxt"+i));
		responsesArr.push("");
		responsesDrags.push("");
	}	
	var imagesLoaded = 0;
	var totalImages = dropImgs.length + dragImgs.length 	
	addControl('totalImages: ' + totalImages);	
	$('#ejercicio img').error(function(){
		if($(this).attr('src')!='undefined'){alert("error al cargar " + $(this).attr('src'));}
		addControl("imgERROR : " +$(this).attr('id'));
	});	
	if(totalImages>0){
		for(i=0;i<dragImgs.length;i++){	
			$("#imgDrag"+i).load(function() {
				imagesLoaded ++;			
				if(imagesLoaded >= totalImages){
					calculatePositions();
				}
			}).attr('src', dragImgs[i]);
		}
		
		for(i=0;i<dropImgs.length;i++){	
			$("#imgDrop"+i).load(function() {
				imagesLoaded ++;				
				if(imagesLoaded >= totalImages){
					addControl('IMG drops loaded')
					calculatePositions();
				}
			}).attr('src', dropImgs[i]);
		}	
	}else{
		calculatePositions();	
	}
}


function calculatePositions(){
	addControl("calculatePositions")
	numDrags = dragElements.length;
	numDrops = dropElements.length;		
	for(i=0;i<dragItems.length;i++){		
		dragTxtItems[i].css("width",dragTxtWidth);
		dragItems[i].css("width",dragWidth);
		dragItems[i].css("height",dragWidth);
		var posT = (($("#dragTxt"+i).height()/2) - (dragItems[i].height()/2));
		var posL = dragItems[i].attr('posT',dragTxtItems[i].position().top - ((dragTxtItems[i].height()/2) - (dragItems[i].height()/2)));
		dragItems[i].css("top",posT);
		dragItems[i].attr('posL',posL/*dragItems[i].position().left*/);
		dragItems[i].attr('posT',posT/*dragItems[i].position().top*/);
	}	
	for(i=0;i<dropItems.length;i++){			
		dropTxtItems[i].css("width",dropTxtWidth);
		dropTxtItems[i].css("height",dropTxtItems[i].height());
		dropItems[i].css("width",dropWidth);
		dropItems[i].css("height",dropWidth);
		var posT = (($("#dropTxt"+i).height()/2)- ($("#drop"+i).height()/2) );
		dropItems[i].css("top",posT);
	}	
	var dragsH = $('#drags').outerHeight(true);
	var dropsH = $('#drops').outerHeight(true);	
	if(dropsH > dragsH ){
		var posTop = (dropsH - dragsH)/2;
		_div = $('#drags');
	}else{
		var posTop = (dragsH - dropsH)/2;		
		_div = $('#drops');
	}	
	if(posTop>15){
		_div.css({
			margin: posTop +'px 10px 10px 10px'
		});
	}			
	$('#ejercicioBase').css({
		  margin:'0 auto 0 auto',
		  width:$('#drags').outerWidth(true)+$('#drops').outerWidth(true)+20+'px'
	});	
	dragEvents();	
}


function calculatePercent(_percent,_total){
	var percent = (_percent * 100)/_total;	
	addControl('PERCENT: ' + percent)
	return percent+"%";	
}


//FUNCIONALIDAD DE LAS lineas ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function dragEvents() {
	var _initialised = false,
	jpcl = jsPlumb//.CurrentLibrary,
	_bind = jpcl.bind,		
		connections = [],
		updateConnections = function(conn, remove) {
			if (!remove) connections.push(conn);
			else {
				var idx = -1;
				for (var i = 0; i < connections.length; i++) {
					if (connections[i] == conn) {
						idx = i; 
						responsesArr[i]="";
						responsesDrags[i]="";
						break;
					}
				}
				if (idx != -1) connections.splice(idx, 1);
			}
			 if (connections.length > 0) {
                var s = "<span><strong>Connections</strong></span><table><tr><th>Scope</th><th>Source</th><th>Target</th></tr>";
				responsesArr = new Array();
				responsesDrags = new Array();
					for (var j = 0; j < connections.length; j++) {
						s = s + "<tr><td>" + connections[j].scope + "</td>" + "<td>" + connections[j].sourceId + "</td><td>" + connections[j].targetId + "</td></tr>";
						var dragArrPos = connections[j].sourceId.split('drag')[1];
						var dropArrPos = connections[j].targetId.split('drop')[1]
						responsesArr[dragArrPos]= dropArrPos;
						responsesDrags[dragArrPos]= dragArrPos;
						dropped = true;
					}
                } 
		};
	
	jsPlumb.ready(function() {
			var instance = jsPlumb.getInstance({
				DragOptions : { cursor: 'pointer', zIndex:2000 },
				PaintStyle : { strokeStyle:'#005145' },
				EndpointStyle : { width:20, height:16, strokeStyle:'#005145' },
				Endpoint : "Rectangle",
				Anchors : ["TopCenter", "TopCenter"],
				Container:"drags"
			});	
			
			// suspend drawing and initialise.
			instance.doWhileSuspended(function() {						
				// bind to connection/connectionDetached events, and update the list of connections on screen.
				instance.bind("connection", function(info, originalEvent) {
					updateConnections(info.connection);
				});
				instance.bind("connectionDetached", function(info, originalEvent) {
					updateConnections(info.connection, true);
					
				});
// configure some drop options for use by all endpoints.
				var exampleDropOptions = {
					tolerance:"touch",
					hoverClass:"dropHover",
					activeClass:"dragActive"
				};
				var dragsEndpoint = {
					endpoint:["Dot", {radius:17} ],
					anchor:"Right",
					paintStyle:{ fillStyle:exampleColor, opacity:0.5 },
					isSource:true,
					scope:'yellow',
					connectorStyle:{ strokeStyle:exampleColor, lineWidth:4 },
					connector : "Straight",
					isTarget:false
				};
				var dropsEndpoint = {
					endpoint:["Dot", {radius:17} ],
					anchor:"Left",
					paintStyle:{ fillStyle:exampleColor, opacity:0.5 },
					isSource:false,
					scope:'yellow',
					connectorStyle:{ strokeStyle:exampleColor, lineWidth:4 },
					connector : "Straight",
					maxConnections:maxConn,
					isTarget:true,
					dropOptions : exampleDropOptions,
					beforeDetach:function(conn) { 
						//return confirm("Cambiar destino?"); 
					},
					onMaxConnections:function(info) {}
				};
				maxConnectionsCallback = function(info) {};
				instance.addEndpoint(jsPlumb.getSelector(".draggable"), dragsEndpoint);
				instance.addEndpoint(jsPlumb.getSelector(".droppable"), dropsEndpoint);
				$('#ejercicio').css('visibility','visible');
			});
			onExEndLoaded();
	});	
	
};


function corrigeDragAndDrop(){	
	addControl("corrigeDragAndDrop")
	var ok= 0;
	var ko = 0;
	var nota = 0;
	var feedBack = ""; 
	var interactions = new Array();
	var dragOkVals = new Array();
	var saveDropEx = false;
	
	if(!dropped){
		showFeedback("<b>"+feedBackNotTried+"</b>")
	}else{			
		for(i=0;i<solDrag.length;i++){			
			if(solDrag[i]==responsesArr[i]){
				ok++;
				dragOkVals[i] = 1;
			}else{
				ko++;	
				dragOkVals[i] = 0;
			}
		}		
		nota = (ok*10)/solDrag.length;
		triesUsed++;
		if(nota>=NotaCorte){
			feedBack += feedbackOk;	
			saveDropEx = true;
		}else{
			if(triesUsed <= numIntentos){
				if(triesUsed==1){
					feedBack += feedbackKo;		
				}
				if(triesUsed==2){
					feedBack += feedback1;		
				}
				if(triesUsed>=numIntentos){
					feedBack += feedback2;
					saveDropEx = true;
				}
			}
		}
		//Muestro el resultado //////////////////////////////////
		var aciertos = "Respuestas correctas: " + ok;
		var fallos ="Respuestas incorrectas: " + ko;		
		
		if(saveDropEx){
			var theAnsw ="";
			for (i= 0; i <solDrag.length; i++){	
				var _val = responsesArr[i]
				if(_val==undefined){
					_val="";
				}
				theAnsw += i + ":" + _val;	
				if(i<solDrag.length-1){
					theAnsw += " - "
				}
			}
			$('#botCorregir').remove();
			showResults(ok,dragOkVals.length,triesUsed,nota);
			relacionaAllShowSolution();
			exercisesNotes[actvPage] = nota;
			exercisesInter[actvPage]= theAnsw;
			exercisesOk[actvPage]= dragOkVals;
			sendNota();	
		}
		showFeedback("<b>"+feedBack + "</b>");
	}
}

var dragOkVals;
function corrigeDragAndDropOne(){
	addControl("corrigeDragAndDropOne")
	var ok= 0;
	var ko = 0;
	var okControl = 0;
	var nota = 0;
	var feedBack = ""; 
	var acierto = false;
	var interactions = new Array();
	dragOkVals = new Array();
	var saveDropEx = false;
	if(!dropped){
		showFeedback('<b>' + feedBackNotTried+'</b>')
	}else{	
		for(i=0;i<dragItems.length;i++){
			dragOkVals[i] = "x";
		}
		for(i=0;i<dragItems.length;i++){
			acierto = false;
			for(j=0;j<solDrag.length;j++){
			//addControl(i + ' - ' + solDrag[j] + " - " +  responsesArr[i]);
				if(responsesArr[i] == "0" && parseInt(solDrag[j])== i){
					ok++;	
					okControl++;
					acierto = true;
					dragOkVals[i] = 1;
				}
			}	
			
			if(acierto==false){					
				if(responsesArr[i] == "0"){
					ko++;
					dragOkVals[i] = 0;
				}else{}
				for(j=0;j<solDrag.length;j++){
					if(responsesArr[i] == "undefined" && parseInt(solDrag[j])== i){
					}
				}	
			}
			//addControl(i + ' - ' + acierto + ' - ' +dragOkVals[i] + '    ---   '  + responsesArr[i]);
		}
	
		var valItem = scoreMax/solDrag.length;
		nota = (ok*valItem)-(ko*valItem);
		//nota = (nota*10)/100;
		if(okControl<solDrag.length/2){
			//nota = 4;	
		}
		if(nota<0){
			nota = 0;	
		}
		//addControl('ok:' +ok + '  ko:' + ko + ' NOTA: ' + nota)
		triesUsed++;		
		//addControl('triesUsed: ' + triesUsed);		
		if(nota>=NotaCorte){
			feedBack += feedbackOk;
			saveDropEx = true;
		}else{
			if(triesUsed <= numIntentos){
				if(triesUsed==1){
					feedBack += feedbackKo;		
				}
				if(triesUsed==2){
					feedBack += feedback1;		
				}
				if(triesUsed>=numIntentos){
					feedBack += feedback2;
					saveDropEx = true;
				}
			}
		}
				
		
		//Muestro el resultado //////////////////////////////////
		var aciertos = "Respuestas correctas: " + ok;
		var fallos ="Respuestas incorrectas: " + ko;
		
		//alert(feedBack + "\n" + aciertos + '\n' + fallos + "\n Nota: " + nota);
		if(saveDropEx){
			var theAnsw ="";
			$('#botCorregir').remove();
			for (i= 0; i <responsesDrags.length; i++){	
				var _val = responsesDrags[i]
				if(_val==undefined){
					_val="";
				}
				theAnsw += _val;	
				if(i<responsesDrags.length-1){
					if(_val!=""){
						theAnsw += " - ";
					}
				}
			}
			showResults(ok,solDrag.length,triesUsed,nota,ko);
			relacionaOneShowSolution();
			exercisesNotes[actvPage] = nota;
			exercisesInter[actvPage]= theAnsw;
			exercisesOk[actvPage]= dragOkVals;
			sendNota();	
		}
		showFeedback('<b>' + feedBack + '</b>');
	}
}

function relacionaAllShowSolution(){
	addControl('relacionaAllShowSolution')
	//jsPlumb.detachEveryConnection();
	for(var i=0;i<solDrag.length;i++){		
		if(solDrag[i]==responsesArr[i]){
				color = "green"
			}else{
				color = "red"
			}
		jsPlumb.connect({
			source:"drag"+i, 
			target:"drop"+solDrag[i],
			anchors:["Right", "Left" ],
			endpoint:["Dot", {radius:17} ],
			endpointStyle:{ fillStyle:color, strokeStyle:color },
			connectorStyle:{ strokeStyle:color, lineWidth:2 },
			paintStyle:{ strokeStyle:color, lineWidth:4  },
			connector : "Straight"
		});
	}
}
var fixSolArray;
function relacionaOneShowSolution(){
	addControl('relacionaOneShowSolution : ' + dragItems.length + '  solDrag.length : ' + solDrag.length);
	for(var i=0;i<dragOkVals.length;i++){
		var color = "green";		
		if(parseInt(dragOkVals[i]) == 0){
			color="red";
		}				
		if(dragOkVals[i] != 'x'){
			jsPlumb.connect({
				source:"drag"+i, 
				target:"drop0",
				anchors:["Right", "Left" ],
				endpoint:["Dot", {radius:17} ],
				endpointStyle:{ fillStyle:color },
				connectorStyle:{ strokeStyle:color, lineWidth:2 },
				paintStyle:{ strokeStyle:color, lineWidth:4  },
				connector : "Straight"
			});
		}		
	}
	fixSolArray = new Array();
	for(var i=0;i<solDrag.length;i++){
		fixSolArray[solDrag[i]] = 1;
	}
	addControl('dragOkVals : ' + dragOkVals);
	addControl('fixSolArray : ' + fixSolArray);
	
	for(var i=0;i<dragOkVals.length;i++){
		if(fixSolArray[i]!=1 && dragOkVals[i]!='x'  || fixSolArray[i]==1 && dragOkVals[i]=='x'){
			color = 'rgb(228, 198, 192)';//ko			
		}else{
			color = 'rgb(167, 199, 165)';//ok
			}	
		$('#dragTxt'+i).css('background-color',color);
	}
	
	
}


function resetRelacionaAll(){
	addControl('resetRelacionaAll');
	dragElements = new Array();
	dropElements = new Array();
	dragItems = new Array();
	dropItems = new Array();
	dragImgs = new Array();
	dropImgs = new Array();
	dragTxtItems = new Array();
	dropTxtItems = new Array();
	responsesArr = new Array();	
	dropped = false;
	triesUsed = 0;
}

function fillRelOneSolution(){
	addControl("fillRelOneSolution");	
	responsesArr = new Array();
	dropped = true;
	color = exampleColor;	
	for(var i=0;i<solDrag.length;i++){
		responsesArr[solDrag[i]]= 0;
		jsPlumb.connect({
		  source:"drag"+solDrag[i], 
		  target:"drop0",
		  anchors:["Right", "Left" ],
		  endpoint:["Dot", {radius:17} ],
		  endpointStyle:{ fillStyle:color},
		  connectorStyle:{ strokeStyle:color, lineWidth:2 },
		  paintStyle:{ strokeStyle:color, lineWidth:4  },
		  connector : "Straight"
		});
	}
}

function fillRelAllSolution(){
	addControl("fillRelOneSolution");	
	responsesArr = new Array();
	dropped = true;
	color = exampleColor;	
	for(var i=0;i<=solDrag.length;i++){
		responsesArr.push(solDrag[i]);
		jsPlumb.connect({
		  source:"drag"+i, 
		  target:"drop"+solDrag[i],
		  anchors:["Right", "Left" ],
		  endpoint:["Dot", {radius:17} ],
		  endpointStyle:{ fillStyle:color},
		  connectorStyle:{ strokeStyle:color, lineWidth:2 },
		paintStyle:{ strokeStyle:color, lineWidth:4  },
		  connector : "Straight"
		});
	}
}