(function($) {
	
	$(document).ready(function() {
		
		twitter_fetch('colegleason', 2, function(tweets) {
			var html = [];
			for (i in tweets) {
				var tweet = tweets[i];
				html.push(_.sprintf('<li>%s <small><a href="%s">%s</a></small></li>', tweet.text, tweet.status, tweet.time));
			}
			$('.widget.twitter_widget ul.nostyle').html(html.join("\n"));
		});
		
	});
	
	function twitter_fetch(username, count, callback) {
		var tweets = [],
			self = this,
			url ='http://twitter.com/statuses/user_timeline/' + username +'.json?count=' + count +'&callback=?';

		$.getJSON(url, function(data) {
			$.each(data, function(i) {
				tweets.push({
					text: data[i].text
						.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,'<a target="_blank" href="$&">$&</a> ')
						.replace(/@([a-zA-Z0-9_]+)/g, '<a target="_blank" href="http://twitter.com/$1">@$1</a>')
						.replace(/#([a-zA-Z0-9_]+)/g,'<a target="_blank" href="http://twitter.com/search/$1">#$1</a>'),
					time: relative_time(data[i].created_at),
					status: 'http://twitter.com/' + username + '/status/' + data[i].id_str
				});
			});
			if ( typeof callback == 'function' ) callback.call(self, tweets);
		});
	}
	
	function relative_time(time_value) { // http://twitter.com/javascripts/blogger.js
		var values = time_value.split(" ");
		time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		delta = delta + (relative_to.getTimezoneOffset() * 60);
		if (delta < 60) {return 'less than a minute ago';}
		else if(delta < 120) {return 'about a minute ago';}
		else if(delta < (60*60)) {return (parseInt(delta / 60)).toString() + ' minutes ago';}
		else if(delta < (120*60)) {return 'about an hour ago';}
		else if(delta < (24*60*60)) {return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';}
		else if(delta < (48*60*60)) {return '1 day ago';}
		else {return (parseInt(delta / 86400)).toString() + ' days ago';}
	}

})(jQuery)
