(function( $ )
{
	$.extend( 
	{
		jTwitter: function( username, numPosts, fnk ) 
		{
			var info = {};
			
			// If no arguments are sent or only username is set
			if( username == 'undefined' || numPosts == 'undefined' ) 
			{
				return;
			}
			else if( $.isFunction( numPosts ) ) 
			{
				// If only username and callback function is set
				fnk = numPosts;
				numPosts = 5;
			}
			
			var url = 'http://twitter.com/status/user_timeline/' + username + '.json?count=' + numPosts + '&callback=?';

			$.getJSON( url, function( data )
			{
				if( $.isFunction( fnk ) ) 
				{
					fnk.call( this, data );
				}
			});
		}
	});
})( jQuery );

var browser = function() {
  var ua = navigator.userAgent;
  return {
	ie: ua.match(/MSIE\s([^;]*)/)
  };
}();

function time_ago(dateString)
{
	  var rightNow = new Date();
	  var then = new Date(dateString);

	 if (browser.ie) {
		// IE can't parse these crazy Ruby dates
		then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
	 }

	  var diff = rightNow - then;

	  var second = 1000,
		  minute = second * 60,
		  hour = minute * 60,
		  day = hour * 24,
		  week = day * 7;

	  if (isNaN(diff) || diff < 0) {
		return ""; // return blank string if unknown
	  }

	  if (diff < second * 2) {
		// within 2 seconds
		return "right now";
	  }

	  if (diff < minute) {
		return Math.floor(diff / second) + " seconds ago";
	  }

	  if (diff < minute * 2) {
		return "about 1 minute ago";
	  }

	  if (diff < hour) {
		return Math.floor(diff / minute) + " minutes ago";
	  }

	  if (diff < hour * 2) {
		return "about 1 hour ago";
	  }

	  if (diff < day) {
		return  Math.floor(diff / hour) + " hours ago";
	  }

	  if (diff > day && diff < day * 2) {
		return "yesterday";
	  }

	  if (diff < day * 365) {
		return Math.floor(diff / day) + " days ago";
	  }

	  else {
		return "over a year ago";
	  }
};

$('#tweets').append('<ul id="twitter_update_list"><\/ul>');

$.jTwitter('Sporting_Globe', 5, function(data)
{
	$('#twitter_update_list').empty();
	$.each(data, function(i, post)
	{
		var date = time_ago(post.created_at);
		var reply = '<a class="twtr-reply" href="http://twitter.com/?status=@Sporting_Globe%20&in_reply_to_status_id=' + post.id + '&in_reply_to=Sporting_Globe">reply<\/a>';
		var status = '<a class="twtr-reply" href="http://twitter.com/Sporting_Globe/status/' + post.id + '">' + date + '<\/a>';
		$('#twitter_update_list li:first-child').addClass('current');
		$('#twitter_update_list').append('<li>' + post.text + ' <div>' + status + ' - ' + reply + '<\/div><\/li>');
	});
});

setInterval(function()
{
	$('ul#twitter_update_list li:first-child').fadeOut('slow')
	.next('li').fadeIn('slow').addClass('current').end()
	.appendTo('ul#twitter_update_list');
}, 10000);
