$(document).ready(function(){

    applyScript();

    /*var pubnub = PUBNUB({
        subscribe_key: 'demo',
        publish_key: 'demo'
    });

    pubnub.subscribe({
        channel: 'comment',
        message: function(m){console.log(m)},
        error: function (error) {
          // Handle error here
          console.log(JSON.stringify(error));
        }
    }); */
});

function applyScript()
{

    var parent_id = 0;

    var textarea = $(".new_comment").find("textarea");
    var replyName;

    $(".comment_reply").each(function()
    {
        $(this).hide();
    });

    $(".btn-reply").each(function()
    {
        $(this).on("click", function()
        {
            replyName = $(this).siblings().find(".comment_username").text();
            parent_id = $(this).parents(".comment_body").attr("comment_id");

            textarea.val(replyName + ', ');

        });

    });

    $(".btn-send").on('click', function()
    {
        var content = textarea.val();

        if (content.indexOf(replyName) > -1 == false)
        {
            parent_id = 0;
        }
        createComment(content, parent_id);
    });

    function reload_comments()
    {
        var path = window.location.protocol + "//" + window.location.host + "/";
        $.ajax({
            type: 'GET',
            url : path + 'comment',
            data : {
                'action' : 'reload'
            },
            success: function(res)
            {
                $("#comment_wrapper").html(res);
                console.log('reloaded');

                applyScript();
            }
        });
    }
    function createComment(content, parent_id)
    {
        $.ajax({
            type: 'POST',
            url : '/comment/create',
            data: {
                'content' : content,
                'parent_id' : parent_id
            },
            success: function(res)
            {
                //reload_comments();
                alert('Comment sent');
            }
        });
    }

}
