﻿/// <reference path="API/Agility.UGC.API.js" />

$(document).ready(function() { RequestComments(); });

function RenderCommentPagination() {
    var LeftAdded = false;
    var RightAdded = false;
    var PageSpace = 2;

    if (CommentsCurrentPage < 4) {
        PageSpace = 5 - CommentsCurrentPage;
    }
    if (CommentsCurrentPage > CommentsTotalPages - 4) {
        PageSpace = 5 - (CommentsTotalPages - CommentsCurrentPage);
    }
    var div = $Comments_divCommentsPagination;

    if (CommentsTotalPages > 1) {
        var html = '<span>Page</span>';
        for (var i = 1; i <= CommentsTotalPages; i++) {
            if (i > CommentsCurrentPage + PageSpace && i < CommentsTotalPages) {
                if (!RightAdded) {
                    html += "<span>&nbsp;...&nbsp;</span>";
                    RightAdded = true;
                }
            }
            else if (i > 1 && i < CommentsCurrentPage - PageSpace) {
                if (!LeftAdded) {
                    html += "<span>&nbsp;...&nbsp;</span>";
                    LeftAdded = true;
                }
            }
            else {
                html += "<a " + (i == CommentsCurrentPage ? "class='Selected'" : "") + " >" + i + "</a>";
            }
        }
        div.html(html);
        $('a:not(.Selected)', div).attr('href', 'javascript:;');
        $('a:not(.Selected)', div).click(function () {
            if (!CommentsDoingRequest) {
                CommentsCurrentPage = eval($(this).text());
                RequestComments();
            }
        });
        div.show();
    }
    else {
        div.hide();
    }
};

var CommentsCurrentPage = 1;
var CommentsTotalPages = 0;
var CommentsDoingRequest = false;

function RequestComments() {

    if (CommentsDoingRequest) return;
    CommentsDoingRequest = true;

    var searchArg = new Agility.UGC.API.SearchArg();
    searchArg.RecordTypeName = "";
    searchArg.PageSize = Comments_PageLen;
    searchArg.RecordOffset = (CommentsCurrentPage - 1) * Comments_PageLen;
    searchArg.Search = "RelatedContentID = " + Comments_ContentID;
    searchArg.SortedField = "Date";
    searchArg.SortDirection = "DESC";
    
    switch (Comments_ContentType.toLowerCase()) {
        case "article":
            searchArg.RecordTypeName = "ArticleComments";
            break;
        case "tip":
            searchArg.RecordTypeName = "TipComments";
            break;
        case "generic":
            searchArg.RecordTypeName = "GenericComments";
            break;
        case "blog":
            searchArg.RecordTypeName = "BlogComments";
            searchArg.Search = "(ExternalProfileType = 'Profile' && RelatedContentID = " + Comments_ContentID + 
                               ") || (ExternalProfileType = 'CS' && RelatedContentID = " + Comments_CSContentID + ")";
            break;
    }

    var div = $Comments_divComments;

    var noComments = function() {
        //No comments
        CommentsTotalPages = 0;
        div.html(Comments_NoCommentsLabel);
        $("#" + Comments_pnlComment + " > div").hide();
        $("#" + Comments_pnlComment + " > textarea").show();
        $("#" + Comments_pnlComment + " > input").show();
        CommentsDoingRequest = false;
    };

    if (searchArg.RecordTypeName != "") {

        Agility.UGC.API.SearchRecords(searchArg, function(data) {

            if (data.ResponseType != Agility.UGC.API.ResponseType.OK) {
                //alert("An error occurred: " + data.Message);
                noComments();
            }
            else if (data.ResponseData.Records.length > 0) {

                var articleComments = data.ResponseData.Records;
                var html = "";

                for (var i = 0; i < articleComments.length; i++) {
                    html += "<b>" + articleComments[i].ExternalProfileID + "</b><br/>"
                    html += articleComments[i].Comment;
                    html += "&nbsp;<i>Added " + dateFormat(ParseUGCDateString(articleComments[i].Date), "mmmm dd yyyy : h:MMtt") + "</i><br/><br/>";
                }
                if (html.length > 0) {
                    div.html(html);
                }
                else {
                    div.html(Comments_NoCommentsLabel);
                }

                CommentsTotalPages = Math.ceil(data.ResponseData.TotalRecords / Comments_PageLen);
                RenderCommentPagination();

                var cookie = GetWNetworkCommentCookie();
                if (cookie != null && cookie.indexOf("," + Comments_ContentType + "-" + Comments_ContentID + ',') > -1) {
                    $("#" + Comments_pnlComment + " > div").show();
                    $("#" + Comments_pnlComment + " > textarea").hide();
                    $("#" + Comments_pnlComment + " > input").hide();
                }
                else {
                    $("#" + Comments_pnlComment + " > div").hide();
                    $("#" + Comments_pnlComment + " > textarea").show();
                    $("#" + Comments_pnlComment + " > input").show();
                }

                //Update Article count aggregation
                if (CommentsCurrentPage == 1) UpdateArticleCommentsCount(data.ResponseData.TotalRecords);

                CommentsDoingRequest = false;
            }
            else {
                noComments();
            }
        });
    }
    else {
        noComments();
    }
};

function ParseUGCDateString(ugcDate) {
    try {
        var dt = ugcDate.split(" ");
        var d = dt[0].split("-");
        var t = dt[1].split(":");
        return new Date(eval(d[0]), eval(d[1]) - 1, eval(d[2]), eval(t[0]), eval(t[1]), eval(t[2]), 0);
    }
    catch (e) { return new Date(); }
};

function SendCommentIfYouCan(sender) {
    if (GetWNetworkUserCookie().length > 0) {
        SendComment(sender);
    }
    else {
        ShowLoginPopup(function() {
            if (GetWNetworkUserCookie().length > 0) {
                SendComment(sender);
            }
        });
    }
};

function HtmlEncode(text) {
    return $('<div/>').html(text).text();
};

function SendComment(sender) {

    GetCurrentLoggedUsername(Agility.ResolveUrl("~/WebServices/AjaxServices.asmx"), function(userName) {

        var button = $(sender);

        var comment = button.prev().val().replace(/'/g, "\\'");
        if (comment.replace(/^\s+|\s+$/g, "").length == 0) {
            alert("Please enter a comment");
            return;
        }

        // Disable the button from being clicked again
        $('#' + Comments_ButtonID).attr('disabled', 'disabled');

        var r = {
            RecordTypeName: "",
            Name: Comments_ContentTitle,
            Comment: HtmlEncode(comment),
            RelatedContentID: Comments_ContentID,
            ExternalProfileID: userName,
            ExternalProfileType: "Profile",
            Date: dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss")
        };

        switch (Comments_ContentType.toLowerCase()) {
            case "article":
                r.RecordTypeName = "ArticleComments";
                break;
            case "tip":
                r.RecordTypeName = "TipComments";
                break;
            case "generic":
                r.RecordTypeName = "GenericComments";
                break;
            case "blog":
                r.RecordTypeName = "BlogComments";
                break;
        }

        if (r.RecordTypeName != "") {
            Agility.UGC.API.SaveRecord(r, function(data) {
                if (data.ResponseType != Agility.UGC.API.ResponseType.OK) {
                    alert("An error occurred: " + data.Message);
                    $('#' + Comments_ButtonID).removeAttr('disabled');
                }
                else {
                    button.prev().val("");
                    button.prev().hide();
                    button.hide();
                    button.prev().prev().show();
                }
            });
        }
    });
};

function UpdateArticleCommentsCount(count) {

    var searchArg = new Agility.UGC.API.SearchArg();
    searchArg.RecordTypeName = "ArticleCommentsCount";
    searchArg.Search = "RelatedContentID = " + Comments_ContentID;
    searchArg.CacheKey = (new Date()).getTime();

    Agility.UGC.API.SearchRecords(searchArg, function(data) {

        var r = null;

        if (data.ResponseType != Agility.UGC.API.ResponseType.OK) {
            alert("An error occurred: " + data.Message);
        }
        else if (data.ResponseData.Records.length > 0) {
            r = data.ResponseData.Records[0];
            if (r.Count == count) r = null;
            else r.Count = count;
        }
        else {
            r = {
                RecordTypeName: "ArticleCommentsCount",
                Name: Comments_ContentTitle,
                RelatedContentID: Comments_ContentID,
                Count: count
            };
        }
        if (r != null) {
            Agility.UGC.API.SaveRecord(r, function(data) {
                if (data.ResponseType != Agility.UGC.API.ResponseType.OK) {
                    alert("An error occurred: " + data.Message);
                }
            });
        }
    });
};
    

