//Modefied version of code from: http://ralphwhitbeck.com/content/binary/twitter-json-jquery.html

var bbg_tweet = {};
bbg_tweet.displayMax = 2;

bbg_tweet.readTwitterData = function() {
	var url = "http://twitter.com/status/user_timeline/bklynbotanic.json?count=20&callback=?";
	$.getJSON(url, bbg_tweet.displayTwitterData);
};

bbg_tweet.displayTwitterData = function(data) {
	//create a ul tag to add the tweets to
	$("#tweets").append("<ul></ul>");

	var tweets_shown = 0;
	//Loop thrugh the data and add the items to the <ul>.
	$.each(data, function(i, item) {
		//If we've added the maximum items to show, exit.
		if(tweets_shown >= bbg_tweet.displayMax) return false;
		
		//If the item has an @ symbol we'll assume it's a reply tweet.
		var is_reply = /\@/.test(item.text);
		//If the item has an 'RT' at the begineing, we'll assume it's a re-tweet.
		var is_retweet = /^RT/.test(item.text);

		//Dislay only non replys and non retweets.
		if((! is_reply) && (! is_retweet)) {
			$("#tweets ul").append("<li>"+bbg_tweet.formatLink(item.text)+
			"<br /><span class='created_at'>"+bbg_tweet.formatRelativeTime(item.created_at)+
			"</span></li>");
			tweets_shown++;
		}
	});

	$("a#twitter_link").html("Follow us on Twitter");
};

bbg_tweet.formatLink = function(string) {
	return string.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) { return m.link(m); });
};

bbg_tweet.formatRelativeTime = function(time_value) {
	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);
  
	var r = '';
	if (delta < 60) {
		r = 'a minute ago';
	} else if(delta < 120) {
		r = 'couple of minutes ago';
	} else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (90*60)) {
		r = 'an hour ago';
	} else if(delta < (24*60*60)) {
		r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		r = '1 day ago';
	} else {
		r = (parseInt(delta / 86400)).toString() + ' days ago';
	}
	return r;
}

bbg_tweet.readTwitterData();