/**
 * Created by jballis on 01.02.20.
 * Based on https://github.com/selfthinker/dokuwiki_template_writr/blob/master/js/skip-link-focus-fix.js
 * See also https://axesslab.com/skip-links/
 */

(function($) {

  jQuery.extend(jQuery.expr[':'], {
    focusable: function(el, index, selector){
      var $element = $(el);
      return $element.is(':input:enabled, a[href], area[href], object, [tabindex]') && !$element.is(':hidden');
    }
  });

  function focusOnElement($element) {
    if (!$element.length) {
      return;
    }
    if (!$element.is(':focusable')) {
      // add tabindex to make focusable and remove again
      $element.attr('tabindex', -1).on('blur focusout', function () {
        $(this).removeAttr('tabindex');
      });
    }
    $element.focus();
  }

  $(document).ready(function(){
    // if there is a '#' in the URL (someone linking directly to a page with an anchor)
    if (document.location.hash) {
      try {
        focusOnElement($(document.location.hash));
      }
      catch (error) {}
    }

    // if the hash has been changed (activation of an in-page link)
    $(window).bind('hashchange', function() {
      var hash = "#"+window.location.hash.replace(/^#/,'');
      if (hash.indexOf('=') === -1) {
        try {
          focusOnElement($(hash));
        }
        catch (error) {}
      }
    });
  });

})(jQuery);
