document.addEventListener('DOMContentLoaded', function() {
  var form = document.getElementById(#{String fvId}).closest('form');


  var formSubmit = form.querySelector('input[type=submit], button[type=submit]:not(.btn-mass-input-add):not(.btn-mass-input-delete)');
  var cellInputs = Array.from(form.querySelectorAll('.massinput--cell input:not([type=hidden])'));

  cellInputs.forEach(function(input) {
      makeImplicitSubmit(input, formSubmit);
  });


  Array.from(form.querySelectorAll('.massinput--add')).forEach(function(wrapper) {
    var addSubmit = wrapper.querySelector('.btn-mass-input-add');
    var addInputs = Array.from(wrapper.querySelectorAll('input:not([type=hidden]):not(.btn-mass-input-add)'));

    addInputs.forEach(function(input) {
      makeImplicitSubmit(input, addSubmit);
    });
  });

  // Override implicit submit (pressing enter) behaviour to trigger a specified submit button instead of the default
  function makeImplicitSubmit(input, submit) {
    if (!submit) {
      throw new Error('implicitSubmit(input, options) needs to be passed a submit element via options');
    }

    var doSubmit = function(event) {
      if (event.keyCode == 13) {
        event.preventDefault();
        submit.click();
      }
    };

    input.addEventListener('keypress', doSubmit);
  }
});
