$(document).ready(function() {

    /***
    * General 
    ***/

    // Demo Stuff

    if ($.cookie("theme-show") == "hidden") {

        $("#demo").css({
            left: "-162px"
        });

        $("a.demo-hide").text("Show");
    }

    $(".themes a").click(function() {
        switchStylestyle(this.getAttribute("rel"));
        $.cookie("theme", this.getAttribute("rel"));
        return false;
    });

    if ($.cookie("theme")) {
        switchStylestyle($.cookie("theme"));
    }

    $(".cookie-clear").click(function() {
        $.cookie("theme", null);
        $.cookie("welcome", null);
        return false;
    });

    function switchStylestyle(styleName) {
        $("link[rel*=style][title]").each(function() {
            this.disabled = true;
            if (this.getAttribute("title") == "green") {
                this.disabled = false;
            } else if (this.getAttribute("title") == styleName) {
                this.disabled = false;
            }
        });
    }

    $("a.demo-hide").toggle(function() {
        $(this).text("Show");

        $("#demo").animate({
            left: "-162px"
        }, 200);

        $.cookie("theme-show", "hidden");

        return false;
    }, function() {
        $(this).text("Hide");

        $("#demo").animate({
            left: "0"
        }, 200);

        $.cookie("theme-show", "visible");

        return false;
    });



    //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 gw1 = new Date("August 14, 2010 15:00:00 GMT+" + offset);
    var gw2 = new Date("January 6, 2011 00:00:00 GMT+" + offset);
    var end = new Date("May 23, 2011 00:00:00 GMT+" + offset);


    if (gw1 > today) {
        var header = "Countdown to Kick-off";
        var date = gw1;
        var exp = "The season starts in:"
    } else if (gw2 > today) {
        var header = "Game Phases";
        var date = gw2;
        var exp = "Game Phases 1 Open, closes in:";
    } else {
        var header = "Game Phases";
        var date = end;
        var exp = "Game Phases 2 Open, closes 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 });
    });


    $("#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") {

        $("#slider").jcarousel({
            scroll: 1,
            visible: 1,
            wrap: "circular",
            auto: 8,
            animation: 500,
            itemVisibleInCallback: { onBeforeAnimation: mycarousel_itemVisibleInCallback },
            itemVisibleOutCallback: { onAfterAnimation: mycarousel_itemVisibleOutCallback },
            buttonNextHTML: '<a href="#" class="next">Next</a>',
            buttonPrevHTML: null
        });

        $(".next").click(function() {
            return false;
        });
    

        $('ul.images-list').kwicks({ max: 300, spacing: 10, sticky: true, duration: 200, easing: 'easeOutQuad' });

        $('ul.images-list li.prizes a').click(function() {
            window.location.href= "Playerlist.aspx";
            return true;
        });

        $('ul.images-list li.stats a').click(function() {
            window.location.href = "Article.aspx?id=503";
            return true;
        });

        $('ul.images-list li.teamscreen a').click(function() {
            window.location.href = "Article.aspx?id=201";
            return true;
        });
    }
    else if ($("body").attr("id") == "ResultsAndFixtures") {

        $("#ResultsAndFixtures table.tabbed").each(function() {
            $(this).find("tr:first").addClass("head");
        });

        $("#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 Mates 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 Mate</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
        $("#Team a.twitter").attr("href", "http://twitter.com/home?status=This week I scored " + roundpoints + " points on " + location.protocol + "//" + location.host);

        // Facebook Connect Show Points        
        $("#share_container a.facebook").click(function() {
            var message = "This week I scored: " + roundpoints + " points on Match Fantasy Footy";
            var actionLinks = [{ "text": "Match Fantasy Footy", "href": "http://match.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       
        $("#share_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 Match Fantasy Footy team is: " + team + "what's yours?";
            var actionLinks = [{ "text": "Match Fantasy Footy", "href": "http://match.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;
        });
        
    }
    // End Doc.Rdy
});


var mycarousel_itemList = [
    { url: 'http://imageseasynet.fantasyleague.com/fast/prem.1011/licensed/match/images/intro1.jpg', link: 'Register.aspx', target: '_self' },
    { url: 'http://imageseasynet.fantasyleague.com/fast/prem.1011/licensed/match/images/intro2.jpg', link: 'Article.aspx?id=117', target: '_self' },
    { url: 'http://imageseasynet.fantasyleague.com/fast/prem.1011/licensed/match/images/intro3.jpg', link: 'Article.aspx?id=201', target: '_self' },
    { url: 'http://imageseasynet.fantasyleague.com/fast/prem.1011/licensed/match/images/intro4.jpg', link: 'http://www.easports.co.uk/fifa', target: '_blank' }
];

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
};

function mycarousel_getItemHTML(item) {
    return '<a target="' + item.target + '" href="' + item.link + '"><img src="' + item.url + '" /></a>';

};
