
$(document).ready(function(){

    //Fix some IE CSS Issues
    if ($.browser.msie) {
        $("ul.forum-list li:last-child,ul.topic-list li:last-child").css("border-bottom","none");
    }
						   
    set_links();
    check_facebook();
});

function set_links()
{
    //Bind the comment links.
    $("a.reply-comment").each(function(index){
        $(this).click(function() {
            if($('form[action="/login.php"]').length != 0)
            {
                $('<div title="ERROR!">You must be logged in to participate in the forum.</div>').dialog({
                    buttons: {
                        'OK': function(){
                            $(this).dialog('close');
                            return;
                        }
                    }
                });
            } else {
                id = $(this).attr("id");
                id = id.substring(id.lastIndexOf('-')+1);
                reply_comment(id);
                return false;
            }
        });
    });

    $(".reply-link").find('a').click(function(){
        if($('form[action="/login.php"]').length != 0)
        {
            $('<div title="ERROR!">You must be logged in to participate in the forum.</div>').dialog({
                buttons: {
                    'OK': function(){
                        $(this).dialog('close');
                    }
                }
            });
        } else {
            id= $(this).attr("id");
            id = id.substring(id.lastIndexOf('-')+1);
            reply_thread(id);
            return false;
        }
    });

    $(".edit-comment").each(function(index){
        $(this).click(function(){
            id = $(this).attr("id");
            id = id.substring(id.lastIndexOf('-')+1);
            edit_comment(id);
            return false;
        });
    });

    $(".remove-comment").each(function(index){
        $(this).click(function(){

            id = $(this).attr("id");
            id = id.substring(id.lastIndexOf('-')+1);
            remove_comment(id);
            return false;
        });
    });

    $(".edit-post").each(function(index){
        $(this).click(function(){
            id = $(this).attr("id");
            id = id.substring(id.lastIndexOf('-')+1);
            edit_post(id,0);
            return false;
        });
    });

    $(".remove-post").each(function(index){
        $(this).click(function(){
            id = $(this).attr('id');
            id = id.substring(id.lastIndexOf('-')+1);
            remove_post(id);
            return false;
        });
    });

    $('ul.topic-list > li').removeClass('odd');
    $('ul.topic-list > li:odd').addClass('odd');
    $('ul.forum-list > li').removeClass('odd');
    $('ul.forum-list > li:odd').addClass('odd');
}

function check_facebook()
{
	try{
	    FB.ensureInit (  function () { //Make sure we have the FB libraries loaded before we make FB.Connect API calls.
	        if(FB.Connect.get_loggedInUser() !== null)
	        {
	            $(".post-facebook").attr('checked','checked');
	            $(".post-facebook").parents('.segment').eq(0).show();
	        } else {
	            $(".post-facebook").attr('checked','');
	            $(".post-facebook").parents('.segment').eq(0).hide();
	        }
	    });
	}
	catch(error)
	{
		$(".post-facebook").attr('checked', '');
		$(".post-facebook").parents('.segment').eq(0).hide();
	} 
}

function reply_comment(comment_id)
{
    commentBlock = $("#comment-"+comment_id);

    if(commentBlock.length)
    {
        if($(commentBlock).find('form').length == 0) {
            commentBlock.append('<form class="comment-form" name="comment-'+comment_id+'" id="'+comment_id+'" action="javascript:new_comment('+comment_id+')" style="display:none;"><input type="hidden" name="comment-id" value="'+comment_id+'" /><div class="segment"><textarea class="ckeditor" name="comment-content-'+comment_id+'" rows="7" style="width:600px;"></textarea></div><div class="segment" style="float:left;"><label for="post-facebook" id="post-facebook-label">Post to Faceboook: </label><input type="checkbox" name="post-facebook" class="post-facebook" checked="checked"  /></div><div class="segment" style="float:right;"><input type="submit" name="submit" id="submit" value="Post Comment" /></div><br class="clear" /><br /></form>');
            $(commentBlock).find('.ckeditor').ckeditor()
            $(commentBlock).find('form[name="comment-'+comment_id+'"]').slideDown('fast');
            check_facebook();
        } else {
            $(commentBlock).find('form').slideUp('fast',function(){
                $(commentBlock).find('.ckeditor').each(function(){
                    var editorID = $(this).attr("name");
                    var instance = CKEDITOR.instances[editorID];
                    if (instance) {
                        CKEDITOR.remove(instance);
                    }
                });
                $(this).remove();
            });
        //$(commentBlock).find('form').remove();
        }
    }
    else
    {
        alert("Invalid Comment ID");
    }
}

function reply_thread(thread_id)
{
    postBlock = $('.post');
    if(postBlock.length)
    {
        if($(postBlock).find('form').length == 0) {
            postBlock.find('.right-block').append('<form class="comment-form" name="post-'+thread_id+'" id="post-comment-form-'+thread_id+'" action="javascript:new_post_comment('+thread_id+')" style="display:none;"><input type="hidden" name="comment-id" value="0" /><input type="hidden" name="post-id" value="'+thread_id+'" /><div class="segment"><textarea class="ckeditor" name="comment-content-'+thread_id+'"></textarea></div><div class="segment" style="float:left;"><label for="post-facebook" id="post-facebook-label">Post to Faceboook: </label><input type="checkbox" name="post-facebook" class="post-facebook" checked="checked"  /></div><div class="segment" style="float:right;"><input type="submit" name="submit" id="submit" value="Post Comment" /></div><br class="clear" /><br /></form><br class="clear" />');
            $(postBlock).find('.ckeditor').ckeditor();
            $(postBlock).find('form').slideDown('fast');
            check_facebook();
        } else {

            $(postBlock).find('.ckeditor').each(function(){
                var editorID = $(this).attr("name");
                var instance = CKEDITOR.instances[editorID];
                if (instance) {
                    CKEDITOR.remove(instance);
                }
            });
            $(postBlock).find('form').remove();

        }
    } else {
        alert("Invalid Post");
    }
    return;
}

function new_comment(comment_id)
{
    // Do Dialog
    the_dialog = $('<div title="Submit Comment?">Are you sure you want to submit your comment to this Post?</div>');
    $(the_dialog).dialog({
        bgiframe: true,
        resizable: false,
        height:'auto',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.8
        },
        buttons: {
            'Yes': function() {
                $(this).dialog('close');
                commentBlock = $("#comment-"+comment_id);
                theForm = $(commentBlock).find('form[name="comment-'+comment_id+'"]');
                $(theForm).slideUp('fast',function(){
                    $(this).find('.ckeditor').each(function(){
                        var editorID = $(this).attr("name");
                        var instance = CKEDITOR.instances[editorID];
                        if (instance) {
                            CKEDITOR.remove(instance);
                        }
                    });
                    $(this).remove();
                });
                commentBlock.append('<div class="spinner" style="float:left;">Posting Comment </div><br class="clear" />');


                if($(theForm).find('input[name="post-facebook"]').attr('checked')) fb_post='1';
                else fb_post='0';
				
                
                //alert("TEST 1");
                $.getJSON('/includes/main/forum/main.php',{page2:"json","request":"new-comment","comment_id":comment_id,"fb_post":fb_post,comment_content:$(theForm).find('textarea').val()},function(data){
                	//alert("TEST 2");
                    $(commentBlock).find('.spinner').fadeOut('slow');
                    if(data.success == 1)
                    {
                        //alert('Parent: '+data.parent+'\nLevel: '+data.level);
                        the_html = $(data.html);
                        $(data.html).css('display','none');
                        if(data.level == 0)
                        {
                            $('ul.comment-list').append(data.html);
                        } else {
                            the_parent=$('li#comment-'+data.parent);
                            $(the_parent).after(the_html);
                        }

                        setTimeout("$('li#comment-"+data.id+"').slideDown('slow');",1000);
                    } else {
                        $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                            buttons: {
                                'OK': function(){
                                    $(this).dialog('close');
                                }
                            }
                        });
                    }
                    $(commentBlock).find('form').remove();

                    set_links();

                });
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
}

function edit_comment(comment_id)
{
    commentBlock = $("#comment-"+comment_id);
    if(commentBlock.length)
    {
        if($(commentBlock).find('form').length == 0){
            current_content=$(commentBlock).find('.comment-right').text();

            commentBlock.append('<form class="comment-form" name="comment-'+comment_id+'" id="'+comment_id+'" action="javascript:submit_edit_comment('+comment_id+')" style="display:none;"><input type="hidden" name="comment-id" value="'+comment_id+'" /><div class="segment"><textarea name="comment-content-'+comment_id+'"  class="ckeditor">'+current_content+'</textarea></div><div class="segment" style="float:right;"><input type="submit" name="submit" id="submit" value="Save Comment" /></div><br class="clear" /><br /></form>');

            $(commentBlock).find('form[name="comment-'+comment_id+'"]').slideDown('fast',function(){
                $(commentBlock).find('.ckeditor').ckeditor();
            });

        } else {
            $(commentBlock).find('form').slideUp('fast',function(){
                $(this).find('.ckeditor').each(function(){
                    var editorID = $(this).attr("name");
                    var instance = CKEDITOR.instances[editorID];
                    if (instance) {
                        CKEDITOR.remove(instance);
                    }
                });
                $(this).remove();
            });
        }
    }
    else
    {
        alert("Invalid Comment ID");
    }
}

function submit_edit_comment(comment_id)
{
    // Do Dialog
    the_dialog = $('<div title="Save Comment?">Are you sure you want to submit your changes to this Comment?</div>');
    $(the_dialog).dialog({
        bgiframe: true,
        resizable: false,
        height:'auto',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.8
        },
        buttons: {
            'Yes': function() {
                $(this).dialog('close');
                commentBlock = $("#comment-"+comment_id);
                theForm = $(commentBlock).find('form[name="comment-'+comment_id+'"]');
                $(theForm).slideUp('fast',function(){
                    $(this).find('.ckeditor').each(function(){
                        var editorID = $(this).attr("name");
                        var instance = CKEDITOR.instances[editorID];
                        if (instance) {
                            CKEDITOR.remove(instance);
                        }
                    });
                });
                commentBlock.append('<div class="spinner" style="float:left;">Saving Comment </div><br class="clear" />');

                $.getJSON('/includes/main/forum/main.php',{page2:"json",request:"edit-comment","comment_id":comment_id,comment_content:$(theForm).find('textarea').val()},function(data){
                    $(commentBlock).find('.spinner').fadeOut('slow');
                    if(data.success == 1)
                    {
                        $(commentBlock).find('.comment-right').html($(theForm).find('textarea').val());
                    } else {
                        $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                            buttons: {
                                'OK': function(){
                                    $(this).dialog('close');
                                }
                            }
                        });
                    }
                    $(commentBlock).find('form').remove();

                    set_links();

                });
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
}


function new_post_comment(thread_id)
{
    // Do Dialog
    the_dialog = $('<div title="Submit Comment?">Are you sure you want to submit your comment to this Post?</div>');
    $(the_dialog).dialog({
        bgiframe: true,
        resizable: false,
        height:'auto',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.8
        },
        buttons: {
            'Yes': function() {
                $(this).dialog('close');
                postBlock = $('.post');
                theForm = $(postBlock).find('form[name="post-'+thread_id+'"]');
                $(theForm).slideUp('fast',function(){
                    $(this).find('.ckeditor').each(function(){
                        var editorID = $(this).attr("name");
                        var instance = CKEDITOR.instances[editorID];
                        if (instance) {
                            CKEDITOR.remove(instance);
                        }
                    });
                    $(this).remove();
                });
                postBlock.append('<div class="spinner" style="float:left;padding-left:122px;">Posting Reply </div><br class="clear" />');

                $.getJSON('/includes/main/forum/main.php',{page2:"json",request:"new-comment","post_id":thread_id,"fb_post":(($(theForm).find('input[name="post-facebook"]').attr('checked') == 'checked')?1:0),comment_content:$(theForm).find('textarea').val()},function(data){
                    $(postBlock).find('.spinner').fadeOut('slow');
                    if(data.success == 1)
                    {
                        //alert('Parent: '+data.parent+'\nLevel: '+data.level);
                        the_html = $(data.html);
                        $(the_html).css('display','none');
                        if(data.level == 0)
                        {
                            $('ul.comment-list').append(the_html);
                        } else {
                            the_parent=$('li#comment-'+data.parent);
                            parent_level = data.level-1;
                            //alert('My Level: '+data.level+'\nParent Level: '+parent_level);
                            $(the_parent).nextAll('li.level-'+parent_level+':eq(0)').before(the_html);
                        }

                        $('li#comment-'+data.id).toggle();


                        set_links();
                    } else {
                        $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                            buttons: {
                                'OK': function(){
                                    $(this).dialog('close');
                                }
                            }
                        });
                    }

                });
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });

}

function remove_comment(comment_id)
{

    the_dialog = $('<div title="Remove Comment?">Are you sure you want to remove this comment?</div>');
    $(the_dialog).dialog({
        bgiframe: true,
        resizable: false,
        height:'auto',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.8
        },
        buttons: {
            'Yes': function() {

                $(this).dialog('close');

                $.getJSON('/includes/main/forum/main.php',{ page2:"json",request:"remove-comment","comment_id":comment_id },function(data){
                    if(data.success == 1)
                    {
                        // Find Children and delete them as well.
                        $('li#comment-'+comment_id).nextAll('li').each(function(){

                            if($(this).is('.level-'+data.level) || $(this).is('.level-'+(data.level-1)) || $(this).is('.level-'+(data.level-2)) || $(this).is('.level-'+(data.level-3)) || $(this).is('.level-'+(data.level-4))) return false;
                            else {
                                $(this).slideUp('slow',function(){
                                    $(this).remove();
                                });
                            }
                        });

                        $('li#comment-'+comment_id).slideUp('slow',function(){
                            $(this).remove();
                        //set_links();
                        });
                    } else {
                        $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                            buttons: {
                                'OK': function(){
                                    $(this).dialog('close');
                                }
                            }
                        });
                    }
                });
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });

}

function edit_post(post_id,form_bool)
{
    switch(form_bool){
        case 0:
            contentBlock = $(".post .right-block");

            title = $(contentBlock).find('h3').text();
            content = $(contentBlock).find('.post-content').text();
            if(contentBlock.length)
            {
                if($(contentBlock).find('form').length == 0){
                    contentBlock.append('<form class="comment-form" name="edit-post-'+post_id+'" id="'+post_id+'" action="javascript:edit_post('+post_id+',1)" style="display:none;border:1px solid #C9C2C1;padding:5px;"><input type="hidden" name="post-id" value="'+post_id+'"/><div class="segment"><label for="post_e_title">Post Title</label></div><input type="text" name="post_e_title" value="'+title+'" style="width:400px;"/><div class="segment"><label for="post_e_content">Post Content</label><textarea name="post_e_content_'+post_id+'"  class="ckeditor">'+content+'</textarea></div><div class="segment" style="float:right;"><input type="submit" name="submit" id="submit" value="Save Comment" /></div><br class="clear" /><br /></form>');

                    $(contentBlock).find('form[name="edit-post-'+post_id+'"]').slideDown('fast',function(){
                        $(contentBlock).find('.ckeditor').ckeditor();
                    });
                } else {
                    $(contentBlock).find('form').slideUp('fast',function(){
                        $(this).find('.ckeditor').each(function(){
                            var editorID = $(this).attr("name");
                            var instance = CKEDITOR.instances[editorID];
                            if (instance) {
                                CKEDITOR.remove(instance);
                            }
                        });
                        $(this).remove();
                    });
                }
            }
            else
            {
                alert("Invalid Comment ID");
            }
            break;
        case 1:
            // Do Dialog
            the_dialog = $('<div title="Remove Comment?">Are you sure you want to save your changes to this Post?</div>');
            $(the_dialog).dialog({
                bgiframe: true,
                resizable: false,
                height:'auto',
                modal: true,
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.8
                },
                buttons: {
                    'Yes': function() {
                        $(this).dialog('close');
                        contentBlock = $(".post .right-block");
                        theForm = $(contentBlock).find('form[name="edit-post-'+post_id+'"]');
                        $(theForm).slideUp('fast');
                        contentBlock.append('<div class="spinner" style="float:left;padding-left:122px;">Saving Post Edits </div><br class="clear" />');


                        $.getJSON('/includes/main/forum/main.php',{ page2:"json",request:"edit-post-full","post_id":post_id,post_content:$(theForm).find('textarea').val(),post_title:theForm.find('input[name="post_e_title"]').val() },function(data){
                            $(contentBlock).find('.spinner').fadeOut('slow');
                            if(data.success == 1)
                            {
                                $(contentBlock).find('h3').text($(theForm).find('input[name="post_e_title"]').val());
                                $(contentBlock).find('.post-content').html(addslashes($(theForm).find('textarea').val()));
                                $(theForm).remove();
                            } else {
                                $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                                    buttons: {
                                        'OK': function(){
                                            $(this).dialog('close');
                                        }
                                    }
                                });
                            }

                        });
                    },
                    'No': function() {
                        $(this).dialog('close');
                    }
                }
            });
            break;
    }
}

function edit_post_title(post_id,form_bool)
{
    contentBlock = $("li#topic-"+post_id);
    switch(form_bool)
    {
        case 0:

            if(contentBlock.length)
            {
                title = $(contentBlock).find('.topic-title').text();
                if($(contentBlock).find('form').length == 0){
                    contentBlock.append('<form class="comment-form" name="edit-post-'+post_id+'" id="'+post_id+'" action="javascript:edit_post_title('+post_id+',1)" style="display:none;border:1px solid #C9C2C1;padding:5px;"><input type="hidden" name="post-id" value="'+post_id+'"/><div class="segment"><label for="post_e_title">Post Title</label></div><input type="text" name="post_e_title" value="'+title+'" style="width:400px;"/><div class="segment"><input type="submit" name="submit" id="submit" value="Save Title" /></div><br class="clear" /><br /></form>');

                    $(contentBlock).find('form[name="edit-post-'+post_id+'"]').slideDown('fast',function(){

                        });
                } else {
                    $(contentBlock).find('form').slideUp('fast',function(){
                        $(this).remove();
                    });
                }
            }
            else
            {
                alert("Invalid Comment ID");
            }
            break;
        case 1:
            // Do Dialog
            the_dialog = $('<div title="Rename Post?">Are you sure you want to rename the Title of this Post?</div>');
            $(the_dialog).dialog({
                bgiframe: true,
                resizable: false,
                height:'auto',
                modal: true,
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.8
                },
                buttons: {
                    'Yes': function() {
                        $(this).dialog('close');
                        theForm = $(contentBlock).find('form[name="edit-post-'+post_id+'"]');
                        $(theForm).slideUp('fast');
                        contentBlock.append('<div class="spinner" style="float:left;padding-left:122px;">Saving Post Edits </div><br class="clear" />');

                        $.getJSON('/includes/main/forum/main.php',{page2:"json",request:"edit-post-title","post_id":post_id,post_title:theForm.find('input[name="post_e_title"]').val()},function(data){
                            $(contentBlock).find('.spinner').fadeOut('slow');
                            if(data.success == 1)
                            {
                                $(contentBlock).find('.topic-title > a').text($(theForm).find('input[name="post_e_title"]').val());
                            } else {
                                $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                                    buttons: {
                                        'OK': function(){
                                            $(this).dialog('close');
                                        }
                                    }
                                });
                            }

                        });
                    },
                    'No': function() {
                        $(this).dialog('close');
                    }
                }
            });
            break;
    }
}

function remove_post(post_id)
{
    the_li = $('li#topic-'+post_id);
    the_title = $(the_li).find('.topic-title > a').text();
    // Do Dialog
    the_dialog = $('<div title="Remove Post?">Are you sure you want to remove this Post?<br/><br />'+the_title+'</div>');
    $(the_dialog).dialog({
        bgiframe: true,
        resizable: false,
        height:'auto',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.8
        },
        buttons: {
            'Yes': function() {

                $(this).dialog('close');

                $.getJSON('/includes/main/forum/main.php',{page2:"json",request:"remove-post","post_id":post_id},function(data){
                    if(data.success == 1)
                    {
                        $(the_li).slideUp('slow',function(){
                            $(this).remove();
                            set_links();
                        });
                    } else {
                        $('<div title="ERROR!">'+data.error_msg+'</div>').dialog({
                            buttons: {
                                'OK': function(){
                                    $(this).dialog('close');
                                }
                            }
                        });
                    }
                });
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
}
