$(function () {
    $('#comment_form').submit(function (e) {
        e.preventDefault();

        $.ajax({
            url: Routing.generate('wi_front_news_create_comment', { 'id': news_id }),
            method: 'POST',
            data: $(this).serialize(),
            dataType: 'JSON',
            success: function (response) {
                if (response.status) {
                    $('#comment_ajax_message').html(response.message);
                    $('#comment_content').val('');
                    moveCommentFormToStartPosition();
                    loadComments();
                } else {
                    $('#comment_ajax_message').html(response.message);
                }
            }
        });
    });

    var loadComments = function() {
        var commentParentInput = $('#comment_parent_id');

        if ($('#comment_parent_id').val() == '') {
            $.ajax({
                url: Routing.generate('wi_front_news_load_comments', { 'id': news_id }),
                method: 'GET',
                success: function (html) {
                    $('#comment-block').replaceWith(html);
                }
            });
        }
    }

    setInterval(loadComments, 60000);

    $('body').on('click', '.comment-reply-link', function (e) {
        e.preventDefault();

        var $li = $(this).closest('li');
        var id = parseInt($li.data('id'));

        moveCommentForm($li.find('> .comment-body'), id);
    });

    $('body').on('click', '#comment_cancel_reply', function (e) {
        e.preventDefault();
        moveCommentFormToStartPosition();
    });

    var moveCommentForm = function (moveTo, parentCommentId) {
        var $commentForm = $('#comment_form');
        var $commentCancel = $('#comment_cancel_reply');
        var $commentParentInput = $('#comment_parent_id');
            $commentCancel.show();

        $(moveTo).append($commentForm);
        $commentParentInput.val(parentCommentId);
    };

    var moveCommentFormToStartPosition = function () {
        var $commentParentInput = $('#comment_parent_id');
        var $commentForm = $('#comment_form');
        var $replyBox = $('#reply-box');

        $commentForm.insertAfter($replyBox);
        $('#comment_cancel_reply').hide();
        $commentParentInput.val('');
    };
});
