var commentForm = null;

$(document).ready(function(){
    commentForm = $("#newCommentForm");
    
    $(".writeCommentBtn").click(ShowHideCommentForm);
    $(".answerBtn").click(ShowHideAnswerForm);
    
    $("#newCommentForm").children('form').children('input[name=parentID]').val(0);
    
    displaytime();
    setInterval("displaytime()", 10000);
    
    AddEventListner();
    
    $('.comments .block:even').addClass('even');
    $('.comments .block:last').removeClass('even');
    
    $('.acceptCommentBtn').click(AcceptComment);
    $('.declineCommentBtn').click(DeclineComment);
    
    $('.deleteCommentBtn').click(DeleteComment);
    $('.restoreCommentBtn').click(RestoreComment);
});

var serverdate = new Date();

function padlength(what)
{
    var output=(what.toString().length==1)? "0"+what : what;
    return output;
}

function displaytime()
{
    serverdate.setSeconds(serverdate.getSeconds() + 10);
    var datestring = padlength(serverdate.getDate())+"."+ (serverdate.getMonth()+1) +"."+ serverdate.getFullYear();
    var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes());
    $(".make-new .time-date").text(datestring+" "+timestring);
    //document.getElementById("servertime").innerHTML=datestring+" "+timestring;
}

function AddEventListner()
{
    $("#commentForm").validate(
    {
        rules: {},
        submitHandler: function(form) 
        {
            $(form).ajaxSubmit(
            {
               success: AddCommentSuccess, 
               beforeSubmit: AddCommentPrepareRequest, 
               dataType: "json",
               type: "POST"
            });
            return false;
        }
    });
}

function commentsAJAXResponseHandler(data, status)
{
    if (status == 'success')
    {
        if (data.error)
        {
            $('#commentForm').children('.block').children('.error').text(data.error);
            $('#commentForm').children('.block').children('.error').show();
            return false;
        }
    }
    else
    {
        $.jGrowl("Ошибка запроса");
        return false;
    }
    return true;
}

function AddCommentSuccess(data, status)
{
    $("#ajaxLoading").remove();
    //$("input:submit").attr("disabled",false);
    if (!commentsAJAXResponseHandler(data, status)) return;
    if (data.msg == "ok") 
    {
        var parent = $("#commentForm").parent();
        //var blockContainer = $("#commentForm").parent().parent().parent();
                
        // Убираем форму
        parent.hide('blind');
        
        //var commentBlock = $("#commentForm").parent("div");
        var commentBlock = $('<div class="block orange" style="display: none;"></div>');
                    
        //commentBlock.removeAttr("id").addClass("comment").html();
        commentBlock.append('<span class="meta"><span class="time-date">'+ data.comment.creationDate +'</span> <span class="username">'+ data.comment.userFIO +'</span>:</span>');
        commentBlock.append('<p>'+ data.comment.comment +'</p>');
        if (data.comment.isModerated == 0)
            commentBlock.append('<div class="moder-msg">Данное сообщение не будет отображаться на сайте, пока не пройдет модерацию</div>');
        commentBlock.append("<div class='corner lt'>&nbsp;<\/div><div class='corner rt'>&nbsp;<\/div><div class='corner rb'>&nbsp;<\/div><div class='corner lb'>&nbsp;<\/div>");
        
        //var blockContainer = $("#commentForm").parent().parent();
        var blockContainer = null;
        if (parent.attr("id") == 'newCommentForm')
        {
            prevBlockContainer = $('<div class="comment"></div>');
            $("#commentForm").parent().parent().before(prevBlockContainer);
            blockContainer = prevBlockContainer;
        }
        else
        {
            prevBlockContainer = $('<div class="comment reply"></div>');
            $("#commentForm").parent().parent().parent().append(prevBlockContainer);
            blockContainer = prevBlockContainer;
        }
        
        blockContainer.append(commentBlock);
        commentBlock.show('blind');
        commentBlock.focus();
        parent.remove();
                
        //$('#requestSuccess').text(data.text).show();
        //$('#subscribeForm').hide('slow');
    };
}

function AddCommentPrepareRequest(form)
{
    //$("input:submit").attr("disabled", true);
    form.push({name:"async",value:"1"});
    form.push({name:$("##commentForm input:submit").attr("name"),value:"1"});
    
    $("#commentForm").children('div.block').children('div.buttons').append('<span id="ajaxLoading"><img src="/images/icons/ajax-loader.gif" /></span>');
}

function HideBlockAfterTimeout()
{
    $("#submitedComment").hide('blind');
    setTimeout("RemoveBlockAfterTimeout()", 1000);
}

function RemoveBlockAfterTimeout()
{
    $("#submitedComment").remove();
}

function ShowHideCommentForm(event)
{
    event.preventDefault();
    
    var newCommentForm = $("div#newCommentForm");
    
    if (newCommentForm.length == 0)
    {
        HideReplyCommentForm();
        $(this).parent().append('<div id="newCommentForm">'+ commentForm.html() +'</div>');
        $(":input[placeholder]").each(function(){ $(this).blurfocus($(this).attr('placeholder')); });
        $("#newCommentForm").children('form').children('input[name=parentID]').val(0);
        $('#commentForm').children('.block').children('.error').text('');
        $('#commentForm').children('.block').children('.error').hide();
        AddEventListner();
    }
    else
    {
        $("div#newCommentForm form textarea").eq(0).focus();
    }
}

function ShowHideAnswerForm(event)
{
    event.preventDefault();
    
    var newCommentForm = $("div#newCommentForm");
    var replyCommentForm = $("div#replyCommentForm");
    
    var parentID = $(this).parent().children("input").val();
    
    if (replyCommentForm.length == 0)
    {
        SetReplyCommentForm($(this), parentID);
        HideNewCommentForm();
        AddEventListner();
        // Ставим фокус на форму
        $("div#replyCommentForm textarea").focus();
    }
    else
    {
        if (replyCommentForm.parent().prev(".block").children(".replyContainer").children("input[name=parentID]").val() != parentID)
        {
            HideReplyCommentForm();
            SetReplyCommentForm($(this), parentID);
            HideNewCommentForm();
            AddEventListner();
            // Ставим фокус на форму
            $("div#replyCommentForm textarea").focus();
        }
        else
        {
            $("div#replyCommentForm textarea").focus();
        }
    }
}

function SetReplyCommentForm(that, parentID)
{
    var parent = that.parent().parent();
    var replyBlock = parent.next("div.reply");

    if (replyBlock.length == 0)
    {
        parent.after('<div class="comment reply"></div>');
        replyBlock = parent.next("div.reply");
    }

    replyBlock.prepend('<div id="replyCommentForm">'+ commentForm.html() +'</div>');
    
    $("#replyCommentForm").children('form').children('input[name=parentID]').val(parentID);
    $('#commentForm').children('.block').children('.error').text('');
    $('#commentForm').children('.block').children('.error').hide();
    
    $(":input[placeholder]").each(function(){ $(this).blurfocus($(this).attr('placeholder')); });
}

function HideReplyCommentForm()
{
    $("div#replyCommentForm").remove();
}

function HideNewCommentForm()
{
    $("div#newCommentForm").remove();
}

function AcceptComment(event)
{
    var commentID = $(this).siblings('input[name=moderateCommentID]').val();
    
    $.post(
        '/comments/accept/',
        {commentID : commentID},
        AcceptCommentResponse,
        'json'
    );
}

function AcceptCommentResponse(data, status)
{
    if (!standartAJAXResponseHandler(data, status)) return;
    if (data.msg == "ok") 
    {
        // Покажем кнопку "ответить"
        $('input[name=moderateCommentID][value='+ data.commentID +']').parent().siblings('.replyContainer').fadeIn('slow');
        
        // Удалим кнопки accept и decline
        $('input[name=moderateCommentID][value='+ data.commentID +']').siblings('.acceptCommentBtn').remove().end().siblings('.declineCommentBtn').remove().end().remove();
    };
}

var commentBlockToRemove = null;
function DeclineComment(event)
{
    var commentID = $(this).siblings('input[name=moderateCommentID]').val();
    
    $.post(
        '/comments/decline/',
        {commentID : commentID},
        DeclineCommentResponse,
        'json'
    );
}

function DeclineCommentResponse(data, status)
{
    if (!standartAJAXResponseHandler(data, status)) return;
    if (data.msg == "ok") 
    {
        commentBlockToRemove = $('input[name=moderateCommentID][value='+ data.commentID +']').parent().parent().parent();
        commentBlockToRemove.fadeOut('slow', DeclineCommentRemoveComment);
    };
}

function DeclineCommentRemoveComment()
{
    if (commentBlockToRemove != null)
    {
        commentBlockToRemove.remove();
        commentBlockToRemove = null;
        
        $('.comments .block').removeClass('even');
        $('.comments .block:even').addClass('even');
        $('.comments .block:last').removeClass('even');
    }
}

function RestoreComment(event)
{
    var commentID = $(this).siblings('input[name=deleteRestoreCommentID]').val();
    
    $.post(
        '/comments/restore/',
        {commentID : commentID},
        RestoreCommentResponse,
        'json'
    );
}

function RestoreCommentResponse(data, status)
{
    if (!standartAJAXResponseHandler(data, status)) return;
    if (data.msg == "ok") 
    {
        // Покажем кнопку "ответить"
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').parent().siblings('.replyContainer').fadeIn('slow');
        
        // Убираем надпись "Комментарий удален"
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').parent().siblings('.deletedCommentNote').fadeOut('slow');
        
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').parent().siblings('.deletedCommentNote').remove();
        
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').siblings('.deleteCommentBtn').show();
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').siblings('.restoreCommentBtn').hide();
        
        // Заменил кнопку
        //$('input[name=deleteRestoreCommentID][value='+ data.commentID +']').siblings('.acceptCommentBtn').remove().end().siblings('.declineCommentBtn').remove().end().remove();
    };
}

function DeleteComment(event)
{
    var commentID = $(this).siblings('input[name=deleteRestoreCommentID]').val();
    
    $.post(
        '/comments/delete/',
        {commentID : commentID},
        DeleteCommentResponse,
        'json'
    );
}

function DeleteCommentResponse(data, status)
{
    if (!standartAJAXResponseHandler(data, status)) return;
    if (data.msg == "ok") 
    {
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').parent().after('<p class="deletedCommentNote">Комментарий удален</p>');
        
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').parent().siblings('.replyContainer').fadeOut('slow');
        
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').siblings('.deleteCommentBtn').hide();
        $('input[name=deleteRestoreCommentID][value='+ data.commentID +']').siblings('.restoreCommentBtn').show();
    };
}