
//  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 lastPage (){
    pages = $('div[data-sg-id="item-page"]');
    // Iterate  and hide all pages
    pages.each(function(){
        $(this).css('display','none');
    })
    // Show last page
    $(pages[pages.length -1 ]).css('display','block');
    console.log('REMOVE IN PRODUCTION BEFORE PACK LO');
}

function validarNumeros(){
	// $("#t1b").focus(function(){
	// 	$(this).val("");
	// });

	$(".valNumOnly").keydown(function (e) {
		var str = $(this).val();
		if (str.length>2) {
			
			$(this).val(str.substring(0,str.length - 1));
		};
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
             // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
             // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }


		
				//var keyboardMap = ["","","","CANCEL","","","HELP","","BACK_SPACE","TAB","","","CLEAR","ENTER","RETURN","","SHIFT","CONTROL","ALT","PAUSE","CAPS_LOCK","KANA","EISU","JUNJA","FINAL","HANJA","","ESCAPE","CONVERT","NONCONVERT","ACCEPT","MODECHANGE","SPACE","PAGE_UP","PAGE_DOWN","END","HOME","LEFT","UP","RIGHT","DOWN","SELECT","PRINT","EXECUTE","PRINTSCREEN","INSERT","DELETE","","0","1","2","3","4","5","6","7","8","9","COLON","SEMICOLON","LESS_THAN","EQUALS","GREATER_THAN","QUESTION_MARK","AT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","WIN","","CONTEXT_MENU","","SLEEP","NUMPAD0","NUMPAD1","NUMPAD2","NUMPAD3","NUMPAD4","NUMPAD5","NUMPAD6","NUMPAD7","NUMPAD8","NUMPAD9","MULTIPLY","ADD","SEPARATOR","SUBTRACT","DECIMAL","DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","F16","F17","F18","F19","F20","F21","F22","F23","F24","","","","","","","","","NUM_LOCK","SCROLL_LOCK","WIN_OEM_FJ_JISHO","WIN_OEM_FJ_MASSHOU","WIN_OEM_FJ_TOUROKU","WIN_OEM_FJ_LOYA","WIN_OEM_FJ_ROYA","","","","","","","","","","CIRCUMFLEX","EXCLAMATION","DOUBLE_QUOTE","HASH","DOLLAR","PERCENT","AMPERSAND","UNDERSCORE","OPEN_PAREN","CLOSE_PAREN","ASTERISK","PLUS","PIPE","HYPHEN_MINUS","OPEN_CURLY_BRACKET","CLOSE_CURLY_BRACKET","TILDE","","","","","VOLUME_MUTE","VOLUME_DOWN","VOLUME_UP","","","SEMICOLON","EQUALS","COMMA","MINUS","PERIOD","SLASH","BACK_QUOTE","","","","","","","","","","","","","","","","","","","","","","","","","","","OPEN_BRACKET","BACK_SLASH","CLOSE_BRACKET","QUOTE","","META","ALTGR","","WIN_ICO_HELP","WIN_ICO_00","","WIN_ICO_CLEAR","","","WIN_OEM_RESET","WIN_OEM_JUMP","WIN_OEM_PA1","WIN_OEM_PA2","WIN_OEM_PA3","WIN_OEM_WSCTRL","WIN_OEM_CUSEL","WIN_OEM_ATTN","WIN_OEM_FINISH","WIN_OEM_COPY","WIN_OEM_AUTO","WIN_OEM_ENLW","WIN_OEM_BACKTAB","ATTN","CRSEL","EXSEL","EREOF","PLAY","ZOOM","","PA1","WIN_OEM_CLEAR",""];
			
	});
}

function init() {
    $("#t1b").attr('maxlength','1');
validarNumeros();

    //Paso a
    $('#btn1validar').click(function() {
        if ($('#t1b').val() === "1") {
            $('#t1b').css('background-color', '#e6efbd');
            $('#btnPopUp12').click();
            sg.sound('success');
        }
        else {
            $('#t1b').css('background-color', '#ed98ab');
            sg.sound('error');
        }
    });

    //Paso b
    $('#btn2validar').click(function() {
        console.log('click 2');
        //Get data array's
        var dataObj = $('.input2b').children('input');
        var success = 0;

        $.each(dataObj, function(key, value) {
            console.log('each '+value);   

            if ($(value).val() === "1") {
              success ++;
              $(value).css('background-color', '#e6efbd');
            }
            else {
                $(value).css('background-color', '#ed98ab');
            }
        });

        //Validate 
        if ( success === dataObj.length ) {
           
            $('#btnPopUp13').click();
            sg.sound('success');
        }
        else {
            $('#t1b').css('background-color', '#ed98ab');
            sg.sound('error');
        }
    });

    /*
    Generate triangle of pascar.
    args = []
    args.size = size of triangle

    //css:
    .pascal .input3b {
      width: 580px;
      text-align: center;
    }

    .input3b input {
      height: 49px;
      width: 58px;
      border: 1px solid black;
    }

    */
    generatePascal = function(args) {
        //Initialize content
        var content = '<div class="input3b texto1 crojo" >';
        //Iteration content's
        var contenti = "";    
        //Array to store current data
        var rows = [];
        //Array to store history  row data 
        var rowsback = new Array();
       
        /*Local variables: 
        valor   = store the succes value  of textbox (=a+b); 
        a       = stored back value on current index and back row; 
        b       = stored back value on current index -1 and back row;  
        */
        var valor, a , b = 0;

        for (var i = 0; i < args.size; i++) {        
            rows[i] = [] ;
            contenti = '';
            contenti = '<div class="line-inputs">';
            //Rows
            for (var j = 0; j <= i; j++) {
                //Initialize row
                rows[i][j] = 1;

                if (rowsback.length>=1){
                    //Get values
                    a = rowsback[i-1][j];
                    b = rowsback[i-1][j-1];
                    //Validate values
                    if (a === undefined) a = 0;
                    if (b === undefined) b = 0;
                    //Assign value to valor variable
                    valor = a+b;
                    //Update row value on current index
                    rows[i][j] = valor;
                }
                else {
                    //Default value
                    valor = 1;
                }
                //Load back data rows
                rowsback = rows;
                //Add textbox on triangle
                contenti += '<input type="text" id="if" class="sg-text-center input-pascal" success="'+valor+'" >';
            };
            contenti += "</di>";    //Close iterator of content
            //Add iterator content to main content
            content += contenti;
        };
        //Add content to main content
        content = content + "</div>";       
        //Renderize to html
        $('.pascal').html(content);
    }
    //Data for triangle
    var data =  [];
    data.size = 10;
    generatePascal(data);

    //Validate triangle of pascal
    $('#btn12validar').click( function() { 
        var obj = $('.input-pascal');

        var input = "";
        var successcount = answer = success = 0;

        $.each(obj, function(key, value) {
            //Convert to int
            answer = parseInt($(value).val());
            success = parseInt($(value).attr('success'));
            //Validate success answer
            if (answer === success){
                successcount ++;
                $(value).css('background-color', '#a7e8bb');
            }
            else{
                $(value).css('background-color', '#ed9dba');
            }
        });
        //All numbers success
        if (successcount === obj.length) {
            sg.sound('success');
            $('#btnPopUp14').click();
        }
        else {
            sg.sound('error');
        }
    });


    divImgPopUp();
    //lastPage();
};