CmdUtils.CreateCommand({
  name: "drupal",
  description: "Jumps to a node on drupal.org.",
  homepage: "http://kourge.net/projects/ubiquity",
  author: { name: "Wilson Lee", email: "kourge@gmail.com" },
  version: "0.2",
  icon: "http://drupal.org/misc/favicon.ico",
  
  takes: { "node ID": noun_arb_text },
  preview: function(block, nodeID) {
    if (!/\d+/.test(nodeID.text)) return;
    block.innerHTML = "Jumps to a node " + nodeID.text + " on drupal.org.";
    jQuery.get("http://drupal.org/node/" + nodeID.text, {}, function(data) {
      var title = data.match(/<title>(.+)<\/title>/)[1].split(" | ")[0];
      // var summary = data.match(/<div id="project-issue-summary-table" class="summary"><table>([.\s]+)\s*<\/table>/);
      block.innerHTML = "#" + nodeID.text + ": " + title;
    }, "text");
  },
  execute: function(nodeID) {
    if (/\d+/.test(nodeID.text)) {
      Utils.openUrlInBrowser("http://drupal.org/node/" + nodeID.text);
    }
    else {
      displayMessage('"' + nodeID.text + '" is not a valid node ID.');
    }
  }
});

var noun_type_drupal_function = {
  _name: "function name",
  suggest: function(text, html) {
    if (text.replace(/^\s+/, '').replace(/\s+$/, '') == "") return [];
    var suggestions;
    jQuery.ajax({
      url: "http://api.drupal.org/api/autocomplete/7/" + text,
      type: "GET", dataType: "json", async: false,
      success: function(data) {
        suggestions = [CmdUtils.makeSugg(name) for (name in data)];
      }
    });
    return suggestions.length == 0 ? [CmdUtils.makeSugg(suggestions[0])] : suggestions;
  }
};

var noun_type_drupal_version = new CmdUtils.NounType(
  "drupal version", ["d" + v for each (v in "6 5 7 4.7 4.6".split(" "))]
);

CmdUtils.CreateCommand({
  name: "drupal-api",
  description: "Looks up a function on api.drupal.org.",
  homepage: "http://kourge.net/projects/ubiquity",
  author: { name: "Wilson Lee", email: "kourge@gmail.com" },
  version: "0.2",
  icon: "http://drupal.org/misc/favicon.ico",
  
  takes: { "function name": noun_type_drupal_function },
  modifiers: { "on": noun_type_drupal_version },
  preview: function(block, functionName, mods) {
    var version = (mods.on.text || "6").replace(/[^\d]+/g, "");
    var name = functionName.text || "a function";
    var parens = (name) != "a function" ? "()" : "";
    block.innerHTML = "Looks up " + name + parens + " on Drupal " + version + ".";
  },
  execute: function(name, mods) {
    var on = mods.on.text || "6";
    var url = "http://api.drupal.org/api/function/${name}/${version}";
    var params = {name: name.text, version: on.replace(/[^\d]+/g, "")};
    Utils.openUrlInBrowser(CmdUtils.renderTemplate(url, params));
  }
});
