/**
 * @provides javelin-behavior-workflow
 * @requires javelin-behavior
 *           javelin-stratcom
 *           javelin-workflow
 *           javelin-dom
 */

JX.behavior('workflow', function() {

  // Listen for both real and synthetic submit events.
  JX.Stratcom.listen(
    ['submit', 'didSyntheticSubmit'],
    ['workflow', 'tag:form'],
    function(e) {
      if (JX.Stratcom.pass()) {
        return;
      }

      // NOTE: We activate workflow if any parent node has the "workflow" sigil,
      // not just the <form /> itself.

      e.prevent();
      JX.Workflow.newFromForm(e.getNode('tag:form')).start();
    });

  JX.Stratcom.listen(
    'click',
    ['workflow', 'tag:a'],
    function(e) {
      if (!e.isNormalClick()) {
        return;
      }

      // NOTE: As above, we want to activate workflow if a parent node has
      // the sigil, not just the <a /> that the user clicked. However, there
      // is an exception in this case: if the <a /> does not have workflow and
      // is inside a <form /> which does, we don't workflow it (this covers
      // things like "help" links in captions). Test if the node with the
      // workflow sigil is a form.

      var workflow_node = e.getNode('workflow');
      if (JX.DOM.isType(workflow_node, 'form')) {
        // This covers the case of an <a /> without workflow inside a <form />
        // with workflow.
        return;
      }

      if (JX.Stratcom.pass()) {
        return;
      }

      e.prevent();
      JX.Workflow.newFromLink(e.getNode('tag:a')).start();
    });

});
