function time(t){
	var s = new Date();
	var sec = parseInt((Date.parse(s.toUTCString()) - Date.parse(t))/1000);
	if(sec<60){
		return "less than a minute ago";
	} else if(sec>=60 && sec<3600){
		min = sec/60; min_float_diff = min - Math.floor(min);
		if(min_float_diff > 0.7)
			return "about " + Math.ceil(min) + " minutes ago";
		int = parseInt(min);
		return (int == 1) ? int + " minute ago" : int + " minutes ago";
	} else if(sec>=3600 && sec<86400){
		hr = sec/3600; hr_float_diff = hr - Math.floor(hr);
		if(hr_float_diff > 0.5)
			return "about " + Math.ceil(hr) + " hours ago";
		int = parseInt(hr);
		return (int == 1) ? int + " hour ago" : int + " hours ago";
	} else if(sec>=86400 && sec<604800){
		days = sec/86400; days_float_diff = days - Math.floor(days);
		if(days_float_diff > 0.7)
			return "about " + Math.ceil(days) + " days ago";
		int = parseInt(days);
		return (int == 1) ? int + " day ago" : int + " days ago";
	} else if(sec>=604800 && sec<2419200){
		weeks = sec/604800; weeks_float_diff = weeks - Math.floor(weeks);
		if(weeks_float_diff > 0.7)
			return "about " + Math.ceil(weeks) + " weeks ago";
		int = parseInt(weeks);
		return (int == 1) ? int + " week ago" : int + " weeks ago";
	}
}

function tweetProcess(tweet){
	tweet = tweet.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g, "<a href='$1'>$1</a>");//link links (do this first to avoid re-linking `href`s)
	tweet = tweet.replace(/(?:(?:^@|[\s\(\[]@(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)/g, "<a href='https://twitter.com/$1'>@$1</a>");//link handles
	tweet = tweet.replace(/(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)/g, " <a href='http://search.twitter.com/search?q=%23$1'>#$1</a>");
	return tweet;
}

function template(id, text, auth, at){
	html = 	"<div class='block'>" +
				"<div class='text'>" + tweetProcess(text) + "</div> " +
				"<div class='author'>by <a href=\"http://twitter.com/"+ auth +"\">" + auth + "</a> " +
					" ... <span class='at'><a href=\"http://twitter.com/"+auth+"/statuses/"+id+"\">" + time(at) + "</a></span>" +
				"</div>" +
			"</div>";
	return html;
}

function showTweets(data){
	var d = eval(data), html = "";
	for(i=0;i<data.results.length;i++){
		d = data.results[i];
		html += template(d.id, d.text, d.from_user, d.created_at);
	}
	$("#tweetbacks").append(html);
}
