﻿_commentTreeView = new function () {
    var _this = this;
    this.init = function (onSubmitCommentFunction) {
        $("#frmCommentEditor").submit(function () { onSubmitCommentFunction(); return false; });
        _this._initValidation();
    }

    this.contentID = function (value) {
        if (typeof value != "undefined") {
            $("#hdnContentID").val(value);
        }
        return $("#hdnContentID").val();
    }

    this.guestNickName = function (value) {
        if (typeof value != "undefined") {
            $("#txtGuestNickName").val(value);
        }
        return $("#txtGuestNickName").val();
    }

    this.guestWebSite = function (value) {
        if (typeof value != "undefined") {
            $("#txtGuestWebSite").val(value);
        }
        return $("#txtGuestWebSite").val();
    }

    this.guestEmail = function (value) {
        if (typeof value != "undefined") {
            $("#txtGuestEMail").val(value);
        }
        return $("#txtGuestEMail").val();
    }

    this.commentBody = function (value) {
        if (typeof value != "undefined") {
            $("#txtCommentBody").val(value);
        }
        return $("#txtCommentBody").val();
    }

    this.captchaField = function (value) {
        if (typeof value != "undefined") {
            $("#recaptcha_response_field").val(value);
        }
        return $("#recaptcha_response_field").val();
    }

    this.addCommentHtml = function (value) {
        $("#pnlComments").append(value);
    }

    this.isGuest = function () {
        return $(".NoAccount").length > 0;
    }

    this.incrementCommentsCount = function () {
        $("#countComment").html(parseInt($("#countComment").text()) + 1);
    }

    this.reloadCaptcha = function () {
        Recaptcha.reload();
    }

    this.cleanUpEditor = function () {
        _this.guestEmail("");
        _this.guestNickName("");
        _this.guestWebSite("");
        _this.commentBody("");
        _this.captchaField("");
        $("#frmCommentEditor").validate().resetForm();
        _this.reloadCaptcha();
    }

    this._initValidation = function () {
        if (_this.isGuest()) {
            $("#frmCommentEditor").validate({
                rules: {
                    "GuestNickName": "required",
                    "GuestEMail": { required: true, email: true },
                    "GuestWebSite": "url",
                    "CommentBody": "required"
                },
                messages: {
                    "GuestNickName": { required: "Please enter your NickName" },
                    "GuestEMail": { required: "Please enter your Email", email: "Please enter correct email" },
                    "CommentBody": { required: "Please enter your Comment" }
                },
                errorElement: "div",
                success: "valid"
                
            });
        }
        else {
            $("#frmCommentEditor").validate({
                rules: {
                    "CommentBody": "required"
                },
                messages: {
                    "CommentBody": { required: "Please enter your Comment" }
                },
                errorElement: "div",
                success: "valid"
            });
        }
    }

    this.areCommentSubmitFieldsValid = function () {
        return $("#frmCommentEditor").valid();
    }

    this.showWarning = function (infoMessage) {
        $("#pnlCommentInfo").html(infoMessage);
        $("#pnlCommentInfo").show();
    }

    this.hideWarning = function () {
        $("#pnlCommentInfo").html("");
        $("#pnlCommentInfo").hide();
    }

    this.setZebraStyle = function () {
        $("div.commentBox").css({ "border-bottom": "none" }); //efefec
        $("div.commentBox:odd").css({ "background": "#f6f6f2" }); //efefec
        $("div.commentBox:last").css({ "border-bottom": "1px solid #dfdfdf" });
        $("div.commentBox:odd").css({ "background": "#f3f3f3" });
        $("div.commentBox:last").css({ "background": "#e6e5e5" });
        /*$("div.commentBox:last").addClass("proba_1");*/
        _this.hideWarning();
    }
}
/**
* Delete/Edit Comments
* starts  
**/
var _editComment = new function editComment() {
    var _this = this
    function saveErrorHandler(data, text, curId) {
        if (data != "") {
            var dynamicElem = $("<div class='commentRspsMsgEdit'></div>");
            dynamicElem.text("Failed ! Or you don't have permission to do that");
            if ($(".commentRspsMsgBan, .commentRspsMsgEdit") != 0) {
                $('.commentRspsMsgBan, .commentRspsMsgEdit').remove();
            }
            $("#" + curId).append(dynamicElem);
            $("#" + curId + " .commentBody").html($("#" + curId + " .commentBody").data("comment"));
        }
    }
    function banErrorHandler(data, text, curId) {
        if (data != "") {
            var dynamicElem = $("<div class='commentRspsMsgBan'></div>");
            dynamicElem.text("It's long story to explain why so, F5 will helps you");
            if ($(".commentRspsMsgBan, .commentRspsMsgEdit") != 0) {
                $('.commentRspsMsgBan, .commentRspsMsgEdit').remove();
            }
            $("#" + curId).append(dynamicElem);
        } else {
            $("#" + curId + " .edit-comnt-2").html("<div align='center'>Removed</div>");
            $("#" + curId + " .commentDetWrapp div, #" + curId + " .commentBody, #" + curId + " .commentDetWrapp span").css({ "color": "#ccc" });
        }
    }
    this.createEditArea = function(target) {

        var currId = _this.getCurrentId(target);
        var strComment = $("#" + currId + " .commentBody").text();
        var saveDeleteButtons = "<div align='right'><a style='cursor:pointer' id='cnlEdit'><img src='/Images/cancel-button.gif' class='ctrlitem' border='0' /></a><a style='cursor:pointer' id='svdEdit'> <img src='/Images/update-blue-notrnsp.gif' class='ctrlitem' border='0'></a></div>"
        var txtArea = $("<textarea class='commentEditArea'></textarea>");

        $(".editLink").unbind("click.startEdit");           //unbind "comment editing" then start inline editting mode
        $(".frst-cmnt-a").unbind("click.stratBan");         //unbind "ban function" then start inline editting mode
        $("#" + currId + " .commentBody").data("comment", $.trim(strComment));

        if (!$("#" + currId + " .commentBody").is(":has('textarea')")) {
            $("#" + currId + " .commentBody").html(txtArea.val($.trim(strComment)));
            $(".commentBody textarea").focus();
            $("#" + currId + " .commentBody").append(saveDeleteButtons);
            $("#cnlEdit").click(function() {                            //bring unbinded back
                $("#" + currId + " .commentBody").html($("#" + currId + " .commentBody").data("comment"));
                $(".editLink").bind("click.startEdit", function() {
                    _editComment.createEditArea($(this))
                });
                $(".frst-cmnt-a").bind("click.stratBan", function() {
                    _editComment.banComment($(this));
                });
            });
            $("#svdEdit").click(function() {                            //bring unbinded back
                _this.saveEdit($(this));
                $(".editLink").bind("click.startEdit", function() {
                    _editComment.createEditArea($(this))
                });
                $(".frst-cmnt-a").bind("click.stratBan", function() {
                    _editComment.banComment($(this));
                });
            })
        }
    }

    this.saveEdit = function(target) {
        var curId = _this.getCurrentId(target);
        var cmntText = $("#" + curId + " .commentBody textarea").val();
        var parcel = { 'commentID': curId, 'commentText': cmntText };
        $("#" + curId + " .ajaxLoaderComment").ajaxStart(function() { $(this).show(); });
        $("#" + curId + " .ajaxLoaderComment").ajaxStop(function() { $(this).hide(); });
        $.ajax({
            url: "/Comment/EditComment",
            type: "POST",
            data: parcel,
            success: function(data, text) {
                saveErrorHandler(data, text, curId);
            },
            error: function() { }
        });
        $("#" + curId + " .commentBody").html(cmntText);
        $(".editLink").bind("click.startEdit", function() {
            _editComment.createEditArea($(this))
        });

    }
    this.banComment = function(target) {
        var curId = _this.getCurrentId(target);
        var banParcel = { 'commentID': curId };
        $("#" + curId + " .ajaxLoaderComment").ajaxStart(function() { $(this).show(); });
        $("#" + curId + " .ajaxLoaderComment").ajaxStop(function() { $(this).hide(); });
        $.ajax({
            url: "/Comment/BanComment",
            type: "POST",
            data: banParcel,
            success: function(data, text) {
                banErrorHandler(data, text, curId);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    this.getCurrentId = function(target) {
        return target.parents().filter(".commentBox").attr("id");
    }

    this.bindEventHandlers = function() {
        $(".editLink").bind("click.startEdit", function() {
            _editComment.createEditArea($(this))
        });
        $(".frst-cmnt-a").bind("click.stratBan", function() {
            _editComment.banComment($(this));
        });
    }

}

/**
* Initialize comments
*
**/
$(document).ready(function() {
    _commentTreeView.init(onSubmitComment);
    _commentTreeView.setZebraStyle();
    _editComment.bindEventHandlers();
});

function onSubmitComment() {    
    if (Recaptcha.get_response() == "") {
        _commentTreeView.showWarning("Please enter the captcha field");
        return;
    }

    if (_commentTreeView.areCommentSubmitFieldsValid()) {
        var returnValue = $.ajax({
            async: false,
            dataType: 'json',
            url: "/Content/IsCaptchaValid",
            data: { 'challengeValue': Recaptcha.get_challenge(), 'responseValue': Recaptcha.get_response() }
        });

        if (returnValue.responseText != "true") {
            Recaptcha.reload();
            _commentTreeView.showWarning("Not valid captcha entry, please try again");
        }
        else {
            $.ajax({
              type: 'POST',
              url: "/Comment/SubmitComment",
              data: { 'contentID': _commentTreeView.contentID(),
                    'guestEmail': _commentTreeView.guestEmail(),
                    'guestWebSite': _commentTreeView.guestWebSite(),
                    'guestNickName': _commentTreeView.guestNickName(),
                    'commentBody': _commentTreeView.commentBody()
                },
              success: addCommentHtml,
              error: addCommentError
            });
        }
    }
}

function addCommentError(commentError) {   
    _commentTreeView.showWarning("Unable to submit comment. Probably you are trying to enter html markup? ;)");
    _commentTreeView.reloadCaptcha();
}

function addCommentHtml(commentHtml, status, request) {    
    _commentTreeView.addCommentHtml(commentHtml);
    _commentTreeView.incrementCommentsCount();
    _commentTreeView.cleanUpEditor();
    _commentTreeView.setZebraStyle();
    _editComment.bindEventHandlers();
}


