
require([ 'jquery-selectric'] );

function init(){
    initBtnGroup();

    require([ 'js/jscurry-0.3.0.js'] );
    require([ 'js/jqmath-0.4.2.js'] );

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

    initValidarSelects(1, results=[1,4,2]);

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


}

// <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')).addClass('animated slideInUp ');
            $('.cont-h'+ $(this).attr('btn-id')).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");
                }
            });
        });
    });
}

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

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

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


            if( results[keyValue] == valSelected){
                sg.sound('success-low');
                resultado.addClass('bgAcierto');
                resultado.removeClass('bgError');
                $(this).attr('disabled','disabled').selectric('refresh');
            }
            else if(valSelected !== 0  ){  // Wrong option
                sg.sound('error');
                resultado.addClass('bgError');
                resultado.removeClass('bgAcierto');
            }
            else{  // 0 ==  Empty first element
                resultado.removeClass('bgAcierto');
                resultado.removeClass('bgError');
            }

        });
    });

}

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

    var rs = ["25", "25", "81", "81", "81", "81", "4/25", "4/25", "5,5225", "20,25" ];
    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
        var divResultado = $(this).next('div .resultado');

        if ( rs[key] === val){
            $(this).parent().parent().find('.resultado').addClass('bgAcierto');
            $(this).parent().parent().find('.resultado').removeClass('bgError');
        }
        else{
            $(this).parent().parent().find('.resultado').addClass('bgError');
            $(this).parent().parent().find('.resultado').removeClass('bgAcierto');
            $(this).val('');
            errorInForm ++;
        }
    });

    if(errorInForm >0){
        sg.sound('error');
        $('#btPop1').css('display','block');
    }
    else{
        sg.sound('success');
    }
}

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

    var rs = ["no hay solucion", "no hay solucion", "no hay solucion", "no hay solucion" ];
    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 =  removeAccent($(this).val().toLowerCase()); // key to answer
        var divResultado = $(this).next('div .resultado');

        if ( rs[key] === val){
            $(this).parent().parent().find('.resultado').addClass('bgAcierto');
            $(this).parent().parent().find('.resultado').removeClass('bgError');
        }
        else{
            $(this).parent().parent().find('.resultado').addClass('bgError');
            $(this).parent().parent().find('.resultado').removeClass('bgAcierto');
            $(this).val('');
            errorInForm ++;
        }
    });

    if(errorInForm >0){
        sg.sound('error');
        $('#btPop3').css('display','block');
    }
    else{
        sg.sound('success');
    }
}

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

    var rs = ["8i", "5i", "12i", "(3/4)i","(9/2)i","3,3i", "3,7i"];
    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 =  removeAccent($(this).val().toLowerCase()); // key to answer
        var divResultado = $(this).next('div .resultado');

        if ( rs[key] === val){
            $(this).parent().parent().find('.resultado').addClass('bgAcierto');
            $(this).parent().parent().find('.resultado').removeClass('bgError');
        }
        else{
            $(this).parent().parent().find('.resultado').addClass('bgError');
            $(this).parent().parent().find('.resultado').removeClass('bgAcierto');
            $(this).val('');
            errorInForm ++;
        }
    });

    if(errorInForm >0){
        sg.sound('error');
        $('#btPop3').css('display','block');
    }
    else{
        sg.sound('success');
    }
}


function setMsgActividadEjercicio(){
    var msg ='<span class="cActividad">Actividad</span> <span class="cEjercicio">Ejercicio</span>';
    $(".ggd_text_act").html( msg);
}

function setMsgActividadNormal(){
    var msg ='<span class="cActividad">Actividad</span>';
    $(".ggd_text_act").html( msg);
}

function setMsgNombre(msg){
    $(".ggd_nombre").html(msg);
}


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


function removeAccent(str){
    var map={'À':'A','Á':'A','Â':'A','Ã':'A','Ä':'A','Å':'A','Æ':'AE','Ç':'C','È':'E','É':'E','Ê':'E','Ë':'E','Ì':'I','Í':'I','Î':'I','Ï':'I','Ð':'D','Ñ':'N','Ò':'O','Ó':'O','Ô':'O','Õ':'O','Ö':'O','Ø':'O','Ù':'U','Ú':'U','Û':'U','Ü':'U','Ý':'Y','ß':'s','à':'a','á':'a','â':'a','ã':'a','ä':'a','å':'a','æ':'ae','ç':'c','è':'e','é':'e','ê':'e','ë':'e','ì':'i','í':'i','î':'i','ï':'i','ñ':'n','ò':'o','ó':'o','ô':'o','õ':'o','ö':'o','ø':'o','ù':'u','ú':'u','û':'u','ü':'u','ý':'y','ÿ':'y','Ā':'A','ā':'a','Ă':'A','ă':'a','Ą':'A','ą':'a','Ć':'C','ć':'c','Ĉ':'C','ĉ':'c','Ċ':'C','ċ':'c','Č':'C','č':'c','Ď':'D','ď':'d','Đ':'D','đ':'d','Ē':'E','ē':'e','Ĕ':'E','ĕ':'e','Ė':'E','ė':'e','Ę':'E','ę':'e','Ě':'E','ě':'e','Ĝ':'G','ĝ':'g','Ğ':'G','ğ':'g','Ġ':'G','ġ':'g','Ģ':'G','ģ':'g','Ĥ':'H','ĥ':'h','Ħ':'H','ħ':'h','Ĩ':'I','ĩ':'i','Ī':'I','ī':'i','Ĭ':'I','ĭ':'i','Į':'I','į':'i','İ':'I','ı':'i','Ĳ':'IJ','ĳ':'ij','Ĵ':'J','ĵ':'j','Ķ':'K','ķ':'k','Ĺ':'L','ĺ':'l','Ļ':'L','ļ':'l','Ľ':'L','ľ':'l','Ŀ':'L','ŀ':'l','Ł':'L','ł':'l','Ń':'N','ń':'n','Ņ':'N','ņ':'n','Ň':'N','ň':'n','ŉ':'n','Ō':'O','ō':'o','Ŏ':'O','ŏ':'o','Ő':'O','ő':'o','Œ':'OE','œ':'oe','Ŕ':'R','ŕ':'r','Ŗ':'R','ŗ':'r','Ř':'R','ř':'r','Ś':'S','ś':'s','Ŝ':'S','ŝ':'s','Ş':'S','ş':'s','Š':'S','š':'s','Ţ':'T','ţ':'t','Ť':'T','ť':'t','Ŧ':'T','ŧ':'t','Ũ':'U','ũ':'u','Ū':'U','ū':'u','Ŭ':'U','ŭ':'u','Ů':'U','ů':'u','Ű':'U','ű':'u','Ų':'U','ų':'u','Ŵ':'W','ŵ':'w','Ŷ':'Y','ŷ':'y','Ÿ':'Y','Ź':'Z','ź':'z','Ż':'Z','ż':'z','Ž':'Z','ž':'z','ſ':'s','ƒ':'f','Ơ':'O','ơ':'o','Ư':'U','ư':'u','Ǎ':'A','ǎ':'a','Ǐ':'I','ǐ':'i','Ǒ':'O','ǒ':'o','Ǔ':'U','ǔ':'u','Ǖ':'U','ǖ':'u','Ǘ':'U','ǘ':'u','Ǚ':'U','ǚ':'u','Ǜ':'U','ǜ':'u','Ǻ':'A','ǻ':'a','Ǽ':'AE','ǽ':'ae','Ǿ':'O','ǿ':'o', '.':','};
    var res='';
     for (var i=0;i<str.length;i++){c=str.charAt(i);res+=map[c]||c;}return res; 
}
