jQuery.fn.replaceURLsWithHTMLLinks = function() {
	// Remove existing links (to avoid weird nesting when adding later)
	var html = this.html();
	var exp = /<a\s.*href=['"](\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])['"].*>.*<\/a>/ig;
	var htmlMinusLinks = html.replace(exp,"$1");
	// Then add links
	exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	var htmlWithLinks = htmlMinusLinks.replace(exp,"<a href='$1' target='_blank'>$1</a>");
	this.html( htmlWithLinks);
	return this;
}

JRS.twitter = {};
JRS.twitter.latest_tweet_id = null;

JRS.twitter.getTweetHTML = function(tweet) {
	return $("<li></li>").attr('class','tweet '+tweet.from_user).append(
		$('<a></a>').attr('class','profilepic').attr('href','http://twitter.com/'+tweet.from_user+'/').html(
			$('<img />').attr('src',tweet.profile_image_url.replace('_normal.','_mini.')).attr('width','24').attr('height','24')
		),
		$('<div></div>').attr('class','contents').html(tweet.text).replaceURLsWithHTMLLinks(),
		$('<div></div>').attr('class','person').html(
			 'by <a href="http://twitter.com/'+tweet.from_user+'/" rel="external" class="userlink">'+tweet.from_user+'</a> '
			+' at <span class="created_at">'+tweet.created_at+'</span>')
	);
}


JRS.twitter.getTweets = function() {
	var numtweets = 10;
	JRS.twitter.timeout = null;

	var url =  "http://search.twitter.com/search.json?callback=?&rpp="+numtweets+"&";
		url += "q=worldjrs%20OR%20juniors2010ca&";
		
	if(JRS.twitter.latest_tweet_id !== null) {
		url += "since_id="+JRS.twitter.latest_tweet_id+"&";
	}
	
	$.getJSON(url,function(data){
		JRS.twitter.latest_tweet_id = data.max_id;
		
		if($('#tweets .tweet').length > 0) {
			//have tweets already.  must hide 10-(number of tweets), prepend these new tweets
			$('#tweets .tweet:gt('+(numtweets - (data.results.length + 1))+')').remove();
			$.each(data.results,function(i,tweet){
				$('#tweets').prepend(JRS.twitter.getTweetHTML(tweet));
			});
		} else {
			// dont have any tweets, can just append.
			$.each(data.results,function(i,tweet){
				$('#tweets').append(JRS.twitter.getTweetHTML(tweet));
			});
		}			
		
	});
	JRS.twitter.timeout = setTimeout('JRS.twitter.getTweets()',10000);
}

$(document).ready(function(){
	if($('#tweets').length > 0) {
		JRS.twitter.getTweets();	
	}
});