// Pagination click
function comment_pagination_click(){
		$(document).ready(function(){
		$('div[@class~=module comments] > div.pagination-wrap > p > a').bind('click', function(e){
			e.preventDefault();
			getComments($(this).attr('href'));
		});
	});
}

/* AJAX COMMENT SUBMIT */
$(document).ready(function(){
	$('#comment-form').bind('submit', function() {
		$(this).ajaxSubmit({
			datatype: 'json',
			success: function(j){
				getComments($('div[@class~=module comments] > div.pagination-wrap > p > a').attr('href'));
				$('#comment-form').hide();
			}
		});
		return false;
	});
});

function renderComments(data){
	// Unset comments
	$('#comment-list').html('');
	// Repopulate list
	$.each(data.comments, function(i,d){
		
		$('<li />').
			append($('<a />').attr('href',d._user_cache.profile_url).attr('title',d._user_cache.username+"'s profile").
				append($('<img />').attr('src',d._user_cache.avatar).attr('height','50').attr('width','50').attr('class','thumb-small'))).
			append($('<div />').append($('<h4 />').append($('<a />').attr('href',d._user_cache.profile_url).attr('title',d._user_cache.username+"'s profile").html(d._user_cache.username))).
				append($('<p />').attr('class','comment-stats').html('on ' + d.date_submitted + ' said...')).
				append($('<p />').html(d.comment))).
		appendTo('#comment-list');
	});
	// Update count
	$('div[@class~=module comments] > div > p.pag-summary').html(data.actual + ' of '+data.total+' comments');
	
	// Update page range
	$('div[@class~=module comments] > div.pagination-wrap > p.pagination').html('');
	
	$.each(data.page_range, function(i, d){
		foo = $('<a />').attr('title','Page ' + d).attr('href',data.href+'?comments='+d).html(d);
		if (d == data.paginator_page && !data.all ) foo.attr('class','active');
		foo.appendTo($('div[@class~=module comments] > div.pagination-wrap > p.pagination'));
	});
	
	// Add view all button
	foo = $('<a />').attr('title','View all').attr('href',data.href+'?comments=all').html('view all');
	
	if (data.all) {
		foo.attr('class','active');
	}
	foo.appendTo($('div[@class~=module comments] > div.pagination-wrap > p.pagination'));
	comment_pagination_click();
}

// Comment page fetch

function getComments(href){
	$.getJSON(href, function(data){
		renderComments(data);
	});
}

comment_pagination_click();
