﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="global.js" />

var COMMENTS_HIDER_PREFIX = "#CommentVote";
var COMMENTS_PREFIX = "#Comment";
var HIDE_COMMENT_CLASS = "hiddenComment";

function $WallTypeEnum() {
    this.None = 0;
    this.Advocacy = 1;
    this.AdocacyUpdate = 2;
    this.User = 3;
    this.UserUpdate = 4;
    this.Ballot = 5;
    this.AdvocacyBallot = 6;
}

var WallType = new $WallTypeEnum();

var DoesCurrentUserHaveAdminRights = false;
var IsCurrentWallEnabledForReporting = false;
//var CurrentWallType = WallType.None;

function displayHiddenComment(commentID) {
    $(COMMENTS_HIDER_PREFIX + commentID.toString()).toggleClass(HIDE_COMMENT_CLASS);
    $(COMMENTS_PREFIX + commentID.toString()).toggleClass(HIDE_COMMENT_CLASS);
}

function RateUp(commentID) {
    var postData = {
        'commentID': commentID
    };

    $.ajax({
        url: '/Walls/RateUp',
        data: postData,
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.error) {
                error('Rating Failed', result.message);
            }
            else {
                $('#MainComment' + result.commentID + 'Area').find('.commentRating:first').html((result.newRating >= 0 ? "+" : "") + result.newRating);
            }
        },
        error: function(xhr) {
            error('Rating Failed', 'There was an unknown error rating up this comment.  Please try again.');
        }
    });
}

function RateDown(commentID) {
    var postData = {
        'commentID': commentID
    };

    $.ajax({
        url: '/Walls/RateDown',
        data: postData,
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.error) {
                error('Rating Failed', result.message);
            }
            else {
                $('#MainComment' + result.commentID + 'Area').find('.commentRating:first').html((result.newRating >= 0 ? "+" : "") + result.newRating);
            }
        },
        error: function(xhr) {
            error('Rating failed', 'There was an unknown error rating down this comment.  Please try again.');
        }
    });
}

function DeleteComment(commentID) {
    var postData = {
        'commentID': commentID
    };

    $.ajax({
        url: '/Walls/DeleteComment',
        data: postData,
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.error) {
                error('Unable to Delete Comment', result.message);
            }
            else {
                $('#MainComment' + result.CommentID + 'Area').hide();
                $('#SubComment' + result.CommentID + 'Area').hide();
                var commentCount = $('.Number')[0].innerText;
                if (commentCount != null && commentCount != '') {
                    commentCount--;
                    $('.Number')[0].innerText = commentCount;
                }
            }
        },
        error: function(xhr) {
            error('Unable to Delete Comment', 'There was an error deleting this comment.  Please try again in a few minutes.');
        }
    });
}

function ReportToModerator(commentID) {
    var postData = {
        'commentID': commentID
    };

    $.ajax({
        url: '/Walls/ReportToModerator',
        data: postData,
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.error) {
                error('Unable to Report Comment', result.message);
            }
            else {
                success('Reported to Moderator', result.message);
            }
        },
        error: function(xhr) {
            error('Unable to Report Comment', 'There was an error reporting this comment to a moderator.  Please try again in a few minutes.');
        }
    });
}

function PostMainComment(wallID) {
    var text = $('#MainCommentInput' + wallID).val();

    PostComment(text, wallID, 0, $('#MainCommentInput' + wallID));
}

function PostComment(text, wallID, parentCommentID, elem) {
    text = $.trim(text);
    //check to see that the user has entered text
    if (!$(elem).hasClass('watermark') && text.length > 0) {
        var postData = {
            'text': text,
            'wallID': wallID,
            'parentCommentID': parentCommentID
        };

        $.ajax({
            url: "/Walls/Post",
            data: postData,
            type: 'POST',
            dataType: 'json',
            success: function(result) {

                RemoveLoader();

                if (result.error) {
                    error('Comment Post Failed', result.message);
                }
                else {
                    RenderComment(result);
                    elem.val('');
                    var numCont = $(elem).parents('.comment').find('.Number').eq(0);
                    console.log('numCont ', numCont);
                    var commentCount = numCont.text();
                    if (commentCount != null && commentCount != '') {
                        commentCount++;
                        numCont.text(commentCount);
                    }
                }
                //InitWatermarks();
            },
            error: function(xhr) {
                error('Comment Post Failed', 'There was an unknown error saving or rendering your comment.');
            }
        });
    }
    else {
        setTimeout('RemoveLoader();', 400);
    }
    
}

function RetrieveAdditionalChildren(commentID, additionalCommentID) {
    var postData = {
        'parentCommentID': commentID,
        'secondSetCommentSeen': additionalCommentID
    };

    $.ajax({
        url: '/Walls/RetrieveAdditionalChildren',
        data: postData,
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (!result.error && result.count > 0) {
                $('#SubcommentSep' + commentID).hide();
                for (var i = 0; i < result.count; i++) {
                    var comment = result.comments[i];

                    var temp = RenderSubcomment(comment);
                    var commentSection = '#MainComment' + comment.ParentID + 'Area div .AllContent .SubComments';
                    temp.insertBefore('#SubcommentSep' + commentID);
                }
            }
        },
        error: function(xhr) {
            error('Error Retrieving Comments', 'There was an error retrieving the latest comments for this thread.  Please try again later.');
        }
    });
}

function RenderComment(comment) {
    if (comment.error) {
        error('Error displaying a comment', comment.message);
        return;
    }
    if (comment.ParentID == 0) {
        RenderMainComment(comment, false);
    }
    else {
        var temp = RenderSubcomment(comment);
        var commentSection = '#MainComment' + comment.ParentID + 'Area div .AllContent .SubComments';
        temp.appendTo(commentSection);
    }
}

function RetrieveAdditionalMainComments(wallID, oldestCommentAlreadyRetrieved) {
    var postData = {
        'wallID': wallID,
        'oldestCommentIDAlreadyRetrieved': oldestCommentAlreadyRetrieved
    };

    $.ajax({
        url: '/Walls/RetrieveAdditionalComments',
        data: postData,
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            if (result.error) {
                error('Error Retrieving Additional Posts', error.message);
            }
            else {
                var count = result.count;
                for (var i = 0; i < result.comments.length; i++) {
                    var current = result.comments[i];
                    RenderMainComment(current, true);
                }

                if (result.moreComments) {
                    $('.OlderComms').attr('href', 'javascript:RetrieveAdditionalComments(' + wallID + ', ' + result.comments[result.comments.length - 1] + ');');
                }
                else {
                    $('.More').hide();
                }
            }
        },
        error: function(xhr) {
            error('Error Retrieving Additional Posts', 'There was an error retrieving additional posts for display.  Please try again.');
        }
    });
}

function __RenderAvatar(profileID, avatarPath, displayName) {
    /// <private />
    /// <summary>Functionally equivalent to Extensions.CommentAvatar    
    if (profileID == 0) {
        var img = document.createElement('img');
        img = $(img);
        img.attr('src', avatarPath);
        img.attr('alt', displayName);
        return img;
    }
    else {
        var a = document.createElement('a');
        var img = document.createElement('img');
        a.appendChild(img);
        img = $(img);
        img.attr('src', avatarPath);
        img.attr('alt', displayName);
        a = $(a);
        a.attr('href', '/Profile/' + profileID.toString());
        return a;
    }
}

function RenderMainComment(comment, bottom) {
    /// <summary>Renders a main top-level comment.</summary>
    /// <param name="comment" type="MoxyVote.Models.Shared.CommentViewData">The comment to render</param>
    /// <param name="bottom" type="Boolean">True to render at the bottom of the list; otherwise the comment will be inserted at the top as if it is new</param>
    var temp = $(template).filter('.mainCommentContainer').clone(true);

    temp.find('.voteUp').attr('href', 'javascript:RateUp(' + comment.CommentID + ');').end()
        .find('.voteUp').attr('title','Rate this comment up +1').end()
        .find('.voteDown').attr('href', 'javascript:RateDown(' + comment.CommentID + ');').end()
        .find('.voteDown').attr('title', 'Rate this comment down -1').end()
        .find('.reportToMod').attr('href', 'javascript:ReportToModerator(' + comment.CommentID + ');').end()
        .find('.reportToMod').attr('title', 'Report this comment to a moderator').end()
        .find('.rightArrRed').html('Make a comment<span class="arr">&nbsp;</span>').end()
        .find('.commentRating:first').html((comment.Rating >= 0 ? "+" : "") + comment.Rating.toString()).end()
        .find('.Ital').html(comment.TimeSince).end()
        .find('textarea').attr('id', 'SubcommentInput' + comment.CommentID).attr('title', "Comment on " + temp.find('.authorNameWithoutLink').html(comment.AuthorDisplayName).text() + "'s post...").end()
        .find('button').click(function() {
            PostComment($('#SubcommentInput' + comment.CommentID).val(), comment.WallID, comment.CommentID, $('#SubcommentInput' + comment.CommentID));
        }).end()
        .find('.displayHidden').attr('href', 'javascript:displayHiddenComment(' + comment.CommentID + ');').end()
        .find('.comment').attr('id', 'Comment' + comment.CommentID.toString()).end()
        .find('.Avatar').append(__RenderAvatar(comment.ProfileID, comment.Thumbnail.Path, comment.AuthorDisplayName)).end()
        .find('.TheContent').html(comment.Text).end();

    // Has User Icon
    for (var i = 0; i < comment.Blings.length; i++) {
        temp.find('.Avatar').append('<br/><img class="Icon" src="' + comment.Blings[i].Image.Path + '" alt="' + comment.Blings[i].Title + '" title="' + comment.Blings[i].Title + '" />');
    }

    if (comment.ProfileID == 0) {
        temp.find('.authorNameWithoutLink').html(comment.AuthorDisplayName).end()
            .find('.authorNameWithLink').css('display', 'none').end();
    }
    else {
        temp.find('.authorNameWithLink').attr('href', '/Profile/' + comment.ProfileID.toString()).html(comment.AuthorDisplayName).end()
            .find('.authorNameWithoutLink').css('display', 'none').end();
    }

    if (DoesCurrentUserHaveAdminRights) {
        temp.find('.reportToMod').attr('href', 'javascript:DeleteComment(' + comment.CommentID + ');').end();
        temp.find('.reportToMod').find('img').attr('alt', 'Delete this comment').attr('src', '/App_Themes/Default/Images/icn/delete.gif').end();
        temp.find('.reportToMod').find('img').attr('title', 'Delete this comment').attr('src', '/App_Themes/Default/Images/icn/delete.gif').end();
    }
    else if (!IsCurrentWallEnabledForReporting) {
        temp.find('.reportToMod').hide();
    }

    if (comment.Rating >= 0) {
        temp.find('.hiddenComment').toggleClass('hiddenComment').end()
            .find('.SubDeclined').toggleClass('hiddenComment').end();
    }
    else {
        temp.find('.SubDeclined').attr('id', 'CommentVote' + comment.CommentID.toString()).end();
    }

    temp.attr('id', 'MainComment' + comment.CommentID + 'Area');

    if (bottom) {
        temp.appendTo('#wall' + comment.WallID.toString() + ' div.comments');
    }
    else {
        $('#wall' + comment.WallID.toString()).find('div.comments').prepend(temp);
    }

    if (comment.TotalChildComments > 0) {
        var commentSection = '#MainComment' + comment.CommentID + 'Area div .AllContent .SubComments';
        if (comment.TotalChildComments > 5) {
            for (var i = 0; i < 3; i++) {
                var child = comment.ThreadComments[i];
                var tempChild = RenderSubcomment(child);
                tempChild.appendTo(commentSection);
            }
            var separator = RenderSubcommentSeparator(comment.CommentID, comment.ThreadComments[3].CommentID);
            separator.appendTo(commentSection);
            for (var i = 3; i < 5; i++) {
                var child = comment.ThreadComments[i];
                var tempChild = RenderSubcomment(child);
                tempChild.appendTo(commentSection);
            }
        }
        else {
            for (var i = 0; i < comment.TotalChildComments; i++) {
                var child = comment.ThreadComments[i];
                var tempChild = RenderSubcomment(child);
                tempChild.appendTo(commentSection);
            }
        }
    }
    BindExpandToAllSubComments();
    
    
    InitWatermarks();
}

function RenderSubcommentSeparator(parentCommentID, secondCommentSetID) {
    var temp = $(template).filter('.subCommentSeparator').find('div:first').clone(true);
    temp.attr('id', 'SubcommentSep' + parentCommentID.toString());
    temp.find('a').attr('href', 'javascript:RetrieveAdditionalChildren(' + parentCommentID.toString() + ', ' + secondCommentSetID.toString() + ');').end();

    return temp;
}

function RenderSubcomment(comment) {
    var temp = $(template).filter('.subCommentContainer').clone(true);
    temp.find('.voteUp').attr('href', 'javascript:RateUp(' + comment.CommentID + ');').end()
        .find('.voteUp').attr('title', 'Rate this comment up +1').end()
        .find('.voteDown').attr('href', 'javascript:RateDown(' + comment.CommentID + ');').end()
        .find('.voteDown').attr('title', 'Rate this comment down -1').end()
        .find('.reportToMod').attr('href', 'javascript:ReportToModerator(' + comment.CommentID + ');').end()
        .find('.reportToMod').attr('title', 'Report this comment to a moderator').end()
        .find('.commentRating:first').html((comment.Rating >= 0 ? "+" : "") + comment.Rating.toString()).end()
        .find('.Ital').html(comment.TimeSince).end()
        .find('.hiddenComment').attr('id', 'Comment' + comment.CommentID).end()
        .find('.displayHidden').attr('href', 'javascript:displayHiddenComment(' + comment.CommentID + ');').end()
        .find('.SubAvatar').append(__RenderAvatar(comment.ProfileID, comment.Thumbnail.Path, comment.AuthorDisplayName)).end()
        .find('.SubContentComment').html(comment.Text).end();

    for (var i = 0; i < comment.Blings.length; i++) {
        temp.find('.SubAvatar').append('<br/><img class="Icon" src="' + comment.Blings[i].Image.Path + '" alt="' + comment.Blings[i].Title + '" title="' + comment.Blings[i].Title + '" />');
    }

    if (comment.Rating >= 0) {
        temp.find('.hiddenComment').toggleClass('hiddenComment').end()
            .find('.SubDeclined').toggleClass('hiddenComment').end();
    }
    else {
        temp.find('.SubDeclined').attr('id', 'CommentVote' + comment.CommentID.toString()).end();
    }

    if (DoesCurrentUserHaveAdminRights) {
        temp.find('.reportToMod').attr('href', 'javascript:DeleteComment(' + comment.CommentID + ');').end();
        temp.find('.reportToMod').find('img').attr('alt', 'Delete this comment').attr('src', '/App_Themes/Default/Images/icn/delete.gif').end();
        temp.find('.reportToMod').find('img').attr('title', 'Delete this comment').attr('src', '/App_Themes/Default/Images/icn/delete.gif').end();
    }
    else if (!IsCurrentWallEnabledForReporting) {
        temp.find('.reportToMod').hide();
    }

    if (comment.ProfileID == 0) {
        temp.find('.authorNameWithoutLink').html(comment.AuthorDisplayName).end()
            .find('.authorNameWithLink').css('display', 'none').end();
    }
    else {
        temp.find('.authorNameWithLink').attr('href', '/Profile/' + comment.ProfileID.toString()).html(comment.AuthorDisplayName).end()
            .find('.authorNameWithoutLink').css('display', 'none').end();
    }

    temp.attr('id', 'MainComment' + comment.CommentID + 'Area')
    return temp;
}

function BindExpandToAllSubComments() {
    $('.SubComment').one('click', null, function() {
        $(this).find('textarea')
        .css({ 'z-index': 999, position: 'relative', height: 70 })
        .parent().find('button').show();

    });
}

function ExpandCommentsToggle(sender, commentDiv) {
    $(sender).toggleClass('rightArrRed').toggleClass('downArrRed');
    $(commentDiv).slideToggle();
}

function ShowSubComments(sender) {
    $(sender).toggleClass('rightArrRed').toggleClass('downArrRed').closest('.AllContent').find('.SubComments').slideToggle(500);
}

function RenderUpdates(result, admin) {


    var updates = result.AdvocacyUpdates.Updates;


    // Get Length And Iterate Updates
    var length = updates.length;
    for (var item = 0; item < length; item++) {

        // Get Updates Container
        var updateItem = $('.UpdateTemplates .UpdateItem').clone(true);

        // Populate Update
        updateItem
                    .attr('id', 'Update' + updates[item].UpdateID)
                    .find('.EditCont .BotRight a:first').attr('onclick', "EditUpdate(" + updates[item].UpdateID + ");").end()
                    .find('.EditCont .BotRight a:last').attr('onclick', "RemoveUpdate('" + updates[item].Url + "/Delete'); $(this).parents('.UpdateItem:first').slideUp().remove();").end()
                    .find('.TopTitle').html(updates[item].Title).end()
                    .find('.TopTime').html(updates[item].FormattedDatePublished).end()
                    .find('.UpdateItemDesc .MainContent .TextContent').html(updates[item].TextContent);

        // Hide Read More Link
        if (updates[item].TextContent.length <= 445) {
            updateItem.find('.UpdateItemDesc .MainContent .TextContent').removeClass('ReadMore').end().find('.UpdateItemDesc .MainContent a').remove();
        }

        // Test For Image
        if (updates[item].Image.Path != null && updates[item].Image.Path.length > 0) {
            updateItem.find('.UpdateItemDesc .MainContent .button').attr('id', 'UploadButton' + updates[item].UpdateID).css('background-image', 'url(' + updates[item].Image.Path + ')');
        }
        else {
            updateItem.find('.UpdateItemDesc .MainContent .button').remove();
        }

        // Get Wall Container
        var wallItem = $($('.UpdateTemplates .WallTemplate').html());

        // Set Wall ID
        wallItem.filter('.profile').attr('id', 'wall' + updates[item].Wall.WallID).hide();

        // Add Comment Count
        wallItem.find('.CommentCount')
                    .addClass('rightArrRed')
                    .attr('onclick', 'ExpandCommentsToggle(this, "#wall' + updates[item].Wall.WallID + '")')
                    .append('<span class="Number">' + updates[item].Wall.TotalComments + '</span>')
                    .append(' Comment' + (updates[item].Wall.TotalComments == 1 ? '' : 's'))
                    .append('<span class="Icn arr">&nbsp;</span>').end()
                    .find('.TopCommentCont button')
                    .attr('onclick', 'PostMainComment(' + updates[item].Wall.WallID + ');').end()
                    .find('.TopCommentCont textarea').attr('id', 'MainCommentInput' + updates[item].Wall.WallID);

        // More Comments Then Page Size
        if (updates[item].Wall.TotalComments <= updates[item].Comments.length) {
            wallItem.filter('.profile').find('.More a:first').remove();
        }

        // Append Wall To  Update
        updateItem.find('.updateComments').append(wallItem);

        // Append Update To Update List
        $('.updates > .List').append(updateItem);

        // Get Comments Length And Iterate
        var comments = updates[item].Wall.Comments;
        var commentLength = updates[item].Wall.Comments.length;
        for (var comment = 0; comment < commentLength; comment++) {
            RenderMainComment(comments[comment], true);
        }

        if (admin) {
            InitializeUpdateUpload(updates[item].UpdateID);
        }
    }

    // Hide Paging
    if ((result.AdvocacyUpdates.PageSize * page) >= result.AdvocacyUpdates.TotalUpdates) {
        $('.updates  button.More').hide();
    }
}