$(document).ready(function() {

    /***
    * General 
    ***/
	
			// hidding stuff function
		$('.hide').toggle( function() {
		var whatToHide = $(this).attr('href')
		$(whatToHide).hide(500)
		$(this).removeClass('open').addClass('closed')
		$(this).text('Show')
		
		}, function() {
		var whatToShow = $(this).attr('href')
		$(whatToShow).show(500)
		$(this).removeClass('closed').addClass('open')
		$(this).text('Hide')
				
		});

    //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 5, 2011 19:45:00 GMT+" + offset);
    var gw2 = new Date("September 01, 2011 00:00:00 GMT+" + offset);
    var gw3 = new Date("October 01, 2011 00:00:00 GMT+" + offset);
    var gw4 = new Date("November 01, 2011 00:00:00 GMT+" + offset);
    var gw5 = new Date("December 01, 2011 00:00:00 GMT+" + offset);
    var gw6 = new Date("January 01, 2012 00:00:00 GMT+" + offset);
    var gw7 = new Date("February 01, 2012 00:00:00 GMT+" + offset);
    var gw8 = new Date("March 01, 2012 00:00:00 GMT+" + offset);
    var gw9 = new Date("April 01, 2012 00:00:00 GMT+" + offset);
    var end = new Date("April 30, 2012 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 = "Transfer Periods";
        var date = gw2;
        var exp = "Month 1 Open, closes in:";
    } else if (gw3 > today) {
        var header = "Transfer Periods";
        var date = gw3;
        var exp = "Month 2 Open, closes in:";
    } else if (gw4 > today) {
        var header = "Transfer Periods";
        var date = gw4;
        var exp = "Month 3 Open, closes in:";
    } else if (gw5 > today) {
        var header = "Transfer Periods";
        var date = gw5;
        var exp = "Month 4 Open, closes in:";
    } else if (gw6 > today) {
        var header = "Transfer Periods";
        var date = gw6;
        var exp = "Month 5 Open, closes in:";
    } else if (gw7 > today) {
        var header = "Transfer Periods";
        var date = gw7;
        var exp = "Month 6 Open, closes in:";
    } else if (gw8 > today) {
        var header = "Transfer Periods";
        var date = gw8;
        var exp = "Month 7 Open, closes in:";
    } else if (gw9 > today) {
        var header = "Transfer Periods";
        var date = gw9;
        var exp = "Month 8 Open, closes in:";
    } else {
        var header = "Transfer Periods";
        var date = end;
        var exp = "Month 9 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") {

        $('ul.images-list').kwicks({ max: 300, spacing: 10, sticky: true, duration: 200, easing: 'easeOutQuad' });

        $('ul.images-list li a').click(function() {
            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");

            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);

} //end team screen functions



	/****************************
		Private Leagues Page
	****************************/
	
	
	    else if ($("body").attr("id") == "FriendsLeague") {
			
				//  Private Leagues positons script
				
				
				if(parseInt($('.friendsleague tr').last().find('td.first').text()) > 3 && parseInt($('.friendsleague  td.end').text()) != 0 ) {
				
				$('#league_podium').show();
				
				for(var i=0; i < 3 ; i++ ){ 
				var places = i
				
				var scores = $('.friendsleague  td.end').get(i); 
				var names = $( $(scores).prevAll()[3]).text()
				
				 $('#place' + ++places + '' ).html('<h4>' + names + '</h4> <p> Current Total:<br />' + $(scores).text() + '</p>' ) 
				
				
				};  
				
				
				var lastplace = $('.friendsleague tr:last  td.end').text(); 
				var loser = $( $('.friendsleague tr:last  td.end').prevAll()[3] ).text()
				$('#woodenspoon').html('<h4>' + loser + '</h4> <p> Gets the wooden spoon, with '  + lastplace + '. Chin up ' + loser + ' maybe next week?' )
				} 
				
		// Share to twitter Private League
        $("a.twitter").click( function() {
		
		window.open("http://twitter.com/share?text=Come%20join%20my%20Texaco%20Fantasy%20Football%20fantasy%20private%20league.%20My%20PIN%20is:%20 " + $('#pin').text() + "&amp\" ", 'name', 'height=350, width=600, titlebar=0, resizable=0, status=0, menu=0, scrollbar=0, location=0, toolbar=0');
			return false
		});
				
		}
		
				else if ($('#accordion').length >= 1 ) {
// accordion function on faq and how to play
$('#accordion a').click(function() {

	if(	$(this).parent().next().hasClass('open')) {
	
	
	$('.open').removeClass('open').addClass('hidden').prev().children().css({backgroundPosition: '-343px -367px'})

	} else {

	

	$('.open').removeClass('open').addClass('hidden').prev().children().css({backgroundPosition: '-343px -367px'})
	
	$(this).css({backgroundPosition:  '-343px -406px' })

	$(this).parent().next().removeClass('hidden').addClass('open');

	}
	})
	}	//end else if 

	
	/**********************************************************************************
	******************************  Load Facebook SDK on doc ready ********************
	**********************************************************************************/

		window.fbAsyncInit = function() {
	   FB.init({appId: '128808333821839', status: true, cookie: true, oauth: true, xfbml: true});
	};
	(function() {
	   var e = document.createElement('script');
	   e.type = 'text/javascript';
	   e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	   e.async = true;
	   document.getElementById('fb-root').appendChild(e);

	}());


/*************************************************************************************/

	
	
	
    // End Doc.Rdy
	
});



/********************************
**********************************
// facebook
*********************************
********************************/

function fbooksend() {
	var weekPoints = $('#team_screen_week .total span').text();
	
			FB.getLoginStatus(function(response) {
			    if (response.authResponse) {
							FB.ui({
								  method: 'stream.publish',
								  message: 'This week my Championship Fantasy Football team scored ' + weekPoints + ' points. How did you get on?',
								  display: 'iframe',
								  attachment: {
													name: 'Texaco Fantasy Football',
											href: '' + document.location ,
											media: [
												  {
													type: 'image',
													href: 'http://fantasy.football-league.co.uk',
													src: 'http://imageseasynet.fantasyleague.com/fast/prem.1112/licensed/texaco/images/texaco_fbook_icon.jpg'
												  }
												]
								  },
								  action_links: [
									{ text: 'Texaco Fantasy Football', href: 'http://fantasy.football-league.co.uk' }
								  ],
								  user_message_prompt: 'come take a look at my team'
								});
								
													  return false 
					  }
					  else {
						  
						  FB.login(function(response) {
						      if (response.authResponse) {
							    // user successfully logged in
							return fbooksend()
							  } else {
								// user cancelled login
							alert("User cancelled Login")
					  			} // end login if statment
	
				  }); // end FB.login()
								
			  }//end if

		})// End FB getlogin
}// end fbooksend function


/************************************************************************************/


        // Facebook Connect Show Team
        function fbooksendteam() {
            var team = "";

            $("#team_screen_container #team_screen_status li a").each(function() {
                team += $(this).text().replace(/\s+$/, '');
                team += ", ";
            });


			FB.getLoginStatus(function(response) {
			    if (response.authResponse) {
							FB.ui({
								  method: 'stream.publish',
								  message: "My Texaco Fantasy Football team for 2011/12 is: " + team + "what's yours?" ,
								  display: 'iframe',
								  attachment: {
													name: 'Texaco Fantasy Football',
											href: '' + document.location ,
											media: [
												  {
													type: 'image',
													href: 'http://fantasy.football-league.co.uk',
													src: 'http://imageseasynet.fantasyleague.com/fast/prem.1112/licensed/texaco/images/texaco_fbook_icon.jpg'
												  }
												]
								  },
								  action_links: [
									{ text: 'Texaco Fantasy Football', href: 'http://fantasy.football-league.co.uk' }
								  ],
								  user_message_prompt: 'come take a look at my team'
								});
					  return false 

					  }
					  else {
						  
						  FB.login(function(response) {
						      if (response.authResponse) {
										// user successfully logged in

							return fbooksendteam()
									  } else {

										// user cancelled login
									  }

						  });

					  return false 
								
					  }//end if
					  return false 
			})// End FB getlogin
			
        };// End fbooksendteam function


/*******************************************************************************************************************/

// send an invite to specific friends on facebook

function inviteFbook() {
	var LeaguePIN = $('#pin').text();
			
FB.getLoginStatus(function(response) {
    if (response.authResponse) {
	
	         FB.ui({ method: 'apprequests', 
			 		display: 'iframe',

            message: "Come and join my Private League on Texaco Fantasy Football! Once you've entered your team, click 'Enter New League' under the 'Private League' section, and then enter the following PIN number to join my league - " + $('#pin').text() + ". See you in there!"});
		  } else {
			   FB.login(function(response) {
				   return inviteFbook() 
			   })
		  }
})
	
	
} //end inviteFbook()

/*****************************************************************************************************************/

// send an invite to specific friends on facebook

function inviteFbookChallenge() {
	
			
FB.getLoginStatus(function(response) {
    if (response.authResponse) {
	
	         FB.ui({ method: 'apprequests', 
			 		display: 'iframe',

            message: "I'm playing Texaco Fantasy Football, come join me! http://fantasy.football-league.co.uk "});
		  } else {
			   FB.login(function(response) {
				   return inviteFbook() 
			   })
		  }
})
	
	
} //end inviteFbook()

/*****************************************************************************************************************/

function fbookSendPin() {
	var LeaguePIN = $('#pin').text();
	
			FB.getLoginStatus(function(response) {
			    if (response.authResponse) {
							FB.ui({
								  method: 'stream.publish',
								  message: 'Come join my Texaco Fantasy Football private league! click the link and enter my PIN: ' + LeaguePIN + ' See you there!',
								  display: 'iframe',
								  attachment: {
													name: 'Texaco Fantasy Football',
											href: '' + document.location ,
											media: [
												  {
													type: 'image',
													href: 'http://fantasy.football-league.co.uk',
													src: 'http://imageseasynet.fantasyleague.com/fast/prem.1112/licensed/texaco/images/texaco_fbook_icon.jpg'
												  }
												]
								  },
								  action_links: [{ text: 'Texaco Fantasy Football', href: 'http://fantasy.football-league.co.uk' }],
								  user_message_prompt: 'come take a look at my team'}); 
								  }
					  else {
						  
						  FB.login(function(response) {
						      if (response.authResponse) {
							    // user successfully logged in
							return fbooksend()
							  } else {
								// user cancelled login
							alert("User cancelled Login")
					  			} // end login if statment
	
				  }); // end FB.login()
								
			  }//end if

		})// End FB getlogin
}// end fbooksend function


/************************************************************************************/





