CmdUtils.CreateCommand({
  name: "ubiqs", 
  takes: {"Ubiqs/SPARQLBot command": noun_arb_text},
  author: [
    { name: "Benjamin Nowack", email: "bnowack@semsol.com"},
    { name: "Michael Hausenblas", email: "michael.hausenblas@joanneum.at"}
  ],
  license: "W3C",

  tmp: function() {
    // new tab
    Application.activeWindow.open(Utils.url(url_dest));
    // doc
    var doc = Application.activeWindow.activeTab.document;
    // doc URL
    var uri = Utils.url(doc.documentURI);
    // open in browser
    Utils.openUrlInBrowser(urlString);
  },

  getPageURL: function() {
    return Application.activeWindow.activeTab.document.documentURI;
  },

  preview: function(p_block, input) {
    if (input.text) {
      //p_block.innerHTML = input.text;
    }
  },

  execute: function(input) {
    var win = CmdUtils.getWindowInsecure();
    if (!win.ubiqs) {
      this.loadUbiqs(input);  
    }
    else {
      displayMessage("calling Ubiqs");
      var api= "http://sparqlbot.semsol.org/api/ubiqs?recipient=web";
      var api_url = api + "&url=" + escape(this.getPageURL());
      api_url += "&input=" + escape(input.text);
      var _this = this;
      jQuery.ajax({
        type: "GET",
        url: api_url,
        datatype: "string",
        error: function(responseData) {
          displayMessage(responseData.responseText);
        },
        success: function(responseData) {
          _this.displayResult(responseData);
        }
      });
    }
  },
  
  loadUbiqs: function(input) {
    displayMessage("loading Ubiqs");
    var win = CmdUtils.getWindowInsecure();
    var _this = this;
    var date = new Date();
    /* css */
    var doc = CmdUtils.getDocumentInsecure();
    var el = doc.createElement("link");
    el.rel = 'stylesheet';
    el.type = 'text/css';
    el.href = 'http://sparqlbot.semsol.org/code/sparqlbot/ubiqs.css?' + date.getTime();
    //el.href = 'http://192.168.27.144/sparqlbot.semsol.org/run/code/sparqlbot/ubiqs.css?' + date.getTime();
    doc.getElementsByTagName('head')[0].appendChild(el);
    CmdUtils.injectJavascript('http://sparqlbot.semsol.org/code/sparqlbot/ubiqs.js', function() {_this.execute(input)});
    //CmdUtils.injectJavascript('http://192.168.27.144/sparqlbot.semsol.org/run/code/sparqlbot/ubiqs.js', function() {_this.execute(input)});
  },

  displayResult: function(val) {
    displayMessage("result received");
    var win = CmdUtils.getWindowInsecure();
    win.ubiqs.onResult(val);
  }  

})
