/*
 * jQuery Twitter Widget
 * Copyright (c) 2009 Anthony Ferguson
 * http://www.fergusweb.net
 * 
 * Usage:
 * 		Simply have have this in your HTML somewhere:
 *		<ul class="TwitterWidget" user="USERNAME" count="3"></ul>
 */


jQuery(document).ready(function($){
	$('ul.TwitterWidget').TweetList();
});


(function($) {
	// Primary Function
	$.fn.TweetList = function(options) {
		return this.each(function() {
			var ul = $(this);
			twitterJSON = 'http://twitter.com/statuses/user_timeline/'+ ul.attr('user') +'.json?count='+ ul.attr('count')+'&callback=?';
			
			$.getJSON( twitterJSON, function(data) {
				$(data).each(function(i) {
					//alert($(data));
					var regUser = /\B@([_a-z0-9]+)/ig;
					var regLink = /((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g;
					// Important to do url before user, otherwise you double-up
					this.text = this.text.replace(regLink, function(url) {
						return '<a href="'+url+'">'+url+'</a>';
					}).replace(regUser, function(user) {
						return '<a href="http://twitter.com/'+user+'">'+user+'</a>';;
					});
					// Prepare & insert the <li>
					var li = $('<li>').attr({ id: this.id }).appendTo( $(ul) );
					var span = $('<span>').appendTo( $(li) );
					$(span).attr( 'class','tweet' );
					$(span).attr( 'innerHTML', this.text );
					var stamp = $('<a>').appendTo( $(li) );
					$(stamp).attr('class', 'time');
					$(stamp).attr('href', 'http://twitter.com/'+ ul.attr('user') +'/statuses/'+ this.id);
					$(stamp).attr('innerHTML', FormatTime(this.created_at));
				});
			});
			
		});
	};
	// Time Formatting
	// Borrows heavily from: http://twitter.com/javascripts/blogger.js
	// Must be a nicer way to do this? Surely?
	function FormatTime(Time) {
		timeVals = Time.split(' ');
		timeValue = timeVals[1]+' '+timeVals[2]+' '+timeVals[5]+' '+timeVals[3]; // Mon DD YYYY HH:ii:ss
		dateObj = Date.parse(timeValue);
		timeRel = new Date(); // Using local timezone
		timeDelta = parseInt((timeRel.getTime() - dateObj) / 1000)+(timeRel.getTimezoneOffset()*60);  // Get the number of seconds since tweet, in local timezone
		if (timeDelta < 10) {
			return 'Just now';
		} else if (timeDelta < 60) {
			return 'Less than a minute ago';
		} else if(timeDelta < (45*60)) {
			return (parseInt(timeDelta / 60)).toString() + ' minutes ago';
		} else if(timeDelta < (120*60)) {
			return 'About an hour ago';
		} else if(timeDelta < (24*60*60)) {
			return 'About ' + (parseInt(timeDelta / 3600)).toString() + ' hours ago';
		} else if(timeDelta < (48*60*60)) {
			return '1 day ago';
		} else {
			return (parseInt(timeDelta / 86400)).toString() + ' days ago';
		}
	};
})(jQuery);
