﻿var rptAbuseChoice;
var rptCommentId;
var modalDlg;
var totalComments = -1;
var requestedPageNum = 1;
var sortChoice = null;
var inEdit = false;
var commentIdUnderEdit = null;

$get = function(x) {
    return $('#' + x)[0];
};

function actualShowCommentCounts() {
    $get("BLKcommentCount").innerHTML = "<h3>Comments (" + totalComments + ")</h3>";
    var obj = $get(divCommentsCount);
    var mesg = "Be the first to leave a comment";

    if (totalComments >= 1) {
        mesg = totalComments.toString() + " Comment";
        if (totalComments > 1) {
            mesg += "s";
        }
    }

    if (obj != null && obj.innerHTML != null) {
        obj.innerHTML = mesg;
    }

    $get("commentingBlock").style.display = "";
}

function add_id_to_cookie(id) {
    if (check_id_in_cookie(id)) return;
    var vals = getCommentIDArray();
    vals.push(id);
    putCommentIDArray(vals);
}


function checkBrowser() {
    var browserName = navigator.appName;
    if (browserName != "Microsoft Internet Explorer") return;
    $get("commentingBlock").style.width = "610px";
    $get("BLKcommentCount").style.width = "610px";
}

function checkVersion() {
    var msg = "You're not using Windows Internet Explorer.";
    var ver = getInternetExplorerVersion();
    if (ver > -1) {
        if (ver >= 8.0)
            msg = "You're using a recent copy of Windows Internet Explorer."
        else
            msg = "You should upgrade your copy of Windows Internet Explorer.";
    }

    alert(msg);
}

function check_id_in_cookie(id) {
    var vals = getCommentIDArray();
    for (var i = 0; i < vals.length; i++) {
        if (vals[i] == id) return true;
    }
    return false;
}

function commentAggregation_PageLoad() {
    inEdit = false;

    if (typeof (commentReadProxy) != 'undefined' && commentReadProxy == null) {
        px_cr_createReadProxy(px_cr_ajaxUrl);
        px_cr_getCommentCountsOfList(contentList, getCommentCountsOfListCompleted, getCommentCountsOfListError);
    }
}

function commentDisplay_HideBlock() {
    var obj;
    obj = $get("pnlRptAbuseConfirm");
    if (obj) {
        obj.innerHTML = "";
        obj.className = "";
    }

    obj = $get("pnlRptAbuseCompleted");
    if (obj) {
        obj.innerHTML = "";
        obj.className = "";
    }
}

function commentDisplay_PageLoad() {

    if (typeof (commentReadProxy) != 'undefined' && commentReadProxy == null)
        px_cr_createReadProxy(px_cr_ajaxUrl);

    if (typeof (commentWriteProxy) != 'undefined' && commentWriteProxy == null)
        px_cw_createWriteProxy(px_cw_ajaxUrl);

    if (totalComments != -1) {
        actualShowCommentCounts();
        return;
    }

    if (typeof (commentReadProxy) != 'undefined' && commentReadProxy != null) {
        sortChoice = SortDirections.CreateTimeAscRN;
        getDisplayCommentCount();
    }
}

function editComment(commentDomId, commentId) {
    var oEditor = null;
    var commentText = null;

    commentText = $get(commentDomId).innerHTML; // gets the actual comment.

    // get the editor and populate it with the text to change.
    oEditor = CKEDITOR.instances.commentEntryBox;
    oEditor.setData(commentText);
    oEditor.focus;

    // set the global of the comment currently being edited.
    commentId = commentId;
}

function generateComments(results) {
    var HTML = "";
    var oldCommentId = "";
    var cmtId = 0;
    var commentItem = null;
    var commentDomId = "";

    if (results != null) {
        for (var it = 0; it < results.length; it++) {
            commentItem = results[it];

            try {
                cmtId = parseInt(commentItem.CommentId.substring(commentItem.CommentId.indexOf(":") + 1), 10);
            } catch (e3) {
                cmtId = -1;
            }

            commentDomId = "comment-block-cmt-" + cmtId;

            HTML += "<div class=\"comment-block\"><p>";

            if (commentItem.Status == "pending")
                HTML += "<div class=\"comment-pending\">Thank you. Your comment is posting and will appear like this when posted:</div>";

            if ((commentItem.UserTypeId & UserType.TVGStaff) == UserType.TVGStaff) {
                HTML += "<img src=\"http://www.tvguide.com/images/global/small-logo.gif\" alt=\"TV Guide Staff\" class=\"comment-tvg-logo\" /> ";
            }
            if ((commentItem.UserTypeId & UserType.Facebook) == UserType.Facebook) {
                HTML += "<img src=\"http://www.tvguide.com/images/global/facebook_share_icon.gif\" alt=\"Facebook\" class=\"comment-tvg-logo\" /> ";
            }

            /* HTML += "<p><strong><a href=\"#\" id=\"userName\" title=\"user\">" + commentItem.userNameField + "</a></strong>" */
            HTML += "<strong>" + commentItem.UserName + "</strong>";

            HTML += ": " + commentItem.CommentTimeStampAsString;
            HTML += "<div id='" + commentDomId + "'>" + commentItem.CommentText + "</div>";

            if (check_id_in_cookie(cmtId)) {
                HTML += "<div class=\"recom-w\"><span class=\"report_recommend\">";
                HTML += "<img src=\"http://www.tvguide.com/Images/global/yourecom-img.gif\" border=\"0\"></span>";
            } else {
                HTML += "<div class=\"recom-w\"><span class=\"report_recommendby\"><a class=\"greynav\" href=\"javascript:recommendComment('" + commentItem.CommentId + "');\">";
                HTML += "<img src=\"http://www.tvguide.com/Images/global/recom-img.jpg\" border=\"0\"></a></span>";
            }

            if (commentItem.AgreeCount != 0) {
                HTML += "<span class=\"report_recommended\">";
                HTML += "Recommended by " + commentItem.AgreeCount + " reader" + (commentItem.AgreeCount > 1 ? "s" : "") + "</span>";
            }

            /* - future to allow comment editing.  A proxy change is needed.
            if (((commentItem.UserTypeId & UserType.TVGStaff) == UserType.TVGStaff) && tvgUserName == commentItem.UserName) {
            HTML += "<p><span class=\"edit_comment\"><a class=\"greynav\" href=\"javascript:editComment('" + commentDomId + "', '" + commentItem.CommentId + "');\">";
            HTML += "edit comment</a></span></p>";
            }
            */

            HTML += "<p><span class=\"report_abuse\"><a class=\"greynav\" href=\"javascript:reportAbuse('" + commentItem.CommentId + "');\">";
            HTML += "report abuse</a></span></p></div>";
            if (it + 1 != results.length) {
                HTML += "<p class=\"greyline_long\">&nbsp;</p>";
            }
            HTML += "</div>"
        }
    }
    return HTML;
}

function generatePager() {
    if (totalComments == -1) {
        setTimeout("generatePager();", 1000);
        return;
    }

    var HTML = getPagerHtml();
    var topPager = $get("topPager");
    if (topPager) topPager.innerHTML = HTML;
    var btmPager = $get("btmPager");
    if (btmPager) btmPager.innerHTML = HTML;
}

function getCommentIDArray() {
    var theCookie = getCookieComment("commentids");
    var vals = new Array();
    if (theCookie != "") {
        vals = theCookie.split(",");
    }
    return vals;
}

function getCommentCountCompleted(results) {
    totalComments = results;
    showCommentCounts();
}

function getCommentCountsOfListError(errorInfo) {
    alert("Could not get comment counts");
    //    alert(errorInfo.toString());
}

function getCommentCountsOfListCompleted(results) {

    for (var it = 0; it < results.length; it++) {
        var commentItem = results[it];

        var commentLbl = $get(commentItem.Name);
        if (commentItem.Value >= 2)
            commentLbl.innerHTML = commentItem.Value + " Comments";
        else if (commentItem.Value == 1)
            commentLbl.innerHTML = commentItem.Value + " Comment";
        else
            commentLbl.innerHTML = "Be the first to leave a comment";
    }
}

function getDisplayCommentCount() {
    if (totalComments == -1) {
        px_cr_getDisplayCommentCount(contentKeyInfo, getCommentCountCompleted)
    }
}

function getCookieComment(c_name) {
    var c_start;
    var c_end;
    try {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
    } catch (e2) {
        return "";
    }
    return "";
}

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }

    return rv;
}

function getPagerHtml() {
    var HTML;
    var currentPage = requestedPageNum
    var span = 3; //numbers to display on each side of the current number
    var totalPages = Math.ceil(totalComments / commentsPerPage);
    var i = Math.max(currentPage - span, 2); //start on page 2 if you're on say page 3 (don't start on page 0)
    var pagesUntil = currentPage + span;

    if (commentsPerPage >= totalComments)
        return "";

    HTML = "<ul class='paginate'>";

    if (currentPage > 1) {
        HTML += "<li class='back'><a href='#BLKcommentCount' onclick='getCommentPage(" + (currentPage - 1) + ");'> back</a></li>";
        HTML += "<li class='firstitem'><a href='#BLKcommentCount' onclick='getCommentPage(1);'>1</a></li>";
    }
    else {
        HTML += "<li class='paginate-current firstitem'>1</li>";
    }

    while (i <= pagesUntil) {
        if (i > totalPages) {
            i++;
            break;
        }

        if (i == currentPage)
            HTML += "<li class='paginate-current'>" + i + "</li>";
        else
            HTML += "<li><a href='#BLKcommentCount' onclick='getCommentPage(" + i + ");'>" + i + "</a></li>";

        i++;
    }

    if (i < totalPages + 1)
        HTML += "<li class='totpages'> ... <a href='#BLKcommentCount' onclick='getCommentPage(" + totalPages + ");'>" + totalPages + "</a></li>";

    if (currentPage < totalPages)
        HTML += "<li class='next'><a href='#BLKcommentCount' onclick='getCommentPage(" + (currentPage + 1) + ");'>next </a></li>";

    HTML += "</ul>";
    return HTML;

}

function getSortedCommentPage(sortList) {
    switch (sortList[sortList.selectedIndex].value) {
        case "1": sortChoice = SortDirections.CreateTimeAscRN; break;
        case "2": sortChoice = SortDirections.CreateTimeDescRN; break;
        case "3": sortChoice = SortDirections.AgreeCountAscRN; break;
        case "4": sortChoice = SortDirections.AgreeCountDescRN; break;
        default: sortChoice = SortDirections.CreateTimeAscRN;
    }

    getCommentPage(1);
}

function getCommentPage(pageNum) {

    if (sortChoice == null)
        sortChoice = SortDirections.CreateTimeAscRN;

    if (totalComments > 0) {
        requestedPageNum = pageNum;
        px_cr_getCommentPage(contentKeyInfo, commentsPerPage, requestedPageNum, sortChoice, getCommentPageCompleted)
    }
}

function getCommentPageError(errorInfo) {
    alert("Could not get comment page");
    //alert(errorInfo._message);
}

function getCommentPageCompleted(results) {
    $get("spottoputcomments").innerHTML = generateComments(results);
    generatePager();
    checkBrowser();
}

function recommendComment(commentId) {
    rptCommentId = commentId;
    px_cw_incrementAgreeForComment(contentKeyInfo, rptCommentId, recommendCommentCompleted, null);
}

function recommendCommentCompleted(results) {
    cmtId = parseInt(rptCommentId.substring(rptCommentId.indexOf(":") + 1), 10);
    add_id_to_cookie(cmtId);
    getCommentPage(requestedPageNum);
}

function reportAbuse(commentId) {
    rptCommentId = commentId;

    jQuery.facebox($get("pnlRptAbuseConfirm").innerHTML);
    $('#facebox .footer').css('display', 'none');
}

function reportAbuseComfirm(choice) {
    //$(document).trigger('close.facebox');

    if (choice == 'yes') {
        px_cw_reportComment(contentKeyInfo, rptCommentId, reportAbuseCompleted, null);
    }
    else {
        $(document).trigger('close.facebox');
        $('#facebox .footer').css('display', 'block');
    }
}

function reportAbuseCompleted(results) {
    $('#facebox .footer').css('display', 'block');
    $('#facebox .content').html($get('pnlRptAbuseCompleted').innerHTML);
    setTimeout("$(document).trigger('close.facebox');", 2000);
}

function putCommentIDArray(vals) {
    while (vals.length > 40) {
        vals.shift();
    }
    setCookieComment("commentids", vals.join(), 365);
}

function setCookieComment(strName, strValue, iDays) {
    var strCookie = strName + "=" + strValue + "; ";
    if (iDays != 0) {
        var date = new Date();
        date.setTime(date.getTime() + (iDays * 24 * 60 * 60 * 1000));
        strCookie += "expires=" + date.toGMTString() + "; ";
    }
    var dom = document.domain;
    var tvg = ".tvguide.com";
    if (dom.indexOf(tvg) == dom.length - tvg.length) {
        strCookie += "domain=" + tvg + "; ";
    }
    strCookie += "path=/";
    document.cookie = strCookie;
}

function showCommentCounts() {
    actualShowCommentCounts();
}
// end of CommentDisplay.js
 

