require([ 'jquery-selectric'] );
function init(){
    divImgPopUp();

    initBtnGroup();

    $('select').selectric({
        disableOnMobile: false,
    });

    $('.fraction').each(function(key, value) {
        $this = $(this)
            var split = $this.html().split("/")
            if( split.length == 2 ){
                $this.html('<span class="top">'+split[0]+'</span><span class="bottom">'+split[1]+'</span>')
            }    
    });
}

// Validation of input groups
function validarEjercicio1(groupKey){

    var rs = ["50", "112"];
    var errorInForm = 0;

    // Grupo de validacion
    groupKey  = (typeof groupKey === "undefined") ? 1 : groupKey;
    inputs = $('input[type="text"][groupKey="'+ groupKey +'"]');

    inputs.each(function(){
        var  key =  $(this).attr('keyValue'); // key to answer
        var  val =  $(this).val(); // key to answer
        val=val.toLowerCase().replace(/ /g,'');;
        var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');

        if ( val === rs[key] ){ //  No error
            divResultado.removeClass('bgError');
            divResultado.addClass('bgAcierto');

        }
        else{
            divResultado.addClass('bgError');
            divResultado.removeClass('bgAcierto');
            $(this).val('');
            errorInForm ++;
        }

    });

    if(errorInForm >0){
        $('#btPopNotOk').trigger('click');
    }
    else{
        $('#btPopOk').trigger('click');
    }
}


// Validation of input groups
function validarEjercicio2(groupKey){

    var rs = ["7", "8", "amplitud","","","12.5","" ];
    var errorInForm = 0;

    // Grupo de validacion
    groupKey  = (typeof groupKey === "undefined") ? 1 : groupKey;
    inputs = $('input[type="text"][groupKey="'+ groupKey +'"]');

    inputs.each(function(){
        var  key =  $(this).attr('keyValue'); // key to answer
        var  val =  $(this).val(); // key to answer
        val=val.toLowerCase().replace(/ /g,'');;
        var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');

        if ( val === rs[key] ){ //  No error
            divResultado.removeClass('bgError');
            divResultado.addClass('bgAcierto');

        }
        else{
            divResultado.addClass('bgError');
            divResultado.removeClass('bgAcierto');
            $(this).val('');
            errorInForm ++;
        }

    });

    if(errorInForm >0){
        $('#btPopNotOk').trigger('click');
    }
    else{
        $('#btPopOk').trigger('click');
    }
}


// Validation of input groups
function validarEjercicio3(groupKey){

    var rs = [
    "50-58"  , "10"  , "10", "10/64"  , "10/64" , "54",
    "59-67"  , "17" , "27", "17/64"  , "27/64" , "63",
    "68-76"  , "15"  , "42", "15/64"  , "42/64" , "72",
    "77-85"  , "7"   , "49", "7/64"   , "49/64" , "81",
    "86-94"  , "5"   , "54", "5/64"   , "54/64" , "90",
    "95-103" , "9"   , "63", "9/64"   , "63/64" , "99",
    "104-112", "1"   , "64", "1/64"   , "64/64" , "108",
    "64", "1"
    ];
    var errorInForm = 0;

    // Grupo de validacion
    groupKey  = (typeof groupKey === "undefined") ? 1 : groupKey;
    inputs = $('input[type="text"][groupKey="'+ groupKey +'"]');

    inputs.each(function(){
        var  key =  $(this).attr('keyValue'); // key to answer
        var  val =  $(this).val(); // key to answer
        val=val.toLowerCase().replace(/ /g,'');
        var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');

        if ( val === rs[key] ){ //  No error
            $(this).addClass('ok');
            $(this).removeClass('notok');
        }
        else if(val !== ""  ){  // Wrong option
            $(this).addClass('notok');
            $(this).removeClass('ok');
            $(this).val('');
            errorInForm ++;
        }
        else{ //Empty
            errorInForm ++;
            $(this).removeClass('notok');
        }


    });

    if(errorInForm >0){
        $('#btPopNotOk').trigger('click');
    }
    else{
        $('#btPopOk').trigger('click');
    }
}

// Validation of input groups
function validarEjercicio4(groupKey){

    var rs = ["6", "6"];
    var errorInForm = 0;

    // Grupo de validacion
    groupKey  = (typeof groupKey === "undefined") ? 1 : groupKey;
    inputs = $('input[type="text"][groupKey="'+ groupKey +'"]');

    inputs.each(function(){
        var  key =  $(this).attr('keyValue'); // key to answer
        var  val =  $(this).val(); // key to answer
        val=val.toLowerCase().replace(/ /g,'');
        var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');

        if ( val === rs[key] ){ //  No error
            $(this).addClass('ok');
            $(this).removeClass('notok');
        }
        else if(val !== ""  ){  // Wrong option
            $(this).addClass('notok');
            $(this).removeClass('ok');
            $(this).val('');
            errorInForm ++;
        }
        else{ //Empty
            errorInForm ++;
            $(this).removeClass('notok');
        }


    });

    if(errorInForm >0){
        $('#btPopNotOk').trigger('click');
    }
    else{
        $('#btPopOk').trigger('click');
    }
}


// Validation of input groups
function validarEjercicio5(groupKey){

    var rs = [
    "7.89-13.89"   , "6"  , "6", "6/30"  , "6/30"  , "10.89",
    "13.89-19.89"  , "2"  , "8", "2/30"  , "8/30"  , "16.89",
    "19.89-25.89"  , "5"  , "13", "5/30" , "13/30" , "22.89",
    "25.89-31.89"  , "9"  , "22", "9/30" , "22/30" , "28.89",
    "31.89-37.89"  , "7"  , "29", "7/30" , "29/30" , "34.89",
    "37.89-43.89"  , "1"  , "30", "1/30" , "30/30" , "40.89",
    "30", "1"
    ];
    var errorInForm = 0;

    // Grupo de validacion
    groupKey  = (typeof groupKey === "undefined") ? 1 : groupKey;
    inputs = $('input[type="text"][groupKey="'+ groupKey +'"]');

    inputs.each(function(){
        var  key =  $(this).attr('keyValue'); // key to answer
        var  val =  $(this).val(); // key to answer
        val=val.toLowerCase().replace(/ /g,'');
        var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');

        if ( val === rs[key] ){ //  No error
            $(this).addClass('ok');
            $(this).removeClass('notok');
        }
        else if(val !== ""  ){  // Wrong option
            $(this).addClass('notok');
            $(this).removeClass('ok');
            $(this).val('');
            errorInForm ++;
        }
        else{ //Empty
            errorInForm ++;
            $(this).removeClass('notok');
        }


    });

    if(errorInForm >0){
        $('#btPopNotOk').trigger('click');
    }
    else{
        $('#btPopOk').trigger('click');
    }
}

//validarAllSelects(1, results=[1,2]);
function validarAllSelects(groupKey, results){

    var selects = $('select[groupkey='+groupKey+']');
    var errors = 0;

    selects.each(function(){
            var valSelected = $(this).val();
            var keyValue= $(this).attr('keyvalue');
            var resultado = $('.resultado[groupkey='+groupKey+'][keyvalue='+keyValue+']');


            if( results[keyValue] == valSelected){
                resultado.addClass('bgAcierto');
                resultado.removeClass('bgError');
                $(this).attr('disabled','disabled').selectric('refresh');
            }
            else if(valSelected !== 0  ){  // Wrong option
                resultado.addClass('bgError');
                resultado.removeClass('bgAcierto');
                errors++;
            }
            else{  // 0 ==  Empty first element
                resultado.removeClass('bgAcierto');
                resultado.removeClass('bgError');
                errors++; // in this case Empty == Error 
            }

    });

    if (!errors){
        $('#btPopOk').trigger('click');
    }
    else{
        $('#btPopNotOk').trigger('click');
    }
}

// <button class="naranja " btn-group="1" btn-id="1">1</button>
// <p class="texto1 cblanco cont-h1  txt">Test</p>
function initBtnGroup(){
    var btn = $('[btn-group]');
    $("[class*='cont-h']").css("display","none");

    btn.each(function(){
        $(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");
                }
            });
        });
    });
}

//  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 useful 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 
