var _thisIndex = "";

function mycarousel_initCallback(carousel) {
    $('.jcarousel-control a').bind('click', function() {
        _thisIndex = $.jcarousel.intval($(this).attr("rel"));
        carousel.scroll(_thisIndex); 
        return false;
     });  
}   

function mycarousel_itemFirstOutCallback() {
    $(".jcarousel-control dt").removeClass("on");
    $(".jcarousel-control a[rel='"+_thisIndex+"']").parent().addClass("on");
}

function mycarousel_itemVisibleInCallback(carousel, object, index) {
    _thisIndex = index;
    $(".jcarousel-control dt").removeClass("on");
    $(".jcarousel-control a[rel='"+_thisIndex+"']").parent().addClass("on");
}

$(document).ready(function() {

    /***
    * General 
    ***/

    //Menu Highlighting!
    var body = $("body").attr("id");
    $("#topMenu li#tab_" + body).addClass("tab-cur");
    $("#logged ul li#tab_" + body).addClass("on");

    // Table Hover
    // Add tr hover class for ie6+
    $("table.tabbed tbody tr").hover(function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });

    $("table tbody tr").each(function() {
        $(this).find("td:first:not(.first)").addClass("first");
        $(this).find("td:last:not(.end)").addClass("end");
    });
    $("table thead tr, table tr.head").each(function() {
        $(this).find("th:first:not(.first)").addClass("first");
        $(this).find("th:last:not(.end)").addClass("end");
    });

    // Menu
    $('#topMenu li').hover(function() {
        $('div', this).show();
        $(this).addClass('hover');
    }, function() {
        $('div', this).hide();
        $(this).removeClass('hover');
    });

    // Forms & Labels
    // Hide overlay on focus
    $("input.text").focus(function() {
        $(this).prev("label.overlay").hide();
    });

    // Show overlay on blur
    $("input.text").blur(function() {
        if ($(this).attr("value") == "") {
            $(this).prev("label.overlay").show();
        }
    });

    // Focus input on overlay click ;)
    $("label.overlay").click(function() {
        $(this).next().focus();
    });

    // Hide if input box filled
    $("input.text").each(function() {
        if ($(this).attr("value") !== "")
            $(this).prev("label.overlay").hide();
    });

    // Feeds / Twitter
    $("#newsFeeds ul.tabs a").click(function() {
        $("#newsFeeds ul.tabs li").removeClass("on");
        $(this).parent().addClass("on");
        $("#twitter_div, #news_div").hide();
        $("#" + $(this).attr("id") + "_div").show();
        return false;
    });

    // Countdown Timer
    var today = new Date();

    var gp1 = new Date("June 11, 2010 15:00:00");
    var gp2 = new Date("June 26, 2010 00:00:00");
    var end = new Date("July 12, 2010 00:00:00");

    if (gp1 > today) {
        var header = "Countdown to Kickoff";
        var date = gp1;
        var exp = "The game starts in:"
    } else if (gp2 > today) {
        var header = "Game Periods";
        var date = gp2;
        var exp = "Game Period 2 starts in:";
    } else {
        var header = "Game Periods";
        var date = end;
        var exp = "Game ends in:";
    }

    $("#counter h2").text(header);
    $("#counter p").html(exp);

    $('#defaultCountdown').countdown({ until: date });
    $('#removeCountdown').toggle(function() {
        $('#defaultCountdown').countdown('destroy');
    }, function() {
        $('#defaultCountdown').countdown({ until: date, compact: true });
    });

    //Feed using Google API, limited to most recent 4
    $.jGFeed('http://www.skysports.com/rss/0,20514,12098,00.xml',
    function(feeds) {
        if (!feeds) {
            return false;
        }
        for (var i = 0; i < 3; i++) {
            var entry = feeds.entries[i];
            $("#news_div ul").append("<li><a href=" + entry.link + ">" + entry.title + "</a><br />" + entry.contentSnippet + "<br /><small>" + entry.publishedDate + "</small></li>");
        }
    }, 10);

    getTwitters('twitter_data', {
        id: 'skysports',
        count: 4,
        enableLinks: true,
        ignoreReplies: true,
        clearContents: true,
        template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
    });


    /***
    * Homepage 
    ***/

    if ($("body").attr("id") == "Index") {

        $("#slider").jcarousel({
            scroll: 1,
            visible: 1,
            auto: 12, /* Time (seconds) between slide */
            animation: 400,
            wrap: "last",
            initCallback: mycarousel_initCallback,
            itemFirstOutCallback: { onBeforeAnimation: mycarousel_itemFirstOutCallback },
            itemVisibleInCallback: { onAfterAnimation: mycarousel_itemVisibleInCallback },
            buttonNextHTML: null,
            buttonPrevHTML: null
        });

        // Groups

        $("#groupC, #groupD, #groupE, #groupF, #groupG, #groupH").hide();

        $("#groups a#tabAB").click(function() {
            $("#groups li").removeClass("on");
            $("#groupC, #groupD, #groupE, #groupF, #groupG, #groupH").hide();
            $("#groupA, #groupB").show();
            $(this).parent().addClass("on");
            return false;
        });

        $("#groups a#tabCD").click(function() {
            $("#groups li").removeClass("on");
            $("#groupA, #groupB, #groupE, #groupF, #groupG, #groupH").hide();
            $("#groupC, #groupD").show();
            $(this).parent().addClass("on");
            return false;
        });

        $("#groups a#tabEF").click(function() {
            $("#groups li").removeClass("on");
            $("#groupC, #groupD, #groupA, #groupB, #groupG, #groupH").hide();
            $("#groupE, #groupF").show();
            $(this).parent().addClass("on");
            return false;
        });

        $("#groups a#tabGH").click(function() {
            $("#groups li").removeClass("on");
            $("#groupC, #groupD, #groupE, #groupF, #groupA, #groupB").hide();
            $("#groupG, #groupH").show();
            $(this).parent().addClass("on");
            return false;
        });


        //Image thingy
        //$("#content ul.images li .zoom").css({ opacity: 0.6 });
        //Image thingy
        $("#content ul.images li").hover(function() {

            // Reset z-index to 10
            $("#content ul.images li").css({
                zIndex: "10"
            });

            // Animate on hover
            $(this).css({
                width: "230px",
                height: "175px",
                marginTop: "-23px",
                marginLeft: "-22px",
                zIndex: "20"
            }).find("a").css({
                bottom: "6px"
            });
        }, function() {
            $(this).stop().css({
                width: "185px",
                height: "130px",
                marginTop: "0",
                marginLeft: "0"
            }).find("a").css({
                bottom: "-150px"
            });
        });
    }

    else if ($("body").attr("id") == "new_select") {

        // Position Tabs
        $("#select #availablePos a").click(function() {
            $("#select #availablePos li").removeClass("on");
            $(this).parent().addClass("on");
            return false;
        });

    }



    /***
    * Team 
    ***/

    else if ($("body").attr("id") == "Team") {

        // Column Highlighting in 1 function + Sticky Clicking
        $("table.cols tr.head th").hover(function() {
            var _this = $(this).parent().parent();

            $(this).addClass("on");
            // Calculate Column Number
            $(_this).find("tr td:nth-child(" + (this.cellIndex + 1) + ")").addClass("on");

        }, function() {
            // Remove Highlighting
            $("table.cols tr.head th, table.cols tr td").removeClass("on");

        }).click(function() {
            var _this = $(this).parent().parent();
            // Sticky Highlighting
            $(_this).find("tr.head th, tr td").removeClass("sticky");
            $(this).addClass("sticky");
            $(_this).find("tr td:nth-child(" + (this.cellIndex + 1) + ")").addClass("sticky");
        });

        // Points
        var totalpoints = parseInt($("#team_screen_container #team_screen_total .total span").text());
        var roundpoints = parseInt($("#team_screen_container #team_screen_month .total span").text());

        $("table.key tfoot td.total").text(totalpoints);

        // Team breakdown flags & sticky
        $("table.teamsold tr, table.teamlist tr").each(function() {
            $(this).find("td:last, th:last").addClass("sticky");
            $(this).find("td.nation").addClass("flag flag_" + ($(this).find("td.nation").text()));
        });

        // Facebook Connect Show Points
        $("#button_container a.facebook").click(function() {
            var message = "This game period I scored: " + roundpoints + " points on Sky Sports Fantasy Football - South Africa";
            var actionLinks = [{ "text": "Sky Sports Fantasy Football - South Africa", "href": "http://worldfantasyfootball.skysports.com"}];

            FB.ensureInit(function() {
                FB.Connect.showPermissionDialog("offline_access, publish_stream", function(perms) {
                    if (!perms) {
                        return false;
                    } else {
                        FB.Connect.streamPublish(message, null, actionLinks);
                    }
                });
            });

            return false;
        });
    }


    else if ($("body").attr("id") == "ResultsAndFixtures") {
    
        $("#ResultsAndFixtures table.tabbed").each(function() {
            $(this).find("tr:first").addClass("head");
        });

        // Flags
        $("#ResultsAndFixtures table.tabbed tr:nth-child(2)").each(function() {
            $(this).addClass("on");
            var thisnation1 = $(this).find("td.first li div").attr("class").replace("team_", "");
            var thisnation2 = $(this).find("td.end li div").attr("class").replace("team_", "");

            $(this).find("td.first").addClass("flag flag_" + thisnation1);
            $(this).find("td.end").addClass("flag flag_" + thisnation2);

        });

        $("#ResultsAndFixtures table.tabbed tr:nth-child(3)").each(function() {
            $(this).remove();
        });

    } else if ($("body").attr("id") == "FriendsLeague") {

        // Facebook Connect Advertise
        $("#button_container a.advertise").click(function() {

            var message = "Come and join my private league on Sky Sports Fantasy Football - South Africa! The league PIN is " + window.location.search.substring(1).replace("p=", "");
            var actionLinks = [{ "text": "Sky Sports Fantasy Football - South Africa", "href": window.location}];

            FB.ensureInit(function() {
                FB.Connect.showPermissionDialog("offline_access, publish_stream", function(perms) {
                    if (!perms) {
                        return false;
                    } else {
                        FB.Connect.streamPublish(message, null, actionLinks);
                    }
                });
            });

            return false;
        });

        // Facebook Connect Reminder
        $("#button_container a.remind").click(function() {

            var message = "Come see how my league is doing on Sky Sports Fantasy Football - South Africa! " + window.location;
            var actionLinks = [{ "text": "Sky Sports Fantasy Football - South Africa", "href": window.location}];

            FB.ensureInit(function() {
                FB.Connect.showPermissionDialog("offline_access, publish_stream", function(perms) {
                    if (!perms) {
                        return false;
                    } else {
                        FB.Connect.streamPublish(message, null, actionLinks);
                    }
                });
            });

            return false;
        });
    } else if ($("body").attr("id") == "PlayerList") {

        // Flags
        $("table#playerlist tr").each(function() {
            $(this).find("td:nth-child(4)").addClass("flag flag_" + ($(this).find("td:nth-child(4)").text()));
        });

    }

    var IE6 = false/*@cc_on || @_jscript_version < 5.7@*/;
    
    if (IE6) {
        DD_belatedPNG.fix('#team_screen_container li, #team_screen_container li a, a.button, #select fieldset, #select #available, #select #selectedTop, #select ul.tabs, #select #selectedPitch .teamInfo, #select ul.tabs, #rhs #login, .countdown_section');
    }
    // End Doc.Rdy
});

