window.looply = window.looply || {};

looply.comment = function()
{
    var _submitForm = function(e)
    {
        e.preventDefault();
        var form = $(this).parents("form");
        var comments = $(".comments");
        comments.html('');
        comments.addClass("loading");
        $.post(window.location.pathname, form.serialize() + "&commentFragment=1", function(html) {
            comments.removeClass("loading");
            comments.html(html);
            if ($($("p.error"), $(html)).is(":visible")) {
                $("body", "html").animate({scrollTop : $("#comments .error").position().top - 20});
            }
        }, "html");
    };

    var _showReplyForm = function(e)
    {
        e.preventDefault();
        var formHtml = $(".formContainer").html();
        var ul = $(".comments > ul");
        $(".formContainer", ul).remove();
        $(this).parents(".column").append('<div class="formContainer">' + formHtml + '</div>');
        var replyToId = $(this).attr("rel");
        $("input[name='reply_to_id']").val(replyToId);
    };

    return {
        init : function()
        {
            $(".comments input.submit").live("click", _submitForm);
            $(".comments a.reply").live("click", _showReplyForm);
        }
    }
} ();

$(document).ready(function() {
   looply.comment.init(); 
});
