(function(){

jQuery(document).ready(function(){
	jQuery('div.post').each(function() {
		var id = jQuery(this).attr('id');
		if(/^post\-[0-9]+$/.test(id)) {
			var toggle = jQuery('<a href="javascript:void(0);" class="toggle"></a>');
			toggle.toggle(function() {
				if(jQuery('#' + id + ' .content').text() == '') {
					var postId = id.slice(5);
					jQuery.ajax({
						type:         'GET'
						,url:         '?action=load_post&id=' + postId
						,cache:       false
						,dataType:    'html'
						,contentType: 'application/json; charset=utf-8'
						,beforeSend:  function(data){loadPostContent(id, '<p class="ajax-loader">Loading...</p>');}
						,success:     function(data){loadPostContent(id, data);}
						,error:       function(data){loadPostContent(id, '<p>Oops, failed to load data.</p>');}
					});
				}
				jQuery('#' + id + ' .content').slideDown();
				jQuery(this).removeClass('collapse').addClass('expand');
			},
			function() {
				jQuery('#' + id + ' .content').slideUp();
				jQuery(this).removeClass('expand').addClass('collapse');
			}).prependTo(jQuery('#' + id + ' h1'));
		}
	});
	jQuery('div.post a.toggle').each(function(index) {
		if(index < 2) {
			jQuery(this).click();
		}
	});
});

function loadPostContent(id, data) {
	jQuery('#' + id + ' .content').html(data);
}

})();
