$(function () {
    var errorField = $("#commentError");

    function onSubmitError(progressIndicator, errorField, data, status, exception) {
        if (data && data.error)
            errorField.text(data.error);
        else
            errorField.text("Could not contact server. Please try again later.");
    }
    
    function onCommentSubmitted(data) {
        if (data && data.not_logged_in) {
            ensureIsLoggedIn();
        }
        else if (data && data.error) {
            errorField.text(data.error);
            errorField.show();
        }
        else if (data && data.comment) {
            var noComment = $(".noComments");
            if (noComment.length > 0)
                $(".commentTable").html(data.comment);
            else
                $(".commentTable").append(data.comment);
            $("#commentForm #id_comment").val("");
        }
    }

    $("#commentForm").validate({
        errorLabelContainer: errorField,
        rules: {
            'comment': {
                required: true,
                maxLength: 10000
            }
        },
        messages: {
            'comment' : {
                'required': "Please enter a comment.",
                'maxLength': "Your comment is a bit too long!"
            }
        },
        submitHandler: function(form) {
            $(form).ajaxSubmit({
                beforeSubmit: function() { errorField.text(""); return true; }, 
                success: onCommentSubmitted,
                error: function(d, s, e) { onSubmitError(null, errorField, d, s, e); },
                dataType: 'json'
            });
            return false;
        }
    });

    $("a.submit").click(function (e) {
        e.preventDefault();
        $(this).parents("form").submit();
    });
});
