/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
(function (window, $) { 
    
    var lastFocus;
    var modalFocusCapture;

    function closeGlossaryModal(dialog) {
        dialog.data.fadeOut('fast', function () {
                dialog.container.slideUp('fast', function () {
                        dialog.overlay.fadeOut('fast', function () {
                            $.modal.close(); // must call this!
                            $('#page').attr('aria-hidden','false'); 
                            lastFocus.focus();
                        });
                });
        });
    }
    
    function createGlossaryModal(event,term,pronunciation,definition){
         event.preventDefault();
         var pronunciationText = '';
         if((pronunciation)&&(pronunciation!='')){
             pronunciationText=' ('+pronunciation+')';
         }
         var glossary_modal_string = '<div id="simplemodal-data-glossary">\n\
            <div class="message glossarytext"><div class="glossaryheader"><h4 class="glossaryterm">'+term+'</h4><div class="glossarypro">' + pronunciationText+': </div></div><div class="glossarybody"><span class="glossarydefinition">'+definition+'</span></div></div></div>',
         $glossary_modal = $('<div/>').html(glossary_modal_string).contents();
         $.modal($glossary_modal, {
            closeHTML: "<a href='#' title='Close' role='button' aria-label='close' class='modal-close nhlbi_button_primary'><i class='fas fa-times'></i></a>",
            position: [$(window).height()/3,"0%"],
            overlayClose: true,
            opacity: 40,
            minWidth: $(window).width()/4,
            overlayId: 'modal-overlay',
            containerId: 'glossary-container',
            containerCss: {
              'maxHeight' : '95%',
              'overflow' : 'auto',
              'width' : '40%'
            },
            autoresize:true,
            focus:true,
            onOpen: function (dialog) {
                $('#page').attr('aria-hidden','true'); 
                $('#glossary-container').attr('role','DIALOG')
                                        .attr('aria-label','Glossary Term')
                                        .attr('tabindex','0')
                                        .focus();
                openGlossaryModal(dialog);
                resizeGlossaryModal();
            },
            onShow: function(dialog){
                lastFocus = document.activeElement;
                modalGlossaryEvents();
                // Unbind the default keydown handler.
                $(document).unbind('keydown.simplemodal');
                // Replace it with a custom function to manage focus within the modal.
                $(document).bind('keydown.simplemodal', function(e) {
                    const focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
                    const focusableContent = $('#glossary-container').find(focusableElements);
                    const firstFocusableElement = focusableContent.first(); // get first element to be focused inside modal
                    const lastFocusableElement = focusableContent.last(); // get last element to be focused inside modal

                    let focusedModalElement = 0; // Index of the focused element in the modal.
                    let isTabPressed = e.key === 'Tab' || e.keyCode === 9;
                    if(e.key == 'Escape' || e.keyCode == 27) {
                        $(dialog.container).find('.modal-close').first().click();
                    }
                    else if (!isTabPressed) {
                        return;
                    }
                    focusedModalElement = (focusedModalElement + 1) % focusableContent.length;
                    focusableContent[focusedModalElement].focus();
                    e.preventDefault();
                });
            },
            onClose: function (dialog) {
                closeGlossaryModal(dialog);
            }
       });
    }
    
    function modalGlossaryEvents(location) {
       $( window ).resize(function() { 
           resizeGlossaryModal();
        });
     }
     
    function openGlossaryModal(dialog) {
        dialog.data.fadeIn('slow', function () {
                dialog.container.slideDown('slow', function () {
                        dialog.overlay.fadeIn('slow', function () {
                             dialog.data.slideDown('slow'); 
                        });
                });
        });
    }
    
    function resizeGlossaryModal() {
            var screenWidth = $(window).width(),
                containerWidth = screenWidth-20,
                messageWidth='';
            switch(true){
                case (screenWidth<320):
                    messageWidth='150px';
                    break; 
                case (screenWidth<768):
                    messageWidth='300px';
                    break; 
                case (screenWidth<1024):
                    messageWidth='500px';
                    break; 
                default:
                    messageWidth='740px';
                    break;
            };
            //window.console&&console.log('screenWidth',screenWidth);
            //window.console&&console.log('messageWidth',messageWidth);
            $("#glossary-container").css('width', parseInt(messageWidth, 10) + 'px')
                                    .css('left',  screenWidth/2 - parseInt(messageWidth, 10)/2 + 'px')
                                    .css('height','auto'); //To reset the container.
            $('.message').css('width', messageWidth);
    }
    
   

    
$( document ).ready(function() { 
 
 $('a.glossary-term').keyup(function(e) {
        e.which = e.which || e.keyCode;
        if(e.which == 13) {
           e.target.click();
    }
});
 
    $('a.glossary-term').click(function(event){
        event.preventDefault();
        var term= this.getAttribute('data-term'),
                pronunciation=this.getAttribute('data-pronunciation'),
                definition=unescape(this.getAttribute('data-definition'))
                        .replace('<p>','')
                        .replace('</p>','');
        
        
           // var term= this.dataset.term,
           //     pronunciation=this.dataset.pronunciation,
           //     definition=unescape(this.dataset.definition)
           //             .replace('<p>','')
           //             .replace('</p>','');
           // window.console&&console.log('definition',definition);
            createGlossaryModal(event,term,pronunciation,definition);  
        });
    });
}(window, window.jQuery));