/* POST AND COMMENT SCRIPT */

function toggleCommentCollapsing() {
    var span = $(this);
	var li = span.parent();
	if (li.hasClass("expanded")) {
		li.removeClass("expanded");
		li.addClass("collapsed");
	}
	else {
		li.removeClass("collapsed");
		li.addClass("expanded");
	}
}

function commentToggleAll(i) {
    if (i == 'collapse') {
        $("ul.post-comment-list li").each(function (n) {
            if ($(this).hasClass("expanded")) {
		        $(this).removeClass("expanded");
		        $(this).addClass("collapsed");
	        }
        });
    } else if (i =='first') {
        $("ul.post-comment-list li.level0").each(function (n) {
            if ($(this).hasClass("collapsed")) {
		        $(this).removeClass("collapsed");
		        $(this).addClass("expanded");
            }
        });
    } else {
        $("ul.post-comment-list li").each(function (li) {
            if ($(this).hasClass("collapsed")) {
		        $(this).removeClass("collapsed");
		        $(this).addClass("expanded");
	        }
        });
    }
}

$(function() {
	$(".post-comment-expander").click(toggleCommentCollapsing);
    $("#comment-expand-all").click(function () {commentToggleAll('expand')});
    $("#comment-expand-first").click(function() {commentToggleAll('first')});
    $("#comment-collapse-all").click(function() {commentToggleAll('collapse')});
});

// ----------
// moderation
// ----------

// document.ready bindings for moderation
$(function() {
    $(".down").click(function() { modComment(this, -1, 0); } );
    $(".up").click(function() { modComment(this, 1, 0); } );
    $(".upOn, .downOn").click(function() { modComment(this, 0, 0); } );
    $(".comment-abuse").click(function() { flagComment(this, 0); } );
    // set up modal loggin window
    $("#loginBox").jqm({ onHide: function(h){h.w.fadeOut('500', function() { h.o.remove(); });},
                         onShow: function(h){h.w.fadeIn('500'); } });
});

// function to do the moderation 
function modComment(thumb, score, isCallback) {
    var loc = window.location.href;
    var doc_id = loc.match(/\d{12}/);
    // get my comment container, comment_id, and the up/down spans that hold the thumbs
    var container = $(thumb).parents("div.post-comment");
    var cid =   $(container).attr("id");
    var up =    $(container).find("span.up, span.upOn");
    var down =  $(container).find("span.down, span.downOn");
    $(up).unbind('click');
    $(down).unbind('click');
    // do ajax comment mod here
    $.getJSON("/ajax/moderate", {id: cid, doc_id: doc_id, score: score, r: Math.random()}, function(data) {
        if (data.user == 0 && isCallback != 1) {
            // not logged in
            $("#loginBox").jqmShow({type:'mod',thumb: thumb, score: score});
        } else {
            // do all the display fun
            switch(score) {
                case 1:
                    // fill in thumbs up. reset thumbs down. reset click handlers.
                    $(up).removeClass("up").addClass("upOn").html(data.up)
                            .click(function() {modComment(up, 0, 1); } );
                    $(down).removeClass("down downOn").addClass("down").html(data.down)
                            .click(function() { modComment(down, -1, 1); } );
                    break;
                case -1:
                    // fill in thumbs down. reset thumbs up. reset click handlers.
                    $(down).removeClass("down").addClass("downOn").html(data.down)
                            .click(function() {modComment(down, 0, 1); } );
                    sib = $(thumb).siblings("span.up, span.upOn");
                    $(up).removeClass("up upOn").addClass("up").html(data.up)
                            .click(function() { modComment(up, 1, 1); } );
                    break;
                case 0:
                    switch($(thumb).attr("class")) {
                        case "upOn":
                            $(thumb).removeClass("upOn").addClass("up").html(data.up)
                                    .click(function() { modComment(up, 1, 1); });
                            $(down).click(function() { modComment(down, -1, 1); } );
                            break;
                        case "downOn":
                            $(thumb).removeClass("downOn").addClass("down").html(data.down)
                                    .unbind('click').click(function() { modComment(down, -1, 1); });
                            $(up).click(function() { modComment(up, 1, 1); } );
                            break;
                    }
                    break;
            }
        }
    });
}

// function to handle flagging comments for abuse
function flagComment(spn) {
    var loc = window.location.href;
    var doc_id = loc.match(/\d{12}/);
    var container = $(spn).parents("div.post-comment");
    var cid =   $(container).attr("id");
    $.getJSON("/ajax/flag", {id: cid, doc_id: doc_id, r: Math.random() }, function(data) {
        if (data.user == 0) {
            //not logged in 
            $("#loginBox").jqmShow({type:'flag',spn:spn});
        } else { 
            $("#modalBox").html(data.modal).jqmShow({type:'none'});
            //bind form submission
            $("#commentFlag").ajaxForm({
                type: 'POST',
                dataType: 'json',
                error: function() { alert("error");},
                success: flagSuccess
            });
        }
    });
}
function flagSuccess(data) {
    alert(data.error);
    if (data.error == 1) {
        $("#modalContent").append(data.error_text);
    } else {
        $("#modalContent").html(data.modal);
    }
}

//----------------
// comment posting
//----------------

// set up bindings for ajaxified comment posting
$(function() {
    $("#commentAdd").click(function() { commentReply('commentReply',0,500); $(this).unbind('click');});
    $(".comment-reply").click(function() {
        var container = $(this).parents("div.post-comment");
        var w = $(container).width() - 20;
        var cid =   $(container).attr("id");
        commentReply(cid,cid,w);
        $(this).unbind('click');
    });
});
// load up a reply form and append under the comment. or show a modal box if comments are closed or user is not logged in
function commentReply(appendTo,parent_id,width) {
        var loc = window.location.href;
        var doc_id = loc.match(/\d{12}/);
        // do stuff
        $.getJSON("/_shared/comments/reply_form", {doc_id: doc_id, parent_id: parent_id, width:width, r: Math.random()}, function(data) {
            if (data.user == 0) {
                //not logged in
                $("#loginBox").jqmShow({type:'reply',appendTo:appendTo,parent_id:parent_id,width:width});
            } else if (data.closed == 1) {
                $("#modalBox #modalContent").html("<h3>Comments are closed for this item</h3>");
                $("#modalBox").jqmShow();
            } else if (data.has_handle == 0) {
                $("#modalSignup").hide();
                $("#modalLogin").html("loading");
                $("#modalLogin").load('/_shared/modal/handle', function() {
                    $("#handleForm").ajaxForm({
                        type: 'POST',
                        dataType: 'json',
                        error: function() { $("#modalLoginError").html("There was an error processing your request"); },
                        success: handleSuccess
                    });
                }).show();
                $("#loginBox").jqmShow({type:'reply',appendTo:appendTo,parent_id:parent_id,width:width});
            } else {
                if (appendTo == 'commentReply') {
                    $("#commentReply").prepend(data.replyForm);
                } else {
                    $("#" + appendTo).append(data.replyForm);
                }
                // set up the text area with markitup
                $("#reply"+parent_id).markItUp(mySettings,{
                    previewParserPath: "/ajax/bbparse?preview=1"});
                // set the width
                $("#markItUpReply" + parent_id).width(width);
                $("#reply"+parent_id).width(width - 27);
                // set up the reply form we got in the json for ajax submission
                $("#replyForm"+parent_id).ajaxForm({
                    type: 'POST',
                    dataType: 'json',
                    error: function() { return false; },
                    success: commentSuccess
                });
                // this is a hackish way to get the preview since markItUp has no simple way to call the preview function.
                $("#previewComment" + parent_id).click(function() { $("#markItUpReply" + parent_id + " .markItUpButton.preview").trigger('click').trigger('mouseup'); return false;});

            }
        });
        
}
function commentSuccess(data) {
    if (data.error == 1 ) {
        // HANDLE BANNED AND OTHER ERRORS HERE
        $("#reply" + data.parent_id).markItUpRemove();
        $("#replyFormDiv" + data.parent_id).remove();
        $("#modalBox #modalContent").html("<h3>" + data.error_text + "</h3>");
        $("#modalBox").jqmShow({type:'none'});
    } else if (data.success == 1) {
        // great success
        if (data.probation) {
            // they are a probationary user so display a message instead of refreshing the page
            $("#reply" + data.parent_id).markItUpRemove();
            $("#replyFormDiv" + data.parent_id).html(data.msg);
        } else {
            // refresh the page and send to the comment they just posted
            $("#reply" + data.parent_id).markItUpRemove();
            $("#replyFormDiv" + data.parent_id).html(data.msg);
            window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + "#" + data.new_cid;
            location.reload(true);
        }        
    }
}
// ajax login & sign_up
$(function() {
    $("#loginForm").ajaxForm({
        type: 'POST',
        dataType: 'json',
        error: function() { $("#modalLoginError").html("Error processing your request.");},
        success: loginCallback
    });
    $("#signupForm").ajaxForm({
        type: 'POST',
        dataType: 'json',
        error: function() { $("#modalLoginError").html("Error processing your request.");},
        success: signupCallback
    });
});
function loginCallback(data) {
    if (data.user == 0 ) {
        //fail
        $("#modalLoginError").html(data.error);
    } else {
        // redefine jqm callbacks
        $("#loginBox").jqm({ onHide: function(h){h.w.fadeOut('1000', function() { h.o.remove(); }); 
            modalCallback(h.t);
        }});

        // logged in
        $("#loginBox").jqmHide();
        $("#hd-tools").html(data.header_div);
        
    }
}
function signupCallback(data) {
    if (data.error == 1) {
        $("#modalLoginError").html(data.error_txt);
    } else {
        $("#loginBox").jqm({ onHide: function(h){h.w.fadeOut('1000', function() { h.o.remove(); }); 
            modalCallback(h.t);
        }});
        $("#modalLoginError").hide();
        $("#signupForm").html(data.thanks);
        $("#loginBox").jqmAddClose('.jqmClose');
        $("#hd-tools").html(data.header_div);
    }
}
function handleSuccess(data) {
    if (data.user == 0 ) {
        //fail
        $("#modalLoginError").html(data.error);
    } else {
        // redefine jqm callbacks
        $("#loginBox").jqm({ onHide: function(h){h.w.fadeOut('1000', function() { h.o.remove(); }); 
            modalCallback(h.t);
            h.o.remove();
        }});

        // handle created successfully.
        $("#loginBox").jqmHide();
        
    }
}
function modalCallback(cb) {
    data = '';
    switch(cb.type) {
        case 'mod':
            modComment(cb.thumb,cb.score,1);
            break;
        case 'flag':
            flagComment(cb.spn);
            break;
        case 'reply':
            commentReply(cb.appendTo,cb.parent_id,cb.width);
            break;
        default:
            break;
    }
// redefine without proper callbacks
$("#loginBox").jqm({ onHide: function(h){h.w.fadeOut('500', function() { h.o.remove(); });},
        onShow: function(h){h.w.fadeIn('500'); } });

}

