//  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, 
//  use attribute  data-no-lock for disable lock images  (useful in drag and drop)  

function init(){
    divImgPopUp();
    triggerAble();
    initBtnGroup();
    detenerVideos();
    limpiarColores();
     validarRespuestas();
    ioToolTip();
    slideMateriales();
   
    //generalClick();
    if (is_function("soundContent")) {
    soundContent("soundContent");
    };

    
require(["jquery-zoomooz"], function(){
$(".zoomTarget").zoomButton();
})
};

function unirMc(){
    var elementos = $("[id*='mce-']");
    elementos.each(function(i, e){
        var parent = $(this).data("parent").toString();     
        var idPos = $(this).attr("id").split("-")[1]; 
        console.log(idPos);
        if (parent != "0" && idPos == "2") {           

            if (parent.split("-").length>1) {

            }else{
                var x1 = $(this).position().left + $(this).innerWidth()/2;
                var y1 = $(this).position().top ;
                var objPadre = $("#mce-"+parent);
                //console.log("id: "+$(this).attr("id")+"\n"+"parent: "+parent);
                var x2 = objPadre.position().left + objPadre.innerWidth()/2;
                var y2 = objPadre.position().top + objPadre.innerHeight();

                var x = Math.abs(x2 - x1);
                var y = Math.abs(y2 - x1);
                var top = Math.abs(y1-y);
                var left = x1; 
                // var shape = document.createElementNS("https://www.w3.org/2000/svg", "line");
                // shape.setAttributeNS(null, "stroke-width", 2);
                // shape.setAttributeNS(null, "stroke", "orange");
                // shape.setAttributeNS(null, "x1",  x1);
                // shape.setAttributeNS(null, "y1", y1); 
                // shape.setAttributeNS(null, "x2", x2); 
                // shape.setAttributeNS(null, "y2", y2); 
                // //shape.appendTo($("#contMc"));
                // var svgObj =  $("<svg/>");
                // svgObj.appendChild(shape);
                // document.documentElement.appendChild(svgObj);

                var linea =  $("<line/>");
                linea.attr( {
                            "stroke-width" : "2",
                            "stroke" : "orange",
                            "x1" : "0",
                            "y1": y,
                            "x2": x,
                            "y2" :"0"
                        });
                var svg = $("<svg/>");
                 svg.attr( {
                            "width" : x,
                            "height" : y                            
                        });
                 svg.css({
                    "position":"absolute", 
                    "top":top,
                    "left": left
                })

                linea.appendTo(svg);
                svg.appendTo($("#contMc"));
                
               $("#contMc").html($("#contMc").html());

            };
        };
    });
}

function slideMateriales(){
    $(".btnAnimated").click(function(){
        window.setTimeout(function(){
            $(".btnAnimated").removeClass("left-490").addClass("left-0");
        }, 0);
        window.setTimeout(function(){
            $(".listadoMateriales").removeClass("d-none",500);
        }, 300);
    });


    $(".btnAnimated-2").click(function(){
        window.setTimeout(function(){
            $(".btnAnimated-2").removeClass("top-115").addClass("top-10");
        }, 0);
        window.setTimeout(function(){
            $(".listadoMateriales-2").removeClass("d-none").addClass("");
        }, 300);
    });

}

function is_function(func) {
    return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}

function  ioToolTip(){
   

    $("#tt_1").click(function(e){
    $("#tooltip_1").toggleClass("d-none");
    $("#tooltip_2").addClass("d-none");
    minusPlus();
     e.stopPropagation();
    });
    $("#tooltip_1").click(function(e){
        minusPlus();
    e.stopPropagation();
    });
    $(document).click(function(){
        $("#tooltip_1").addClass("d-none");
        minusPlus();
    });



    $("#tt_2").click(function(e){
    $("#tooltip_2").toggleClass("d-none");
     $("#tooltip_1").addClass("d-none");
     minusPlus();
    console.log("yeah");
     e.stopPropagation();
    });
    $("#tooltip_2").click(function(e){
        minusPlus();
        e.stopPropagation();
    });
    $(document).click(function(){
        $("#tooltip_2").addClass("d-none");
        minusPlus();
    });



}

function minusPlus(){
    if ($("#tooltip_2").hasClass("d-none")) {
        $("#tt_2").html("+");
    }else{
        $("#tt_2").html("-");
    };

    if ($("#tooltip_1").hasClass("d-none")) {
        $("#tt_1").html("+");
    }else{
        $("#tt_1").html("-");
    };

}






function validarRespuestas(){
    $(".pregunta1").click(function(){
        $(".pregunta1").removeClass("rojo",300).removeClass("verdeOk",300);
        limpiarClick($(this).html(), "Autor", $(this));
    });

    $(".pregunta2").click(function(){
        $(".pregunta2").removeClass("rojo",300).removeClass("verdeOk",300);
        limpiarClick($(this).html(), "Género", $(this));
    });

    $(".pregunta3").click(function(){
        $(".pregunta3").removeClass("rojo",300).removeClass("verdeOk",300);
        limpiarClick($(this).html(), "Época", $(this));
    });

     $(".pregunta4").click(function(){
        $(".pregunta4").removeClass("rojo",300).removeClass("verdeOk",300);
        limpiarClick($(this).html(), "Tema", $(this));
    });
}

function limpiarClick(res, correcta ,obj){
        if (res == correcta) {
           sg.sound("success-low");
            obj.addClass("verdeOk");
        }
        else
        {
             sg.sound("error");
            obj.addClass("rojo");
        };
    }

function playStopAu(){

    $(".play").click(function(){

    });

     $(".stop").click(function(){
        
    });

};


function limpiarColores()
{
    $("[class*='validar-']").click(function(){
    var classes = $(this).attr("class").split(" ");  
     $.each(classes, function(i){
        if (classes[i].substring(0,8)=='validar-') {
            if (classes[i].split("-")[1]=="2") {
                $("."+classes[i]).animate({backgroundColor:"white"}, 300);
            }
            else
            {
                $("."+classes[i]).animate({backgroundColor:"transparent"}, 300);
            };
        };
     });
    });
}


function validar(ej){

var ok =[];

switch(ej) {
    case 1:
       ok = ["4","4","10,0%","10,0%","1,30","3","7","7,5%","17,5%","2,0","4","11","10,0%","27,5%","2,75","8","19","20,0%","47,5%","3,50","14","33","35,0%","82,5%","4,20","7","40","17,5%","100,0%","4,90"];      
        break;
    case 2:
        ok = ["3,8","17,5%","3,8","4,4","3,1","3,7","29","72,5%","27,5%"];
        break;
    case 3:
        ok = ["x","2","-","xb","+","ax","-","ab","x","2","-","x","*","(b-a)","-","ab"];
    case 4:
     ok = ["iguales","equivalentes", "son iguales", "son equivalentes", "=", "son =", "lo mismo", "son lo mismo", "la misma"];
        break;
    case 5:
      //console.log("entro al 5");
        ok = ["x","2","2x","3x","6","x","2","x","6"];
         break;
    case 6:
        ok = ["y","2","4y","6y","24","y","2","2y","24"];
         break;
    case 7:
    //console.log("entro al 7");
        ok = ["a","2","ac","ba","bc","a","2","a","*","(c-b)","bc"];
         break;
     case 8:
        ok = ["comun","comunes","termino","terminos","comunes"];
         break;
            }


var porValidar = $(".validar-"+ej);
var errados = 0;
//console.log(ej+"\n"+ok);

 $.each(porValidar, function(i){
        var idv = $(this).data("idv");
        console.log(idv);
        var multi = $(this).data("multi");
        var val = $(this).val();    
       
        if (multi !== undefined) {
            var limpia = val.toLowerCase().trim();
            var limpiaValidada = $.isNumeric(limpia)? limpia : removeAccent(limpia);
            //console.log(limpiaValidada);
            if ($.inArray(limpiaValidada, multi.split(","))<0) {
                $(this).val("");
                sg.sound("error");
                $(this).css('background-color','#F69');
                errados++;
            }
            else
            {
                $(this).css('background-color','#96FAB7');

            };
        }else{ 
            var limpia = val.toLowerCase().trim().replace(' ','').replace('.',',');
             var limpiaValidada = $.isNumeric(limpia)? limpia : removeAccent(limpia);
             //console.log(limpiaValidada);
        if (ok[idv-1]!=limpiaValidada) 
            {
                $(this).val("");
                sg.sound("error");
                $(this).css('background-color','#F69');
                errados++;
            }
            else
            {
                $(this).css('background-color','#96FAB7');
            };
        };
    });

 if (errados == 0) {
    sg.sound("success");
 };

}



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





function changeTitle(){
    $(".change_title").click(function(){},function(){

    var pages = $(".paginable");
        $.each(pages, function(){
        var key = $(this).data("sgKey");
        if ($(this).is(":visible")) 
            {
                var info = "Haz <span class='icon click'>clic</span> para ver la información";
                var video = "Haz <span class='icon click'>clic</span> para ver el video";
                switch(key) {
                    case 1:
                    
                        $(".ggd_title").html("Formación de la imagen en espejos ");
                        $(".ggd_text_exp").html(info);
                        break;
                    case 2:
                    
                        $(".ggd_title").html("Formación de la imagen en espejos ");
                        $(".ggd_text_exp").html(video);
                        break;
                    case 3:
                    
                         $(".ggd_title").html("Historia sobre las mediciones de la velocidad de la luz");
                        $(".ggd_text_exp").html(info);
                        break;
                    case 4:
                    
                         $(".ggd_title").html("Experimento de Newton");
                        $(".ggd_text_exp").html(info);
                        break;
                    case 5:
                    
                         $(".ggd_title").html("Experimento de Newton");
                        $(".ggd_text_exp").html(info);
                        break;
                    case 6:
                    
                         $(".ggd_title").html("Experimento de Newton");
                        $(".ggd_text_exp").html(info);
                        break;
                    case 7:
                    
                         $(".ggd_title").html("Experimento de Newton");
                        $(".ggd_text_exp").html(info);
                        break;
                }
            };
    });
    });

}

function detenerVideos(){
$(".tab, .stopVideo, [class^='ggd_flecha_']").click(function(){
        $("video").each(function () { this.pause(); });
    });
}

function controlFlecha()
{
    $('.ggd_flecha_avanzar, .ggd_flecha_volver').click(function(){
        var state_1 = $("#controlPage-1").is(":visible");
        var state_2 = $("#controlPage-2").is(":visible");
        //console.log("primera: "+state_1+"\nsegunda: "+state_2);
        if ( state_2 ) {
            $("#controlButton-1").hide();  
        };

        if (state_1) {
             $("#controlButton-1").show();  
        };

        if (state_1==false && state_2==false) {
             $("#controlButton-1").hide();  
        };
       
    });
}

function initBtnGroup(){
        var btn = $('[btn-group]');
        $("[class*='cont-h']").css("display","none");
        $.each(btn,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");
                                }                       
                        });
                    });
            });
}


function triggerAble(){
    $('span[id^="trigger-"]').click(function(){      
       $("#triggerAble-"+$(this).attr("id").split("-")[1]).click();
    });
}

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 



