$(document).ready(function(){
    initCommentColor();
    initCommentTab();
    initCommentAction();
})

function initCommentColor(){
    $("li.comment:odd").addClass("oddcomment");
}

function initCommentTab(){
    $("#thetrackbacks").hide();
    doCommentTab();
}

function initCommentAction(){
    doReply();
    doReplyHover();
    doQuote();
}

function doCommentTab(){
    $('#commenttab').click(function(){
        $('#trackbacktab').removeClass("curtab").addClass("tab");
        $(this).addClass("curtab");
        $("#thetrackbacks").hide();
        $("#whole_comments").fadeIn(600);
    });
    $('#trackbacktab').click(function(){
        $('#commenttab').removeClass("curtab").addClass("tab");
        $(this).addClass("curtab");
        $("#whole_comments").hide();
        $("#thetrackbacks").fadeIn(600);
    });
}

function doReply(){
    $(".c_action .reply").live("click",function(){
        var author_id = "#commentauthor-" + $(this).attr("rel");
        var comment_id = "#comment-" + $(this).attr("rel");
        var author = $(author_id).text();
        var insertStr = '<a href="' + comment_id + '">@' + author.replace(/\t|\n|\r\n/g, "") + ' </a>\n';
        if($("#comment").val().indexOf(insertStr) > -1){
            alert("You've already appended this reply!");
            return;
        }

        doInsertToComment(insertStr);
    });
}

function doQuote(){
    $(".c_action .quote").live("click",function(){
        var author_id = "#commentauthor-" + $(this).attr("rel");
        var comment_id = "#comment-" + $(this).attr("rel");
        var cbody_id = "#commentbody-" + $(this).attr("rel");
        var author = $(author_id).text();
        var comment = $(cbody_id).html();

        var insertStr = '<blockquote cite="' + cbody_id + '">';
        insertStr += '\n<strong><a href="' + comment_id + '">' + author.replace(/\t|\n|\r\n/g, "") + '</a> :</strong>\n';
        insertStr += comment.replace(/\t/g, "");
        insertStr += '</blockquote>\n';

        doInsertToComment(insertStr);
    });
}

function doInsertToComment(insertStr){
    var oriStr = $.trim($("#comment").val());
    if(oriStr==''){
        $("#comment").val(insertStr);
    } else {
        $("#comment").val(oriStr+'\n'+insertStr);
    }
    $("#comment").focus();
}

function doReplyHover(){
    var id=/^#comment-/;
    var at=/^@/;
    $('#thecomments li p a').each(function() {
        if(jQuery(this).attr('href').match(id)&& jQuery(this).text().match(at)) {
            jQuery(this).addClass('atreply');
        }
    });
    $('.atreply').live('mouseover mouseout', function(event){
        if(event.type == 'mouseover'){
            var target = this;
            var _commentId = $(this).attr('href');
            if($(_commentId).is('.comment')) { // if replied comment is in the same page
                var innerbox = jQuery('<div class="innerbox"></div>').html($(_commentId).html());
                jQuery('<li class="comment tip"></li>').hide().append('<div class="arrow"></div>')
                .append(innerbox).appendTo($('#thecomments'));

                $('#thecomments .tip').css({
                    left:cumulativeOffset(this)[0] + $(this).width() + 10,
                    top:cumulativeOffset(this)[1] - 22
                }).fadeIn();
            } else { // if replied comment is in the other pages
                var id = _commentId.slice(9);
                $.ajax({
                    type:         'GET'
                    ,
                    url:         '?action=load_comment&id=' + id
                    ,
                    cache:       false
                    ,
                    dataType:    'html'
                    ,
                    contentType: 'application/json; charset=utf-8'
                    ,
                    beforeSend: function(){
                        var innerbox = jQuery('<div class="innerbox"></div>').html('<p class="ajax-loader msg">Loading...</p>');
                        jQuery('<li class="comment tip"></li>').hide().append('<div class="arrow"></div>')
                        .append(innerbox).appendTo($('#thecomments'));
                        $('#thecomments .tip').css({
                            left:cumulativeOffset(target)[0] + jQuery(target).width() + 10,
                            top:cumulativeOffset(target)[1] - 22
                        }).fadeIn();
                    }
                    ,
                    success: function(data){
                        var addedComment = jQuery(data + '</li>');
                        addedComment.hide().appendTo($('#thecomments'));
                        $('#thecomments .tip .msg').html(addedComment.html());
                    }
                    ,
                    error: function(){
                        $('#thecomments .tip .msg').html('<p class="msg">Oops, failed to load data.</p>');
                    }
                });
            }
        } else {
            $('#thecomments .tip').fadeOut(400, function(){
                $(this).remove();
            });
        }
    });
}


function cumulativeOffset(element) {
    var valueT = 0, valueL = 0;
    do {
        valueT += element.offsetTop  || 0;
        valueL += element.offsetLeft || 0;
        element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
}
