﻿/* 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, newestTop, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.LoadComments(this.moduleId, this.itemId, parentId, pageS, pageN, newestTop, 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,rating, isAppr, onSuccess, onError) {
    CodingStaff.Modules.Comments.CommentsService.UpdateComment(this.moduleId, id, text, rating, 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, modId) {

    //config.collapsed = false;
    //alert(config.collapsed);
    
    var proxy = new CommentsServiceProxy(config.serviceUrl, config.moduleId, config.itemId);
    var fckId = 'fck_comments_editor'+modId;
    var currentPage = 1;
    if (pageN) currentPage = pageN;
    var oFCKeditor;
    //
    var onHidePostForm;

    var hidePostForm = function() {
        $("#comment_form_container"+modId).remove();
        if (onHidePostForm) onHidePostForm();
    };

    var updateCommentCount = function(id, count) {
        var childsCmd = $("#comment_childs_" + id + modId);
        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 (!config.collapsed) {
            //comment_commands_childs
            //$("#comment_childcomments_" + id).find(".comment_commands_childs").click();
            if (destId && (destId == id)) {
                window.location.hash = "comment_item_" + destId + modId;
                destId = undefined;                
            }
            return;
        }
        if (rootsI == 0 && destId) {
            window.location.hash = "comment_item_" + destId + modId;
            destId = undefined;
        }
        if (rootsI > 0) {
            var cmdChilds = $("#comment_childs_" + roots[rootsI--]+modId);
            cmdChilds.click();
        }
    };

    var renderComment = function(comment, containerId, parentId, insertAfrerId, level) {

        var html = "";
        var ratingBeforeEdit = -1;
        var id = comment.CommentId;
        var approved = comment.IsApproved;

        html += "<div id='comment_item_" + id + modId +"' level='" + level + "' commentId='" + id + "' collapsed='false' parentId='" + parentId + "' class='comment'><div class='comment_inner'>";
        if (config.ratingEnabled) {
            html += "<div class='comment_rating comment_rating_"+ id + modId +"'><div class='comment_rating_inner_"+ id + modId +"'>"
            //alert(comment.Rating);
            if (comment.Rating && parentId == -1) {
                var rating = comment.Rating;
                while (rating > 0) {
                    html += "<img src='" + config.ratingStarUrl + "'/>";
                    rating--;
                }
            }
            html += "</div></div>";
        }
        //html += renderRating(-1,id);
            $(".comment_rating_"+ id + modId).show();
        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 + modId +"'>";
        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 + modId+"'>" + 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 + modId +"'>";
        html += comment.Comment;
        html += "</div>";

        html += "<div class='comment_text_edit' id='comment_text_edit_" + id + modId +"'></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 + modId+"'>" + 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 + modId +"'>" + 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 + modId +"'>" + 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 + modId +"'>" + 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 + modId +"'>" + 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 + modId +"'>" + 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 + modId +"'>" + 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 + modId +"'>";
        html += "</div></div>";
        html += "<div class='cs_comments_post'><div class='cs_comments_inner' id='comment_replayform_" + id + modId +"'>";
        html += "</div></div>";

        html += "</div></div>";

        if (insertAfrerId) {
            $(html).insertAfter("#comment_item_" + insertAfrerId + modId);
        }
        else {
            $(html).prependTo("#" + containerId);
        }

        var commentBody = $("#comment_body_" + id + modId);
        var childsDiv = $("#comment_childcomments_" + id + modId);

        var cmdChilds = $("#comment_childs_" + id + modId);
        var cmdReplay = $("#comment_replay_" + id + modId);
        var cmdEdit = $("#comment_edit_" + id + modId);
        var cmdUpdate = $("#comment_update_" + id + modId);
        var cmdCancel = $("#comment_cancel_" + id + modId);
        var cmdApprove = $("#comment_approve_" + id + modId);
        var cmdDelete = $("#comment_delete_" + id + modId);

        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 || (config.deep && level >= config.deep)) cmdReplay.hide();
        if (comment.ChildCount == 0) cmdChilds.hide();

        cmdChilds.click(function() {
            childsDiv.toggle();
            childsVisible = !childsVisible;
            $("#comment_item_" + id + modId).attr("collapsed", childsVisible);
            if (childsVisible) loadComments(id, "comment_childcomments_" + id + modId, 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 + modId, id, "comment_childcomments_" + id + modId, function() { childsDiv.show(); childsVisible = true; updateChildsButton(); });
            $("#comment_text_field" + modId).focus();
        });

        cmdEdit.click(function() {
            cmdEdit.hide();
            cmdApprove.hide();
            cmdUpdate.show();
            cmdCancel.show();

            commentBody.hide();
            //hidePostForm();
            var text = $("#comment_text_" + id + modId).html();
            text = $("<p>" + text + "</p>").find("br").remove().end().html();
            $("#comment_text_" + id + modId).hide();
            $("#comment_text_edit_" + id + modId).html("<textarea id='comment_edit_" + id + modId +"' />");
            $("#comment_edit_" + id + modId).val(text);
            $("#comment_text_edit_" + id + modId).show();
            $("#comment_edit_" + id + modId).focus();
            var rating = $(".comment_rating_inner_"+ id + modId+" img").length;
            
            if (rating){
                if(ratingBeforeEdit == -1){
                    ratingBeforeEdit = rating;}
                $(".comment_rating_"+ id + modId).html(renderRating(-1,id));
                $(".comment_rating_"+ id + modId).show();
                $('input.star').rating() ;                
                $(".comment_rating_"+ id + modId +" input.star").rating('select',rating-1) ;
            }
            
            //renderEditor('comment_body_edit_' + id, function(editor) { editor.SetHTML(commentBody.html()); });
            onHidePostForm = function() { cmdCancel.click(); };
        });

        var setRating = function(rating){
                var _html= '';
                var _rating = rating;
                _html += "<div class='comment_rating_inner_"+ id + modId +"'>";
                while (_rating > 0) {
                    _html += "<img src='" + config.ratingStarUrl + "'/>";
                    _rating--;
                }
                _html += "</div></div>";
                
                $(".comment_rating_"+ id + modId).html(_html);        
        }
        

        cmdUpdate.click(function() {
            cmdEdit.show();
            if (!approved) cmdApprove.show();
            cmdUpdate.hide();
            cmdCancel.hide();
            var text = $("#comment_edit_" + id + modId).val();
            var rating = 1;
            if (comment.Rating){                    
            
                $(".comment_rating_"+ id + modId +" input.star").each(function(index){
                    if(this.checked)
                    rating = index+1;
                });
            setRating(rating);
            ratingBeforeEdit = rating;
                
            }
            
            proxy.updateComment(id, text,rating, approved, function() {
                proxy.getCommentById(id, function(comment) {
                    $("#comment_text_" + id + modId).html(comment.Comment);
                    $("#comment_text_" + id + modId).show();
                    $("#comment_text_edit_" + id + modId).hide();
                });
            }, function() { });
            //
            //commentBody.show();
            //$("#comment_body_edit_" + id).empty();
            //onHidePostForm = null;
        });

        cmdCancel.click(function() {
            cmdEdit.show();
            cmdUpdate.hide();
            cmdCancel.hide();
            if (comment.Rating){
                setRating(ratingBeforeEdit);
            }
            if (!approved) cmdApprove.show();

            $("#comment_text_edit_" + id + modId).hide();
            $("#comment_text_" + id + modId).show();

            //onHidePostForm = null;
        });

        cmdDelete.click(function() {
            proxy.deleteComment(id, function() {
                updateChildComments(parentId);
            }, function() { /*alert("faild!");*/ });

            //onHidePostForm = null;
        });

        if (!config.collapsed) {
            cmdChilds.click();
        }
    };

    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"));
            var pId = parseInt($(this).attr("parentId"));
            if (pId == parentId && !containsComment(comments, cId)) {
                $("#comment_item_" + cId + modId).remove();
            }
        });
        var level = $("#comment_item_" + parentId + modId).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 + modId);
            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, config.newestTop, function(comments) { updateComments(comments, containerId, parentId, onSuccess); });
        }
        else {
            proxy.getComments(parentId, null, 1, config.newestTop, function(comments) { updateComments(comments, containerId, parentId, onSuccess); });
        }
    };

    var updateChildComments = function(commentId, onSuccess) {
        if (commentId == -1) {
            loadComments(-1, "cs_comments_container" + modId, onSuccess);
        }
        else {
            loadComments(commentId, "comment_childcomments_" + commentId  + modId, onSuccess);
        }
    };

    var gotoLastPage = function(onSuccess) {
        if (config.pageSize) {
            proxy.getCommentsCount(-1, function(count) {
                var pageCount = Math.ceil(count / config.pageSize);
                ///if (currentPage != pageCount) {
                if (config.newestTop)
                    currentPage = 1;
                else
                    currentPage = pageCount;
                loadComments(-1, "cs_comments_container" + modId, onSuccess);
                //}
            });
        }
        else {
            loadComments(-1, "cs_comments_container" + modId, 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  + modId +  "' 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" + modId).hide();
        $("#comment_form_validator_user" + modId).hide();
        $("#comment_form_validator_email" + modId).hide();
        $("#comment_form_validator_captcha" + modId).hide();
        $("#comments_validator_global" + modId).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" + modId); //FCKeditorAPI.GetInstance(fckId).GetHTML(false);
        if (text.trim().length < 2 ) {
            $("#comments_validator_text" + modId).text(localStr.errorEmptyText);
            $("#comments_validator_text" + modId).show();
            isValid = false;
        }
        //validate Nick
        if (config.isAnonym) {
            var nick = getInputValue("#comment_form_user" + modId);
            if (nick == "") {
                isValid = false;
                $("#comment_form_validator_user" + modId).text(localStr.errorEmptyNick);
                $("#comment_form_validator_user" + modId).show();
            }
        }
        //validate Email
        if (config.isAnonym && config.showEmail) {
            var email = getInputValue("#comment_form_email" + modId);
            if (email == "") {
                isValid = false;
                $("#comment_form_validator_email" + modId).text(localStr.errorEmptyEmail);
                $("#comment_form_validator_email" + modId).show();
            }
            else if (!emailExpt.test(email)) {
                isValid = false;
                $("#comment_form_validator_email" + modId).text(localStr.errorInvalidEmailFormat);
                $("#comment_form_validator_email" + modId).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" + modId);
                proxy.testUniqueUserName(nick, function(res) {
                    if (!res) {
                        isValid = false;
                        $("#comment_form_validator_user" + modId).text(localStr.errorUserExists);
                        $("#comment_form_validator_user" + modId).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" + modId);
                if (captcha == "") {
                    isValid = false;
                    $("#comment_form_validator_captcha" + modId).text(localStr.errorEmptySecurityCode);
                    $("#comment_form_validator_captcha" + modId).show();
                }
                if (isValid) {
                    proxy.testCAPTCHA(captcha, function(res) {
                        if (res != 0) {
                            isValid = false;
                            $("#comment_form_validator_captcha" + modId).text(localStr.errorInvalidSecurityCode);
                            $("#comment_form_validator_captcha" + modId).show();
                            proxy.getCAPTCHA(function(captcha) { $("#captcha_img" + modId).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"+modId+"'><div class='comment_form_inner' id='comment_form"+modId+"'>";

        html += "<div class='comment_form_header'><div class='comment_form_header_inner' id='comment_form_header"+modId+"'><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"+modId+"'/>";
            //html += "<span>" + localStr.labeluserName + "</span>";
            html += "</div>";
            html += "<div><span class='validator' id='comment_form_validator_user"+modId+"'></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"+modId+"'/>";
                //html += "<span>" + localStr.labelEmail + "</span>";
                html += "</div>";
                html += "<div><span class='validator' id='comment_form_validator_email"+modId+"'></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"+modId+"'/>";
            //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"+modId+"'>";
        html += "<textarea class='input comment_text_field' id='comment_text_field"+modId+"'/>"
        html += "</div></div>";
        html += "<div><span class='validator' id='comments_validator_text"+modId+"'></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"+modId+"'><option>1</option><option>2</option><option selected='selected'>3</option><option>4</option><option>5</option></select>";
//            html += "</div></div>";
//        }
        if (config.ratingEnabled && parentId == -1) {
            html += renderRating(parentId,555);
        }

        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"+modId+"' />";
            html += "<input  class='input comment_form_captcha' type='text' defaultvalue='" + localStr.labelSecurityCode + "' id='comment_form_captcha"+modId+"'/>";
            //html += "<span>" + localStr.labelSecurityCode + "</span>";
            html += "<div class='validator_container'><span class='validator' id='comment_form_validator_captcha"+modId+"'></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"+modId+"' 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"+modId+"'></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"+modId+"'>" + 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"+modId+"'>" + localStr.lbCancel + "</a>"
        html += "</div></div>";

        html += "</div></div>";

        html += "</div></div>";

        $("#" + containerId).html(html);

        $("#comments_validator_text"+modId).hide();
        $("#comment_form_validator_user"+modId).hide();
        $("#comment_form_validator_email"+modId).hide();
        $("#comment_form_validator_captcha"+modId).hide();
        $("#comments_validator_global"+modId).hide();


        $("#comment_form"+modId).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"));
                        }
                    });
                }
            }
        );
        
        /*--------------------------------------------*/
        
        function setKeyDownEvent(field)
        {
            if(field){
                field.keydown(function(event) {
                    if (event.keyCode == '13') 
                    {
                        $("#comment_form_commands_post"+modId).click();
                        event.cancelBubble = true;
                        return false;
                    }
                });
            }
        }
        var formUser = $("#comment_form_user"+modId);
        var formEmail = $("#comment_form_email"+modId);
        var formSite = $("#comment_form_site"+modId);
        var formCapcha = $("#comment_form_captcha"+modId);
        
        setKeyDownEvent(formUser);
        setKeyDownEvent(formEmail);
        setKeyDownEvent(formSite);
        setKeyDownEvent(formCapcha);   
        
        /*-----------------------------------------------*/

        renderEditor("comments_postform_editor"+modId, function() { });

        if (config.CAPTCHA && config.isAnonym) {
            proxy.getCAPTCHA(function(captcha) { $("#captcha_img"+modId).attr("src", captcha) }, function() { /*alert("failed")*/ });
        }

        var cancelBtn = $("#comment_form_commands_cancel"+modId);
        var postBtn = $("#comment_form_commands_post"+modId);

        cancelBtn.click(function() {
            hidePostForm();
            renderPostForm("cs_comments_form_container" + modId, -1, "cs_comments_container"+modId);
            
        });

        postBtn.click(function() {
            validatePostForm(function() {
                var text = getInputValue("#comment_text_field"+modId);

                var captcha = "";
                if (config.CAPTCHA && config.isAnonym) {
                    captcha = getInputValue("#comment_form_captcha"+modId);
                }
                var nick = "";
                if (config.isAnonym) {
                    nick = getInputValue("#comment_form_user"+modId);
                }
                var email = "";
                if (config.isAnonym && config.showEmail) {
                    email = getInputValue("#comment_form_email"+modId);
                }
                var rating = 1;
                if (config.ratingEnabled && parentId == -1) {
                    $("#comment_form_inner"+modId+"555 input.star" ).each(function(index){
                        if(this.checked)
                        rating = index+1;
                    });
                }

                var site = "";
                if (config.showWebSite && config.isAnonym) {
                    site = getInputValue("#comment_form_site"+modId);
                }

                var reciveNotifications = false;
                if (config.subCommentsNotifications) {
                    reciveNotifications = $("#comment_form_reciveNotifications"+modId).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"+modId+"'>";
                            html += "<div class='cs_comments_message' id='okMessage"+modId+"'><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"+modId+"'>Ok</a></div></div>";
                            html += "</div>";
                            $("#comment_form"+modId).html(html);
                            $("#comments_postform_ok"+modId).click(function() {
                                $("#cs_comments_message_container"+modId).remove();
                                renderPostForm("cs_comments_form_container" + modId, -1, "cs_comments_container"+modId);
                            });
                        }
                        else {
                            hidePostForm();

                            if (parentId == -1) {
                                //alert("gotolastPage");
                                gotoLastPage(onSuccess);
                            }
                            else {
                                //alert(parentId);
                                loadComments(parentId, commentsContainerId, onSuccess);
                            }
                            renderPostForm("cs_comments_form_container"+modId, -1, "cs_comments_container"+modId);
                            //if (onSuccess) onSuccess();                            
                        }
                    }
                    else {
                        proxy.getCAPTCHA(function(captcha) { $("#captcha_img"+modId).attr("src", captcha); });
                        switch (status) {
                            case 5:
                                $("#comment_form_validator_user"+modId).text(localStr.errorUserExists);
                                $("#comment_form_validator_user"+modId).show();
                                break;
                            case 6:
                                $("#comment_form_validator_email"+modId).text(localStr.errorDuplicateEmail);
                                $("#comment_form_validator_email"+modId).show();
                                break;
                            case 8:
                                $("#comment_form_validator_email"+modId).text(localStr.errorInvalidEmailFormat);
                                $("#comment_form_validator_email"+modId).show();
                                break;
                            case 9:
                                $("#comment_form_validator_user"+modId).text(localStr.errorInvalidUserName);
                                $("#comment_form_validator_user"+modId).show();
                                break;
                            default:
                                $("#comments_validator_global"+modId).text(localStr.errorUnexpected);
                                $("#comments_validator_global"+modId).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("Failed!"); });

            });
        });
      $(function(){
            $('input.star').rating();
            }); 
    };

    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" + modId).html("");
            //alert(pageCount);
            if (pageCount > 1) {
                for (var i = 1; i <= pageCount; i++) {
                    if (currentPage == i) {
                        $("<span>" + i + "</span>").appendTo(".cs_comments_paging_inner"+ modId);
                    }
                    else {
                        $("<a class='cs_comments_pagelink' page='" + i + "' id='cs_comments_pagelink_" + i + modId +"'>" + i + "</a>").appendTo(".cs_comments_paging_inner"+ modId);
                        //alert($("#cs_comments_pagelink_" + i).size());                    
                        //alert(i);                        
                    }
                }
                $(".cs_comments_pagelink").click(function() {
                    currentPage = parseInt($(this).attr("page"));
                    loadComments(-1, "cs_comments_container"+modId);
                });
            }
        }, function() { /*alert('faild');*/ });
    };
    
    var renderRating = function(parentId,id) {
    var html = "";
    if (config.ratingEnabled && parentId == -1) {
            html += "<div class='comment_form_field'><div class='comment_form_inner' id='comment_form_inner"+modId+id+"'>";
            
            html += "<div class='rating_stars'>";
            html += "<div class='rating_label'><div class='rating_label_inner'><span class='rating_label'>" + localStr.labelRating + "</span></div></div>";
            html += "<input name='star"+modId+id+"' type='radio' value='1' class='star'  checked='checked' title='1'/>";
            html += "<input name='star"+modId+id+"' type='radio' value='2' class='star' title='2' />";
            html += "<input name='star"+modId+id+"' type='radio' value='3' class='star' title='3'/>";
            html += "<input name='star"+modId+id+"' type='radio' value='4' class='star' title='4'/>";
            html += "<input name='star"+modId+id+"' type='radio' value='5' class='star' title='5'/>";
            html += "</div></div></div>";
        }
        return html;
    }

    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"+modId+"' id='cs_comments_paging_container"+modId+"'>";
        html += "</div></div>";

        html += "<div class='cs_comments_container'><div class='cs_comments_container_inner' id='cs_comments_container"+modId+"'>";
        html += "</div></div>";

        html += "<div class='cs_comments_paging'><div class='cs_comments_paging_inner"+modId+"' id='cs_comments_paging_bottom_container"+modId+"'>";
        html += "</div></div>";

        html += "<div class='cs_comments_form_container'><div class='cs_comments_form_container_inner' id='cs_comments_form_container"+modId+"'>";
        html += "</div></div>";

        html += "</div></div>";


        $(html).appendTo("#" + placeHolderId);

        if (config.canView) {
            loadComments(-1, "cs_comments_container"+modId, function() {
                if (rootId && destId && config.collapsed) {
                    if (rootId == destId) {
                        window.location.hash = "comment_item_" + destId + modId;
                        destId = undefined;
                    }
                    else {

                        var expandRoots = function() {
                            rootsI--;
                            var cmdChilds = $("#comment_childs_" + roots[rootsI--] + modId);
                            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"+modId, -1, "cs_comments_container"+modId);
        }
        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"+modId);
        }
        else {
            $("<div class='cs_comments_message'><div class='cs_comments_message_inner'><span>" + localStr.messageNoAccess + "</span></div></div>").appendTo("#cs_comments_form_container"+modId);
        }

    };

    renderRootComments();
}
