(function (window, rJS, RSVP) {
    "use strict";

    function validateHttpUrl(value) {
      /*jslint regexp: true*/
      if (/\(?(?:(http|https):\/\/)(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[\dabcedf:]+\])(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}\#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.\#]*)?([\.]{1}[^\s\?\#]*)?)?(?:\?{1}([^\s\n\#\[\]]*))?([\#][^\s\n]*)?\)?/i.test(value)) {
        return true;
      }
      /*jslint regexp: false*/
      return false;
    }

    rJS(window)
    .declareAcquiredMethod("notifySubmitting", "notifySubmitting")
    .declareAcquiredMethod("notifySubmitted", "notifySubmitted")
    .declareAcquiredMethod("setSetting", "setSetting")
    .declareAcquiredMethod("getSetting", "getSetting")
    .declareAcquiredMethod("jio_get", "jio_get")
    .declareAcquiredMethod("jio_post", "jio_post")

    .declareMethod("preRenderDocument", function (parent_options) {
        var gadget = this;
        return gadget.jio_get(parent_options.jio_key)
          .push(function (parent_document) {
              return parent_document;
          });
    })

    .declareMethod("handleSubmit", function (content_dict, parent_options) {
        var return_submit_dict,
        gadget = this,
        list = parent_options.doc.links,
        index_name = parent_options.doc.title,
        jio_key = parent_options.action_options.jio_key,
        link_list,
        i;

        return_submit_dict = {
          notify: {
            message: "",
            status: "success"
          },
          redirect: {
            command: "display",
            options: {page : "ojs_local_controller", jio_key: jio_key}
          }
        };

        link_list = list.split("\n").filter(l => l.length > 0);
        for (i = 0; i < link_list.length; i += 1) {
          if (!validateHttpUrl(link_list[i])) {
            return_submit_dict.notify.message = "Links paramter has invalid URL(s)!";
            return_submit_dict.notify.status = "error";
            return return_submit_dict;
          }
        }

        return gadget.getSetting("build_dict", {})
        .push(function(build_dict){
          build_dict[jio_key] = {
            links: list,
            index_name: index_name,
            jio_key: jio_key,
            id: Date.now()
          };
return gadget.setSetting("build_dict", build_dict);
        })
        .push(function(){
           return_submit_dict.notify.message = "Index " + index_name  +
             " will start building...";
            return return_submit_dict;
        });
    });

}(window, rJS, RSVP));