var tooltip_link, tooltip_bub, counter = false;
var xmlLoaderImage = '/images/ajax-loader.gif';
$(document).ready(function() {
    $("#header-menu li.menu-button").hover(
        function(){
            $(this).addClass("select");
           // $(this).fadeOut(100);$(this).fadeIn(100);
        },
        function () {
            $(this).removeClass("select");
    });
    $('.cmt-wrap').hover(
        function() {
            $(this).parent().find('.cmt-menu').show();
        },
        function() {
            $(this).parent().find('.cmt-menu').hide();
        });
    $("#spoiler h2").toggle(function(){
            $(this).next().show();
    $(this).html('Hide spoiler');
            }, function () {
            $(this).next().hide();
    $(this).html('Show spoiler');
    });
    $("#notifyBox").click(function() {
        var totalNotify = $(".notifi").text();
        $("#notifications").html('<div style="text-align:center;margin-top:60px;"><img src="'+xmlLoaderImage+'"></div>').show();
        $.getJSON('/fajax/getMsg', function(data) {
             $("#notifications").html('<ul style="width:350px;display:none;position:absolute;z-index:8999;"></ul>');
             //$("#notifications ul").show();
             var output = '<li class="note-new" style="border-bottom:0px;padding:5px 10px;"><span style="font-size:14px;font-weight:bold;color:#111;">Notifications</span><a class="fr" href="/notifications">View all »</a></li>';
             if(data[0] == false) 
                 output = '<li><a name="#e">Empty.</a></li>';
             else {
                for(var n in data) {
                    var username = '';
                    var status = '';
                    if(data[n].f_username != '')
                        username = '<div style="width:30px;height:30px;overflow:hidden;float:left;margin:0 10px 0;"><a href="/user/'+data[n].f_username+'"><img src="'+data[n].image+'" style="width:30px;top:0;"/></a></div><a href="/user/'+data[n].f_username+'" class="bold">'+data[n].f_username+'</a>';
                    if(data[n].status == 0 && totalNotify != 0) status = ' class="note-new"';
                    output += '<li'+status+' style="padding:5px;line-height:14px;">'+username+' <a href="/'+data[n].url+'">'+data[n].message+'</a><div class="clear"></div></li>';
                }
                
             }
             $(".notifi").text(0).removeClass('color2');
             $("#notifications ul").html(output);
        });
        return false;
        
    });
    $("#account-menu .menu-button").hover(
        function() {
            $(this).addClass('menu-popout');
        },
        function() {
            $(this).removeClass('menu-popout');
        }
    );

    var topOffset = 0;
    var topOffset2 = 0; //var arrowPos = 209;

    $(".tooltip-cat").mouseenter(function() {
        if(counter == false) {
        counter = true;
        } else {
            setTimeout("setBubbleCounter()", 400);
        }
        var pos = $(this).offset();
        var newleft = pos.left+200;
        var winTop = $(window).scrollTop();
        var winHeight = $(window).height();
        var offSetTest2 = (winTop+winHeight)-380;

        var offSetTest = winTop-(pos.top-200);
        var newtop = pos.top-200;

        if(offSetTest > 0) {
            topOffset = offSetTest+6;
            topOffset2 = 0;
        } else if(offSetTest2 < newtop) {
            topOffset2 = newtop-offSetTest2+20;
            topOffset = 0;
            
        } else {
            topOffset2 = 0;
        }
        newtop = newtop-topOffset2+topOffset;


        var id = $(this).attr("id");

        tooltip_link = true;
        $("#main-bubble").stop().fadeTo(0,1).animate({"top": newtop+"px","left": newleft+"px"}, function() {
                var testTop = pos.top-newtop;
                if(testTop < 0) testTop = 0;
                else if(testTop > 340) testTop = 340;
                $("#main-bubble .main-bubble-arrow").animate({'top' : testTop+'px'},300);
                
                $("#main-bubble .content").html('<img src="'+groupContent[id]['img']+'" height="130" style="margin-bottom:10px;"><div class="section"><h3>'+groupContent[id]['title']+'</h3></div><p>'+groupContent[id]['desc']+'</p><p><b>Genre:</b> '+groupContent[id]['genre']+'<br/><b>Film Date:</b> '+groupContent[id]['year']+'<br/><b>Episodes:</b> '+groupContent[id]['eps']+'<br/><b>Category:</b> '+groupContent[id]['category']);
        }); 

        
        }).mouseleave( function() {
            tooltip_link = false;
    });

    $("#main-bubble").mouseenter(function() {
        tooltip_bub = true;
        //if(counter > 0) counter--;
    }).mouseleave(function() {
        tooltip_bub = false;
        setTimeout("hideBubble()", 300);
        topOffset = 0;
    });
    $(".login_link").click(function() {
        blackOutModule('getLoginModule("#login_form")');
        return false;
    });
    $(".register_link").click(function() {
        blackOutModule('getRegisterModule("#register_form")');
        return false;
    });
    $(".api-bo").click(function() {
        var m_bo = $(this).attr('id');
        blackOutModule('zA_Pa_BO("'+m_bo+'")');
        return false;
    });
});
var BO = "#blackout";
function zA_Pa_BO(m) {

    var vxa = m.split('#',2);
    var azw = vxa[1].split('-',2);

    var med = vxa[0];
    var id = azw[0];
    var p = azw[1];
    if(p == undefined) p = ''; else p = '/'+p;
    //alert(p);
    var ajaxURL = '/fajax/'+med+'/'+id+p;

    $.getJSON(ajaxURL, function(data) {
          //var ddd = data.html;
          //var dd = jQuery.parseJSON
          $("#module").html(data.html);
          //alert('Debugging #1' + data.html);
          $("#fajax_form").die("submit");
          $("#fajax_form").live('submit', function(event){

            $.post($(this).attr("action"), $(this).serialize(), function(data) {
                if(data.status) {
                    $("#module").html('<div style="text-align:center;margin-top:60px;"><img src="'+xmlLoaderImage+'"></div>');
                    setTimeout('removeBO(false)', 800);
                } else {
                    $("#module").html(data.html);
                    //alert('Debugging #2!');
                    for(var v in data.errors) {
                        displayInputError("#"+v, data.errors[v]);
                    }
                }
            });

            event.preventDefault();
          });
    });
}
function blackOutModule(module) {
    $(BO).remove();
    $('#content-body').append('<div id="blackout"><div id="module"></div></div>');
    $("#module").html('<a href="#" class="close">Close</a><div style="text-align:center;margin-top:60px;"><img src="'+xmlLoaderImage+'"></div>');
    setTimeout(module, 500);
    
    $(".close").live('click', function() {
        removeBO(false);
        return false;
    });
}
function removeBO(r) {
    $(BO).fadeOut(300, function() {
            $(this).remove();
           if(r) window.location.reload(true);
           //alert(window.location);
    });
}
function setModuleError(msg) {
    if(msg != undefined) {
        $("#module").parent().find('p.error').remove();
        $("#module h1").after('<p class="error">'+msg+'</p>');
    }
}
function getLoginModule() {
    $("#module").load('/ajax/module #login_form', function() {
        $('input#login_username').focus();
        $("#login_form").die("submit");
        $("#login_form").live('submit', function(event){
            
            $.post($(this).attr("action"), $(this).serialize(), function(data) {
                if(data.status) {
                    
                    $("#module").html('<div style="text-align:center;margin-top:60px;"><img src="'+xmlLoaderImage+'"></div>');
                    setTimeout('removeBO("true")', 800);
                } else {
                    for(var v in data) {
                        if(v != 'status') {
                            displayInputError("#"+v, data[v]);
                        }
                    }
                }
            });

            event.preventDefault();
        });

        $(".register_link").live('click', function() {
            blackOutModule('getRegisterModule("#register_form")');
            return false;
        });
    });
}
function getRegisterModule() {
    $("#module").load('/ajax/module #register_form', function() {
        $('input#register_username').focus();
        
        $("#register_form").die("submit");
        $("#register_form").live('submit', function(event){
            $.post($(this).attr("action"), $(this).serialize(), function(data) {
                if(data.status) {
                    $("#register_form").html('<h1>Success!</h1><p>Your account has been created. Please click <a href="#" class="login_link">here</a> to login.</p>');
                } else {
                    for(var v in data) {
                        if(v != 'status') {
                            displayInputError("#"+v, data[v]);
                        }
                    }
                }
            });
            event.preventDefault();
        });

        $(".login_link").live('click', function() {
            blackOutModule('getLoginModule("#login_form")');
            return false;
        });
    });
}
function displayInputError(field, message) {
    field = BO+" "+field;
    $(field).parent().find('span.error').remove();
    /*if(message != '') {
        $(field).addClass('error')
        $(field).parent().append('<span class="error">'+message+'<span>');
        return false;
    } else {
        $(field).removeClass('error').parent().remove('.error');
        return true;
    }*/
    if(message != '') {
        $(field).addClass('error').parent().append('<span class="error">'+message+'</span>');
        return false;
    } else {
        $(field).removeClass('error').parent().remove('.error');
        return true;
    }
}

function setBubbleCounter() {
    counter = false;
    //alert(counter);
}
function addBookmark(e) {
    //e.preventDefault(); // this will prevent the anchor tag from going the user off to the link
    var bookmarkUrl = e.href;
    var bookmarkTitle = e.title;

    if (window.sidebar) { // For Mozilla Firefox Bookmark
            window.sidebar.addPanel(bookmarkTitle, bookmarkUrl,"");
    } else if( window.external || document.all) { // For IE Favorite
            window.external.AddFavorite( bookmarkUrl, bookmarkTitle);
    } else if(window.opera) { // For Opera Browsers
            $("a.jQueryBookmark").attr("href",bookmarkUrl);
            $("a.jQueryBookmark").attr("title",bookmarkTitle);
            $("a.jQueryBookmark").attr("rel","sidebar");
    } else { // for other browsers which does not support
             alert('Your browser does not support this bookmark action');
             return false;
    }
    return false;
}
function hideBubble() {
    if(tooltip_bub === false && tooltip_link === false) {
        $("#main-bubble").stop().fadeOut(300);
        //$("#main-bubble .content").hide();
        //counter = 0;
    }
}
function statusChange() {
    var cont = $("#statusChange input");
    //$(cont).focus( function() {
        if($(cont).val() == "What's on your mind?")
        $(cont).val("");
    //});
    $(cont).blur(function () {
        if($(cont).val().length == 0)
        $(cont).val("What's on your mind?");
    });
}
function submitForm(tar) {
    $("#"+tar).submit();
}
function clickGenre(g,k) {
    var id = "#genres_"+k;
    //$(id).remove();
    var c = $(g).attr('class');
    if(c == 'either') {
        $(g).removeClass(c).addClass('include');
        $(id).val(1);
    } else if(c == 'include') {
        $(g).removeClass(c).addClass('exclude');
        $(id).val(2);
    } else {
        $(g).removeClass(c).addClass('either');
        $(id).val(0);
    }
}
var lastcmt = 0;

function commentReply(e) {
    var cmt = "#"+$(e).closest("li").attr("id");
    if(lastcmt != cmt) {
        $(lastcmt+" .reply-box").slideUp('fast');
        lastcmt = cmt;
    }
    if($(cmt+" .reply-box").is(':empty')) {
        $("#comments_form").clone().hide().appendTo(cmt+" .reply-box").slideDown('fast', function() {
            $(".comment_text",this).focus();
            $(".cid",this).val(cmt.split('-',2).pop());
        });
    } else {
        $(cmt+" .reply-box").slideToggle('fast', function() {
            $(".comment_text",this).focus();
        });
    }

    return false;
}
function removeComment(e) {
    var cid = $(e).closest("li").attr("id").split('-', 2).pop();
    if(confirm("Are you sure?")) {
        $.post("/ajax/CAPIremove10", {cid:cid}, function(data) {
            $("#commentid-"+cid).fadeOut('normal');
            if(data) alert('ERROR: Deleting comment');
        });
    }
    return false;
}
var x = 0;
function togCommentBox(e) {
    $("#comment-bottom").toggle('fast');
    $("#comments_form_container").animate({
        'opacity' : 'toggle',
        'height' : 'toggle'
    }, 200);
    /*if(x == 0) {
        $("#comment-bottom").hide('fast');
        $("#comments_form_container").slideDown('fast', function() {
            $("#comments_form_container .comment_text").focus();
        });
        x = 1;
    } else {
        $("#comment-bottom").show('fast');
        $("#comments_form_container").slideUp('fast');
        x = 0;
    }
    */
}
function gotoUrl(url) {
    window.location.href=url;
}
var t64 = "/ajax/FAPIt64";
var s64 = "/ajax/s64";
var topicOptionsDisplay = 0;

function topicOptions(topicid,status,locked,gMod)
{
    //$("#topicOptions").html('<img src="'+xmlLoaderImage+'">');
    var cont = ".topicOptions .dropdown";
    if(gMod == '1') t64 = '/ajax/FAPIt64g';
     $.post(t64, {topicid:topicid,status:status,locked:locked,gMod:gMod}, function(data) {
        $(cont).html(data).fadeIn();
    });

    $(cont).live('mouseleave', function() {
        $(this).fadeOut();
    })
}
function getRec(pid)
{
    var cont = "#rec"+pid;
    if($(cont).is(":empty")) {
        $.ajax({
            type: 'POST',
            url: '/ajax/getRec',
            data: 'pid='+pid,
            success: function(data){
                $(cont).html(data);
            }
        });
    } else {
        $(cont).toggle();
    }
    return false;
}
function topicSubscribe(topicid)
{
    var cont = "#topicSubscribe";
    $(cont).html('<img src="'+xmlLoaderImage+'">');
    $.post(s64, {topicid:topicid}, function(data) {
        if(data == 'subscribed')
            $(cont).html('Unsubscribe');
        else 
            $(cont).html('Subscribe');
    });
}
function verify(txt) {
    var txty = 'Are you sure you want to ';
    var txtx = txty+'change this topic to a ';
    switch(txt) {
        case 'deletepost':
            txt = txty+'delete this post?';
            break;
        case 'delete':
            txt = txty+'delete this topic?';
            break;
        case 'unlock':
            txt = txty+'unlock this topic?';
            break;
        case 'lock':
            txt = txty+'lock this topic?';
            break;
        case 0:
            txt = txtx+'"Standard Topic"?';
            break;
        case 1:
            txt = txtx+'"Sticky"?';
            break;
        case 2:
            txt = txtx+'"Announcement"?';
            break;
        case 3:
            txt = txtx+'"Global Announcement"?';
            break;
    }
    if(confirm(txt) == false) {
        return false;
    }
    return true;
}
function disablesubmit() {
    $('.submit').attr("disabled","disabled");    
}

function findForum() {
    
    var cont = "#result";
    var val = $("#fsearch").val();
    if(val.length > 2) {
        $(cont).html('<img src="'+xmlLoaderImage+'">');
        $.post('/ajax/f32', {search:val}, function(data) {
            $(cont).html(data);
        });
    }
}
function selForum(id,name) {
    $("#selected").html('<a href="javascript:removeForum();">'+name+'</a><input type="hidden" value="'+id+'" name="move_forum_id">');
}
function removeForum() {
    $("#selected").html('None');
}
function showHidden(val,x) {
    $('#'+val).slideDown('fast', function () {
        $(x).fadeOut(150);
    });
    return false;
}
function submitEditMembers() {
    var action = $('#member_action').val();

    if(action == 'remove') {
        if (confirm('Are you sure?')) { 
            $('#editoption').val('APIGroup_Remove');
        }
    } else if(action == 'ban') {
        if (confirm('Are you sure?')) { 
            $('#editoption').val('APIGroup_Ban');
        }
    } else {
        var option = action.split(':');
        if(option[0] == 'change') {
            $('#editoption').val('APIGroup_Change');
            $('#change_position').val(option[1]);
        }
    }
    $('#member-form').submit();
}
function SAPIcover(msg) {
    $("#image").html('<img src="'+xmlLoaderImage+'">');
    $.ajax({
        type: 'POST',
        url: '/ajax/SAPIcover',
        data: 'api_pid='+msg,
        success: function(data){
            $("#image").hide().html(data).fadeIn('fast');
        }
    });
    //alert(msg);
}
function addTag() {
    var x = $(".tags-list > span").size()+1;
    var tag = $("#tags").val().replace(/(<([^>]+)>)/ig,"");
    $("#tags").val('');
    var search = '/'+tag+'/i';
    if(tag) {
        if(tag.length < 3) {
            alert("The tag must be at least 3 characters in length.");
        } else if(tag.length > 40) {
            alert('The tag must be under 50 characters in length');
        } else {
            var list = $(".tags-list");
            var listHTML = list.html();
            var insertTag = '<span id="tag-'+x+'" onclick="removeTag(this);" class="tag-icon frb"></span>';
            if(listHTML.search('>'+tag+'<') < 0) {
                    list.append(insertTag);
                    $(".tags-list span").last().hide().append(tag).fadeIn();
                    $("#tags-container").append('<input type="hidden" value="" name="tags[]" id="tag-'+x+'c"/>');
                    $("#tag-"+x+"c").val(tag);
            }else {
                alert('Cannot add the same tag twice.')
            }
        }
    } else {
        alert('The tag field cannot be empty.');
    }
    return false;
}
function addTagByKey(e) {
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13) {
          addTag();
          return false;
     }
     else
          return true;
}
function removeTag(x) {
    $(x).fadeOut( function(){
        $(this).remove();
        var tagID = $(this).attr('id');
        $("#"+tagID+"c").remove();
    });
}
function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}
function likes(x) {
    var API_PID = $(x).attr("id");
    $.ajax({
        type: 'POST',
        url: '/ajax/APIlikes',
        data: 'api_pid='+API_PID,
        success: function(data){
            if(data.status == true) {
                var val = parseInt($(".like-count span").text())+1;
                $(".like-count span").text(val);
            }

            $(x).children().hide().text('Liked').fadeIn(300);
        }
    });
    return false;
}
function searchSeriesTitlesInput(e) {
    var key;
    if(window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if(key == 13) {
        searchSeriesTitles();
        //alert(1);
        return false;
    }
    else
        return true;

}
function searchSeriesTitles() {
    var title = $(".findTile").val();
    $("#searchResult").show();
    if(title.length > 2) {
        $("#searchResult .content").html('<img src="'+xmlLoaderImage+'">');
        $.ajax({
            type: 'POST',
            url: '/ajax/API_FST',
            data: 'api_query='+title,
            success: function(data){
                //$("#searchResult").html('<img src="'+xmlLoaderImage+'">');
                $("#searchResult .content").html(data.search_result);
            },
            error: function() {
                $("#searchResult .content").html("Error: Please contact Administrator");
            }
        });
    } else {
        $("#searchResult .content").html("The search must be at least 3 characters in length.");
    }
}
function hideMe(h) {
    $(h).hide();
}
function removeDiv(id) {
    $("#"+id).remove();
}

function checkNames() {
    var fname = $("#fname").val();
    var lname = $("#lname").val();

    $("#charSimilarResults").show();
    if(fname.length > 1 || lname.length > 1) {
        $("#charSimilarResults .content").html('<img src="'+xmlLoaderImage+'">');
        $.ajax({
            type: 'POST',
            url: '/ajax/API_FSC',
            data: 'api_fquery='+fname+'&api_lquery='+lname,
            success: function(data){
                //$("#searchResult").html('<img src="'+xmlLoaderImage+'">');
                $("#charSimilarResults .content").html(data.search_result);
            },
            error: function() {
                $("#charSimilarResults .content").html("Error: Please contact Administrator");
            }
        });
    } else {
        $("#charSimilarResults .content").html("The search must be at least 2 characters in length.");
    }
}
function submitForm() {
    $("#submit_form").submit();
    //alert(1);
}
