(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.usgs_tabs = {
    attach: function (context) {
      $(context).find('div.usgs-tabs-wrapper').once('usgs-tabs-wrapper').each(function() {
        $(this).tabs({
          activate: function(event ,ui){
            Drupal.attachBehaviors(this);
            window.history.pushState(null,null, '#'+ ui.newPanel.attr('id'));
          }
        });
      });
    }
  }


  $(".topic a.tab").click(function() {
    $(this).parent().toggleClass('active').find('.usgs-tabs-main').slideToggle('fast');

    // Fix the masony images layout on mobile
    if ($('.related-content-tabs-mobile').length) {
      $('.masonry-layout-related-media-tabs').masonry();
    }

    $(".topic a").not(this).parent().removeClass('active').find('.usgs-tabs-main').slideUp('fast');
  });

  // For Volcano VONAs accordion
  $('.vona-toggle').click(function(event){
    event.preventDefault();
    $(this).siblings('.vona-details').slideToggle();
  });


  // Overview tab anchor links on mobile
  $(".related-content-tabs-mobile .more-link a").click(function() {
     var overview = $(this).closest('.usgs-tabs-main').siblings('.tab');
    $(overview).parent().toggleClass('active').find('.usgs-tabs-main').slideToggle('fast');
    // Get hash from clicked link
    var hash = $(this).attr('href').split('#');
    if(hash.length > 1) {
      $('.related-content-tabs-mobile .usgs-tabs-main #' + hash[1] + '').parent().toggle().parent('.topic').toggleClass('active');
    }
  });

  // Overview tab anchor links on desktop
  window.addEventListener("popstate", function(e) {

    // So we can trigger the hash link on Overview tab desktop
    if ($('.usgs-tabs').length != 0) {
      $('.related-content-tabs-desktop a[href="' + location.hash + '"]').trigger('click');

    }
  });

})(jQuery, Drupal);
