var commentPage = 1;

function GetCommentList(table, articleIndex, page, moveTop)
{
    // $("#commentList").html("<center><span class=\"text-bold\">댓글 로딩 중이래요....</span></center>");
    $("#commentList").css("cursor", "wait");

    $.ajax(
    {
      url: "CommentList.jsp?table=" + table + "&articleIndex=" + articleIndex + "&page=" + page,
      cache: false,
      success: function(html)
      {
        $("#commentList").html(html);
        commentPage = page;
        $("#commentList").css("cursor", "auto");

        if(moveTop == true)
        {
            document.location.href = "#comments";
        }
      },
      error: function()
      {
        $("#commentList").html(
            "<br /><span class=\"text-highlight align-center\">댓글 목록 로드 중 오류가 발생하였습니다.<br />" +
            "사용자가 로딩을 취소하지 않았다면, 페이지를 새로고침하여 다시 로드하시기 바랍니다.<br /><br /></span>\n");
        $("#commentList").css("cursor", "auto");
      }
    });
}

function RefreshCommentList(table, articleIndex, commentMasterIndex)
{
    $("#commentList").css("cursor", "wait");

    $.ajax(
    {
      url: "CommentList.jsp?table=" + table + "&articleIndex=" + articleIndex + "&page=" + commentPage,
      cache: false,
      success: function(html)
      {
        $("#commentList").html(html);

        UnfoldSubCommentList(table, articleIndex, commentMasterIndex, false, false);
        $("#commentList").css("cursor", "auto");
      },
      error: function()
      {
        $("#commentList").html(
            "<center><span class=\"text-highlight text-bold\">댓글 목록 로드 중 오류가 발생하였습니다.<br />페이지를 새로고침 해 주세요.<br />\n" +
            "</span></center>");

        $("#commentList").css("cursor", "auto");
      }
    });
}

var unfoldedContent = new Array();

function UnfoldSubCommentList(table, articleIndex, commentIndex, unfoldWriteForm, unfoldModifyForm)
{
    $("#commentList").css("cursor", "wait");

    unfoldedContent[commentIndex] = $("#commentItem_" + commentIndex).html();
    $("#commentItem_fold_" + commentIndex).html("<div class=\"text-bold\"><img src=\"" + siteConfig['staticStyleURL'] + "/" + bbsConfig['skinName'] + "/reply_loading.gif\" style=\"vertical-align:middle; padding-bottom:2px;\" /> " +
                                                "댓글 펼치는 중이래요..</div>");

    $.ajax(
    {
        url: "CommentList_Subtree.jsp?table=" + table + "&articleIndex=" + articleIndex + "&commentIndex=" + commentIndex,
        cache: false,
        success: function(html)
        {
            $("#commentItem_" + commentIndex).html(html);

            if(unfoldWriteForm == true)
            {
                setTimeout(function()
                {
                    InitTinyMCEForm("tinymce-comment-" + commentIndex);
                    tinyMCE.execCommand('mceFocus', true, "comment-body-" + commentIndex);
                }, 0);

                $("#comment_" + commentIndex + "_replyform").show();
                //$("#comment_" + commentIndex + "_replyform").focus();
            }

            if(unfoldModifyForm == true)
            {
                setTimeout(function()
                {

                    InitTinyMCEForm("tinymce-commentmodify-" + commentIndex);
                    tinyMCE.execCommand('mceFocus', true, "commentmodify-body-" + commentIndex);
                }, 0);

                $("#comment_" + commentIndex + "_modifyform").show();
                //$("#comment_" + commentIndex + "_modifyform").focus();
            }

            $("#commentList").css("cursor", "auto");
        },
        error: function()
        {
            $("#commentItem_fold_" + commentIndex).html("<span class=\"text-highlight text-bold\">오류! 잠시 후 다시 시도하세요.</span>");
            FoldSubCommentList(commentIndex);

            $("#commentList").css("cursor", "auto");
        }
    });
}

function FoldSubCommentList(commentIndex)
{
    $("#commentItem_" + commentIndex).html(unfoldedContent[commentIndex]);
    unfoldedContent[commentIndex] = null;
}

/*
 * 댓글 작성 부분 (addAjaxCommentForm, sendComment, afterSendCommentForm)
 * jquery-form plugin 사용
 */

var table, articleIndex, commentMasterIndex, commentParentIndex;
var formId, textareaId;

function addAjaxCommentForm(formId)
{
    var options = {
        //target:        '#resultDiv',
        beforeSubmit:  beforeSendCommentForm,
        success:       afterSendCommentForm,

        //url:       "Comment_Write_Post.jsp",
        //type:      "POST",
        //dataType:  "html",
        //clearForm: true,
        //resetForm: true,

        // $.ajax options can be used here too
        error: function()
        {
            alert("댓글 전송 도중 치명적인 오류가 발생하였습니다.");
        }
    };

    $("#" + formId).submit(function()
    {
        // http://www.nabble.com/Problem-With-jquery-form-plugin-and-tinymce-td14788650s27240.html
        tinyMCE.triggerSave();

        // inside event callbacks 'this' is the DOM element so we first
        // wrap it in a jQuery object and then invoke ajaxSubmit
        $(this).ajaxSubmit(options);

        // !!! Important !!!
        // always return false to prevent standard browser submit and page navigation
        return false;
    });
}

// 비밀번호 창에서 엔터키 입력시 sendComment 호출.
function pressEnterSendComment(mode, formId, textareaId, table, articleIndex, commentMasterIndex, commentParentIndex, e)
{
    if(!(e && e.which))
    {
        e = event;
    }
    
    if(e.keyCode == 13)
    {
        sendComment(mode, formId, textareaId, table, articleIndex, commentMasterIndex, commentParentIndex);
        return false;
    }

    return true;
}

function sendComment(mode, formId, textareaId, table, articleIndex, commentMasterIndex, commentParentIndex)
{
    var frmObj = $("#" + formId);
    writer = $("input[name='writer']", frmObj).attr('value');
    password = $("#" + formId + " input[name='password']").attr('value');
    commentBody = tinyMCE.get(textareaId).getContent();

    if(writer.length <= 0)
    {
        alert("작성자명을 입력하세요.");
        return;
    }
    else if(commentBody.length < 2)
    {
        alert("댓글 내용은 2글자를 넘어야 합니다.");
        return;
    }

    // 비밀번호 유효성 체크
    if(mode == "write" && password.length < 4)
    {
        alert("비밀번호를 4글자 이상 입력하세요.");
        return;
    }
    else if(mode == "modify" && password.length <= 0)
    {
        alert("글 작성시 입력하셨던 비밀번호를 입력하세요.");
        return;
    }

    // OK
    this.table = table;
    this.articleIndex = articleIndex;
    this.commentMasterIndex = commentMasterIndex;
    this.commentParentIndex = commentParentIndex;

    this.formId = formId;
    this.textareaId = textareaId;

    $("#" + formId).trigger("submit");
}

function beforeSendCommentForm(formData, jqForm, options)
{
    $("#" + formId + " input[name='btnSubmit']").attr("disabled", "disabled");
    $("#" + formId + " input[name='btnSubmit']").css("cursor", "wait");
    //var queryString = $.param(formData);
    //alert('About to submit: \n\n' + queryString);
}

function afterSendCommentForm(responseText, statusText)
{
    $("#" + formId + " input[name='btnSubmit']").removeAttr("disabled");
    $("#" + formId + " input[name='btnSubmit']").css("cursor", "auto");

    if(responseText.indexOf("WRITE_SUCCESS", 0) > 0 || responseText.indexOf("MODIFY_SUCCESS", 0) > 0)
    {
        alert("댓글을 저장했습니다.");
        resetCommentForm(formId, textareaId);

        if(commentParentIndex <= 0)
        {
            // 루트 댓글 쓰기.
            setTimeout("GetCommentList('" + table + "', '" + articleIndex + "', 1, false)", 0);
        }
        else
        {
            // 더댓글 쓰기.
            RefreshCommentList(table, articleIndex, commentMasterIndex);
        }
    }
    else if(responseText.indexOf("PASSWORD_MISMATCH", 0) > 0)
    {
        alert("비밀번호가 올바르지 않습니다.");
    }
    else if(responseText.indexOf("TOO_FAST_RESPAWN", 0) > 0)
    {
        alert("댓글 작성주기가 너무 빠릅니다. 잠시 기다리신 후 작성해 주세요.");
    }
    else
    {
        alert("댓글 전송 중 오류가 발생하였습니다.\n작성하신 항목을 다시 확인하여 주세요.");
    }
    
    this.table = null;
    this.articleIndex = null;
    this.commentMasterIndex = null;
    this.commentParentIndex = null;

    this.formId = null;
}

/*
 * 댓글 폼 리셋 (resetCommentForm)
 */

function resetCommentForm(formId, textareaId)
{
    // $("#" + formId + " input[name='writer']").attr('value') = "";
    $("#" + formId + " input[name='password']").val("");
    tinyMCE.get(textareaId).setContent("");

    $("#" + formId + " .uploadedFileList").html("");
}

function ToggleDeleteCommentForm(commentIndex)
{
    $("#comment_" + commentIndex + "_deleteform").toggle();
}

function DeleteComment(table, articleIndex, commentIndex, isGuest)
{
    confirmed = confirm("정말로 삭제하시겠습니까?");
    if(!confirmed)
    {
        return;
    }

    if(isGuest)
    {
        postData = "table=" + table + "&articleIndex=" + articleIndex + "&commentIndex=" + commentIndex +
               "&password=" + encodeURIComponent($("#commentPassword_" + commentIndex).val());
    }
    else
    {
        postData = "table=" + table + "&articleIndex=" + articleIndex + "&commentIndex=" + commentIndex;
    }

    $.ajax({
      type: "POST",
      url: "Comment_Delete_Post.jsp",
      data: postData,

      success: function(data)
      {
        if(data.indexOf("DELETE_SUCCESS", 0) > 0)
        {
            alert("삭제하였습니다.");
            GetCommentList(table, articleIndex, commentPage, false);
        }
        else if(data.indexOf("PASSWORD_MISMATCH", 0) > 0)
        {
            alert("비밀번호가 올바르지 않습니다.");
        }
        else
        {
            alert("댓글 삭제 도중 오류가 발생하였습니다!\n잠시 후 다시 시도하여 주세요.");
        }
      },
      error: function()
      {
        alert("댓글 삭제 도중 치명적인 문제가 발생하였습니다.");
      }
    });
}

// 서브트리 리스트에서 사용!
function ToggleChildCommentFormSub(mode, commentIndex)
{
    if(mode == "write")
    {
        setTimeout(function()
        {
            InitTinyMCEForm("tinymce-comment-" + commentIndex);
            tinyMCE.execCommand('mceFocus', false, "comment-body-" + commentIndex);
        }, 0);

        $("#comment_" + commentIndex + "_replyform").toggle();
        //$("#comment_" + commentIndex + "_replyform").focus();
    }
    else
    {
        setTimeout(function()
        {
            InitTinyMCEForm("tinymce-commentmodify-" + commentIndex);
            tinyMCE.execCommand('mceFocus', false, "commentmodify-body-" + commentIndex);
        }, 0);

        $("#comment_" + commentIndex + "_modifyform").toggle();
        //$("#comment_" + commentIndex + "_modifyform").focus();
    }
}

// 메인 리스트에서 사용!
function ToggleChildCommentFormMain(mode, table, articleIndex, commentIndex)
{
    if(unfoldedContent[commentIndex] == null || unfoldedContent[commentIndex].length <= 0)
    {
        UnfoldSubCommentList(table, articleIndex, commentIndex, (mode == "write"), (mode == "modify"));
    }
}

