

//  Requires:
//  Suffix _big for the popup img  and   PopUp and Button PopUp  with id = 100
//  <div data-img-zoom  data-src="img/image.png"> <div class="stack"> Apa </div> </div>
//  class="no-style" for no decoration  and  for no pop-up use attribute:  data-no-zoom
//  data-title="Title of popup img" 
//  data-no-lock   (no lock images on drag exercises
function divImgPopUp(){
    var divImages = $('div[data-img-zoom]');
    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 contAspectRatio = MAX_WIDTH_IMG / MAX_HEIGHT_IMG;

     divImages.each(function(index){

         var divApa = $(this).find('div.stack');
         var imgSrc = $(this).attr("data-src");
         var attrZoom = $(this).attr("data-no-zoom");
         var attrLock = $(this).attr("data-no-lock");
         var attrTitle = $(this).attr("data-title");

         // Create an image in the container 

         var myImg = $("<img src='" + imgSrc + "' />").appendTo($(this));

         // Lock images 

         if( typeof divApa  !== typeof undefined && divApa !== false) {
             var heightStack = divApa.outerHeight();
             divApa.css({'position': 'absolute', 'height': heightStack,  'bottom': -heightStack })
         }

         if( typeof attrLock  == typeof undefined ) { // Lock images for default
             $(myImg).on('mousedown', function(){return false;});
         }


         //End Create Img

         if( typeof attrZoom  === typeof undefined ){ 
             // POP UP 
             var myZoom = $("<div class='zoomImg'></div>").appendTo($(this));

             myZoom.on('click', function(){
                 var content=popUp.find('#imgContainer');
                 content.html(''); //Clear any prev content
                 var baseName =  imgSrc.substr(0, imgSrc.lastIndexOf('.')) || input;
                 var fileExt = imgSrc.split('.').pop();
                 var big = baseName+"_big."+fileExt;
                 var popUpImgContainer = $('<img id="imgContainer">'); 
                 var heightApa = 0;


                 var title=popUp.find('h1');
                 if( typeof attrTitle  != typeof undefined ) { //  Set Img popup Title
                     title.text(attrTitle);
                 }
                 else{
                     title.html('&nbsp;'); //Empty by default 
                 }



                 popUpImgContainer.attr("src",big).load(function(){

                     var width = this.width; 
                     var height = this.height;


                     // Lock Img big 
                     $(this).on('mousedown', function(){return false});

                     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'});

                     popUpImgContainer.appendTo(content);  // ADDS the magic!! 

                     btPopUp.trigger('click'); // Activate pop up 

                 }); // End Load
             });
         }
     });
} // Fin Img Pop Up 

function initBtnGroup(){
        var btn = $('[btn-group]');
        $("[class*='cont-h']").css("display","none");
        $.each(btn,function(){
                console.log(this);
                $(this).click(function(){
                    var idBtnClick = $(this).attr('btn-id');
                    $(this).addClass("selected");
                    $('.cont-h'+ $(this).attr('btn-id')).effect('slide').css('display','block');sg.sound('success-low');
                    var btnGrupo = $('[btn-group ='+$(this).attr('btn-group')+']');
                        btnGrupo.each(function() {
                            var idBtn = $(this).attr('btn-id');
                            if(idBtn!=idBtnClick){
                                    $('.cont-h'+idBtn).css("display","none");
                                    $(this).removeClass("selected");
                                }                       
                        });
                    });
            });
}

//change on select

function changed(){

console.log($(this).children('option:selected').text());
console.log($(this).children('option:selected').prop('value'));


    if ($(this).children('option:selected').text() === $(this).children('option:selected').prop('value')){
        $(this).parent().parent().children('.selectric').css("background-color","green");
        sg.sound('success')
    }else{
        $(this).parent().parent().children('.selectric').css("background-color","red");
        sg.sound('error')
    }

}


function init() {
	divImgPopUp();
	$('#tab-container2').easytabs();
	initBtnGroup();
    initDragDrop('.drag', '.drop') ;
    $('select').selectric({
        onChange: changed
    });
}

function validRadio(radio){
   
    if ($(":input[name=r1]:checked").val() === "1"){
        $('#ok').click()
    }
    else {
        $('#wrong').click()
    }

}

function  validar(args, btnAcive) {

	var d1,d2, successcount = 0;

	$.each(args, function(key, value) {    

		d1 = d2 = "";
		d1 = $(value).val().replace(/\s/g, "").toLowerCase();	
		d2 = $(value).attr('success').replace(/\s/g, "");

		//Validate
		if ( d1 === d2  ) {
		
			$(value).css('background-color', '#5da066');
			successcount ++;
		}
		else {
			
			$(value).css('background-color', '#d6a5b1');
		}
	});


	if (successcount === args.length) {
		$(btnAcive).click();
		sg.sound('success');

	}
	else {
		sg.sound('error');
      
	}
}

function  validarClass(classtext, btnAcive) { 

    console.log('validar class ' +btnAcive);
  
    var args = $(classtext);
    
    var d1,d2, successcount = 0;
    $.each(args, function(key, value) {      
        d1 = d2 = "";
        d1 = $(value).val().replace(/\s/g, "").toLowerCase();        

        d2 = $(value).attr('success').replace(/\s/g, "");

        //Validate
        if ( d1 === d2  ) {           
            $(value).css('background-color', '#5da066');
            successcount ++;
        }
        else {
            $(value).css('background-color', '#d6a5b1');
            $(value).val("");
        }
    });

    if (successcount === args.length) {
        $(btnAcive).click();
        sg.sound('success');
        $('#ok').click();
    }
    else {
        sg.sound('error');
         $('#wrong').click();
       
    }
}



var normalize = function() {
  var from = "ÃÀÁÄÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç", 
      to   = "AAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc",
      mapping = {};
 
  for(var i = 0, j = from.length; i < j; i++ )
      mapping[ from.charAt( i ) ] = to.charAt( i );
 
  return function( str ) {
      var ret = [];
      for( var i = 0, j = str.length; i < j; i++ ) {
          var c = str.charAt( i );
          if( mapping.hasOwnProperty( str.charAt( i ) ) )
              ret.push( mapping[ c ] );
          else
              ret.push( c );
      }      
      return ret.join( '' );
  }
 
};

function validar1() {
    var obj = $('.inputs');
    var op = "", val = "";

    $.each(obj, function (key, value) {       
        op = "", val = "";
        op = $(value).attr('op');
        val = $(value).val();


        if (val.length > 0){
            switch(parseInt(op)) {
                    case 1:
                        if (val < 3) { $(value).css('background-color', '#d9ed8a'); } else  { $(value).css('background-color', '#e28fa8'); }
                        break;
                    case 2:
                        if (val >= -7) { $(value).css('background-color', '#d9ed8a'); } else  { $(value).css('background-color', '#e28fa8'); }
                        break;
                    case 3:
                        if ( (val >= -100) && (val < 8) ) { $(value).css('background-color', '#d9ed8a'); } else  { $(value).css('background-color', '#e28fa8'); }
                        break;
                    case 4:
                        if ( (val < -24) && (val < 9) ) { $(value).css('background-color', '#d9ed8a'); } else  { $(value).css('background-color', '#e28fa8'); }
                        break;
                    case 5:
                        if ( (val > -6) && (val < 9) ) { $(value).css('background-color', '#d9ed8a'); } else  { $(value).css('background-color', '#e28fa8'); }
                        break;
                }
        }
        else {
            $(value).css('background-color', '#e28fa8');
        }
    });
}
