﻿// Creates all of the reply and abuse report links for the comments
var usernameValidated = false;
var threadedComments = false;
var premoderateComments = false;

function initializeComments(commentsAllowed, threadComments, premoderate) {

    threadedComments = threadComments;
    premoderateComments = premoderate;
    
    if (!commentsAllowed)
        $('#comments-header').append("<p>Comments for this post are closed.</p>");
    else {
    		Sys.require([Sys.scripts.ApplicationServices, Sys.scripts.ComponentModel], applicationServicesScriptReady);
    }
}

function applicationServicesScriptReady() {
	Sys.Services._RoleService.DefaultWebServicePath = '/Role_JSON_AppService.axd';
	Sys.Services.RoleService.load(loadRolesCompleted, loadRolesFailed, null);
}

function loadRolesCompleted(result, userContext, methodName) {
    if (Sys.Services.RoleService.isUserInRole("Full") || Sys.Services.RoleService.isUserInRole("Administrator")) {

        $('#comments-header').append("<p>You are currently signed in. <a href='/Account/Logout/'>Click to Log Out.</a></p>");
        enableCommenting();

        if (Sys.Services.RoleService.isUserInRole("Administrator")) {
            enableCommentModeration();
        }
    }
    else {
        // Show login message and links
        $('#comments-header').append("<p>Create a comment account or log in here: </p>");        
            
        var loginCommand = $("<span class='command'>[create account or login]</span>");
        loginCommand.bind('click', redirectToLogin);
        $('#comments-header').append(loginCommand);

        if (threadedComments)
            $(".comment-tools").append(loginCommand);
        
    }
}

function loadRolesFailed(error, userContext, methodName) {
    alert(error.get_message());
}


function enableCommenting() {

    if (threadedComments == true) {

        $('#comments-header').append("<p>You may reply directly to the above post by clicking the [Reply to Post] link below, or you may reply to a specific comment by using the [Reply] link below the individual comment.</p>");

        // Add the reply commands
        var replyCommand = $("<span class='command'>[Reply]</span>");
        replyCommand.bind('click', replyInline);
        $(".comment-tools").append(replyCommand);

        replyCommand.text("[Reply to Post]");
        $('#comments-header').append(replyCommand);
        
    }
    else {
        $("#cancelCommentButton").hide();    
    }
    
    // Add an abuse reporting command to all comments
    //var reportAbuseCommand = $("<span class='command'>[Report Abuse]</span>");
    //reportAbuseCommand.bind('click', showCommentAbuseForm);
    //$(".comment-tools").append(reportAbuseCommand);
    //$("#cancelAbuseReportButton").bind('click', cancelAbuseReport);

    // Wire the cancel buttons
    $("#cancelUsernameButton").bind('click', cancelUsername);    
    $("#cancelCommentButton").bind('click', cancelComment);
    
    
    // See if the user already has a username
    $.getJSON("/Account/GetCurrentUsername", function(result) {

        usernameValidated = (result.Username != '');

        if (!threadedComments)
            showReplyForm($('#comments-header'));
    });

    $("p.comment-policy-link a").attr("target", "_blank");

}

function enableCommentModeration() {

    $("#comment-container").addClass('moderate');

    var rejectCommand = $("<span class='command reject'>[Reject]</span>");
    $(".comment-tools").append(rejectCommand);
    
    var approveCommand = $("<span class='command approve'>[Approve]</span>");
    $(".comment-tools").append(approveCommand);
    
    $("span.command.reject").live('click', rejectComment);
    $("span.command.approve").live('click', approveComment);
}


// "Command" Functions
function redirectToLogin(event) {
    window.location = "/Account/Login?ReturnUrl=" + escape(location.href);
}


function replyInline(sender) {

    var container = $("<div'>");
    var parent = $(this).parent();
    container.insertAfter(parent);
    showReplyForm(container);   
}


function showReplyForm(container) {

    if (usernameValidated == true)
        showCommentForm(container);
    else {
        showUsernameForm(container);
    }
}


function rejectComment(event) {

    var rejectLink = $(this);
    var commentId = getParentCommentId($(this));
    var parentComment = $(this).parents("div.comment:first");

    $.post("/Comment/Reject", { commentUniqueId: commentId }, function(result) {

        rejectLink.hide();
        parentComment.removeClass('unreviewed').removeClass('approved').addClass('rejected');
    });
}


function approveComment(event) {

    var approveLink = $(this);
    var commentId = getParentCommentId($(this));
    var parentComment = $(this).parents("div.comment:first");

    $.post("/Comment/Approve", { commentUniqueId: commentId }, function(result) {

        approveLink.hide();
        parentComment.removeClass('unreviewed').removeClass('rejected').addClass('approved');

    });  
}




// COMMENT FUNCTIONS

function showCommentForm(container) {

    // Show the comment form
    var commentForm = $("#comment-form-container");
    commentForm.hide();

    var commentId = getParentCommentId(container);

    // Set the parent comment id in the form
    var parentCommentUniqueIdInput = $("#parentCommentUniqueId");
    if (commentId)
        parentCommentUniqueIdInput.val(commentId);
    else
        parentCommentUniqueIdInput.val('');

    container.append(commentForm);
    
    if (threadedComments)
        commentForm.show("slow");
    else
        commentForm.show();
}



function onCreateCommentBegin(sender) {

    return $("#comment-form").validate({
        rules: {
            title: {
                required: true
            },
            content: {
                required: true
            }
        },
        messages: {
            title: {
                required: '*'
            },
            content: {
                required: '*'
            }
        },
        errorClass: "input-validation-error"
    }).form();
}

function onCreateCommentComplete(sender) {

    var result = sender.get_response().get_object();

    if (result.success) {
        
        var commentForm = $("#comment-form-container");
        cancelComment();

		var commentNotice = premoderateComments ? "Comments are moderated during regular business hours and are posted as they are deemed as adhering to the <a href='/policy/Terms'>Terms</a>." : "Thank you for your comment. It may take a few minutes to appear.";
        showFormResultMessage(commentNotice, commentForm);
    }
    else {
        $("#comment-username-error").text(result.errorMessage);
    }
}

function cancelComment() {
    var commentForm = $("#comment-form-container");
    commentForm.hide("slow", clearCommentForm);
}

function clearCommentForm() {
    $("#comment-form")[0].reset();
}

function showCommentSuccess(container) {
    var successDiv = $("#comment-success");
    successDiv.insertAfter(container);
    successDiv.show("slow");
}



// USERNAME FUNCTIONS

function showUsernameForm(container) {

    // Show the username form
    var form = $("#comment-username-container");
    form.hide();

    container.append(form);
    form.show("slow");
}


function onAssignUsernameBegin(sender) {

    return $("#comment-username-form").validate({
        rules: {
            username: {
                required: true,
                minlength: 3
            }
        },
        messages: {
            username: {
                required: "Username is required",
                minlength: jQuery.format("Enter at least {0} characters")
            }
        },
        errorClass: "input-validation-error"
    }).form();
}

function onAssignUsernameComplete(sender, args) {

    var result = sender.get_response().get_object();
    usernameValidated = result.success;

    if (usernameValidated) {
        
        // Hide username form and show comment form
        var container = $("#comment-username-container").parent();
        cancelUsername();
        showCommentForm(container);
    }
    else {
        $("#comment-username-error").text(result.errorMessage);
    }
}

function cancelUsername() {
    var commentForm = $("#comment-username-container");
    commentForm.hide("slow", clearUsernameForm);
}

function clearUsernameForm() {
    $("#comment-username-form")[0].reset();
}




// ABUSE REPORTING FUNCTIONS
function showCommentAbuseForm(event) {

    var commentId = getParentCommentId($(this));

    $("#abuseCommentUniqueId").val(commentId);

    var abuseForm = $("#comment-abuse-form-container");
    abuseForm.hide();
    abuseForm.insertAfter($(this).parent());
    abuseForm.show("slow");
}

function onReportAbuseComplete(sender, args) {
    var result = sender.get_response().get_object();
    if (result.success) {
        var abuseForm = $("#comment-abuse-form-container");
        cancelAbuseReport();
        showFormResultMessage("Thank you for reporting potential abuse. It will be reviewed.", abuseForm);
    }
}

function cancelAbuseReport() {
    var abuseForm = $("#comment-abuse-form-container");
    abuseForm.hide("slow", clearAbuseForm);
}

function clearAbuseForm() {
    $("#comment-abuse-form")[0].reset();
}




// Helper Functions
function getParentCommentId(childObject) {

    // Get the comment's unique id
    var parentComment = childObject.parents("div.comment");

    var commentId = '';
    if (parentComment.length > 0) {
        commentId = parentComment.attr("id").substring(8); // 8 = length of "comment-" in id
    }

    return commentId;
}



function showFormResultMessage(message, location) {
    var messageContainer = $("#comment-form-message");
    messageContainer.html("<p>" + message + "</p>");
    messageContainer.insertAfter(location);
    messageContainer.show("slow");
}