
function spellHumanizeNumber(number){
 var multipliers = [1e9, 1e6]
  var names = "billion million".split(" ")
  for (var i=0; i <= multipliers.length ; i++){
    multiplier = multipliers[i];
    name = names[i];
    if (number > multiplier){
      return number / multiplier + " " + name;
    }
  }
  return String(number);
}

function spellTrim(string){
    return string.replace(/^ *| $/g, '');
}



CmdUtils.CreateCommand({
  names: ["spell"],
  description: "Given a guessed spelling, return the (probably) correct spelling using google.",
  help: '<br/> <b>spell</b> <em>guess</em> <ul> <li><span style="color:red">Red</span> means google corrected the spelling</li> <li><span style="color:green">Green</span> means the guess wasn\'t corrected and had a lot of matches</li> <li><span style="color:orange">Orange</span> means guess wasn\'t corrected and had fewer matches</li></ul> Accepting shows the google search page.',
  author: {name: "Tom Wright", email: "tat.wright@googlemail.com"},
  license: "BSD",
  homepage: "http://tat.wright.name/ubiquity-spell/",
  arguments: [{role: 'object', nountype: /^ *[a-zA-Z]+ *$/, label: 'guess'}],
  preview: function preview(pblock, args) {
    var word = spellTrim(args.object.text);
    if (!word){
      pblock.innerHTML = "";
      return;
    }
    jQuery.get("http://www.google.com/search", {q: word}, function(data){
      var parsetree = jQuery(data);
      var suggestion = parsetree.find(".spell i").filter(":first").text();
      var count = parseInt(parsetree.find('#ssb p b').filter(":eq(2)").text().replace(/,/g, ""));
      var countString = spellHumanizeNumber(count);
      var template = '<span style="color:${color}; font-size:300%">${word}</span>';
      if (suggestion){
        pblock.innerHTML = _(template, {word: suggestion, color: 'red'});
      } else if (count > 9e4) {
        pblock.innerHTML = _(template, {word: word, color:'green'}) +  "    (" + countString + " matches)" ;
        suggestion = word;
      } else {
        pblock.innerHTML = _(template, {word: word, color:'orange'}) + "     (" + countString + " matches)";
        suggestion = word;
      }
      var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].
      getService(Components.interfaces.nsIClipboardHelper);
      gClipboardHelper.copyString(suggestion);
    });
  },

  execute: function execute(args) {
    Utils.openUrlInBrowser("http://www.google.com/search?q=" +
        spellTrim(args.object.text));
  }
});


