/**
 * @file
 * JavaScript behaviors for webforms 508 using jQuery UI.
 */

(function ($, Drupal) {

  'use strict';

  /**
   * Handle webform submission errors for 508 accessibility. Focus on the
   * error status message close button. When closed focus on the error field.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior for submission errors.
   *
   */
  Drupal.behaviors.submissionErrors = {
    attach: function attach(context) {
      var $context = $(context);

      $context.find('div.alert-danger').once('submission-error').each(function () {
        var $messageContext = $(this);
        var $formContext = $context.find('form.webform-submission-form');

        var closeButton = $messageContext.find('.close');
        var text = $messageContext.find('.placeholder').html();
        var errorField = $formContext.find('div:contains(' + text + ') > input');
        if (!$(errorField).length) {
          errorField = $formContext.find('input[value="' + text + '"]');
        }

        $(closeButton).focus(function (e) {
          $('html, body').animate({scrollTop: 0}, 'slow');
          e.stopPropagation();
          e.stopImmediatePropagation();
          return false;
        });

        $(closeButton).click(function () {
          $(errorField).focus();
        });

        $(closeButton).focus();
      });
    }
  };

  /**
   * Handle webform pii with 508 accessibility.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior for submission protected input.
   *
   */
  Drupal.behaviors.submissionProtected = {
    attach: function attach(context) {
      var $context = $(context);
      $context.find(".protected-input").once("submission-protected").each(function () {
        var element_type = getElementType($(this));
        var supported = isSupportedType(getElementType);
        if (isSupportedType(element_type) === -1) {
          return false;
        }
        showToggleLink($(this), element_type);
        toggleElement($(this), element_type);
      });

      $("a.toggle-protected").on('click', function (e) {
        var element = ($(this).parents("fieldset.protected-input").length === 0)
            ? $(this).siblings(".protected-input")
            : $(this).parents("fieldset.protected-input");

        toggleLink($(this));
        toggleElement($(element), getElementType($(element)));
        e.stopPropagation();
        e.stopImmediatePropagation();
        return false;
      });
    }
  };

  function getElementType(element) {
    return $(element).prop('tagName').toLowerCase();
  }

  function isSupportedType(element_type) {
    var arr = ['input', 'select', 'fieldset'];
    return jQuery.inArray(element_type, arr);
  }
  function showToggleLink(element, element_type) {
    var label = (element_type == 'fieldset')
        ? $(element).children('legend').children('span')
        : $(element).siblings('label');

    var show_protect = '<a href="#" class="toggle-protected protected'
        + ' float-sm-right">'
        + '<i role="presentation" class="fa-solid fa-eye"></i><span>Show</span> '
        + $(label).html().replace(':', '') + '</a>';
    $(label).after($(show_protect));
  }


  function toggleElement(element, element_type) {
    if (element_type == 'fieldset') {
      toggleElement_fieldset($(element));
    }
    if (element_type == 'input') {
      toggleElement_input($(element));
    }
    if (element_type == 'select') {
      toggleElement_select($(element));
    }
  }

  /**
   * Toggle show/hide for input elements.
   */
  function toggleElement_input(element) {
    $(element).toggleClass('protected');

    if (navigator.userAgent.indexOf("Firefox") != -1) {
      if ($(element).attr('type') == "password") {
        $(element).attr('type', 'text');
      } else {
        $(element).attr('type', 'password');
      }
    }
    $(element).focus();
  }
  /**
   * Toggle show/hide for select elements.
   */
  function toggleElement_select(element) {
    $(element).toggleClass('protected');
    $(element).focus();
  }

  /**
   * Toggle show/hide elements in fieldset.
   */
  function toggleElement_fieldset(element) {
    $(element).find("select").toggleClass('protected');
    $(element).find("input").toggleClass('protected');
    if (navigator.userAgent.indexOf("Firefox") !== -1) {
      $(element).find("input").each(function () {
        if ($(this).attr('type') === "password") {
          $(this).attr('type', 'text');
        } else {
          $(this).attr('type', 'password');
        }
      });
    }
    $(element).find('input[type=text],textarea,select').filter(':visible:first').focus();
  }

  /**
   * Toggle the hide/show link.
   */
  function toggleLink(element) {
    $(element).toggleClass('protected');
    $(element).find('[data-fa-i2svg]').children('svg')
        .toggleClass('fa-eye-slash')
        .toggleClass('fa-eye');

    if ($(element).children('span').html() == 'Show') {
      $(element).find('span').html('Hide');
    } else {
      $(element).find('span').html('Show');
    }
  }
})(jQuery, Drupal);