
require([ 'jquery-selectric'] );

function init(){

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

}


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

    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+']');
        var errorInInput = false;
        switch (key) {
            case '0':
                var pat = new RegExp('^2[a-z]=90$'); 
                if(!pat.test(val)){
                    errorInInput = true;
                }

                break;

            case '1':
                var pat = new RegExp('no');  //Considerar otros patrones o un select
                if(!pat.test(val) ||  val=='' ){ //si no o vacio
                    errorInInput = true;

                }
                break;

            case '2':
                var pat = new RegExp('^\\([a-z]\/2\\)\\+5=71$'); 
                if(!pat.test(val)){
                    errorInInput = true;
                }

                break;

            case '3':
                var pat = new RegExp('no');  //Considerar otros patrones o un select
                if(!pat.test(val) ||  pat === '' ){ //si no o vacio
                    errorInInput = true;

                }
                break;
            case '4':
                var pat = new RegExp('^\\([a-z]\\+50\\)\\/2=65$'); 
                if(!pat.test(val)){
                    errorInInput = true;
                }

                break;

            case '5':
                var pat = new RegExp('no');  //Considerar otros patrones o un select
                if(!pat.test(val) ||  pat === '' ){ //si no o vacio
                    errorInInput = true;

                }
                break;

            default:
                console.log('Default');
        }

        if ( !errorInInput ){ //  No error
            divResultado.removeClass('bgError');
            divResultado.addClass('bgAcierto');

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

    });

    if(errorInForm >0){
        sg.sound('error');
    }
    else{
        sg.sound('success-low');
    }
}



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

    var respuestas = ['12x-40>20', '2y+5<=21', '(P/5)'];

    // Grupo de validacion
    var groupKey  =  2
    var input = $('input[type="text"][groupKey=2][keyValue='+key+']');
    var  val =  input.val(); // key to answer
    val=val.toLowerCase().replace(/ /g,'');;
    var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');
    var errorInInput = false;

        switch (key) {
            case 0:
                console.log(val);
                var pat = new RegExp('^12[a-z]\\-40>20$'); 
                if(!pat.test(val)){
                    errorInInput = true;
                }
                break;

            case 1:
                var pat = new RegExp('^2[a-z]\\+5<=21$'); 
                if(!pat.test(val) ||  val=='' ){ //si no o vacio
                    errorInInput = true;

                }
                break;

            case 2:
                var pat = new RegExp('^\\([a-z]\/5\\)\\-4<5$'); 
                if(!pat.test(val)){
                    errorInInput = true;
                }
                break;

            case 3:
                var pat = new RegExp('^3[a-z]\\+6<20$'); 
                if(!pat.test(val) ||  pat === '' ){ //si no o vacio
                    errorInInput = true;

                }
                break;
            case 4:
                var pat = new RegExp('^[a-z]\\-5>=-7$'); 
                if(!pat.test(val)){
                    errorInInput = true;
                }

                break;

            default:
                console.log('Default');
        }

        if ( !errorInInput ){ //  No error
            divResultado.removeClass('bgError');
            divResultado.addClass('bgAcierto');
            sg.sound('success-low');

        }
        else{
            divResultado.addClass('bgError');
            divResultado.removeClass('bgAcierto');
            input.val('');
            sg.sound('error');
        }


}


function validarEjercicio3(groupKey){

    var errorInForm = 0;

    // Grupo de validacion
    groupKey  = (typeof groupKey === "undefined") ? 2 : groupKey;
   
    inputs = $(".selectric .label");
    //console.log(inputs);
    inputs.each(function(key, elem){
        //var  key =  $(this).attr('keyValue'); // key to answer
       var  val =  removeAccent($(this).html()); // key to answer
       console.log(key);
        val=val.toLowerCase().replace(/ /g,'');
        var divResultado = $('div.resultado[keyValue="'+key+'"][groupKey='+groupKey+']');
        var errorInInput = false;
         switch (key) {
            case 0:       

                if(val!="desigualdad"){
                    errorInInput = true;
                }

                break;

            case 1:
                 if(val!="letras"){
                    errorInInput = true;
                }

                break;

            case 2:
                 if(val!="numeros"){
                    errorInInput = true;
                }

                break;

            case 3:
                 if(val!="operaciones"){

                    errorInInput = true;
                }

                break;
            case 4:
                 if(val!="incognitas"){
                    errorInInput = true;
                }

                break;
            case 5:
                 if(val!="conjunto"){
                    errorInInput = true;
                }
                break;
             case 6:
                 if(val!="valores"){
                    errorInInput = true;
                }
                break;
             case 7:
                 if(val!="inecuacion"){
                    errorInInput = true;
                }
                break;
             case 8:
                 if(val!="cumpla"){
                    errorInInput = true;
                }
                break;
            default:
                console.log('Default');
        }

        if ( !errorInInput ){ //  No error
            divResultado.removeClass('bgError');
            divResultado.addClass('bgAcierto');

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

    });

    if(errorInForm >0){
        sg.sound('error');
    }
    else{
        sg.sound('success-low');
    }
}



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