$( document ).ready(function() {
    // GLOBALS
    // Link elements that do not have href out of the box
    $('.link').on("click", function () {
      window.location=$(this)[0].dataset.href+window.location.search+window.location.hash;
    });

    // init Infinite Scroll
    $('main').infiniteScroll({
      path: '.pagination__next',
      append: '.abv-entry',
      //status: '.scroller-status',
      //hideNav: '.pagination',
    });

    // SEARCH RESULTS MODAL
    $('#abv-btn-searchResults').on("click", function () {
      $('#modal_searchResults')[0].showModal();
    });

    // Close search modal
    $('.abv-close-search').on("click", function () {
      $('#modal_searchResults')[0].close();
    });

    // MAP MODAL
    // This event binding is done on page load and also whenever new entries are loaded.
    bindMapOpen = function () {
      let url = `./dict/map-info/${$(this).data('abv-entry')}`;

      fetch(url)
      .then(res => res.json())
      .then(out => {
        $('#modal_map').data('map',out);
        $('#modal_map')[0].showModal();
      })
      .catch(err => console.log(err));
    };

    // Event to open map modal.
    $('.abv-map').on("click", bindMapOpen);

    $('main').on( 'append.infiniteScroll', function( event, body, path, response ) {
        $('.abv-map').on("click", bindMapOpen);
    });

    // Close map modal
    $('.abv-close-map').on("click", function () {
      $('#modal_map')[0].close();
    });

    // Load map data when dialog opens
    $('#modal_map').on("toggle", function () {
      map = document.getElementById('map_display');
      var layout = {
              // title: {
              //     text: 'Canadian cities',
              //     font: {
              //         family: 'Droid Serif, serif',
              //         size: 16
              //     }
              // },
              geo: {
                  scope: 'world',
                  resolution: 50,
                  fitbounds: 'locations',
                  showrivers: true,
                  rivercolor: '#fff',
                  showlakes: true,
                  lakecolor: '#fff',
                  showland: true,
                  landcolor: '#EAEAAE',
                  showcountries: false,
                  subunitcolor: '#d3d3d3'
              }
          };
      Plotly.newPlot(map, [$(this).data('map')], layout);
    });

    // HASH NAVIGATION
    // If the hash is on the page, scroll a little bit above to account for top nav height
    if ( $(decodeURI(document.location.hash)).length > 0) {
      window.scrollBy(0,-$('header').height());
    }

    // If the hash is not on the page, go to the right page by using the ID interface
    $( window ).on('hashchange', function() {
      const hash = decodeURI(document.location.hash);

      if ( hash.startsWith('#entry_') ) {
        if ( $(hash).length == 0) {
          window.location.replace(document.location.pathname + '/' + document.location.hash.substring(1));
        }
        else {
          window.scrollBy(0,-$('header').height());
        }
      }
    });

    // ENTRY LIST SIDE PANEL
    // Function to scroll the entry list to the selected entry OR to the first entry displayed on the current page if there is no hash in the URL
    function scrollView() {
      var $container = $('#entrylist')
      if (document.location.hash.length > 0) {
        var $scrollTo = $(`#link_${$(decodeURI(document.location.hash)).attr('id')}`);
      }
      else {
        var $scrollTo = $(`#link_${$('article:first').attr('id')}`);
      }
      $container.scrollTop(
            $scrollTo.offset().top - $container.offset().top + $container.scrollTop())
    }

    // Click to open the offcanvas entry list
    $( '#open-leftbar' ).on('click', function() {
      // $("#leftbar")[0].style.width = "250px";
      $("#leftbar").show();
      // $("#leftbar")[0].style.paddingLeft = "10px";

      $("main")[0].style.marginLeft = "250px";
      $("header nav")[0].style.marginLeft = "250px";
      $("footer nav")[0].style.marginLeft = "250px";
      $("#open-leftbar").hide();
      $("#close-leftbar").show();

      scrollView();
    });

    // Click to close the offcanvas entry list
    $( '#close-leftbar' ).on('click', function() {
      $("#leftbar").hide();
      // $("#leftbar")[0].style.paddingLeft = null;
      $("main")[0].style.marginLeft = null;
      $("header nav")[0].style.marginLeft = null;
      $("footer nav")[0].style.marginLeft = null;
      $("#open-leftbar").show();
      $("#close-leftbar").hide();
    })

    // Quick filter functionality
    $('#filter-entries').on("keyup", function () {
        var value = $(this).val().toLowerCase();
        if (value.length > 0) {
          $("#entrylist > ul > li:not([hidden])").filter(function () {
              return $(this).toggle($(this).children('a').text().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").startsWith(value))
          });
        }
        else {
          $("#entrylist > ul > li").show();
        }

        return false;
    });

      // Event handler to show subentries
      $('#show-re').on("change", function () {
        if($(this).prop('checked')) {
          console.log('haha')
          $('li.abv-menu-re').removeAttr('hidden');
        }
        else {
          $('li.abv-menu-re').prop('hidden',true);
        }
      });
});
