function bindReplyLink(div) {
	div.find('.reply-link').bind('click',
		function(e) {
			id = $(this).attr('href').substr(('?parent=').length);
			id = id.substr(0, id.indexOf('#'));
			
			username = $(this).parent().find('.profile-link').html();
			div.find('form input[name=parent]').val(id);
			div.find('form textarea')[0].focus();
			div.find('.in-reply-to').html('In reply to ' + username);
			
			return false;
		}
	);
}

function bindCommentsForm(div) {
	form = div.find('.comments-form');
	
	form.ajaxForm(
		{
			target: div.find('.comment-placeholder'),
			url: form.attr('action') + '?ajax=1',
			success: function(responseText) {
				comment_count = div.find('.comment-placeholder .post').size();
				if (comment_count == 1) {
					div.find('.header h3').html(comment_count + ' comment')
				} else {
					div.find('.header h3').html(comment_count + ' comments')
				}
				
				bindReplyLink(div);
				bindCommentRatings(div);
			}
		}
	);
	
	bindReplyLink(div);
}

function bindCommentRatings(div) {
	div.find('.thumb-links a').each(
		function(i) {
			$(this).bind('click',
				function(e) {
					url = $(this).attr('href') + '&ajax=1';
					link = $(this);
					
					$.ajax(
						{
							url: url,
							dataType: 'text',
							success: function(data) {
								link.parent().html('Thanks!');
							},
							error: function() {
								alert(url);
							}
						}
					);

					return false;
				}
			);
		}
	);
}

$(document).ready(
	function() {
		$('.widget.comments').each(
			function(i) {
				bindCommentsForm($(this));
				bindCommentRatings($(this));
			}
		);
	}
);