var comments_form_loaded = false;
var comments_loaded = false;

function trim(str)
{
    return str.replace(/^\s*|\s*$/g,"");
}

function loadCommentsForm(table, key)
{
    if (!comments_form_loaded) {
        $('comments_form_container').style.display = 'none';
        new Ajax.Request('/action/comments/showCommentForm', {
            asynchronous:true,
            evalScripts:false,
            onComplete:loadedCommentsForm,
            onLoading:loadingCommentsForm,
            parameters:'table=' + table + '&key=' + key
        });
    }

    return false;
}

function loadComments(table, key)
{
    new Ajax.Request('/action/comments/listComments', {
        asynchronous:true,
        evalScripts:false,
        onComplete:loadedComments,
        onLoading:loadingComments,
        parameters:'table=' + table + '&key=' + key
    });

    return false;
}


function loadingCommentsForm(request, json)
{
    $('comments_load_indicator').innerHTML = '';
    $('comments_load_indicator').appendChild(Builder.node('img', {src: '/images/indicator.white.gif'}));
}

function loadedCommentsForm(request, json)
{
    $("comments_load_indicator").innerHTML = "";

    $('comments_form_container').innerHTML = request.responseText;
    comments_form_loaded = true;
    Effect.SlideDown(
        'comments_form_container'
    );
}

function loadingComments(request, json)
{
    $('comments_load_indicator').innerHTML = '';
    $('comments_load_indicator').appendChild(Builder.node('img', {src: '/images/indicator.white.gif'}));
}

function loadedComments(request, json)
{
    $("comments_load_indicator").innerHTML = "";

    if (comments_loaded) {
        Effect.SlideUp(
            'comments_container',
            {
                afterFinish: function (o)
                {
                    if (json[0] == "ok") {
                        $("comments_container").innerHTML = request.responseText;
                        $("comments_count").firstChild.nodeValue = json[1];
                        Effect.SlideDown('comments_container');
                    }
                }
            }
        );
    } else {
        comments_loaded = true;
        if (json[0] == "ok") {
            $('comments_container').style.display = 'none';
            $('comments_container').innerHTML = request.responseText;
            $("comments_count").firstChild.nodeValue = json[1];
            Effect.SlideDown('comments_container');
        }
    }
}


function updateComments(request, json)
{
    $("comments_container").innerHTML = request.responseText;
    Effect.SlideDown('comments_container');
}

function updateBottomHref(request, json)
{
    $("add_comment_href_span").innerHTML = request.responseText;
}

function submitComment()
{
    var text = trim($("comments_text").value);

    if (text.length < 3) {
        new Effect.Highlight("comments_text", {startcolor:'#ff0000', endcolor:'#ffffff'});
        $("comments_text").focus();
        return;
    }

    $("comments_submit_button").disabled = true;

    var parameters = $('addCommentForm').serialize(true);

    new Ajax.Request('/action/comments/add', {
        method:'post',
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request, json){submittedComment(request, json)},
        onLoading:function(request, json){submittingComment()},
        parameters: parameters
    })
}

function submittedComment(req, json)
{
    var parameters = 'table=' + $('table').value + '&key=' + $('key').value;
    if (json == 'ok') {
        var nick = $("comments_nick");
        var nickname = '';
        var nickclass = null;

        if (nick) {
            nickname = nick.value;
        } else {
            nickname = $('comment_form_nick').firstChild.nodeValue;
            nickclass = {className: 'registered'};
        }


        new Ajax.Request('/action/comments/listComments', {
            asynchronous:true,
            evalScripts:false,
            onComplete:updateComments,
            parameters: parameters
        });

        new Ajax.Request('/action/comments/bottomHref', {
            asynchronous:true,
            evalScripts:false,
            onComplete:updateBottomHref,
            parameters: parameters
        });

        new Effect.Highlight(
            "comments_text",
            {
                startcolor:'#00ff00',
                endcolor:'#ffffff',
                afterFinish: function (o) {
                    var mesg = "Спасибо, ваш комментарий был добавлен."
                    if (nick) {
                        mesg += " Остальные пользователи смогут увидеть его после подтверждения администратором."
                    }

                    $("comments_text").value = mesg;
                    pauseComments();
                }
            }
        );
        $('comments').style.display="block";
    } else if (json == 'err: length') {
        new Effect.Highlight("comments_text", {startcolor:'#ff0000', endcolor:'#ffffff'});
    } else if (json == 'err: nickname taken') {
        new Effect.Highlight(
            "comments_nick",
            {
                startcolor:'#ff0000',
                endcolor:'#ffffff',
                afterFinish: function (o)
                {
                    $("comments_submit_button").disabled = false;
                    alert("Указаное вами имя уже занято");
                }
            }
        );
    }
}

function pauseComments()
{
    var nick = $("comments_nick");

    $("comments_text").readOnly = true;

    if (nick) {
        nick.readOnly = true;
    }

    $("comments_submit_button").value = "30 сек. пауза…";

    window.setTimeout(
        function()
        {
            $("comments_text").value = '';
            $("comments_text").readOnly = false;
            if (nick) {
                nick.readOnly = false;
            }
            $("comments_submit_button").value = "Добавить";
            $("comments_submit_button").disabled = false;
        },
        30000
    )
}

function submittingComment()
{

}