/**
 * This JS library appears on the category landing pages (/tobacco, /opioids, etc):
 *
 * On that page, each tab will contain an exposed filter with a full selector of Topics
 *
 * This library will:
 * 1) load (click) a proper tab on page load
 * 2) change the url's hash when any tab is clicked
 */

(function ($, Drupal) {
  Drupal.behaviors.category_landing_url_handler = {
    attach: function (context, settings) {

      if (typeof settings['category_landing'] === 'undefined') {
        return;
      }
      // 1) jump to right nav item when loaded with that hash
      $(once('jumpToRightHash','body', context)).each(function() {
        var currentHash = document.location.hash;
        // jump to featured by default
        if (currentHash == '') {
          currentHash = '#featured';
        }
        var $oRightAnchor = $("div.paragraph--type--category-landing.paragraph--view-mode--default ul.nav a[href='"+currentHash+"']");
        if ($oRightAnchor.length > 0) {
          $oRightAnchor[0].click();
        }
      });

      // 2) change the URL when clicking a tab
      $(once('anchorGenerate','div.paragraph--type--category-landing.paragraph--view-mode--default ul.nav a', context)).each(function() {
        var $oAnchor = $(this);
        var sAnchorHref = $oAnchor.attr('href').replace('#', '');
        $oAnchor.on('click', function() {
          document.location.hash = sAnchorHref;
        });
      });

    }
  };
})(jQuery, Drupal);
