﻿var commentToDelete;
var ajaxImage;
var commentsCount;

$(document).ready(function(){ ajaxImage = $("#ajaxImage"); commentsCount = $("span.commentsCount"); });
function updateCount(offset)
{
    var currentCount = parseInt(commentsCount.html());
    var newCount = currentCount + offset;
    commentsCount.html(newCount);
}
function toggleAjaxImage()
{
    ajaxImage.css("visibility", ajaxImage.css("visibility") == "hidden" ? "visible" : "hidden");
}
function deleteComment(commentID, item)
{    
    commentToDelete = item.parentNode;
    if (confirm("Are you sure you want to delete this comment?"))
    {
        toggleAjaxImage();
        PageMethods.DeleteComment(commentID, OnDelete, OnFailed);
    }
    return false;
}
function OnDelete() {
    commentToDelete.parentNode.removeChild(commentToDelete);
    toggleAjaxImage();
    updateCount(-1);
}

function saveComment(itemType, itemID, name, email, website, text, notify)
{
    if (Page_ClientValidate())
    {
        toggleAjaxImage();
        PageMethods.SaveComment(
            itemType,
            itemID,
            $("#" + name).val(),
            $("#" + email).val(),
            $("#" + website).val(),
            $("#" + text).val(),
            $("#" + notify).attr("checked"),
            OnSave,
            OnFailed
        );
    }
}
function OnSave(comment)
{
    var template = $(".newComment");
    var newComment = template.clone(true);
    newComment.attr({"class" : "", "id" : "comment_" + comment.ID});
    var authorNameSpan = newComment.find("span.commentAuthorName");
    if (comment.Link != null)
    {
        var commentAuthorLink = document.createElement("a");
        commentAuthorLink.className = "commentAuthorName";
        $(commentAuthorLink).attr({"target" : "_blank", "href" : comment.Link})
        .html(comment.AuthorName)
        .insertBefore(authorNameSpan[0]);
        authorNameSpan.remove();
    }
    else
        authorNameSpan.html(comment.AuthorName);
    
    newComment.find("span.commentTime").html(comment.HebTime);
    newComment.find("div.commentBody").html(comment.Text);
    var deleteBtn = newComment.find("a.commentDeleteLink");
    
    if(deleteBtn.length == 1)
    {
        deleteBtn.data("Comment", {commentID : comment.ID})
        .attr("onclick", "")
        .click(function(){ return deleteComment($(this).data("Comment").commentID, this); });
    }

    newComment.insertBefore(template[0]);
    $(".commentTextInput").val("");
    toggleAjaxImage();
    updateCount(1);
}
function OnFailed(error) {
   toggleAjaxImage();
   alert(error.get_message());
}