function showTweets(elem){
	var html = '<ul>';

	//var tweetFeed = 'http://twitter.com/status/user_timeline/juptrking.json?count=2&include_rts=1&callback=?'
	var tweetFeed = 'http://api.twitter.com/1/statuses/user_timeline.json?include_rts=1&screen_name=juptrking&trim_user=true&count=2&callback=?';
	$.getJSON(tweetFeed, function(d){
		var limit = 1;
		$.each(d, function(i,item) {	
			if(i > limit) {
				return false;
			}	
			var myNewDate = new Date(item.created_at);
			var pubDate = human_time_diff(myNewDate);
			var theTweet = twitterFormat(item.text);
			html+='<li>'+theTweet+'<span><a href="http://twitter.com/#!/juptrking/status/'+item.id_str+'">'+pubDate+' ago.</a></span></li>';
		});
		
		html+="</ul>";
		
		elem.children().fadeOut('fast',function(){
			elem.append(html);
		});
		
	});
}

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;
}

$(function() {
	$('.dataError').remove();
	$('#preload').show();
	showTweets($('#tweets'));
});
	

