(function($) {
  
  $(document).on('click', '.js-form-item-program-select-program-1', function(e) {
    e.preventDefault();
  });
  
  const $rfi = $('.webform-submission-rfi-embedded-program-form-form');
  const $chat = $('.open-chat');
  let timeout = false;
  if ($rfi.length && $chat.length) {
    $chat.css('transition', 'transform .5s');
    
    /**
     * Revalidate the timeout involved with re-introducing chat to the viewport.
     *
     * @param {boolean} set
     *   True if a new timeout is to be set, otherwise the old timeout is destroyed.
     */
    function revalidate_timeout(set) {
      if (timeout !== false) {
        clearTimeout(timeout);
      }
      if (set) {
        timeout = setTimeout(function() {
          if (!$rfi[0].matches(':focus-within')) {
            $chat.css('transform', 'none');
          }
        }, 5000);
      }
    }
    
    const focusable = '.webform-submission-rfi-embedded-program-form-form a, .webform-submission-rfi-embedded-program-form-form input, .webform-submission-rfi-embedded-program-form-form select, .webform-submission-rfi-embedded-program-form-form button';
    
    // Immediately translate the chat bubble off the screen and kill the timeout.
    $(document).on('focus', focusable, function() {
      $chat.css('transform', 'translateX(200px)');
      revalidate_timeout(false);
    });
    
    // Reset the timeout to make it work consistently.
    $(document).on('focusout', focusable, function() {
      revalidate_timeout(true);
    });
  }
})(jQuery);