(function () {

  var submitButton = document.querySelectorAll('[data-xapi-submit]')[0];
  // Nothing to enable - exit early.
  if (submitButton.getAttribute('disabled') !== 'disabled') {
    return;
  }

  function processIframe() {
    var iframe = document.getElementById('xapi-iframe');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if the activity has been finished.
    // @todo Overriding the XMLHttpRequest send() method is a very drastic
    // measure. Iframe has the TinCan object available so it'd be good
    // to check if we can somehow hook into that if there only was some
    // decent documentation.
    if (iframeDoc.readyState !== 'complete') {
      // The iframe is not loaded yet. Keep checking.
      window.setTimeout(processIframe, 100);
      return;
    }

    var proxied = iframe.contentWindow.XMLHttpRequest.prototype.send;
    iframe.contentWindow.XMLHttpRequest.prototype.send = function () {
      // Determine if a Xapi statement is being sent and if it has the
      // result.completion property.
      if (arguments.length === 0) {
        return proxied.apply(this, [].slice.call(arguments));
      }
      try {
        var statement = JSON.parse(arguments[0]);
      }
      catch (e) {
        return proxied.apply(this, [].slice.call(arguments));
      }
      if (
        typeof(statement.verb) === 'undefined' ||
        typeof(statement.result) === 'undefined' ||
        typeof(statement.result.completion) === 'undefined'
      ) {
        return proxied.apply(this, [].slice.call(arguments));
      }

      if (statement.result.completion) {
        submitButton.removeAttribute('disabled');
        submitButton.classList.remove('is-disabled');
      }

      return proxied.apply(this, [].slice.call(arguments));
    }
  }

  processIframe();
})();
