/*jslint nomen: true, indent: 2, maxerr: 3 */
/*global window, rJS */
(function (window, rJS) {
  "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: JSON.parse(jio_string),
        application_id: "cribjs"
      })
    })
    .push(function (url_list) {
      console.log(url_list);
      document.location = document.location.href + "crib-editor4/";
    })
  }

  rJS(window)

    .declareMethod('render', function (options) {
    var gadget = this,
        jio_configuration_string = "";
    if (localStorage.hasOwnProperty("crib_js_loader_jio")) {
      jio_configuration_string = localStorage.getItem("crib_js_loader_jio");
    } else {
      jio_configuration_string = '{"type": "dav", "url": "' +  document.location.href + 'cribjs-storage/"}';
    }
    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;
    });

  });
}(window, rJS));