function twit(response) {
	var target = $('#tweets');
	target.find('div.tweet').remove();
	for(var i in response.results) {
		var tweet = response.results[i];
		target.append('<div class="tweet"><h3><span class="time ts' + (Date.parse(tweet.created_at)/1000) + '"></span><a href="http://twitter.com/' + tweet.from_user + '/status/' + tweet.id + '">@' + tweet.from_user + '</a></h3><p>' + linkify(tweet.text) + '</p></div>')
	}
	time_ago();
}

function news(response) {
	var results = response.ysearchresponse.resultset_news;
	var target = $('#news')
	target.find('div.entry').remove();
	for(var i in results) {
		var result = results[i];
		target.append('<div class="entry"><h3>' + result.source + ' &raquo; <a href="' + result.url + '">' + result.title + '</a></h3><p>' + result.abstract + '</p></div>');
	}
}

function linkify(string) {
    
    string = string.replace(/(https?:\/\/\S+)/g, '<a href="$1">$1</a>')
                   .replace(/(^|\s)@(\w+)/g, ' <a href="http://twitter.com/$2">@$2</a>')
                   .replace(/(^|\s)#(\w+)/g, ' <a href=http://search.twitter.com/search?q=%23$2">#$2</a>');
    return string;
}

function time_ago() {
	
	var ref = (new Date())/1000;
	var suffix = ' ago';

	var pl = function(val) {
		return (val == 1 ? '' : 's');
	}
	
	$('span.time').each(function() {
		var classes = this.className.split(' ');
		for(var n = 0; n < classes.length; n++) {
			if (classes[n].substr(0,2) == 'ts') {
				var t = classes[n].substr(2);
				var seconds = Math.abs(t - ref);
			}
		}
		
		if (seconds < 60)
			return $(this).html('under a minute' + suffix);
			
		if (seconds < 120)
			return $(this).html('about a minute' + suffix);
		
		var minutes = Math.floor(seconds / 60);
		if (minutes < 60)
			return $(this).html(minutes + ' minute' + pl(minutes) + suffix);
		
		var hours = Math.floor(seconds / 3600); // 60 * 60
		if (hours < 48)
			return $(this).html(hours + ' hour' + pl(hours) + suffix);
		
		var days = Math.floor(seconds / 86400); // 60 * 60 * 24
		if (days < 8)
			return $(this).html(days + ' day' + pl(days) + suffix);
		
		var weeks = Math.floor(seconds / 604800); // 60 * 60 * 24 * 7
			return $(this).html(weeks + ' week' + pl(weeks) + ' ' + (days - weeks*7) + ' day' + pl(days - weeks*7) + suffix);
	});
}

function loadTweets() {
	$.getJSON('http://search.twitter.com/search.json?q=pandemic&rpp=15&lang=en&callback=?', twit)
	return false;
}

function loadNews() {
	$.getJSON('http://boss.yahooapis.com/ysearch/news/v1/pandemic?appid=gKVyPEPV34H1jWnX.hyIDxNglVQ_1NOXYoRi6O_nJzy6LvxyLue239yHLFKbmHCvWGdu&age=7d&orderby=date&count=10&region=uk&lang=en&format=json&callback=?', news);
	return false;
}

$(function() {
	$('#news a.reload').click(loadNews);
	$('#tweets a.reload').click(loadTweets);
	loadNews();
	loadTweets();
	setInterval(time_ago, 30000);
});