var reply_form = '';
var current_form = '';
var form_options = {
        dataType: 'json',
        beforeSubmit: sendingForm,
        success: processForm
    };

$(document).ready(function() {
	$('body').append('<div id="commentDialog"><!-- --></div>');

	$("#commentDialog").dialog({
        autoOpen: false,
        buttons: { "Ok": function() { $(this).dialog("close"); } },
        modal: true,
        title: "Message",
        width: 500
    });

    var s = '13e09k23dof4jfiu2hy3ggvhecnx';
    var k = MD5($("#iv").attr("value") + s);

    $("#k").attr("value",k);

	$('#submitForm').submit(function() {
		return submitForm();
	});

	reply_form = $('#commentReplyFormContainer').html();
	
    $('a.commentReplyLink[rel]').live('click', function () {
		var comment_id = $(this).attr('rel');
		var author = $("#author" + comment_id).val();

		if( current_form == '' ) {
			$('#commentReplyFormContainer').html('');
		} else {
			current_form.html('');
		}
		current_form = $('#commentReply' + comment_id)

		current_form.html(reply_form);

		$('#submitForm').unbind('submit').bind('submit',submitForm);

		$("#parentID").val(comment_id);
		$('#commentReply' + comment_id + " h2").text("Reply to " + author);

        return false;
    });
});

function submitForm() {
    $('#submitForm').ajaxSubmit(form_options);
	return false;
}

function sendingForm(formData, jqForm, options) {
    $('#formContainer').fadeTo("slow", 0.35);
}

function processForm(data) {
    if( data.status == "OK" ) {
        $('#formContainer').slideUp();

		// Load comments
		$("#commentListing").load( site_url + '/comments?comments&post_id=' + data.post_id );

        $('.commentCount' + data.post_id).html( data.comment_count );
    } else {
        $('#formContainer').fadeTo("fast", 100);
    }

    $("#commentDialog").html(data.message).dialog("option", "title", data.title).dialog('open');
}

