var conversations = {

    sanitize: function(s) {
        if (s) {
            s = s.replace(/javascript:/ig, "");
            s = s.replace(/<script>/ig, "");
            s = s.replace(/<\/script>/ig, "");
            s = s.replace(/<style>/ig, "");
            s = s.replace(/<\/style>/ig, "");
            s = s.replace(/</g, "&lt;");
        }
        return s;
    },

    getJsonSync: function(url, f) {
        jQuery.ajax({
            type: "GET",
            async: false,
            url: url,
            dataType: "json",
            success: f
        });
    },

    getTextSync: function(url) {
        return jQuery.ajax({
            type: "GET",
            async: false,
            url: url,
            dataType: "text"
        }).responseText;
    },

    newGuid: function() {
        return conversations.getTextSync("/Handlers/NewGuid.ashx");
    },

    getGenreIfDuc: function(id) {
        var result = "";
        conversations.getJsonSync("/Handlers/GetGenre.ashx?id=" + id, function(json) {
            result = json.genreid;
        });
        return result;
    },

    isArray: function(o) {
        //see: http://thinkweb2.com/projects/prototype/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
        return Object.prototype.toString.call(o) === '[object Array]';
    },

    fixMimeTypes: function(item) {
        var oldMimeType = JSON.parse(item.MimeType);
        if (conversations.isArray(oldMimeType)) {
            var requestBatch = new RequestBatch();
            var newMimeType = JSON.stringify({ threadId: oldMimeType[0], parentThreadId: oldMimeType[1], articleId: oldMimeType[2] });
            requestBatch.AddToRequest(new UpdateCustomItemAction(new CustomItemKey(item.CustomItemKey.Key), item.Name, newMimeType, item.DisplayText, item.Content));
            requestBatch.BeginRequest(serverUrl, function(responseBatch) {
                log_dir("fixMimeTypes response", responseBatch);
            });
        }
    },

    disableVoting: function(key) {
        jQuery("#" + key + " .agreeLink").attr("href", "#").addClass("disabled").click(function(e) {
            e.preventDefault();
        });
        jQuery("#" + key + " .disagreeLink").attr("href", "#").addClass("disabled").click(function(e) {
            e.preventDefault();
        });
    },

    agree: function(key) {
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(new RecommendAction(new CustomItemKey(key)));
        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            //log_dir("recommend response", responseBatch);
            jQuery("#" + key + " .agreeLink").attr("href", "#").addClass("disabled").click(function(e) {
                e.preventDefault();
            });
            conversations.updateNumberOfRecommendations(key);
            conversations.disableVoting(key);
        });
    },

    updateNumberOfRecommendations: function(key) {
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(new CustomItemKey(key));
        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            if (responseBatch.Messages[0].Message == "ok") {
                jQuery("#" + key + " .agreeLink").html("Agree (" + responseBatch.Responses[0].CustomItem.NumberOfRecommendations + ") ");
            }
        });
    },

    disagree: function(key) {
        var antiItemKey = new CustomItemKey(key + "-anti");
        var commentName = "anti-recommendation-comment";

        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(new UpdateCustomItemAction(antiItemKey, commentName, "anti-recommendation-comment", "anti-recommendation-comment", "anti-recommendation-comment"));
        requestBatch.AddToRequest(new RecommendAction(antiItemKey));
        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            //log_dir("anti recommend response", responseBatch);
            jQuery("#" + key + " .disagreeLink").attr("href", "#").addClass("disabled").click(function(e) {
                e.preventDefault();
            });
            conversations.updateNumberOfAntiRecommendations(key);
            conversations.disableVoting(key);
        });
    },

    updateNumberOfAntiRecommendations: function(key) {
        //console.log("updateNumberOfAntiRecommendations");
        var requestBatch = new RequestBatch();
        var antiItemKey = new CustomItemKey(key + "-anti");
        requestBatch.AddToRequest(new UpdateCustomItemAction(antiItemKey, "anti-recommendation-comment", "anti-recommendation-comment", "anti-recommendation-comment", "anti-recommendation-comment"));
        requestBatch.AddToRequest(antiItemKey);
        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            if (responseBatch.Messages[0].Message == "ok") {
                jQuery("#" + key + " .disagreeLink").html("Disagree (" + responseBatch.Responses[0].CustomItem.NumberOfRecommendations + ") ");
            }
        });
    },

    initDisagreeLink: function(key) {
        //console.log("init disagree link enter: " + key);

        if (jQuery("#" + key).attr("voted") == "true") {
            jQuery("#" + key + " .disagreeLink").html("Disagree (0) ").addClass("disabled").attr("href", "#").click(function(e) {
                e.preventDefault();
            });
        } else {
            jQuery("#" + key + " .disagreeLink").html("Disagree (0) ").removeClass("disabled").attr("href", "javascript:conversations.disagree('" + key + "');");
        }

        var antiItemKey = new CustomItemKey(key + "-anti");
        var commentName = "anti-recommendation-comment";

        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(new UpdateCustomItemAction(antiItemKey, commentName, "anti-recommendation-comment", "anti-recommendation-comment", "anti-recommendation-comment"));
        requestBatch.AddToRequest(antiItemKey);
        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            //log_dir("init disagree link response", responseBatch);
            if (responseBatch.Messages[0].Message == "ok") {
                jQuery("#" + key + " .disagreeLink").html("Disagree (" + responseBatch.Responses[0].CustomItem.NumberOfRecommendations + ") ");
                if (jQuery("#" + key).attr("voted") != "true") {
                    var b = responseBatch.Responses[0].CustomItem.CurrentUserHasRecommended;
                    if (b == "False") {
                        jQuery("#" + key + " .disagreeLink").removeClass("disabled").attr("href", "javascript:conversations.disagree('" + key + "');");
                    } else {
                        jQuery("#" + key).attr("voted", "true");
                        conversations.disableVoting(key);
                    }
                }
            }
        });
    },

    getAndRenderLatestConversations: function() {
        var requestBatch = new RequestBatch();

        jQuery("#fakeLine").hide();

        var collectionKey;
        if (pageIsOneOf("Profile")) {
            var conversationsProfileID = gSiteLife.GetParameter("userid") || getPluckLoggedInUser();
            collectionKey = conversationsProfileID + "_USER_ALL";
        } else if (pageIsOneOf("Genre")) {
            collectionKey = conversations.subjectId + "_GENRE_ALL";
        } else if (pageIsOneOf("ConversationsDetails")) {
            collectionKey = conversations.subjectId;
        } else {
            collectionKey = conversations.subjectId + "_ALL";
        }
        requestBatch.AddToRequest(new CustomCollectionPage(new CustomCollectionKey(collectionKey), conversations.itemsInPage, conversations.pageNumber, "PositionDescending"));
        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            (function($) {
                if (responseBatch.Messages[0].Message == "ok") {
                    //log_dir("getAndRenderLatestConversations", responseBatch);

                    var totalItems = responseBatch.Responses[0].CustomCollectionPage.NumberOfItems;
                    if (totalItems > 0) {
                        $("#fakeLine").show();
                        $(".paginator").removeClass("hidden");
                        var extraPage = (totalItems % conversations.itemsInPage) > 0 ? 1 : 0;
                        var totalPages = Math.floor(Math.abs(totalItems / conversations.itemsInPage)) + extraPage;
                        if (conversations.pageNumber >= totalPages) {
                            $("#paginatorNextPageLink").addClass("disabled").click(function(e) {
                                e.preventDefault();
                            });
                        } else {
                            $("#paginatorNextPageLink").removeClass("disabled").unbind("click");
                        }
                        $("#paginatorPageNo").html(conversations.pageNumber);
                        $("#paginatorPagesTotal").html(totalPages);
                    }
                    conversations.renderConversationsFromCustomItems($, responseBatch.Responses[0].CustomCollectionPage.Items);
                }
            })(jQuery);
        });
        return false;
    },

    renderConversationsFromCustomItems: function($, arr) {
        var commentsList = $("#commentsList").empty();
        if (arr.length > 0) {
            $("#commentsList").removeClass("noborders");
        } else {
            $("#commentsList").addClass("noborders");
        }
        for (var i = 0, len = arr.length; i < len; i++) {

            if (conversations.isArray(JSON.parse(arr[i].CustomItem.MimeType))) {
                conversations.fixMimeTypes(arr[i].CustomItem);
            }

            var clone = $("#commentTemplate").clone().removeClass("hidden").removeAttr("id").attr("id", arr[i].CustomItem.CustomItemKey.Key);
            if (i == 0) clone.addClass("first"); else clone.removeClass("first");
            clone.find("p.body").html(conversations.sanitize(arr[i].CustomItem.Content));
            clone.find("div.profile h2 a").html(arr[i].CustomItem.Author.DisplayName);
            clone.find("div.profile span.timestamp").html(dateFormat(new Date(arr[i].CustomItem.LastUpdated), "mmmm d, yyyy h:MM TT"));
            clone.find("div.takePart a").attr("href", conversations.conversationsDetailsUrl + "?commentid=" + arr[i].CustomItem.CustomItemKey.Key);
            if (pageIsOneOf("Profile")) {
                clone.find("div.profile img").remove();
                clone.find("div.profile h2").remove();
            } else {
                conversations.getJsonSync("/Handlers/AvatarUrl.ashx?userid=" + arr[i].CustomItem.Author.UserKey.Key, function(json) {
                    clone.find("div.profile img").attr("src", json.imageurl);
                    clone.find("div.profile h2 a").attr("href", json.profileurl);
                });
            }
            if (pageIsOneOf("Duc", "Feature", "ConversationsViewAll", "ConversationsDetails")) {
                clone.find("div.conHeader").remove();
            }
            //log_dir("mime type", [arr[i].CustomItem.CustomItemKey.Key, arr[i].CustomItem.MimeType]);
            if (pageIsOneOf("Genre", "Profile")) {
                conversations.getJsonSync("/Handlers/FeaturedContentHeader.ashx?id=" + JSON.parse(arr[i].CustomItem.MimeType).articleId, function(json) {
                    clone.find("div.conHeader .flyingHead").html(json.flyinghead);
                    clone.find("div.conHeader h3 a").attr("href", json.url);
                    clone.find("div.conHeader h3 a").html(json.title).append("&nbsp;<span class=\"subHead\">" + json.subtitle + "</span>");
                });
            }
            conversations.initAgreeLink(clone, arr[i].CustomItem.CustomItemKey.Key, arr[i].CustomItem.NumberOfRecommendations, arr[i].CustomItem.CurrentUserHasRecommended);
            conversations.renderReportAbuse(clone, arr[i].CustomItem.CustomItemKey.Key, arr[i].CustomItem.AbuseReportCount);
            commentsList.append(clone);
        }

        for (var i = 0, len = arr.length; i < len; i++) {
            conversations.initDisagreeLink(arr[i].CustomItem.CustomItemKey.Key);
        }

    },

    initAgreeLink: function(commentRootJQueryElem, key, numberOfRecommendations, currentUserHasRecommended) {
        var agreeLink = commentRootJQueryElem.find(".feedback .agreeLink").html("Agree (" + numberOfRecommendations + ") ");
        if (currentUserHasRecommended == "False") {
            agreeLink.removeClass("disabled").attr("href", "javascript:conversations.agree('" + key + "');");
            commentRootJQueryElem.removeAttr("voted");
        } else {
            agreeLink.addClass("disabled").attr("href", "#").click(function(e) {
                e.preventDefault();
            });
            commentRootJQueryElem.attr("voted", "true");
        }
    },

    renderReportAbuse: function(commentRootJQueryElem, key, abuseReportCount) {
        console.log('renderReportAbuse ' + key + ' ' + abuseReportCount);
        try {
            abuseReportCount = parseInt(abuseReportCount);
        } catch (err) {
            abuseReportCount = 0;
        }
        if (abuseReportCount > 0) {
            //commentRootJQueryElem.find(".reportAbuse a").hide(); -- does not work in Safari 
            commentRootJQueryElem.find(".reportAbuse a").css('display', 'none');
            //commentRootJQueryElem.find(".reportAbuse span").show(); -- does not work in safari
            commentRootJQueryElem.find(".reportAbuse span").css('display', 'inline');
        } else {
            //commentRootJQueryElem.find(".reportAbuse span").hide();
            //commentRootJQueryElem.find(".reportAbuse a").show();
            commentRootJQueryElem.find(".reportAbuse span").css('display', 'none');
            commentRootJQueryElem.find(".reportAbuse a").css('display', 'inline');
            commentRootJQueryElem.find(".reportAbuse a").click(function() {
                console.log('clicked on report abuse');
                var requestBatch = new RequestBatch();
                var abuseReport = new ReportAbuseAction(new CustomItemKey(key), "abusive content", "reported by " + getPluckLoggedInUser());
                requestBatch.AddToRequest(abuseReport);
                requestBatch.BeginRequest(serverUrl, function(responseBatch) {
                    log_dir("report abuse response", responseBatch);
                    if (responseBatch.Messages[0].Message == 'ok') {
                        conversations.renderReportAbuse(commentRootJQueryElem, key, abuseReportCount + 1);
                    }
                });
            });
        }
    },

    //first comment on an article
    startConversation: function() {

        try {
            updateTracking('-Added to Conversation');
        }
        catch (err) {
            log_dir("message calling updateTracking", err);
        }

        var requestBatch = new RequestBatch();

        var commentKey = new CustomItemKey(conversations.newGuid());
        var commentName = "comment";
        var mimeType = JSON.stringify({ threadId: conversations.subjectId, parentThreadId: "", articleId: conversations.subjectId });
        var content = conversations.sanitize(jQuery("#startConversationText").val());
        var abstractText = content.substring(0, 50);

        requestBatch.AddToRequest(new UpdateCustomItemAction(commentKey, commentName, mimeType, abstractText, content));

        var articleThreadKey = new CustomCollectionKey(conversations.subjectId);
        var articleMasterKey = new CustomCollectionKey(conversations.subjectId + "_ALL");
        var userMasterKey = new CustomCollectionKey(getPluckLoggedInUser() + "_USER_ALL");


        requestBatch.AddToRequest(new AddCustomCollectionAction(articleThreadKey, "ArticleThread"));
        requestBatch.AddToRequest(new AddCustomCollectionAction(articleMasterKey, "ArticleMaster"));
        requestBatch.AddToRequest(new AddCustomCollectionAction(userMasterKey, "UserMaster"));

        requestBatch.AddToRequest(new InsertIntoCollectionAction(articleThreadKey, commentKey, 0));
        requestBatch.AddToRequest(new InsertIntoCollectionAction(articleMasterKey, commentKey, 0));
        requestBatch.AddToRequest(new InsertIntoCollectionAction(userMasterKey, commentKey, 0));

        if (pageIsOneOf("Duc")) {
            var articleGenreKey = new CustomCollectionKey(conversations.ducPageGenreId + "_GENRE_ALL");
            requestBatch.AddToRequest(new AddCustomCollectionAction(articleGenreKey, "GenreMaster"));
            requestBatch.AddToRequest(new InsertIntoCollectionAction(articleGenreKey, commentKey, 0));
        }

        requestBatch.AddToRequest(new CommentAction(new ArticleKey(conversations.subjectId), window.document.location.href.split("?")[0], window.document.title, content));

        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            log_dir("startConversation", responseBatch);
            jQuery("#startConversationText").val("");
            conversations.getAndRenderLatestConversations();
        });
        return false;
    },

    commentOnComment: function() {
        var requestBatch = new RequestBatch();

        var headComment = conversations.headComment; //left there by ConversationsDetailsSublayout.ascx

        if (conversations.isArray(JSON.parse(headComment.MimeType))) {
            conversations.fixMimeTypes(headComment);
        }

        var headMimeType = JSON.parse(headComment.MimeType);
        var parentThreadId = headMimeType.threadId;
        var articleId = headMimeType.articleId;

        var commentKey = new CustomItemKey(conversations.newGuid());
        var commentName = "comment";
        var mimeType = JSON.stringify({ threadId: conversations.subjectId, parentThreadId: parentThreadId, articleId: articleId });
        var content = jQuery("#startConversationText").val();
        var abstractText = content.substring(0, 50);

        requestBatch.AddToRequest(new UpdateCustomItemAction(commentKey, commentName, mimeType, abstractText, content));

        var articleThreadKey = new CustomCollectionKey(conversations.subjectId);
        var articleMasterKey = new CustomCollectionKey(articleId + "_ALL");
        var userMasterKey = new CustomCollectionKey(getPluckLoggedInUser() + "_USER_ALL");

        requestBatch.AddToRequest(new AddCustomCollectionAction(articleThreadKey, "ArticleThread"));
        requestBatch.AddToRequest(new AddCustomCollectionAction(articleMasterKey, "ArticleMaster"));
        requestBatch.AddToRequest(new AddCustomCollectionAction(userMasterKey, "UserMaster"));

        requestBatch.AddToRequest(new InsertIntoCollectionAction(articleThreadKey, commentKey, 0));
        requestBatch.AddToRequest(new InsertIntoCollectionAction(articleMasterKey, commentKey, 0));
        requestBatch.AddToRequest(new InsertIntoCollectionAction(userMasterKey, commentKey, 0));

        if (pageIsOneOf("Duc", "ConversationsDetails")) {
            var articleGenreKey;
            if (pageIsOneOf("Duc")) {
                articleGenreKey = new CustomCollectionKey(conversations.ducPageGenreId + "_GENRE_ALL");
            } else if (pageIsOneOf("ConversationsDetails")) {
                articleGenreKey = new CustomCollectionKey(conversations.getGenreIfDuc(articleId) + "_GENRE_ALL");
            }
            requestBatch.AddToRequest(new AddCustomCollectionAction(articleGenreKey, "GenreMaster"));
            requestBatch.AddToRequest(new InsertIntoCollectionAction(articleGenreKey, commentKey, 0));
        }

        requestBatch.AddToRequest(new CommentAction(new ArticleKey(articleId), window.document.location.href.split("?")[0], window.document.title, content));

        requestBatch.BeginRequest(serverUrl, function(responseBatch) {
            log_dir("commentOnComment", responseBatch);
            jQuery("#startConversationText").val("");
            conversations.getAndRenderLatestConversations();
        });
        return false;
    },

    initLatestConversations: function($) {
        $(document).ready(function() {

            if (pageIsOneOf("ConversationsDetails")) {
                $("#startConversationSubmit").click(function(e) {
                    e.preventDefault();
                    conversations.commentOnComment();
                });
            } else {
                $("#startConversationSubmit").click(function(e) {
                    e.preventDefault();
                    conversations.startConversation();
                });
            }

            $("div.startConversation a.startLink").click(function(e) {
                e.preventDefault();
                $("#addToConversationFormDivID").removeClass("hidden");
            });

            var moduleRoot = $("#latestConversationsModuleRoot");
            if (pageIsOneOf("Duc", "Profile", "Feature", "Genre")) {
                moduleRoot.find("#latestConversationsModuleRoot .header").html("Latest Conversations"); //5.x.1 pages => Join , Responses (03)
            }
            if (pageIsOneOf("Duc", "Feature")) {
                moduleRoot.removeAttr("class").addClass("article").addClass("latestConversations");
            } else if (pageIsOneOf("Genre")) {
                moduleRoot.removeAttr("class").addClass("article").addClass("latestConversations").addClass("clearfix");
                moduleRoot.find("#addToConversationFormDivID").remove();
                moduleRoot.find("div.startConversation").remove(); //no "start conversation" link for genres
            } else if (pageIsOneOf("Profile")) {
                moduleRoot.removeAttr("class").addClass("article").addClass("latestConversations").addClass("bioConversations");
                moduleRoot.find("#addToConversationFormDivID").remove();
                moduleRoot.find(".startConversation").remove();
            }

            if (pageIsOneOf("ConversationsDetails")) {
                moduleRoot.removeAttr("class").addClass("article").addClass("latestConversations").addClass("clearfix");
                moduleRoot.find(".header").html("Responses");
                moduleRoot.find("#addToConversationFormDivID").removeClass("hidden");
                moduleRoot.find(".startConversation").remove();
            }

            if (pageIsOneOf("ConversationsViewAll")) {
                moduleRoot.removeAttr("class").addClass("article").addClass("latestConversations").addClass("clearfix");
                moduleRoot.find(".header").html("All Conversations");
                moduleRoot.find("#addToConversationFormDivID").remove();
                moduleRoot.find(".startConversation").remove();

                if (conversations.pageNumber <= 1) {
                    moduleRoot.find("#paginatorPrevPageLink").addClass("disabled").click(function(e) {
                        e.preventDefault();
                    });
                } else {
                    moduleRoot.find("#paginatorPrevPageLink").removeClass("disabled").unbind("click");
                }

                var baseUrl = window.document.location.href.split("?")[0];
                moduleRoot.find("#paginatorPrevPageLink").attr("href", baseUrl + "?articleid=" + conversations.subjectId + "&pagenumber=" + (conversations.pageNumber - 1));
                moduleRoot.find("#paginatorNextPageLink").attr("href", baseUrl + "?articleid=" + conversations.subjectId + "&pagenumber=" + (conversations.pageNumber + 1));
            }
            if (!pageIsOneOf("ConversationsViewAll", "ConversationsDetails")) {
                moduleRoot.find(".paginator").remove();
            }

            conversations.getAndRenderLatestConversations();
        });
    }

}