var bindCommentDeletion = function(node) {
	if (typeof(node) == 'undefined') {node = document;}
	$(node).find('form.commentdelete').submit(function () {
		if (!confirm('Are you sure you want to delete this comment?')) {return false;}
		markFormActive(this);
		var self = this;
		$(this).ajaxSubmit({
			success: function(data, stat) {
				$(self).parents('.comment').fadeRemove();
				clearAjaxMsg();
				unmarkFormActive(self);
			},
			error: function(xhr, stat, e) {
				clearAjaxMsg();
				displayAjaxErr('Comment deletion failed.', stat, xhr);
				unmarkFormActive(self);
			}
		});
		return false;
	});
}

var FCKeditor_OnComplete = function(editorInstance) {
	$('#autobreaksline').remove();
}

$(document).ready(function() {
	// they're working on opera/fckeditor compatibility, but it's not solid yet
	if (!$.browser.opera) {
		// nbsp prevents focus in IE
		$('textarea.wysiwyg').val('&nbsp;')
			.fck({path: '/js/fckeditor/', toolbar: 'Blog', height: '400', width: '100%'});
	}
	
	bindCommentDeletion();
	
	$('#comment').submit(function() {
		if (window.FCKeditorAPI) {FCKeditorAPI.GetInstance('commenthtml').UpdateLinkedField();}
		if (!this.elements['commenthtml'].value && !this.elements['tags'].value) {
			if (!confirm('Are you sure you want to submit this comment with no message?')) {return false;}
		}
		markFormActive(this);
		var self = this;
		$(this).ajaxSubmit({
			success: function(data, stat) {
				var data = handleJSON(data);
				clearAjaxMsg();
				unmarkFormActive(self);
				self.reset();
				if (window.FCKeditorAPI) {
					FCKeditorAPI.GetInstance('commenthtml').SetHTML('');
				}
				if (data.html) {
					$newComment = $(data.html);
					$('#commentParent').yellowAppend($newComment);
					bindCommentDeletion($newComment);
				} else {
					displayAjaxMsg(data.msg);
				}
			},
			error: function(xhr, stat, e) {
				clearAjaxMsg();
				displayAjaxErr('Comment posting failed.', stat, xhr);
				unmarkFormActive(self);
			}
		});
		return false;
	});
	
	window.onbeforeunload = function() {
		var comment;
		if (!(comment = $('#comment')[0])) {return;}
		if (window.FCKeditorAPI) {FCKeditorAPI.GetInstance('commenthtml').UpdateLinkedField();}
		if (comment.elements['commenthtml'].value || comment.elements['tags'].value) {
			return 'You have not submitted your comment.';
		}
	};
});
