﻿registerNS("Tegud.Comments");

Tegud.Comments.GetNewAuthToken = function (holder) {
    // Retrieves a new Authorisation Token.
    Tegud.AJAX.SendRequest("/Home/GetCATCHPAToken/",
            {},
            {
                Success: function (data) {
                    holder
                        .children("img").attr("src", "/AuhtorisationToken/?token=" + data.AuthToken)
                            .closest(".AddComment")
                                .data("CurrentToken", data.AuthToken);
                }
            });
}

Tegud.Comments.Hide = function(item) {
    item.fadeOut(500);
}

Tegud.Comments.AddNew = function (addDiv) {
    var blogID = addDiv.closest(".BlogItem").attr("id").replace("BlogItem_", "");

    var name = $("#BlogCommentAdd_" + blogID + "_Name").val();
    var email = $("#BlogCommentAdd_" + blogID + "_Email").val();
    var comment = Tegud.Comments.ReplaceTags($("#BlogCommentAdd_" + blogID + "_Comment").val());
    var codeField = $("#BlogCommentAdd_" + blogID + "_Code")
    var code = codeField.val();
    var token = addDiv.data("CurrentToken");

    if (name == "" || email == "" || comment == "" || (codeField.is(":visible") && code == "")) {
        alert("You must enter a name, email, comment and enter the code displayed above.");
        return;
    }

    // Validate email address
    if (!email.toUpperCase().match(Tegud.Utilities.RegEx.Email)) {
        alert("Incorrect email address entered.");
        return;
    }

    Tegud.AJAX.SendRequest("/Home/AddBlogComment/" + blogID,
            {
                Name: name,
                Email: email,
                Comment: comment,
                Token: token,
                AuthCode: code
            },
            {
                Success: function (data) {
                    var newComment = data.NewComment;

                    // Add the comment we just submitted to the bottom.
                    addDiv
                        .prev()
                            .prepend($("<div class=\"BlogComment" + (newComment.IsSiteAdmin ? " AdminComment" : "") + "\" style=\"display: none; background-image: url('http://www.gravatar.com/avatar/" + newComment.AuthorEmailHash + "?s=50');\">"
                                        + "<h6>" + newComment.AuthorName + "</h6>"
                                        + newComment.Text
                                        + "<div class=\"BlogCommentDetails\">Posted " + newComment.Date + " at " + newComment.Time + "</div>"
                                    + "</div>")
                                .fadeIn(500));

                    // Increment the blog items count by one.
                    var blogItemCount = addDiv
                                            .closest(".BlogItem")
                                                .children(".BlogItemFooter")
                                                    .children(".BlogCommentIcon")
                                                        .children(".CommentCount");

                    var currentCount = parseInt(blogItemCount.text());
                    blogItemCount.text(currentCount + 1);

                    $("#BlogCommentAdd_" + blogID + "_Comment").val("");
                    $("#BlogCommentAdd_" + blogID + "_Name").val("");
                    $("#BlogCommentAdd_" + blogID + "_Email").val("");
                    $("#BlogCommentAdd_" + blogID + "_Code").val("");

                    // Now that we've done the authorisation once, we wont make the user do it again (unless cookies are turned off).
                    if ((data.AuthToken || "") != "") {
                        // Cookies are disabled, so unfortunately the user will have to keep entering the CATCHPA code.
                        addDiv
                            .data("CurrentToken", data.AuthToken)
                            .children(".BlogCommentCatchpaHolder")
                                .children("img")
                                    .attr("src", "/AuhtorisationToken/?token=" + data.AuthToken);
                    }
                    else {
                        // Cookies are enabled so we can just remember that they're human for 7 days.
                        $(".BlogCommentCatchpaHolder").hide();
                    }
                }
            });
}

Tegud.Comments.Show = function (item) {
    if (item.is(":visible")) {
        Tegud.Comments.Hide(item);
        return;
    }

    var callback = item.data("Loaded") ? $.noop : function () {
        Tegud.Comments.Load(item);
    }

    item.fadeIn(500, callback);
}

Tegud.Comments.Load = function (item) {
    item
        .children(".BlogCommentLoading")
            .show()
            .end()
        .children(".BlogCommentHolder")
            .hide()
            .html("");

    var id = item.closest(".BlogItem").attr("id").replace("BlogItem_", "");
    Tegud.AJAX.SendRequest("/Home/GetCommentsForBlogItem/",
            { id: id },
            {
                Success: function (data) {
                    var authToken = data.AuthToken;
                    data = data.Comments;

                    item.data("Loaded", true);

                    var commentHtml = "";

                    if (data) {
                        for (var x = 0; x < data.length; x++) {
                            commentHtml += "<div class=\"BlogComment" + (data[x].IsSiteAdmin ? " AdminComment" : "") + "\" style=\"background-image: url('http://www.gravatar.com/avatar/" + data[x].AuthorEmailHash + "?s=50');\">"
                                + "<h6>" + data[x].AuthorName + "</h6>"
                                + data[x].Text
                                + "<div class=\"BlogCommentDetails\">Posted " + data[x].Date + " at " + data[x].Time + "</div>"
                            + "</div>";
                        }
                    }

                    var addCommentDiv = item.children(".AddComment").show();

                    addCommentDiv
                        .children(".BlogCommentAddHolder")
                            .children(".BlogCommentAdd_AddComment")
                                .button({
                                    icons: { primary: 'ui-icon-check' }
                                });

                    addCommentDiv.children(".BlogCommentAddTextField").children("textarea").tinymce({
                        script_url: '/Scripts/tiny_mce/tiny_mce.js',
                        // General options
                        theme: "advanced",
                        theme_advanced_buttons1: "bold,italic,underline",
                        theme_advanced_buttons2: "",
                        theme_advanced_buttons3: "",
                        theme_advanced_toolbar_location: "top",
                        theme_advanced_toolbar_align: "left"
                    });

                    if (!authToken)
                        authorisationHolder.hide();
                    else {
                        var authorisationHolder = addCommentDiv
                                                    .data("CurrentToken", authToken)
                                                    .children(".BlogCommentCatchpaHolder");

                        if (!authorisationHolder.children("img").length)
                            $("<img src=\"/AuhtorisationToken/?token=" + authToken + "\" />")
                                .insertBefore(authorisationHolder.children(".BlogCommentCatchpaCodeRefresh"));
                    }

                    item
                        .children(".BlogCommentLoading")
                            .hide()
                            .end()
                        .children(".BlogCommentHolder")
                            .show()
                            .html(commentHtml);
                },
                Failure: function () {
                    item
                        .children(".BlogCommentLoading")
                            .hide()
                            .end()
                        .children(".BlogCommentHolder")
                            .show()
                            .html("<div class=\"BlogCommentsError\">Could not retrieve blog comments, <span class=\"RetryComments Link\">try again</span>.</div>");
                }
            });
}

Tegud.Comments.ReplaceTags = function (input) {
    if (!input)
        return input;

    // Hack attack!
    // This could be made oh so much nicer with a lovely complicated regex I havent been bothered to write yet
    // Much less ugly code and looping. 
    // Still in the short term, this will allow through the HTML tags I want, standard .NET input validation prevents any naughty content.
    input = Tegud.Utilities.ReplaceAll(input, "<p>", "[p]");
    input = Tegud.Utilities.ReplaceAll(input, "</p>", "[/p]");

    input = Tegud.Utilities.ReplaceAll(input, "<b>", "[b]");
    input = Tegud.Utilities.ReplaceAll(input, "</b>", "[/b]");

    input = Tegud.Utilities.ReplaceAll(input, "<i>", "[i]");
    input = Tegud.Utilities.ReplaceAll(input, "</i>", "[/i]");

    input = Tegud.Utilities.ReplaceAll(input, "<u>", "[u]");
    input = Tegud.Utilities.ReplaceAll(input, "</u>", "[/u]");

    input = Tegud.Utilities.ReplaceAll(input, "<br/>", "[br]");
    input = Tegud.Utilities.ReplaceAll(input, "<br />", "[br]");

    input = Tegud.Utilities.ReplaceAll(input, "<strong>", "[b]");
    input = Tegud.Utilities.ReplaceAll(input, "</strong>", "[/b]");

    input = Tegud.Utilities.ReplaceAll(input, "<em>", "[i]");
    input = Tegud.Utilities.ReplaceAll(input, "</em>", "[/i]");

    input = Tegud.Utilities.ReplaceAll(input, "<span style=\"text-decoration: underline;\">", "[u]");
    input = Tegud.Utilities.ReplaceAll(input, "</span>", "[/u]");

    return input;
}

