$( document ).ready(function() {
    function bindMapOpen() {
        // $('#modal_map').data('abv-entry',$(this).data('abv-entry'));
        // $('#modal_map')[0].showModal();
        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. We have to bind it
    // when the button is shown, otherwise it will
    // not work for newly loaded entries.
    $('.abv-map').on("click", bindMapOpen);

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

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

    // 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());
        }
      }
    });

    // 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")[0].style.marginLeft = "250px";
      $("footer")[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")[0].style.marginLeft = null;
      $("footer")[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 > 1) {
          $("#entrylist > ul > li").filter(function () {
              return $(this).toggle($(this).children('a').text().toLowerCase().indexOf(value) > -1)
          });
        }

        return false;
    });

    // 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);



      // var data = [{
      //   type: 'scattergeo',
      //   mode: 'markers+text',
      //   text: [
      //       'Montreal', 'Toronto', 'Vancouver', 'Calgary', 'Edmonton',
      //       'Ottawa', 'Halifax', 'Victoria', 'Winnepeg', 'Regina'
      //   ],
      //   hovertext: 'HIMEM.SYS<br>EGAVGA.BGI',
      //   hoverinfo: 'text',
      //   lon: [
      //       -73.57, -79.24, -123.06, -114.1, -113.28,
      //       -75.43, -63.57, -123.21, -97.13, -104.6
      //   ],
      //   lat: [
      //       45.5, 43.4, 49.13, 51.1, 53.34, 45.24,
      //       44.64, 48.25, 49.89, 50.45
      //   ],
      //   marker: {
      //       size: 7,
      //       // color: [
      //       //     '#bebada', '#fdb462', '#fb8072', '#d9d9d9', '#bc80bd',
      //       //     '#b3de69', '#8dd3c7', '#80b1d3', '#fccde5', '#ffffb3'
      //       // ],
      //       line: {
      //           width: 1
      //       }
      //   },
      //   name: 'Canadian cities',
      //   textposition: [
      //       'top right', 'top left', 'top center', 'bottom right', 'top right',
      //       'top left', 'bottom right', 'bottom left', 'top right', 'top right'
      //   ],
      // }];
    });
});
