CmdUtils.CreateCommand({
  names: ["pingfm", "ping"],
  arguments: [{role: 'object', nountype: noun_arb_text, label: 'status'}],
  icon: "http://ping.fm/favicon.ico",
 
  homepage: "http://maloki.net/projects/pingfm-ubiquity/",
  author: {name: "Richard Locsin"},
  license: "MPL",
  description: _("Post updates through Ping.fm."),
  help: _("You'll be asked to set up your <a href=\"http://ping.fm/key\">Ping.fm API key</a> using pingfm-key first, then you can post as you please."),
 
  _api_key: function() {
    var key = Application.prefs.getValue("Ping.fm key", "");
    if ( key != "" && key.length == 43) {
      return key;
    }
    else {
      return null;
    }
  },
  
  _parseText: function(text) {
    var postText = new Array();
    if (text[0] == "@" || text[0] == "#") {
      postText[0] = text.substring(0, text.indexOf(" "));
      postText[1] = text.substring(text.indexOf(" ") + 1);
    }
    else {
      postText[1] = text;
    }
    return postText;
  },

  preview: function(previewBlock, statusText) {
    var key = this._api_key();
    if (key != null) {
      var text = this._parseText(statusText.object.text);
      var previewTemplate = _("Posts this to Ping.fm: <br/><b>${status}</b><br /><br />Character count: <b>${charCount}</b>");
      
	  var trigText;
	  if ( text[0] != null ) {
	    trigText = text[0];
        previewTemplate += _("<br /> Trigger: <b>${trigger}</b>");
      }
	  else {
	    trigger = "";
	  }
	  
      var previewData = {
        status: text[1],
        charCount: text[1].length,
		trigger: trigText
        };      
    
      var previewHTML = CmdUtils.renderTemplate(previewTemplate, previewData);
       
      if(previewData.charCount > 140) {
	    var truncateTemplate = _("<br /><font color=\"pink\">Warning: In some services with a 140-character limit, the last <b>${truncate}</b> characters will not be posted!</font>");
      
        var truncateData = { truncate: previewData.charCount - 140 };
        previewHTML += CmdUtils.renderTemplate(truncateTemplate,truncateData);
      }
      previewBlock.innerHTML = previewHTML;
    }
    else {
        previewBlock.innerHTML = _('<b>Please update using the "pingfm-key" command first</b>');
    }
  },
 
  execute: function(statusText) {
    if(this._api_key() == null) {
      displayMessage( _('You need to set your API key before you can post. Use "pingfm-key" to set your it.'));
      return;
    }
    
    text = this._parseText(statusText.object.text);
    var updateUrl, updateParams;
    if(text[1] < 1) {
      displayMessage( _("Ping.fm requires a status to be entered"));
      return;
    }
    
    if (text[0] == null || text[0][0] == "@") {
      if (text[0] != null && text[0][0] == "@") {
        text[1] = statusText.object.text;
      }
      updateUrl = "http://api.ping.fm/v1/user.post";
      updateParams = {
        api_key: "94f2d8a0dfc0510b0b8e399086aac2ee",
        user_app_key: this._api_key(),
        post_method: "default",
        body: text[1]
      };
    }
    else {
      updateUrl = "http://api.ping.fm/v1/user.tpost";
      updateParams = {
        api_key: "94f2d8a0dfc0510b0b8e399086aac2ee",
        user_app_key: this._api_key(),
        trigger: text[0].substring(1),
        body: text[1]
      };
    }
    
    jQuery.post( updateUrl,
      updateParams,
      function(data) {
        xml = data.documentElement
        result = xml.getAttribute("status");
        if ( result == "OK" ) {
          displayMessage( _("Got it!  I'll go ahead and post that for you."));
        }
        else {
          displayMessage( _("Uh oh! Something went wrong!"));
        }
      }, "xml" );
  }
});

CmdUtils.CreateCommand({
  names: ["pingfm-key", "pingkey", "ping-api", "pingapi" ],
  arguments: [{role: 'object', nountype: noun_arb_text, label: 'api_key'}],
  icon: "http://ping.fm/favicon.ico",
 
  homepage: "http://maloki.net/projects/pingfm-ubiquity/",
  author: {name: "Richard Locsin", homepage: "http://maloki.net/"},
  license: "MPL",
  description: _("Sets your Ping.fm API key."),
  help: _('Set up using the command "pingfm-key this" (while your key is selected) or "pingfm-key <i>[paste the key here]</i>."'),

  _testKey: function(key) {
    if (/[a-f0-9]{32}-[0-9]{10}/.test(key))
      return true;
    else 
      return false;
  },
  _extractKey: function(key) {
    if ( this._testKey(key) ) {
      return /[a-f0-9]{32}-[0-9]{10}/.exec(key)[0];
    }
    else {
      return "";
    }
  },
  preview: function(previewBlock, newKey) {
    if (newKey.object.text == "clear") {
      previewBlock.innerHTML = _("Clears your Ping.fm App key. </br>When cleared, you can set it again using pingfm-key.");
      return;
    }
    var previewTemplate = _("Updates your Ping.fm App key from ${curKey} to: <br/><br/><b>&nbsp;&nbsp;&nbsp;&nbsp;${extract}</b><br/><br/>${validity}<br><i>You typed: ${newKey}</i>");
    var curKey = Application.prefs.getValue("Ping.fm key", "");
	if (curKey == "") {
      curKey = _("<b>no set key</b>");
    }
	
    var pretest = "";
    if (this._testKey(newKey.object.text) ) {
      pretest = _("<font color=\"lime\">That key looks good! Now let's set that key!</font>");
    }
    else {
      if (newKey.object.text.length < 43) {
        pretest += _("<font color=\"pink\"> The key is too short. Are you typing it yourself? You can just highlight it, use the \"this\" keyword or copy and paste it here!");
      }
      else if (newKey.object.text.length > 43) {
        pretest += _("<font color=\"pink\"> The key is too long. It doesn't seem to have a valid key in it too. ");
      }
      else {
        pretest += _("<font color=\"pink\"> The key has some wrong characters in it.");
      }
      pretest += _(" Remember, You can get your key from <b>http://ping.fm/key!</b></font>");
    }
    
    var previewData = {
      newKey: newKey.object.text,
      curKey: curKey,
      validity: pretest,
      extract: this._extractKey(newKey.object.text)
      };
   
    var previewHTML = CmdUtils.renderTemplate(previewTemplate, previewData);
    previewBlock.innerHTML = previewHTML;
  },
 
  execute: function(newKey) {
    if (newKey.object.text == "clear") {
      Application.prefs.setValue("Ping.fm key", "");
      displayMessage( _("Your Ping.fm App key has been cleared!"));
      return;
    }
    var updateUrl = "http://api.ping.fm/v1/user.validate";
    if (!this._testKey(newKey.object.text)) {
      displayMessage( _("Please make sure that your key is valid before we can set it. It's easy! Just go to http://ping.fm/key to get your own application key!"));
      return;
    }
    var key = this._extractKey(newKey.object.text);
    var updateParams = {
        api_key: "94f2d8a0dfc0510b0b8e399086aac2ee",
        user_app_key: key
      };
    jQuery.post( updateUrl,
      updateParams,
      function(data) {
        xml = data.documentElement
        result = xml.getAttribute("status");
        if ( result == "OK" )
        {
          Application.prefs.setValue("Ping.fm key", key);
          displayMessage( _("Woohoo! You can now post to Ping.fm!"));
        }
        else
        {
          displayMessage( _("Uh oh! Please make sure you have the right key! Remember, you can get it at http://ping.fm/key/!"));
        }
      }, "xml" );
  }
});
