$(document).ready(function () {
  $('.modal.inail-modale').on('shown.bs.modal', function () {
    var $modal = $(this);

    // Focus sul titolo della modale
    var $title = $modal.find('div.inail-modale-title');

    $title.trigger('focus');

    var $focusableElements = $modal.find(
      'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex]:not([tabindex="-1"]), [contenteditable]'
    );

    var $firstFocusable = $focusableElements.first();
    var $lastFocusable = $focusableElements.last();

    // $firstFocusable.trigger('focus');

    function trapFocus(e) {
      if (e.key === 'Tab' || e.keyCode === 9) {
        if (e.shiftKey) {
          if (document.activeElement === $firstFocusable[0]) {
            e.preventDefault();
            $lastFocusable.focus();
          }
        } else {
          if (document.activeElement === $lastFocusable[0]) {
            e.preventDefault();
            $firstFocusable.focus();
          }
        }
      }
    }

    $modal.on('keydown', trapFocus);

    $modal.on('hidden.bs.modal', function () {
      $modal.off('keydown', trapFocus);
    });
  });
});
