function cleanForm() {
	$(".flash, .validation-errors").remove();
}

function commentSuccess(r) {
	if (r.first_comment == 1) {
		$("#comment").before('<h2>Comments</h2><section id="comments"></section>');
		$(".comment-add").before(r.comment_count + ' - ');
	} else {
		$(".comment-count").replaceWith(r.comment_count);
	}
	$("#comments").append(r.new_comment);
}

function commentErrors(r) {
	$.each(r.errors, function() {
		$("#comment_" + this[0]).after('<ul class="validation-errors"><li>' + this[1] + '</li></ul>');
	});
}

$(function() {	
	var $commentForm = $("#new_comment");
	if (/*@cc_on!@*/0) {
		$commentForm.after('<div class="flash notice"><h2>Internet Explorer = :(</h2>Ajax comments have been disabled because your browser doesn\'t play nice with HTML5. Don\'t worry, you can still comment normally, but please consider upgrading to a browser such as <a href="http://www.google.com/chrome/">Google Chrome</a>, <a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a>, or <a href="http://www.apple.com/safari/">Safari</a>. Help the web evolve!</div>');
		reEqualizeHeights();
	}
	$commentForm.submit(function(e) {
		if (/*@cc_on!@*/0) {
			return true;
		}
		$.post('/comments', $commentForm.serialize(), function(data) {
			cleanForm();
			$commentForm.prepend(data.flash);
			if (data.result == 'success') {
				$commentForm[0].reset();
				commentSuccess(data);
			} else {
				commentErrors(data);
			}
			reEqualizeHeights();
		}, 'json');
		e.preventDefault();
	});
});