
$(function() {
	tw.init();
})

var tw = {

	init: function() {
		tw.feed = $('#twitter');
		tw.id = $('li:first-child', tw.feed).attr('id').replace(/tweet_/, '');
		tw.timer = setTimeout(tw.fetch, 1000);
	},
	
	fetch: function() {
		tw.ajax = $.ajax({
			type: 'GET',
			url: '/js/feed.php',
			dataType: 'json',
			success: function(data) {
				if (data.tweet_id != tw.id) {
					tw.update(data);
					tw.id = data.tweet_id;
				}
				if (tw.timer) tw.timer = setTimeout(tw.fetch, 6000);
			}			
		});
	},
	
	update: function(data) {
		var entry = $('<li class="latest"></li>'), 
			tweet = $('<div class="tweet">' + 
				'<p class="avatar"><a href="http://www.twitter.com/' + data.from_user + '"><img src="' + data.profile_image_url + '" width="48px" height="48px" alt="' + data.from_user + '" /></a></p>' + 
				'<p class="content"><a href="http://www.twitter.com/' + data.from_user + '" class="username">' + data.from_user + '</a> ' + data.text + '</p>' + 
				'<p class="status"><a href="http://www.twitter.com/' + data.from_user + '/status/' + data.id + '">' + data.created_at + '</a> from ' + data.source + '</p>' + 
				'</div>');
		$('li:first-child', tw.feed).removeClass('latest');
		entry.append(tweet);
		tw.feed.prepend(entry);
		entry.height(entry.height());
		entry.hide();
		tweet.hide();
		entry.slideDown('slow', function() { 
			tweet.fadeIn('slow') 
		});		
		$('li:last-child', tw.feed).remove();
	}
	
};
