// This code derived from the tweet jquery plugin from tweet.seaofclouds.com
$.fn.extend({
      
      // Helper function to replace any link (such as http://xxx...)
      // with an actual HTML link (such as <a href="http://xxx...">http://xxx...</a>)
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\">$1</a>"))
        });
        return $(returning);
      },
      // Helper function to replace any directed tweet (such as @rwenderlich)
      // with a link to that user's account in twitter (such as <a href="http://twitter.com/rwenderlich">@rwenderlich</a>)
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>"))
        });
        return $(returning);
      }

});

// This code derived from an example in Chris Coyier's book Digging into Wordpress, pg. 112
jQuery.fn.lastTwitterMessage = function(username) {
	
	// Store the current element for later reference, because we can't get to this from
	// the JSON callback function otherwise
	var $base = this;
	
	// This is the URL to the twitter JSON api to search for updates from a particular
	// user.  Details here: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline
	var url='http://www.twitter.com/statuses/user_timeline.json?callback=?';
	$.getJSON(url, { count:10, screen_name: username }, function(data) {		
		try {
			
			// Make sure we actually got a response
			if (data && data.length >=1) {
				var item = null;
				// Ignore any tweets directed to a specific users
				for(var i = 0; i < data.length; i++) {
					if (/^@/i.test(data[i].text)) continue;
					item = data[i]; break;
				}
				
				// Now replace the current element's body with the tweet, using the helper functions
				// to add links as appropriate, and display the element
				$base.empty().append($([item.text]).linkUrl().linkUser()[0])
								
			}
		} catch (e) { };			
	});
	return this;
};
