// JavaScript Document
function init(){
	//imgPopUp()
};

function pause(idVideo){ 
    		$('#'+idVideo).trigger('pause'); 
		}
function initGame(){
	$('.panel').each(function(index, element) {
        $(this).removeClass('flip animated zoomOut');
    });
	//console.log('Juego inicializado');
	var firstObj = new Object();
	var secontObj = new Object();
	var count = 0;
	var selected = [];	

	$('.panel').click(function(){
		if( $.inArray($(this).prop('id'),selected) !== -1 ) {
			//console.log("El elemento ya fue seleccionado previamente por el usuario");
			return;
			}
		if( !firstObj.id ){
			firstObj.id = $(this).prop('id');
			firstObj.key = $(this).attr('key');
			$(this).addClass('flip');
			//console.log({FirstID: firstObj.id, FirstKEY: firstObj.key});	
		}else{
			secontObj.id = $(this).prop('id');
			secontObj.key = $(this).attr('key');
			$(this).addClass('flip');
			//console.log({SecontID: secontObj.id, SecontKEY: secontObj.key});
			if( firstObj.id != secontObj.id ){
				if( firstObj.key == secontObj.key ){
					setTimeout(function(){
						//console.log('El usuario encontro una pareja');
						sg.sound('success-low');
						count++;
						$('#'+firstObj.id).addClass('animated zoomOut');
						$('#'+secontObj.id).addClass('animated zoomOut');
						selected.push(firstObj.id,secontObj.id);
						firstObj.id  = undefined;
						secontObj.id = undefined;
						if( count == 5 ){
							setTimeout(function(){
								//console.log('El usuario completo el juego');
								$("[data-sg-key='99']").trigger('click');
							},1000)
						}
						//console.log({Aciertos:count,ElementosSeleccionados:selected});
					},500)					
				}else{
					setTimeout(function(){
						//console.log('El usuario no encontro una pareja');
						$('#'+firstObj.id).removeClass('flip');
						$('#'+secontObj.id).removeClass('flip');
						firstObj.id  = undefined;
						secontObj.id = undefined;	
					},500)
				}
			}else{
			//console.log('El usuario selecciono el mismo obj');
			$('#'+firstObj.id).removeClass('flip');
			firstObj.id  = undefined;
			secontObj.id = undefined;
			}	
		}		
	});
}


function imgPopUp(){
			console.log('init img_popup');
			images = $('img[big]');
			var btPopUp = $('[data-sg-id="btn-popup"][data-sg-key="100"]');
			var popUp = $('[data-sg-id="item-popup"][data-sg-key="100"]');
			var MAX_WIDTH_IMG = 900;
			var MAX_HEIGHT_IMG = 550;
			var MAX_HEIGHT_POPUP = 765;
			var contAspectRatio = MAX_WIDTH_IMG / MAX_HEIGHT_IMG;
		
			 images.each(function(){
		
				 $(this).on('click', function(){
					 var content=popUp.find('#imgContainer');
					 content.html(''); //Clear any prev content
					 var src = $(this).attr('src');
					 var baseName =  src.substr(0, src.lastIndexOf('.')) || input;
					 var fileExt = src.split('.').pop();
					 var big = baseName+"_big."+fileExt;
					 var imgContainer = $('<img id="imgContainer">'); 
		
					 imgContainer.attr("src",big).load(function(){
		
						var width = this.width;
						var height = this.height;
		
						if(width > MAX_WIDTH_IMG){
							ratio = MAX_WIDTH_IMG / width;           // get ratio for scaling image
							$(this).css("width", MAX_WIDTH_IMG);     // Set new width
							$(this).css("height", height * ratio);   // Scale height based on ratio
							height = height * ratio;                 // Reset height to match scaled image
							width = width * ratio;                   // Reset width to match scaled image
						}
		
						// Check if current height is larger than max
						if(height > MAX_HEIGHT_IMG){
							ratio = MAX_HEIGHT_IMG / height; 		 // get ratio for scaling image
							$(this).css("height", MAX_HEIGHT_IMG);   // Set new height
							$(this).css("width", width * ratio);     // Scale width based on ratio
							width = width * ratio;    // Reset width to match scaled image
						}
		
						$(this).css({'display': 'block' , 'margin': 'auto'});
		
					 imgContainer.appendTo(content);                 // ADDS the magic!! 
					 btPopUp.trigger('click');                       // Activate pop up 
		
					 }); // End Load
		
				 });
			 });
} // Fin Img Pop Up Carlos U	



function initDrag(){
	console.log('drag init');	
	$(".draggable").each(function(i, e) {
        var key = $(this).attr("data-dragkey");
		sg.setDraggable("[data-dragkey="+key+"]", {
			dropSelector: "[data-dropkey="+key+"]",
			revert: true,			
			success:function(){
				sg.sound("success");
				var drop = $("[data-dropkey="+key+"]");
				var position = drop.position();
				$(this).data("dropobjkey",key);					
				var clone = $(this).clone();
				drop.html(clone);
				clone.removeClass('draggable');	// important for dropCheck!!!			
				clone.css({'top': 0 ,'left': 0});				
				sg.destroyDraggable($(this));
				$( $(this) ).css({'background-color':'grey','cursor':'default'});													
				var resultado = dropCheck( '.draggable','.droppable');				
				console.log(resultado);
				if( resultado ){ $("div[data-sg-key='99']").trigger("click"); }
			},
			fail:function(){
				sg.sound("error");
			}
		});    
	});
}


function dropCheck( dragSelec , dropSelec ){	
		var dragObj = $( dragSelec ); 
		var dropObj = $( dropSelec ); 
		var error = 0;	
	
		dragObj.each(function() {			
			var dropKeyData = $(this).data("dropobjkey");
			if( typeof dropKeyData === 'undefined' ){			
				error++;
				console.log('false');										
				}
			});		
		if( error > 0 ){ return false }else{ return true }
}
function verificarTxt(){
	var respuestas = ['citosina','adenina','adenina','citosina'];		
	var n = 0;
	$("#form input[type=text]").each(function(i,e) {
       var originalVal = $(this).val();	   
	   var lowerCaseValue  = $(this).val().toLowerCase();
	   console.log(lowerCaseValue);
	   var valRegex = lowerCaseValue.replace(/\s+/g, '');
	   $(this).val(valRegex);
	   
	   if( valRegex == respuestas[i]){
			$(this).css('background-color','#96FAB7');	
			n++				
			}else{
				$(this).css('background-color','#F69');							
				};	
    });
	if ( n == respuestas.length){ sg.sound('success')}else{sg.sound('error')}
}