﻿function initCommentsForms()
{
    initEditFormSubmit();
    initReplyButtons();
    initEditButtons();
    initDeleteButtons();
    bindCtrlEnter();    
}

function initEditFormSubmit()
{
    $('div.comments_comment-new-form-placeholder  form').live("submit", function(event){


       var form = $(this)[0];
       var url = $(this).attr("action");
       var parentDiv = $(this).parent().parent().parent()[0];


            $(parentDiv).hide(200, function(){
                $.post(url, $(form).serialize(), function(data, textStatus, XMLHttpRequest){
                    $(parentDiv).html(data);
                    $(parentDiv).show(200);                    
                });

            });

        return false;
    });
}

function initReplyButtons()
{
    $(".comments_comment-reply-button").live("click", function(event){

        var button_id = $(this).attr("id");
        var id_num = button_id.substring(6); // "reply_[id]"
        var form_id = "comment-form-reply_" + id_num; // form_id = comment-form-reply_[id]

            $.get("/comments/commentform_" + id_num + "_0", function(data, textStatus, XMLHttpRequest){

                $(data).prependTo("#" + form_id);
                $("#" + form_id).show(200);
                //$("#" + form_id).html(data);
                //;
                $("#" + form_id + " textarea").focus();
            })


    });
}

function initEditButtons()
{
    $(".comments_comment-edit-button").live("click", function(event){
        var button_id = $(this).attr("id");
        var id_num = button_id.substring(5); // "edit_[id]"
        var placeholder_id = "comment-box-placeholder_" + id_num;
        $("#" + placeholder_id).hide(200, function(){

            $.get("/comments/commentform_0_" + id_num, function(data, textStatus, XMLHttpRequest){
                $("#" + placeholder_id).html(data);                
                $("#" + placeholder_id).show(200);
                $("#" + placeholder_id + " textarea").focus();
            })
        });

    });
}

function initDeleteButtons()
{
    $(".comments_comment-delete-button").live("click", function(event){
        var button_id = $(this).attr("id");
        var id_num = button_id.substring(7); // "delete_[id]"
        var placeholder_id = "comment-box-placeholder_" + id_num;
        if (confirm("Вы действительно хотите удалить комментарий?"))
        {

          $("#" + placeholder_id).hide(200, function(){
                $.post("/comments/deletecomment_" + id_num, function(data, textStatus, XMLHttpRequest){

                });

        });
        }


    });
}

function bindCtrlEnter()
{
    $("form textarea").live("keydown",function (e){
        if (e.ctrlKey && e.keyCode == 13) {
            $(this).parent().trigger("submit");
        }


    });
}
