(function ($) {
  /**
   * Scroll a given fieldset into view as much as possible.
   */
  const collapseScrollIntoView = function (node) {
    var h = document.documentElement.clientHeight || document.body.clientHeight || 0;
    var offset = document.documentElement.scrollTop || document.body.scrollTop || 0;
    var posY = $(node).offset().top;
    var fudge = 55;
    if (posY + node.offsetHeight + fudge > h + offset) {
      if (node.offsetHeight > h) {
        window.scrollTo(0, posY);
      }
      else {
        window.scrollTo(0, posY + node.offsetHeight - h + fudge);
      }
    }
  };

  /**
   * Toggle the visibility of a block.
   */
  const toggleblock = function (block) {
    var $block = $(block);
    if ($block.is('.collapsed')) {
      $block
        .removeClass('collapsed')
        .attr('aria-expanded', 'true')
        .find('>:first-child .collapse-action').html("Cacher");
  
      collapseScrollIntoView(block);
    } else {
      $block
        .addClass('collapsed')
        .attr('aria-expanded', 'false')
        .find('>:first-child .collapse-action').html("Montrer");
    }
  };

  $('.collapsible').each(function () {
    const $block = $(this);

    // Add the Aria attributes to our custom element
    if ($block.hasClass('collapsed')) {
      $block.attr('aria-expanded', 'false');
    } else {
      $block.attr('aria-expanded', 'true');
    }

    // Turn the legend into a clickable link
    const $legend = $('>:first-child', this);

    $('<span class="collapse-action element-invisible"></span>')
      .append($block.hasClass('collapsed') ? "Montrer" : "Cacher")
      .prependTo($legend)
      .after(' ');

    // .wrapInner() does not retain bound events.
    const $link = $('<a href="#"></a>')
      .prepend($legend.contents())
      .appendTo($legend)
      .click(function () {
        toggleblock($block.get(0));
        return false;
      });
  });
})($);