function hideCommentForms () {
    // get the formcontainer
    $('.streamlike .comments li').each(function() {
        
        var li = $(this);
        
        var formcontainer = $('.form', li);
        var footer = $('.footer', li);

        // if there are no comments for the element, hide the form and add a comment link
        if ($('.comments > li', li).get().length == 1) {

            if (!$('.comment', footer).get().length) {

                // hide the form
                formcontainer.addClass('hidden');

                // append the link to display the form
                // TODO
                // - pass the string with Django
                footer.append(' - <a class="comment" href="#" title="comment">comment</a>');

                $('.comment', footer).click(function() {
                    formcontainer.toggleClass('hidden');
                    return false;
                });
            }
        }
        
        // hide the submit button
        $('input[type=submit]', li).addClass('hidden');

        $('textarea', li).focus(function() {
            $('input[type=submit]', li).removeClass('hidden');
        });

        $('textarea', li).blur(function() {
            if (!$('input[name=comment]', li).attr('value')) {
                $('input[type=submit]', li).addClass('hidden');
            }
        });
        
    });
}

var comment;

function reloadComments(data) {
    $("#"+data.object_id).html(data.comments);
    initRemove();
	comment.unblock();
}

var bind_event = function () {
    $('.comment').unbind('submit');
    $('.comment').bind('submit' ,function () {
        comment = $(this).find("ul");
        comment.block({ message: '<div class="loading"></div>' });

        try {
            if (_gaq) {
                _gaq.push(['_trackEvent', 'comment', 'post']);
            }
        } catch (exception) {
            //nothing
        }

        // submit comments
        $(this).ajaxSubmit({
            success: function(){
                //delete input
                comment.find('textarea').val('');

                var comments= $(".comments");
                var object_id = comments.attr("id");
                var content_type = comment.find('input[name="content_type"]').val();

                Dajaxice.comments.reload(reloadComments, {
                    'object_id': object_id,
                    'content_type': content_type
                });
            }
        });

        return false; 
    });
}

// FIXME: Should be only execute if the ajax call changes stream
$(document).ajaxStop(function() {
    hideCommentForms();
    bind_event();
});

$(document).ready(function() {
    hideCommentForms();
    bind_event();
});

