/*jslint nomen: true, indent: 2, maxerr: 3 */
/*global window, rJS */
(function (window, rJS, loopEventListener) {
  "use strict";
  
  function loadCribJS (gadget, event) {
    var jio_cribjs_gadget,
      jio_configurator_gadget;
    return RSVP.Queue()
    .push(function() {
      return RSVP.all([
        gadget.getDeclaredGadget("jio_cribjs"),
        gadget.getDeclaredGadget("jio_configurator")]);
    })
    .push(function(gadget_list) {
      jio_cribjs_gadget = gadget_list[0];
      jio_configurator_gadget = gadget_list[1];
      return jio_configurator_gadget.getContent();
    })
    .push(function (jio_string) {
      return jio_cribjs_gadget.load({
        path: document.location.href,
        jio_config: jio_string,
        application_id: "cribjs"
      })
    })
    .push(function (url_list) {
      document.location = document.location.href + "crib-editor4/";
    })
    .push(console.log, console.log);
  }

  rJS(window)

    .declareMethod('render', function (options) {
    var gadget = this,
        jio_configuration_string = "https://cribjs.nexedi.net/cribjs-latest.zip";
    return RSVP.Queue()
      .push(function () {
      return gadget.getDeclaredGadget('jio_configurator');
    })
      .push(function (jio_configurator_gadget) {
      return jio_configurator_gadget.render({value: jio_configuration_string});
    })
      .push(function () {
      return loopEventListener(
        gadget.props.element.querySelector("form.loading"),
        'submit',
        false,
        function (event) {loadCribJS(gadget, event)}
      );
    })
    .fail(function(e){console.log(e)})
  })

    .ready(function (g) {
    g.props = {};
    return g.getElement()
      .push(function (element) {
      g.props.element = element;
    }).push(function() {
      g.render({})
    })
    ;

  });
}(window, rJS, loopEventListener));