(function() {
  'use strict';

  window.utils = window.utils || {};

  // registers input-listener for each element in <inputs> (array) and
  // enables <button> if <validation> for these inputs returns true
  window.utils.reactiveButton = function(form, button, validation) {
    var requireds = Array.from(form.querySelectorAll('[required]'));
    if (requireds.length == 0) {
      return false;
    }
    if (typeof button.dataset.formnorequired !== 'undefined' && button.dataset.formnorequired !== null) {
      button.addEventListener('click', function() {
        form.submit();
      });
      return false;
    }
    updateButtonState();

    requireds.forEach(function(el) {
      var checkbox = el.getAttribute('type') === 'checkbox';
      var eventType = checkbox ? 'change' : 'input';
      el.addEventListener(eventType, function() {
        updateButtonState();
      });
    });

    function updateButtonState() {
      if (validation.call(null, requireds) === true) {
        button.removeAttribute('disabled');
      } else {
        button.setAttribute('disabled', 'true');
      }
    }
  };

  window.utils.interactiveFieldset = function(form, fieldSets) {
    var fields = fieldSets.map(function(fs) {
      return {
        fieldSet: fs,
        condId: fs.dataset.conditionalId,
        condValue: fs.dataset.conditionalValue,
        condEl: form.querySelector('#' + fs.dataset.conditionalId),
      };
    }).filter(function(field) {
      return !!field.condEl;
    });

    function updateFields() {
      fields.forEach(function(field) {
        field.fieldSet.classList.toggle('hidden', field.condEl.value !== field.condValue);
      });
    }

    function addEventListeners() {
      fields.forEach(function(field) {
        field.condEl.addEventListener('input', updateFields)
      });
    }

    if (fieldSets.length) {
      addEventListeners();
      updateFields();
    }
  };
})();

document.addEventListener('setup', function(e) {
  if (e.detail.module && e.detail.module !== 'showHide')
    return;

  var forms = e.detail.scope.querySelectorAll('form');
  Array.from(forms).forEach(function(form) {
    // auto reactiveButton submit-buttons with required fields
    var submitBtns = Array.from(form.querySelectorAll('[type=submit]:not([formnovalidate])'));
    submitBtns.forEach(function(submitBtn) {
      window.utils.reactiveButton(form, submitBtn, validateForm);
    });

    // auto conditonal fieldsets
    var fieldSets = Array.from(form.querySelectorAll('fieldset[data-conditional-id][data-conditional-value]'));
    window.utils.interactiveFieldset(form, fieldSets);
  });

  function validateForm(inputs) {
    var done = true;
    inputs.forEach(function(inp) {
      var len = inp.value.trim().length;
      if (done && len === 0) {
        done = false;
      }
    });
    return done;
  }
});

document.addEventListener('DOMContentLoaded', function() {
  document.dispatchEvent(new CustomEvent('setup', { detail: { scope: document.body, module: 'showHide' }, bubbles: true, cancelable: true }))
});


document.addEventListener('setup', function(e) {
    if (e.detail.module && e.detail.module !== 'autoSubmit')
        return;

    Array.from(e.detail.scope.querySelectorAll('[data-autosubmit]:not(.js-initialized)')).forEach(function(elem) {
        if ((elem instanceof HTMLInputElement && elem.type == 'submit') || (elem instanceof HTMLButtonElement && elem.type == 'submit')) {
            var ancestor = elem.closest('.form-group');
            var target = ancestor || elem;

            target.classList.add('hidden');
        }

        elem.classList.add('js-initialized');
    });
});

document.addEventListener('DOMContentLoaded', function() {
  document.dispatchEvent(new CustomEvent('setup', { detail: { scope: document.body, module: 'autoSubmit' }, bubbles: true, cancelable: true }))
});
