var _commentService;


function setCommentService(service) {
    _commentService = service;
}

function deleteComment(elementId, commentableId) {
    var a = elementId.split("_");
    var commentId = $A(a)[1];
    _commentService.deleteComment(commentId, commentableId, {
        callback:_updateCommentsView,
        errorHandler:_handleError
    });
}

function addComment(commentableId) {
    var commentText = dwr.util.getValue("commentFormText");
    _commentService.addComment(commentText, commentableId, {
        callback:_updateCommentsView,
        errorHandler:_handleError
    });
    $('commentForm').reset();
    $('commentFormText').onfocus = function() {
        $('commentFormText').value = "";
        $('commentFormText').onfocus = function() {
            null;
        };
    }
}

function loadComments(commentableId) {
    _commentService.loadAllComments(commentableId, {
        callback:_updateCommentsView,
        errorHandler:_handleError
    });
}

function _updateCommentsView(comments) {
    _clearComments();
    var comment, id;
    for (var i=0; i< comments.length; i++) {
        comment = comments[i];
        id = comment.id;
        dwr.util.cloneNode("template", {
            idSuffix:comment.id
            });
        dwr.util.setValue("commentAuthor" + id, comment.authorName);
        dwr.util.setValue("commentDate" + id, comment.createDate);
        dwr.util.setValue("commentText" + id, comment.text);
        a = $("commentAuthorLink" + id);
        a.href = a.href + comment.authorId;
        a.style.backgroundImage = comment.avatarStyle;
        if (true == comment.deletable) {
            dwr.util.byId("commentDelete_" + id).style.display = "inline";
        }
        dwr.util.byId("template" + id).style.display = "block";
    }
}

function _clearComments() {
    $$("#comments > div").each(function(el){
        if (el.id != "template") {
            $(el).remove()
        }
    })
}

function _handleError(msg) {
    alert("Oops: " + msg);
}
