var limit = '4';
var count = '0';

var buildString = "";;

var TwitterAPI = {
	Statuses: {
		user_timeline:function(screen_name, count, callback){
			jQuery.getJSON("http://twitter.com/statuses/user_timeline/" + screen_name + ".json?count="+count+"&b="+Math.random()+"&callback=?",
			callback);
		}
	}
};

$(document).ready(function($) {
	var container = $('#tweet_container');
	
	TwitterAPI.Statuses.user_timeline("forx", 20, function(json) {
		var content = ''
		$.each(json, function(i) {
			if(count < limit) {
				if(this['in_reply_to_user_id_str'] == null) {
					var str = 
					'<div class="tweet">\
					<div class="txt">' + formatString(this.text) + '</div>\
					<div class="time"><a href="http://www.twitter.com/' + this.from_user + '/status/' + this.id_str + '/" target="_blank">' + relativeTime(this.created_at) + '</a></div>\
					</div>';
					content += str;
					count++;
				}
			}
		});
		container.html('');
		container.append(content);
	});
});

function formatString(str) {
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
	return str;
}

function relativeTime(pastTime) {
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	var difference = parseInt((currentStamp - origStamp)/1000);

	if(difference < 0) {
		return false;
	} else if(difference <= 5) {
		return "Just now";
	} else if(difference <= 20) {
		return "Seconds ago";
	} else if(difference <= 60) {
		return "A minute ago";
	} else if(difference < 3600) {
		return parseInt(difference/60)+" minutes ago";
	} else if(difference <= 1.5*3600) {
		return "One hour ago";
	} else if(difference < 23.5*3600) {
		return Math.round(difference/3600)+" hours ago";
	} else if(difference < 1.5*24*3600) {
		return "One day ago";
	} else {
		var dateArr = pastTime.split(' ');
		return dateArr[3].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1];
	}
}
