$( 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 produce HTML for the entry list
    function filterEntryList(list, filter, showSubentries) {
      let listHtml = "";
      for (entry of list) {
        let entryID = entry.xmlid;
        let entryForm = entry.form;
        if (entryForm.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").startsWith(filter)
          && (!entry.subentry || showSubentries)
        ) {
          listHtml += `<li id="link_${entryID}"${entry.subentry ? ' class="abv-menu-re"' : ''}"><a href="./dict/${entryID}">${entryForm}</a></li>`
        }
      }
      listHtml = $(`<ul>${listHtml}</ul>`);
      $("#entrylist").append(listHtml);
    }

    // Fetch entries from the server when page loads
    var entries = [];

    fetch('./api/entries')
    .then(res => res.json())
    .then(out => {
      entries = out;
      filterEntryList(entries, '', false);
    })
    .then(err => console.log(err));

    // 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").show();
      $("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 () {
        $("#entrylist > ul").remove();
        var value = $(this).val().toLowerCase();
        filterEntryList(entries, value, $('#show-re').prop('checked'))
        // 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 () {
        $("#entrylist > ul").remove();
        filterEntryList(entries, $("#filter-entries").val().toLowerCase(), $(this).prop('checked'));
        scrollView();
      });
});
