jQuery(function ($) {

    var commentsCount = 0; // for the current article

    $.ajaxSetup({
        type: "POST",
        dataType: "json"
    });

    // In the form notice, using <code></code> without specifying
    // the language will highlight the code using this language syntax.
    $("#formatting-language").text(gFormattingLanguage);

    // TEMPLATES

    // use for syntax highlight
    var codeTemplate = ""+
            "<textarea class='" + gFormattingClassName + "' cols='60' rows='1' name='commentcode'>"+
            "</textarea>";
    

    // use for displaying full comment
    var commentTemplate = ""+
            "<div class='comment-entry'>"+
                "<div class='header'>"+
                    "<span class='comment-number'><a class='anchor' name='id{id}'>{n}</a></span>"+
                    //"<span class='comment-number'>{n}</span>"+
                    "<span class='name'>{name}</span>"+
                    //"<span class='date'><a class='anchor' name='id{id}'>{date}</a></span>"+
                    "<span class='date'>{date}</span>"+
                "</div>"+
                "<div class='body'>"+
                    "<pre>{body}</pre>"+
                "</div>"+
            "</div>";

    // sidebar section for comments, if any
    var sidebarComments = ""+
            "<h3>Recent Comments</h3>"+
            "<div class='sb-entry'>"+
                "<div id='comments-abstract'>"+
                "</div>"+
                "<p class='line'><a href='#comments'>All comments</a> (<span class='comments-count-no-text'></span>)</p>"+
                "<p class='line'><a href='#leave-comment'>Leave a comment</a></p>"+
            "</div>";

    // use for most recent comments, each single entry
    var sidebarCommentHeaderEntry = ""+
            "<p class='line header'>"+
                "<span class='name'></span>"+
                "<span class='date'></span>"+
            "</p>";
    var sidebarCommentAbstractEntry = ""+
            "<p class='line abstract'>"+
                "<a></a>"+
            "</p>";


    // When major error happens, no form will be display with an error message
    function disableComments () {
        $("#comments .error").show();
        $("#comment-form").hide();
    }

    // append to the comments section a single comment entry
    function addComment(comment) {
        var name;
        var body = $(commentTemplate.supplant(comment));
        body.find("code").each(function (i, val) {
            var code = $(this).text();
            var formatedCode = $(codeTemplate);
            if (code && code !== "") {
                formatedCode.text(code).insertAfter($(this));
                $(this).remove();
            }
        });
        if (comment.url !== "") {
            name = body.find(".name");
            name.html("<a href='" + comment.url + "'>" + name.text() + "</a>");
        }

        if (comment.is_from_myself) {
            body.addClass("from-me");
        }

        $("#comments").append(body);
    }

    // Get all comments for the current article on page load
    $.ajax({
        url: "/comments/index",
        data: {
            article: gArticleName
        },
        success: function(comments) {
            var sbCommentsPlaceHolderElt;
            if (comments === false) {
                disableComments();   
            }
            if (comments.length > 0) {
                commentsCount = comments.length;
                $.each(comments, function (i, comment) {
                    addComment(
                        $.extend({}, comment, {
                            n: i + 1
                        }
                    ));
                });

                // highlight code after content have been dynamically add
                dp.SyntaxHighlighter.HighlightAll('commentcode'); 

                // If there is an emplacement found for the comments in the sidebar,
                // put it there, otherwise append it to the sidebar
                sbCommentsPlaceHolderElt = $("#comments-abstract-emplacement");
                if (sbCommentsPlaceHolderElt.length === 1) {
                    sbCommentsPlaceHolderElt.replaceWith(sidebarComments);
                } else {
                    $("#sidebar").append(sidebarComments);
                }

                // Generat the sidebar for comments
                for (var i = 0; i < gRecentCommentsMax && i < commentsCount; i++) {
                    var comment = comments[commentsCount - i - 1];
                    var entryHeader = $(sidebarCommentHeaderEntry);
                    var entryAbstract = $(sidebarCommentAbstractEntry);
                    entryHeader.find(".name").text(comment.name + ", ");
                    entryHeader.find(".date").text(comment.date);
                    entryAbstract.find("a")
                        .text(comment.abstract_text)
                        .attr("href", "#id" + comment.id);

                    $("#comments-abstract").prepend(entryAbstract);
                    $("#comments-abstract").prepend(entryHeader);
                }
            }

            // Update the count at some places on the page
            $(".comments-count").text(commentsCount + " Comment" + (commentsCount > 1 ? 's' : ''));
            $(".comments-count-no-text").text(commentsCount);

        },
        error: function() {
            disableComments();   
        },
        complete: function () {
            // show up the whole section when everything is generated
            $("#comments").removeClass("offset");
        }
    });


    // About the form events and behavior
    (function () {
        function resetForm() {
            $("#comment-form input.resettable, #comment-form textarea").each(function () {
                $(this).val("");
            });
        }
    //<p class="comment-response success hidden">Your comment has been successfully added.</p>
    //<p class="comment-response field-error error hidden">There was a problem adding your comment. Did you provide all required field?</p>
    //<p class="comment-response request-error error hidden">Oops, comment are temporarily unavailable for the moment. Sorry!</p>
        function displayCommentSuccess() {
            $("#comment-form .comment-response")
                .text("Your comment has been successfully added.")
                .addClass("success")
                .removeClass("error")
                .removeClass("invisible");
        }
        function displayCommentError() {
            $("#comment-form .comment-response")
                .text("There was a problem adding your comment. Did you provide all required field?")
                .addClass("error")
                .removeClass("successs")
                .removeClass("invisible");
        }
        function displayRequestError() {
            $("#comment-form .comment-response")
                .text("Oops, comment are temporarily unavailable for the moment. Sorry!")
                .addClass("error")
                .removeClass("successs")
                .removeClass("invisible");
        }
        function preventDefaultSubmitBhv() {
            return false;
        }
        function unbindSubmit() {
            $("#comment-form > form")
                .unbind("submit", submitBhv)
                .bind("click", preventDefaultSubmitBhv);
        }
        function bindSubmit() {
            $("#comment-form > form")
                .bind("submit", submitBhv)
                .unbind("click", preventDefaultSubmitBhv);
        }
        // Prevent default form submit behavior.
        function submitBhv() {
            $.ajax({
                url: "/comments/create",
                data: $(this).serializeArray(),
                beforeSend: function () {
                    unbindSubmit();
                    // hide previous server response message
                    $("#comment-form .comment-response").addClass("invisible");
                },
                success: function (ok) {
                    if (ok) {
                        displayCommentSuccess();
                        resetForm();
                    } else {
                        displayCommentError();
                    }
                },
                error: displayRequestError,
                complete: bindSubmit
            });
            return false;
        }
        $("#comment-form > form").bind("submit", submitBhv);
    })();

});
