(function($){
	
	$.fn.latestTweets = function(settings){
		var config = {
			limit: 5,
			username: '',
			header: '<h3>LatestTweets</h3>'
		};
		
		if (settings != null){
			settings = $.extend(config, settings);
		}
		/*
		 * Error handling
		 */
		if (settings.username.length === 0){
			throw('A Twitter username is required.');
		}
		if (settings.limit <= 0){
			throw('The supplied limit must be greater than or equal to 1. It is currently set to ' + settings.limit);
		}
		
		var _this = this;
		$.getJSON(
			'http://twitter.com/status/user_timeline/' + settings.username + '.json?callback=?',
			{},
			function(result){
				if (result.length > 0){
					_this.each(function(){
						var output = $('<div class=\"latestTweets-output\"></div>');
						$(this).html(settings.header);
						var html = '';
						for (var i=0; i < settings.limit; i++){
							var tweet = result[i];
							/*
							 * Gather date information for later functionality
							 */
							var tweet_date = new Date(tweet.created_at);
							var date_now = new Date();
							var date_diff = date_now - tweet_date;
							var span = date_diff/(1000*60*60*24);
							var label = 'day';
							
							/*
							 * Figure out the relative elapsed time (seconds, minutes, hours, days)
							 */
							if (span < 1){
								span = Math.round(date_diff/(1000*60*60));
								label = 'hour';
							}
							if (span <= 0){
								span = Math.round(date_diff/(1000*60));
								label = 'minute';
							}
							if (span <= 0){
								span = Math.round(date_diff/(1000));
								label = 'second'
							}
							if (label === 'day'){
								span = Math.round(span);
							}
							if (span > 1){
								label += 's';
							}
							
							/*
							 * Parse the tweet text and turn URLs, @usernames and hashtags into anchor tags
							 */
							var tweet_text = tweet.text;
								tweet_text = tweet_text.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/,'<a href=\"$1\" target=\"_blank\">$1</a>');
								tweet_text = tweet_text.replace(/(@\w+)/gi,'<a href=\"http://twitter.com/$1\" target=\"_blank\">$1</a>');
								tweet_text = tweet_text.replace('/@','/');
								tweet_text = tweet_text.replace(/(#\w+)/gi,'<a href=\"http://search.twitter.com/search?q=$1\" target=\"_blank\">$1</a>');
								tweet_text = tweet_text.replace('q=#','q=%23');
							html += '<div class=\"ttTweet\">';
							html += tweet_text;
							if (!isNaN(span)){
								html += '<span class=\"ttDate\"> ' + span + ' ' + label + ' ago</span>';
							}
							html += '</div>';
						}
						output.html(html);
						$(this).after(output);
					});
				}
			}
		);
	}
	
})(jQuery);
