$(document).ready(function() {
	displayFeed('/js/blog/', true);
	// if (start <= 0) {
	// 	displayFeed('/js/twitter/', false);
	// }
});

displayFeed = function(feedURL, insertLink) {
	$.ajax({
		type: 'GET',
		url: feedURL+'?start='+start+'&per_page='+per_page,
		data: '',
		dataType: 'json',
		success: function(data) {
			$.each(data, function (i, entry) {
				html = $('#'+entry.id);
				if (html[0]) {
				} else {
					displayEntry(entry);
					if (insertLink) {
						var postLink = $('<li/>');
						postLink.html('<a href="'+entry.slug+'">'+entry.title+'</a>');
						$('#recent_menu ul').prepend(postLink);
					}
				}
			});
		}
	});
}

var timestamps = new Array();
var guids = new Array();
var initialCount = 0;

displayEntry = function(entry) {
	if (timestamps.length == 0) {
		$('li.post').each(function(i, item) {
			timestamps.push($(this).attr('timestamp'));
			guids.push($(this).attr('id'));
		});
	}

	var guid_pos = $.inArray(entry.guid, guids);
	initialCount = timestamps.length;
	
	if (guid_pos < 0) {
		timestamps.push(entry.timestamp);
		timestamps.sort();
		var pos = $.inArray(entry.timestamp, timestamps);
		var newPos = initialCount - pos;
	
		var entryLI = $('<li/>').addClass('post').attr('timestamp', entry.timestamp).html(entry.html);
		if (newPos <= 0) {
			$('#blog ul').prepend(entryLI);
		}
		else if (newPos <= initialCount) {
			$($('#blog ul').children("li")[newPos - 1]).after(entryLI);
		}
		entryLI.slideDown(600);
	}
	
}

