$(document).ready(function() {

    /***
    * General 
    ***/

    //Menu Highlighting!
    var body = $("body").attr("id");
    $("#topMenu li#tab_" + body).addClass("tab-cur");
    $("#navigation 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() {
        $('ul', this).show();
        $(this).addClass('hover');
    }, function() {
        $('ul', 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 offset = (new Date().getTimezoneOffset() / 60) * -1;

    var pre = new Date("August 14, 2010 12:45:00 GMT+" + offset);
    var gp1 = new Date("August 31, 2010 23:59:59 GMT+" + offset);
    var gp2 = new Date("September 30, 2010 23:59:59 GMT+" + offset);
    var gp3 = new Date("October 31, 2010 23:59:59 GMT+" + offset);
    var gp4 = new Date("November 30, 2010 23:59:59 GMT+" + offset);
    var gp5 = new Date("December 31, 2010 23:59:59 GMT+" + offset);
    var gp6 = new Date("January 31, 2011 23:59:59 GMT+" + offset);
    var gp7 = new Date("February 28, 2011 23:59:59 GMT+" + offset);
    var gp8 = new Date("March 31, 2011 23:59:59 GMT+" + offset);
    var gp9 = new Date("April 30, 2011 23:59:59 GMT+" + offset);
    var end = new Date("May 23, 2011 00:00:00 GMT+" + offset);


    if (pre > today) {
        var header = "Countdown to Kick-off";
        var date = pre;
        var exp = "The season starts in:"
    } else if (gp1 > today) {
        var header = "Game Phases";
        var date = gp1;
        var exp = "Game Months, Game Month 1:";
    } else if (gp2 > today) {
        var header = "Game Phases";
        var date = gp2;
        var exp = "Game Months, Game Month 2:";
    } else if (gp3 > today) {
        var header = "Game Phases";
        var date = gp3;
        var exp = "Game Months, Game Month 3:";
    } else if (gp4 > today) {
        var header = "Game Phases";
        var date = gp4;
        var exp = "Game Months, Game Month 4:";
    } else if (gp5 > today) {
        var header = "Game Phases";
        var date = gp5;
        var exp = "Game Months, Game Month 5:";
    } else if (gp6 > today) {
        var header = "Game Phases";
        var date = gp6;
        var exp = "Game Months, Game Month 6:";
    } else if (gp7 > today) {
        var header = "Game Phases";
        var date = gp7;
        var exp = "Game Months, Game Month 7:";
    } else if (gp8 > today) {
        var header = "Game Phases";
        var date = gp8;
        var exp = "Game Months, Game Month 8:";
    } else if (gp9 > today) {
        var header = "Game Phases";
        var date = gp9;
        var exp = "Game Months, Game Month 9:";
    } else {
        var header = "Game Phases";
        var date = end;
        var exp = "Game Months, Game Month 10:";
    }

    $("#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 });
    });



    /***
    * Homepage 
    ***/

    if ($("body").attr("id") == "Index") {

        //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: "210px",
                marginTop: "-30px",
                marginLeft: "-30px",
                zIndex: "20"
            }).find("a").css({
                bottom: "10px"
            });
        }, function() {
            $(this).stop().css({
                width: "175px",
                height: "150px",
                marginTop: "0",
                marginLeft: "0"
            }).find("a").css({
                bottom: "-150px"
            });
        });
    }
    /***
    * Results and Fixtures 
    ***/

    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 li div").attr("class", "flag flag_" + thisnation1);
            $(this).find("td.end li div").attr("class", "flag flag_" + thisnation2);

        });

        $("#ResultsAndFixtures table.tabbed tr:nth-child(3)").each(function() {
            $(this).remove();
        });

    }
    
    
    /***
    * Team 
    ***/

    else if ($("body").attr("id") == "Team") {



        var preseason = false;



        if (preseason) {



            $("#welcome p").remove();

            $("#welcome b.welcome-user").text($("#rhs #navigation h2").text());

            $("#welcome").append("<p>If you haven't joined or created a Private League yet, <a href='FriendsLeague.aspx?mode=new'>click here to do so</a>, and then head straight to the <a href='Challenge.aspx'>Challenge A Friend</a> page to get all of your mates involved</p>");



            var IsOwner = $(".IsOwnerTrue").length;

            var thisTeamId = window.location.search.split("&")[0].split("=")[1];

            var weekpoints = parseInt($("#team_screen_week .total").text());



            // Check to see if owner

            if (IsOwner == 1) {

                // If owner, check for this team's cookie exists

                if ($.cookie(thisTeamId) == null) {

                    $("#welcome-container").show();

                } else {

                    // if the cookie is out of date

                    if ($.cookie(thisTeamId) !== weekpoints.toString()) {

                        $("#welcome-container").show();

                    }

                }

            }



        } else {



            // Welcome

            var IsOwner = $(".IsOwnerTrue").length;

            var thisTeamId = window.location.search.split("&")[0].split("=")[1];

            var weekpoints = parseInt($("#team_screen_week .total").text());
			
			var overallpoints = parseInt($("#team_screen_total .total").text());

            var statement = "";

            var worst = null;

            var best = null;

            var worstplayer = "";

            var bestplayer = "";


			if (weekpoints > 0 && weekpoints <= 20) {

                statement = "not great.";

            } else if (weekpoints <= 50) {

                statement = "good job!";

            } else {

                statement = "that's amazing!"

            }



            // Check to see if owner

            if (IsOwner == 1) {

                // If owner, check for this team's cookie exists

                if ($.cookie(thisTeamId) == null) {

                    $("#welcome-container").show();

                } else {

                    // if the cookie is out of date

                    if ($.cookie(thisTeamId) !== weekpoints.toString() && weekpoints != 0) {

                        $("#welcome-container").show();

                    }

                }

            }

			// Find worst scoring player
			
			$("#content table.tabbed.cols.teamlist.teamBreakdown tr td.played").each(function() {

                var _thisPlayed = parseInt($(this).text());
				var _points = $(this).parent().children("td.total").text();
				
				if (_thisPlayed > 2)
				{
					var average = _points / _thisPlayed;

					if (average > best || best == null) {

						best = Math.round(average);

						bestplayer = $(this).parent().children("td.name").text();

						bestplayer = bestplayer.substr(bestplayer.indexOf(" ") + 1, (bestplayer.length) - bestplayer.indexOf(" "));

					}

					if (average <= worst || worst == null) {

						worst = Math.round(average);

						worstplayer = $(this).parent().children("td.name").text();

						worstplayer = worstplayer.substr(worstplayer.indexOf(" ") + 1, (worstplayer.length) - worstplayer.indexOf(" "));

					}
				}
            });

			var fullName = $("#rhs #navigation h2").text();
			var nameSplitIndex = fullName.indexOf(" ");
			var firstName = fullName.substr(0, nameSplitIndex);
			
            $("#welcome b.welcome-user").text(firstName);

            $("#welcome b.welcome-total").text(weekpoints);

            $("#welcome b.welcome-statement").text(statement);

            $("#welcome b.welcome-bp").text(bestplayer);

            $("#welcome b.welcome-wp").text(worstplayer);

            $("#welcome b.welcome-bp-total").text(best);
			
			$("#welcome b.welcome-wp-total").text(worst);
        }

        $("#welcome a.welcome-close").click(function() {
            $("#welcome-container").fadeOut(200, "easeOutQuad", function() {
                $(this).remove();
            });

            $.cookie(thisTeamId, weekpoints, { expires: 10 });
            return false;
        });

        // 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");

            var _this = $(this).find("td.club").text();
            $(this).find("td.club").html("<span class='flag flag_" + _this + "'>" + _this + "</span>");

        });

        // Share to twitter
        $("#share_container ul li a.twitter").attr("href", "http://twitter.com/home?status=This week I scored " + roundpoints + " points on " + location.protocol + "//" + location.host);

        // Facebook Connect Show Points
        $("#button_container a.facebook").click(function() {
            var message = "This week I scored: " + roundpoints + " points on Elephant Fantasy Footie";
            var actionLinks = [{ "text": "Elephant Fantasy Footie", "href": "http://elephant.fantasyleague.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;
        });

        // Facebook Connect Show Team
        $("#button_container a.facebookteam").click(function() {
            var team = "";

            $("#team_screen_container #team_screen_status li a").each(function() {
                team += $(this).text().replace(/\s+$/, '');
                team += ", ";
            });

            var teammessage = "My Elephant Fantasy Footie team is: " + team + "what's yours?";
            var actionLinks = [{ "text": "Elephant Fantasy Footie", "href": "http://elephant.fantasyleague.com"}];

            FB.ensureInit(function() {
                FB.Connect.showPermissionDialog("offline_access, publish_stream", function(perms) {
                    if (!perms) {
                        return false;
                    } else {
                        FB.Connect.streamPublish(teammessage, null, actionLinks);
                    }
                });
            });
            return false;
        });        
    }

    if (/msie|MSIE 6/.test(navigator.userAgent)) {
        DD_belatedPNG.fix('a.button, h3#signup, h3#signup a, span.countdown_section, img.arrow, #team_screen_container li, #team_buttons li.on a, #team_screen_container .total, #team_screen_container .total div, #select ul.tabs li.on, #select fieldset, #select .teamInfo fieldset, #select .remove');
    }

    // End Doc.Rdy
});



