﻿/* Proxy Service */

CommentsServiceProxy.prototype.moduleId = undefined;
CommentsServiceProxy.prototype.itemId = undefined;
CommentsServiceProxy.prototype.serviceUrl = undefined;

function CommentsServiceProxy(serviceUrl, moduleId, itemId) {
    this.moduleId = moduleId;
    this.itemId = itemId;
    this.serviceUrl = serviceUrl;
}

CommentsServiceProxy.prototype.getCAPTCHA = function(onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.GetCAPTCHAImgUrl(onSuccess, onError);
};

CommentsServiceProxy.prototype.testCAPTCHA = function(captcha, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.TestCAPTCHA(captcha, onSuccess, onError);
};

CommentsServiceProxy.prototype.testUniqueUserName = function(nick, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.TestUniqueUserName(nick, onSuccess, onError);
};

CommentsServiceProxy.prototype.getComments = function(parentId, pageS, pageN, onSuccess, onError) {    
    CodingStaff.Modules.Comments.CommentsService.LoadComments(this.moduleId, this.itemId, parentId, pageS, pageN, onSuccess, onError);
};

CommentsServiceProxy.prototype.getCommentsCount = function(parentId, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.GetCommentCount(this.moduleId, this.itemId, parentId, onSuccess, onError);
};

CommentsServiceProxy.prototype.postComment = function(parentId, text, nick, email, site, capthca, rating, reciveNotifications, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.PostComment(parentId, this.moduleId, this.itemId, text, nick, email, site, capthca, rating, reciveNotifications, onSuccess, onError);
};

CommentsServiceProxy.prototype.deleteComment = function(id, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.DeleteComment(this.moduleId, id, onSuccess, onError);
};

CommentsServiceProxy.prototype.updateComment = function(id, text, isAppr, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.UpdateComment(this.moduleId, id, text, isAppr, onSuccess, onError);
};

CommentsServiceProxy.prototype.approveComment = function(id, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.ApproveComment(this.moduleId, id, onSuccess, onError);
};

CommentsServiceProxy.prototype.getCommentById = function(id, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.GetCommentById(this.moduleId, id, onSuccess, onError);
};
//


/* Main */

function runComments($, placeHolderId, config, localStr, pageN, rootId, destId) {

    var proxy = new CommentsServiceProxy(config.serviceUrl, config.moduleId, config.itemId);
    var fckId = 'fck_comments_editor';
    var currentPage = 1;
    if (pageN) currentPage = pageN;
    var oFCKeditor;
    //
    var onHidePostForm;

    var hidePostForm = function() {
        $("#comment_form_container").remove();
        if (onHidePostForm) onHidePostForm();
    };

    var updateCommentCount = function(id, count) {
        var childsCmd = $("#comment_childs_" + id);
        childsCmd.text(localStr.lbComments + "(" + count + ")");
        if (count > 0) {
            childsCmd.show();
        }
        else {
            childsCmd.hide();
        }
        //body.html(comment.Comment);
    };

    var rootsI = 0;
    var roots = new Array();


    var childsExpanded = function(id) {
        if (rootsI == 0 && destId) {
            window.location.hash = "comment_item_" + destId;
            destId = undefined;
        }
        if (rootsI > 0) {     
            var cmdChilds = $("#comment_childs_" + roots[rootsI--]);
            cmdChilds.click();
        }        
    };

    var renderComment = function(comment, containerId, parentId, insertAfrerId, level) {

        var html = "";

        var id = comment.CommentId;
        var approved = comment.IsApproved;

        html += "<div id='comment_item_" + id + "' level='" + level + "' commentId='" + id + "' class='comment'><div class='comment_inner'>";
        if (config.ratingEnabled) {
            html += "<div class='comment_rating'><div class='comment_rating_inner'>"
            //alert(comment.Rating);
            if (comment.Rating) {
                var rating = comment.Rating;
                while (rating > 0) {
                    html += "<img src='" + config.ratingStarUrl + "'/>";
                    rating--;
                }
            }
            html += "</div></div>";
        }
        html += "<div class='comment_main'><div class='comment_main_inner'>"

        html += "<div class='comment_header'><div class='comment_header_inner'>";

        if (config.gravatarEnabled) {
            html += "<div class='comment_avatar'><div  class='comment_avatar_inner'><img src='" + comment.ImgUrl + "' /></div></div>"; // avatar
        }
        html += "<div class='comment_user'><div class='comment_user_inner'><span id='comment_nick_" + id + "'>";
        if (config.linkName && comment.WebSite != "") {
            html += "<a ";
            if (!config.doFollow) {
                html += "rel='external nofollow' ";
            }
            html += "href='" + comment.WebSite + "'>";
        }
        html += comment.CreatedByName;
        if (config.linkName && comment.WebSite != "") {
            html += "</a>";
        }
        html += "</span></div></div>"; //nick
        html += "<div class='comment_date'><div class='comment_date_inner'><span id=comment_date_'" + id + "'>" + comment.CreatedOnStr + "</span></div></div>" //date
        html += "</div></div>";

        html += "<div class='comment_arrow'><img src='" + config.commentArrowImg + "' /></div>";

        html += "<div class='comment_body'><div class='comment_body_inner'>";
        html += "<div class='comment_text' id='comment_text_" + id + "'>";
        html += comment.Comment;
        html += "</div>";

        html += "<div class='comment_text_edit' id='comment_text_edit_" + id + "'></div>";

        html += "<div class='comment_commands'><div class='comment_commands_inner'>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_childs' id='comment_childs_" + id + "'>" + localStr.lbComments + "(" + comment.ChildCount + ")</a>"
        html += "</div></div>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_replay' id='comment_replay_" + id + "'>" + localStr.lbRelpay + "</a>"
        html += "</div></div>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_edit' id='comment_edit_" + id + "'>" + localStr.lbEdit + "</a>"
        html += "</div></div>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_update' id='comment_update_" + id + "'>" + localStr.lbUpdate + "</a>"
        html += "</div></div>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_cancel' id='comment_cancel_" + id + "'>" + localStr.lbCancel + "</a>"
        html += "</div></div>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_approve' id='comment_approve_" + id + "'>" + localStr.lbApprove + "</a>"
        html += "</div></div>";

        html += "<div class='comment_commands_item'><div class='comment_commands_item_inner'>";
        html += "<a class='link_command comment_commands_delete' id='comment_delete_" + id + "'>" + localStr.lbDelete + "</a>"
        html += "</div></div>";

        html += "</div></div>";

        html += "</div></div>";

        html += "</div></div>"; //main

        html += "<div class='cs_comments_childs'><div class='cs_comments_childs_inner' id='comment_childcomments_" + id + "'>";
        html += "</div></div>";
        html += "<div class='cs_comments_post'><div class='cs_comments_inner' id='comment_replayform_" + id + "'>";
        html += "</div></div>";

        html += "</div></div>";

        if (insertAfrerId) {
            $(html).insertAfter("#comment_item_" + insertAfrerId);
        }
        else {
            $(html).prependTo("#" + containerId);
        }

        var commentBody = $("#comment_body_" + id);
        var childsDiv = $("#comment_childcomments_" + id);

        var cmdChilds = $("#comment_childs_" + id);
        var cmdReplay = $("#comment_replay_" + id);
        var cmdEdit = $("#comment_edit_" + id);
        var cmdUpdate = $("#comment_update_" + id);
        var cmdCancel = $("#comment_cancel_" + id);
        var cmdApprove = $("#comment_approve_" + id);
        var cmdDelete = $("#comment_delete_" + id);

        cmdUpdate.hide();
        cmdCancel.hide();
        childsDiv.hide();
        var childsVisible = false;

        if (!config.canEdit) {
            cmdEdit.hide();
            cmdDelete.hide();

        }

        if (approved) {
            cmdApprove.hide();
        }

        if (!config.canPost || !config.subCommentsEnabled || level >= config.deep) cmdReplay.hide();
        if (comment.ChildCount == 0) cmdChilds.hide();

        cmdChilds.click(function() {
            childsDiv.toggle();
            childsVisible = !childsVisible;
            if (childsVisible) loadComments(id, "comment_childcomments_" + id, function() { childsExpanded(id); });

        });

        var updateChildsButton = function() {
            //alert("update childs");
            var childsCount = childsDiv.find(".cs_comments_item").size();
            if (childsCount > 0) {
                cmdChilds.text(localStr.lbComments + "(" + childsCount + ")");
                cmdChilds.show();
            }
        };

        cmdApprove.click(function() {
            var text = commentBody.html();
            approved = true;
            proxy.approveComment(id, function() { cmdApprove.hide(); }, function() { approved = false; });
        });

        cmdReplay.click(function() {
            hidePostForm();
            renderPostForm("comment_replayform_" + id, id, "comment_childcomments_" + id, function() { childsDiv.show(); childsVisible = true; updateChildsButton(); });
            $("#comment_text_field").focus();
        });

        cmdEdit.click(function() {
            cmdEdit.hide();
            cmdApprove.hide();
            cmdUpdate.show();
            cmdCancel.show();

            commentBody.hide();
            //hidePostForm();
            var text = $("#comment_text_" + id).html();
            text = $("<p>" + text + "</p>").find("br").remove().end().html();
            $("#comment_text_" + id).hide();
            $("#comment_text_edit_" + id).html("<textarea id='comment_edit_" + id + "' />");
            $("#comment_edit_" + id).val(text);
            $("#comment_text_edit_" + id).show();
            $("#comment_edit_" + id).focus();

            //renderEditor('comment_body_edit_' + id, function(editor) { editor.SetHTML(commentBody.html()); });
            onHidePostForm = function() { cmdCancel.click(); };
        });

        cmdUpdate.click(function() {
            cmdEdit.show();
            if (!approved) cmdApprove.show();
            cmdUpdate.hide();
            cmdCancel.hide();
            var text = $("#comment_edit_" + id).val();
            proxy.updateComment(id, text, approved, function() {
                proxy.getCommentById(id, function(comment) {
                    $("#comment_text_" + id).html(comment.Comment);
                    $("#comment_text_" + id).show();
                    $("#comment_text_edit_" + id).hide();
                });
            }, function() { });
            //
            //commentBody.show();
            //$("#comment_body_edit_" + id).empty();
            //onHidePostForm = null;
        });

        cmdCancel.click(function() {
            cmdEdit.show();
            cmdUpdate.hide();
            cmdCancel.hide();
            if (!approved) cmdApprove.show();

            $("#comment_text_edit_" + id).hide();
            $("#comment_text_" + id).show();

            //onHidePostForm = null;
        });

        cmdDelete.click(function() {
            proxy.deleteComment(id, function() {
                updateChildComments(parentId);
            }, function() { /*alert("faild!");*/ });

            //onHidePostForm = null;
        });
    };

    var containsComment = function(comments, id) {
        for (var i = 0; i < comments.length; i++) {
            if (comments[i].CommentId == id) return true;
        }
        return false;
    }

    var mergeComments = function(comments, containerId, parentId) {
        $("#" + containerId).find(".comment").each(function() {
            var cId = parseInt($(this).attr("commentId"));
            if (!containsComment(comments, cId)) {
                $("#comment_item_" + cId).remove();
            }

        });
        var level = $("#comment_item_" + parentId).attr("level");
        if (level == undefined) {
            level = 0;
        }
        else {
            level = parseInt(level);
        }

        var insertAfterId = undefined;
        $(comments).each(function() {
            var exists = $("#" + containerId).find("#comment_item_" + this.CommentId);
            if (exists.size() == 0) {
                renderComment(this, containerId, parentId, insertAfterId, level + 1);
            }
            insertAfterId = this.CommentId;
        });
    }

    var updateComments = function(comments, containerId, parentId, onSuccess) {

        if (parentId == -1) renderPaging();
        if (parentId != -1) {
            //proxy.getCommentById(parentId, function(comment) { updateComment(comment); });
            proxy.getCommentsCount(parentId, function(count) { updateCommentCount(parentId, count); });
        }
        mergeComments(comments, containerId, parentId);        
        if (onSuccess) onSuccess();
    };

    var loadComments = function(parentId, containerId, onSuccess) {
        //proxy.getComments(parentId, function(comments) { updateComments(comments, containerId, parentId, onSuccess); }, function() { alert('faild!'); });
        //alert(currentPage);
        if (parentId == -1) {
            proxy.getComments(parentId, config.pageSize, currentPage, function(comments) { updateComments(comments, containerId, parentId, onSuccess); });
        }
        else {
            proxy.getComments(parentId, null, 1, function(comments) { updateComments(comments, containerId, parentId, onSuccess); });
        }
    };

    var updateChildComments = function(commentId, onSuccess) {
        if (commentId == -1) {
            loadComments(-1, "cs_comments_container", onSuccess);
        }
        else {
            loadComments(commentId, "comment_childcomments_" + commentId, onSuccess);
        }
    };

    var gotoLastPage = function(onSuccess) {
        if (config.pageSize) {
            proxy.getCommentsCount(-1, function(count) {
                var pageCount = Math.ceil(count / config.pageSize);
                ///if (currentPage != pageCount) {
                currentPage = pageCount;
                loadComments(-1, "cs_comments_container", onSuccess);
                //}
            });
        }
        else {
            loadComments(-1, "cs_comments_container", onSuccess);
        }
    };

    var editorTxt;

    var renderEditor = function(containerId, onComplite) {
        /*
        FCKeditor_OnComplete = function(editor) { if (onComplite) onComplite(editor); };
        oFCKeditor = new FCKeditor(fckId);
        oFCKeditor.BasePath = config.fckEditorBase;
        oFCKeditor.Config["CustomConfigurationsPath"] = config.fckConfig;
        oFCKeditor.ToolbarSet = 'Basic';
        if (!config.linkingEnable) oFCKeditor.ToolbarSet = 'Basic2';*/

        $("<div><textarea style='width:100%; height:300px;'  id='" + fckId + "' value='test text'/></div>").appendTo("#" + containerId);
    };

    var getInputValue = function(obj) {
        if ($(obj).attr("defaultvalue")) {
            if ($(obj).val() == $(obj).attr("defaultvalue")) {
                return "";
            }
        }
        return $(obj).val();
    };

    var validatePostForm = function(onValid) {

        $("#comments_validator_text").hide();
        $("#comment_form_validator_user").hide();
        $("#comment_form_validator_email").hide();
        $("#comment_form_validator_captcha").hide();
        $("#comments_validator_global").hide();

        var isValid = true;
        var emailExpt = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        var text = getInputValue("#comment_text_field"); //FCKeditorAPI.GetInstance(fckId).GetHTML(false);
        if (text == "") {
            $("#comments_validator_text").text(localStr.errorEmptyText);
            $("#comments_validator_text").show();
            isValid = false;
        }
        //validate Nick
        if (config.isAnonym) {
            var nick = getInputValue("#comment_form_user");
            if (nick == "") {
                isValid = false;
                $("#comment_form_validator_user").text(localStr.errorEmptyNick);
                $("#comment_form_validator_user").show();
            }
        }
        //validate Email
        if (config.isAnonym && config.showEmail) {
            var email = getInputValue("#comment_form_email");
            if (email == "") {
                isValid = false;
                $("#comment_form_validator_email").text(localStr.errorEmptyEmail);
                $("#comment_form_validator_email").show();
            }
            else if (!emailExpt.test(email)) {
                isValid = false;
                $("#comment_form_validator_email").text(localStr.errorInvalidEmailFormat);
                $("#comment_form_validator_email").show();
            }
        }
        //proxy.testCAPTCHA("asd", function(xml) { alert($(xml).text()); }, function() { });
        //testUniqueUserName
        var validateUserName = function() {
            if (false /*config.isAnonym && config.autoRegister*/) {
                var nick = getInputValue("#comment_form_user");
                proxy.testUniqueUserName(nick, function(res) {
                    if (!res) {
                        isValid = false;
                        $("#comment_form_validator_user").text(localStr.errorUserExists);
                        $("#comment_form_validator_user").show();
                    }
                    if (isValid && onValid) {
                        onValid();
                    }
                }, function() { });
            }
            else {
                if (isValid && onValid) {
                    onValid();
                }
            }
        };

        var validateCaptcha = function() {
            if (config.CAPTCHA && config.isAnonym) {
                var captcha = getInputValue("#comment_form_captcha");
                if (captcha == "") {
                    isValid = false;
                    $("#comment_form_validator_captcha").text(localStr.errorEmptySecurityCode);
                    $("#comment_form_validator_captcha").show();
                }
                if (isValid) {
                    proxy.testCAPTCHA(captcha, function(res) {
                        if (res != 0) {
                            isValid = false;
                            $("#comment_form_validator_captcha").text(localStr.errorInvalidSecurityCode);
                            $("#comment_form_validator_captcha").show();
                            proxy.getCAPTCHA(function(captcha) { $("#captcha_img").attr("src", captcha) });
                        }
                        validateUserName();
                    }, function() { });
                }
            }
            else {
                validateUserName();
            }
        };

        validateCaptcha();
    };

    var renderPostForm = function(containerId, parentId, commentsContainerId, onSuccess) {
        var html = "";

        //var fckId = 'fck_asd_id';
        //var oFCKeditor = new FCKeditor(fckId);

        //oFCKeditor.BasePath = config.fckEditorBase;
        //oFCKeditor.ToolbarSet = 'Basic';

        html += "<div class='comment_form' id='comment_form_container'><div class='comment_form_inner' id='comment_form'>";

        html += "<div class='comment_form_header'><div class='comment_form_header_inner' id='comment_form_header'><h3>";
        html += localStr.messageAddYour;
        html += "</h3></div></div>"

        if (config.isAnonym) {
            html += "<div class='comment_form_field'><div class='comment_form_inner'>";
            html += "<div class='input_container'>";
            html += "<input class='input comment_form_user' type='text' MAXLENGTH='100' defaultvalue='" + localStr.labeluserName + "' id='comment_form_user'/>";
            //html += "<span>" + localStr.labeluserName + "</span>";
            html += "</div>";
            html += "<div><span class='validator' id='comment_form_validator_user'></span></div>"
            html += "</div></div>";

            if (config.showEmail) {
                html += "<div class='comment_form_field'><div class='comment_form_inner'>";
                html += "<div class='input_container'>"
                html += "<input class='input comment_form_email' type='text' defaultvalue='" + localStr.labelEmail + "' id='comment_form_email'/>";
                //html += "<span>" + localStr.labelEmail + "</span>";
                html += "</div>";
                html += "<div><span class='validator' id='comment_form_validator_email'></span></div>"
                html += "</div></div>";
            }
        }

        if (config.showWebSite && config.isAnonym) {
            html += "<div class='input_container comment_form_field'><div class='comment_form_inner'>";
            html += "<input class='input comment_form_site' type='text' defaultvalue='" + localStr.labelSite + "' id='comment_form_site'/>";
            //html += "<span>" + localStr.labelSite + "</span>";
            html += "</div></div>";
        }

        html += "<div class='input_container comment_form_text'><div class='comment_form_text_inner' id='comment_form_text'>";
        html += "<textarea class='input comment_text_field' id='comment_text_field'/>"
        html += "</div></div>";
        html += "<div><span class='validator' id='comments_validator_text'></span></div>"

        if (config.ratingEnabled && parentId == -1) {
            html += "<div class='comment_form_field'><div class='comment_form_inner'>";
            html += "<div class='rating_label'><div class='rating_label_inner'><span class='rating_label'>" + localStr.labelRating + "</span></div></div>";
            html += "<select class='input comment_form_rating' id='comment_form_rating'><option>1</option><option>2</option><option selected='selected'>3</option><option>4</option><option>5</option></select>";
            html += "</div></div>";
        }

        if (config.CAPTCHA && config.isAnonym) {
            html += "<div class='comment_form_field comment_form_captcha_container'><div class='comment_form_inner'>";
            html += "<img id='captcha_img' />";
            html += "<input  class='input comment_form_captcha' type='text' defaultvalue='" + localStr.labelSecurityCode + "' id='comment_form_captcha'/>";
            //html += "<span>" + localStr.labelSecurityCode + "</span>";
            html += "<div class='validator_container'><span class='validator' id='comment_form_validator_captcha'></span></div>"
            html += "</div></div>";
        }

        if (config.subCommentsNotifications) {
            html += "<div class='comment_form_field'><div class='comment_form_inner comment_form_reciveNotifications'>";
            html += "<input id='comment_form_reciveNotifications' type='checkbox' />";
            html += "<span>" + localStr.messageNotifyByEmail + "</span>";
            html += "</div></div>";
        }

        html += "<div class='cs_comments_postform_field'><div class='cs_comments_postform_field_inner'>";
        html += "<div><span class='validator' id='comments_validator_global'></span></div>"
        html += "</div></div>";

        html += "<div class='comment_form_commands'><div class='comment_form_commands_inner'>";

        html += "<div class='comment_form_commands_item'><div class='comment_form_commands_item_inner'>"
        html += "<a class='comment_form_commands_post' id='comment_form_commands_post'>" + localStr.lbPost + "</a>"
        html += "</div></div>";

        html += "<div class='comment_form_commands_item comment_form_commands_cancel'><div class='comment_form_commands_inner'>"
        html += "<a class='' id='comment_form_commands_cancel'>" + localStr.lbCancel + "</a>"
        html += "</div></div>";

        html += "</div></div>";

        html += "</div></div>";

        $("#" + containerId).html(html);

        $("#comments_validator_text").hide();
        $("#comment_form_validator_user").hide();
        $("#comment_form_validator_email").hide();
        $("#comment_form_validator_captcha").hide();
        $("#comments_validator_global").hide();


        $("#comment_form").find(".input").each(
            function() {
                if ($(this).attr("defaultvalue") && $(this).attr("defaultvalue") != '') {
                    $(this).val($(this).attr("defaultvalue"));
                    $(this).focus(function() {
                        if ($(this).val() == $(this).attr("defaultvalue")) {
                            $(this).val("");
                        }
                    });
                    $(this).blur(function() {
                        if ($(this).attr("defaultvalue") && $(this).attr("defaultvalue") != '' && $(this).val() == '') {
                            $(this).val($(this).attr("defaultvalue"));
                        }
                    });
                }
            }
        );

        renderEditor("comments_postform_editor", function() { });

        if (config.CAPTCHA && config.isAnonym) {
            proxy.getCAPTCHA(function(captcha) { $("#captcha_img").attr("src", captcha) }, function() { alert("faild") });
        }

        var cancelBtn = $("#comment_form_commands_cancel");
        var postBtn = $("#comment_form_commands_post");

        cancelBtn.click(function() {
            hidePostForm();
            renderPostForm("cs_comments_form_container", -1, "cs_comments_container");
        });

        postBtn.click(function() {
            validatePostForm(function() {
                var text = getInputValue("#comment_text_field");

                var captcha = "";
                if (config.CAPTCHA && config.isAnonym) {
                    captcha = getInputValue("#comment_form_captcha");
                }
                var nick = "";
                if (config.isAnonym) {
                    nick = getInputValue("#comment_form_user");
                }
                var email = "";
                if (config.isAnonym && config.showEmail) {
                    email = getInputValue("#comment_form_email");
                }
                var rating = 0;
                if (config.ratingEnabled && parentId == -1) {
                    rating = getInputValue("#comment_form_rating");
                }

                var site = "";
                if (config.showWebSite && config.isAnonym) {
                    site = getInputValue("#comment_form_site");
                }

                var reciveNotifications = false;
                if (config.subCommentsNotifications) {
                    reciveNotifications = $("#comment_form_reciveNotifications").attr('checked');
                }

                var posted = function(status) {
                    if (status == 0) {
                        if (config.approvalRequired) {

                            var html = "";
                            html += "<div class='cs_comments_message_container' id='cs_comments_message_container'>";
                            html += "<div class='cs_comments_message' id='okMessage'><div class='cs_comments_message_inner'><span>";
                            html += "Comment send for approval";
                            html += "</span></div></div>";
                            html += "<div class='comment_form_commands_item'><div><a id='comments_postform_ok'>Ok</a></div></div>";
                            html += "</div>";
                            $("#comment_form").html(html);
                            $("#comments_postform_ok").click(function() {
                                $("#cs_comments_message_container").remove();
                                renderPostForm("cs_comments_form_container", -1, "cs_comments_container");
                            });
                        }
                        else {
                            hidePostForm();

                            if (parentId == -1) {
                                //alert("gotolastPage");
                                gotoLastPage(onSuccess);
                            }
                            else {
                                //alert(parentId);
                                loadComments(parentId, commentsContainerId, onSuccess);
                            }
                            renderPostForm("cs_comments_form_container", -1, "cs_comments_container");
                            //if (onSuccess) onSuccess();                            
                        }
                    }
                    else {
                        proxy.getCAPTCHA(function(captcha) { $("#captcha_img").attr("src", captcha); });
                        switch (status) {
                            case 5:
                                $("#comment_form_validator_user").text(localStr.errorUserExists);
                                $("#comment_form_validator_user").show();
                                break;
                            case 6:
                                $("#comment_form_validator_email").text(localStr.errorDuplicateEmail);
                                $("#comment_form_validator_email").show();
                                break;
                            case 8:
                                $("#comment_form_validator_email").text(localStr.errorInvalidEmailFormat);
                                $("#comment_form_validator_email").show();
                                break;
                            case 9:
                                $("#comment_form_validator_user").text(localStr.errorInvalidUserName);
                                $("#comment_form_validator_user").show();
                                break;
                            default:
                                $("#comments_validator_global").text(localStr.errorUnexpected);
                                $("#comments_validator_global").show();
                                break;
                        }
                    }
                };
                //alert(parentId + "\n" + text + "\n" + captcha + "\n" + nick + "\n" + email + "\n" + rating + "\n" + site);
                proxy.postComment(parentId, text, nick, email, site, captcha, rating, reciveNotifications, function(res) {
                    posted(res);
                }, function() { posted("Faild!"); });

            });
        });
    };

    var renderPaging = function() {
        if (config.pageSize == null) return;

        proxy.getCommentsCount(-1, function(count) {
            //alert(count);            
            var pageCount = Math.ceil(count / config.pageSize);
            $(".cs_comments_paging_inner").html("");
            //alert(pageCount);
            if (pageCount > 1) {
                for (var i = 1; i <= pageCount; i++) {
                    if (currentPage == i) {
                        $("<span>" + i + "</span>").appendTo(".cs_comments_paging_inner");
                    }
                    else {
                        $("<a class='cs_comments_pagelink' page='" + i + "' id='cs_comments_pagelink_" + i + "'>" + i + "</a>").appendTo(".cs_comments_paging_inner");
                        //alert($("#cs_comments_pagelink_" + i).size());                    
                        //alert(i);                        
                    }
                }
                $(".cs_comments_pagelink").click(function() {
                    currentPage = parseInt($(this).attr("page"));
                    loadComments(-1, "cs_comments_container");
                });
            }
        }, function() { alert('faild'); });
    };

    var renderRootComments = function() {
        var html = "";
        html += "<div class='cs_comments'><div class='cs_comments_inner'>";

        html += "<div class='cs_comments_paging'><div class='cs_comments_paging_inner' id='cs_comments_paging_container'>";
        html += "</div></div>";

        html += "<div class='cs_comments_container'><div class='cs_comments_container_inner' id='cs_comments_container'>";
        html += "</div></div>";

        html += "<div class='cs_comments_paging'><div class='cs_comments_paging_inner' id='cs_comments_paging_bottom_container'>";
        html += "</div></div>";

        html += "<div class='cs_comments_form_container'><div class='cs_comments_form_container_inner' id='cs_comments_form_container'>";
        html += "</div></div>";

        html += "</div></div>";


        $(html).appendTo("#" + placeHolderId);

        if (config.canView) {
            loadComments(-1, "cs_comments_container", function() {
                if (rootId && destId) {
                    if (rootId == destId) {
                        window.location.hash = "comment_item_" + destId;
                        destId = undefined;
                    }
                    else {

                        var expandRoots = function() {
                            rootsI--;
                            var cmdChilds = $("#comment_childs_" + roots[rootsI--]);
                            cmdChilds.click();
                        }
                        var getForRoot = function(id) {
                            roots[rootsI++] = id;
                            proxy.getCommentById(id, function(com) {
                                if (com.ParentCommentId && com.ParentCommentId != -1) {
                                    getForRoot(com.ParentCommentId);
                                }
                                else expandRoots();
                            });
                        }
                        getForRoot(destId);
                    }
                }
            });
        }


        if (config.canPost) {
            renderPostForm("cs_comments_form_container", -1, "cs_comments_container");
        }
        else if (config.isAnonym) {
            $("<div class='cs_comments_message'><div class='cs_comments_message_inner'><span>" + localStr.messageRegisterOrLogin + "</span></div></div>").appendTo("#cs_comments_form_container");
        }
        else {
            $("<div class='cs_comments_message'><div class='cs_comments_message_inner'><span>" + localStr.messageNoAccess + "</span></div></div>").appendTo("#cs_comments_form_container");
        }

    };

    renderRootComments();
}