function showTweets(elem,user,limit){
	var html = '<ul>';
	var tweetFeed = 'http://api.twitter.com/1/statuses/user_timeline.json?include_rts=1&screen_name='+user+'&trim_user=true&count='+limit+'&callback=?';
	$.getJSON(tweetFeed, function(d){
		$.each(d, function(i,item) {	
			var tweetDate = new Date(item.created_at);
			var newDate = human_time_diff(tweetDate);
			var tweet = twitterFormat(item.text);
			if (i == 0) {
				html += '<li class="latest-tweet">' + tweet + '<br/><a href="http://twitter.com/#!/' + user + '/status/' + item.id_str + '"><span class="date">' + newDate + ' ago</span></a></li>';
			} else {
				html += '<li>' + tweet + '<br/><a href="http://twitter.com/#!/' + user + '/status/' + item.id_str + '"><span class="date">' + newDate + ' ago</span></a></li>';
			}	
		});
		html+="</ul>";
		elem.append(html);
	});
}

// format the text to make raw text links
function twitterFormat(text) {
	var tweet = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
		var wrap = document.createElement('div');
		var anch = document.createElement('a');
		anch.href = url;
		anch.target = "_blank";
		anch.innerHTML = url;
		wrap.appendChild(anch);
		return wrap.innerHTML;
	});
	tweet = tweet.replace(/(^|\s)@(\w+)/g, '$1@<a href="http://www.twitter.com/$2" target="_blank">$2</a>');
	return tweet.replace(/(^|\s)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>');
}

// javascript implementation of the php function human_time_diff
function human_time_diff(from, to){
var since;
 if(!to)
   to = new Date();
 diff = Math.abs(to.getTime() / 1000 - from.getTime() / 1000);
 if(diff <= 3600) {
   mins = Math.round(diff / 60);
   if(mins <= 1) {
     mins = 1;
   }
   since = mins + (mins > 1 ? " minutes" : " minute");
 } else if((diff <= 86400) && (diff > 3600)) {
   hours = Math.round(diff / 3600);
   if(hours <= 1) {
     hours = 1;
   }
   since = hours + (hours > 1 ? " hours" : " hour");
 } else if(diff >= 86400) {
   days = Math.round(diff / 86400);
   if(days <= 1) {
     days = 1;
   }
   since = days + (days > 1 ? " days" : " day");
 }
 return since;
}

jQuery.fn.twitter = function (user,limit) {
	showTweets(this,user,limit);	
}	
