var competitionInfoText = "<p>And so, we come to the end of the SEAP competition. For the final time, we're awarding the prizes, and the winners list is now online here. Congratulations to melvin_gualberto2009 on winning the Nokia N8 grand prize!</p><p>Thanks to everyone for playing... it's been awesome, and we're gonna have more cool stuff for you guys soon!</p>";

var roachCompetitionInfoText = "<img src = \"images/roachmadness_main.png\"/><h2>THAT'S A WRAP</h2><p>Competition was fierce, but we finally have our last set of winners from Week 4 of Roach Madness! Like the others, they'll be receiving a C3, an X3, and some sweet Barking Seed loot.</p><p>Thanks to everyone who played, and a big Happy New Year from Barking Seed! And of course, as always keep a lookout for further Barking Seed competitions coming your way next year... :)</p>" + 
"<h2>Winners Week 1</h2>" + 
"<div class='user_row'><small><a href = '#arena_game_3' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH AFRICA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_18230'><img src = 'images/avatars/playerpics25.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/MY.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_18230'>Weim IV</a>" +
        "</small>" +		
    "</div>" +
"</div>" +
"</div>" +
"<div class='user_row'><small><a href = '#arena_game_13' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH EAST ASIA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_17634'><img src = 'images/avatars/playerpics42.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/ID.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_17634'>sangunsyah</a>" +
        "</small>" +
    "</div>" +
"</div>" +
"</div>" +
"<h2>Winners Week 2</h2>" + 
"<div class='user_row'><small><a href = '#arena_game_3' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH AFRICA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_14232'><img src = 'images/avatars/playerpics20.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/PH.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_14232'>jp07_sodium</a>" +
        "</small>" +		
    "</div>" +
"</div>" +
"</div>" +
"<div class='user_row'><small><a href = '#arena_game_13' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH EAST ASIA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_55059'><img src = 'images/avatars/playerpics10.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/ID.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_55059'>jimii_luvsnsd</a>" +
        "</small>" +
    "</div>" +
"</div>" +
"</div>" + 
"<h2>Winners Week 3</h2>" + 
"<div class='user_row'><small><a href = '#arena_game_3' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH AFRICA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_55764'><img src = 'images/avatars/playerpics8.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/MY.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_55764'>Weiloon95</a>" +
        "</small>" +		
    "</div>" +
"</div>" +
"</div>" +
"<div class='user_row'><small><a href = '#arena_game_13' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH EAST ASIA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_7154'><img src = 'images/avatars/playerpics6.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/ID.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_7154'>RONNY GIROTH</a>" +
        "</small>" +
    "</div>" +
"</div>" +
"</div>" + 
"<h2>Winners Week 4</h2>" + 
"<div class='user_row'><small><a href = '#arena_game_3' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH AFRICA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_56031'><img src = 'images/avatars/playerpics3.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/PH.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_56031'>08gab22</a>" +
        "</small>" +		
    "</div>" +
"</div>" +
"</div>" +
"<div class='user_row'><small><a href = '#arena_game_13' class = 'game_name page_link' style='text-transform:uppercase;'>THAT ROACH GAME SOUTH EAST ASIA</a></small>" +
"<div class='user_row_holder'>" +
    "<div class='user_row_image'>" +
      "<a href='#arena_stats_55080'><img src = 'images/avatars/playerpics28.png' class = 'score_image' width='35' height='35' border='2'></a>" +
    "</div>" +
    "<div class='user_row_content'>" +
        "<small>" +
        "<img src = 'images/flags/MY.gif' class = 'score_countryFlag' align='left' width='15' height='8' style='padding-top:2px;'>" +
        "<a class = 'score_name page_link' style='text-transform:uppercase;' href = '#arena_stats_55080'>Mahathir95</a>" +
        "</small>" +
    "</div>" +
"</div>" +
"</div>";


var thaiCompetitionInfoText = "<p>Welcome to the MASTER OF GAMES Competition, brought to you by Nokia Thailand and Barking Seed!</p><p>That's right! For the next month and a half (the competition runs from August 1st to September 20th), we have a special competition open to all our players in Thailand, with lots of great prizes up for grabs.</p><p>5 Nokia 5530XpressMusic phones, and 6 Nokia 5130 XpressMusic are going to go to the lucky winners!<p>There are two different ways to win these excellent prizes: players finishing in first place in any one of the five supported games at the end of the competition will win a Nokia 5530XpressMusic, and the player with the most scores submitted each week starting on the 13th will win a Nokia 5130 XpressMusic.</p><p><a href = \"#info_thailand\">Click here</a> to see detailed competition information including the terms and conditions.</p><p>We are also allowing players to have their participation count towards a school based scoreboard. If you would like your activity to count towards your school, you will need to put the code for your school in the front of your username. <a href = \"#info_thailandSchools\">Click here</a> to see more information and the code for each school.</p><p>You can also send email to <a href = 'mailto:masterofgame@ovi.com'>masterofgame@ovi.com</a> with questions about this competition.</p>";

var thaiCompetitionInfoTextThai = "<p>ยินดีต้อนรับเหล่าเกมเมอร์กับกิจกรรมการแข่งขันเกมส์ครั้งยิ่งใหญ่ Master of Games จากโนเกีย (ประเทศไทย) และ Barking Seed!</p><p>โดยการแข่งขันชิงความเป็นจ้าวแห่งเกมส์ในครั้งนี้เริ่มตั้งแต่วันที่ 1 สิงหาคม ถึงวันที่ 20 กันยายน 2553 เหล่าเกมเมอร์ในประเทศไทยไม่ควรพลาด ลุ้นรับของรางวัลเป็นโทรศัพท์มือถือ Nokia 5530 XpressMusic จำนวน 5 เครื่อง และ Nokia 5130 XpressMusic จำนวน 6 เครื่อง รวมทั้งหมดถึง 11 รางวัล!</p>สำหรับกติกาการตัดสินนั้นแบ่งเป็น 2 ประเภทด้วยกัน ได้แก่ ผู้ชนะที่ได้คะแนนมากที่สุดในแต่ละเกมส์จากทั้ง 5 เกมส์ที่เข้าร่วมการแข่งขัน จะได้รับรางวัลเป็นโทรศัพท์มือถือ Nokia 5530 XpressMusic หลังสิ้นสุดกิจกรรม และผู้ชนะที่มีจำนวนการส่งคะแนนเข้าร่วมการแข่งขันมากที่สุดในแต่ละสัปดาห์ เริ่มจากวันที่ 14 สิงหาคมเป็นต้นไปจะได้รับรางวัลเป็นโทรศัพท์มือถือ Nokia 5130 XpressMusic 1 เครื่อง ต่อ 1 สัปดาห์</p><p>สามารถดูรายละเอียดเกี่ยวกับการแข่งขัน และกฏเกณฑ์การร่วมรายการเพิ่มเติมได้ที่นี่ (<a href = \"#info_thailand\">คลิกที่นี่`</a>)</p><p>นอกจากจะสามารถส่งคะแนนเข้าแข่งขันระดับประเทศแล้ว ยังสามารถส่งคะแนนตามรายชื่อโรงเรียนได้อีกด้วย โดยการใส่ Code ของโรงเรียนไว้หน้า Username ของคุณ เท่านี้คุณก็สามารถช่วยโรงเรียนของคุณประกาศศักดาความเป็นจ้าวแห่งเกมส์ได้แล้ว สามารถดูรายละเอียดเกี่ยวกับการส่งคะแนนตามรายชื่อโรงเรียน และ Code ของโรงเรียนของคุณได้ที่นี่ (<a href = \"#info_thailandSchools\">คลิกที่นี่`</a>)</p><p>สำหรับข้อสงสัยเพิ่มเติมเกี่ยวกับการแข่งขันในครั้งนี้ สามารถส่งคำถามของคุณมาได้ที่อีเมล <a href = 'mailto:masterofgame@ovi.com'>masterofgame@ovi.com</a></p>";

var thaiCompetitionMostActiveText = '<img src = "images/winbanner.png"/><p>Congratulations to Callaway for being our 5th weekly winner!</p><p>You have been the most active player this last week and will be joining Foxblackart, Omxpert, Mostaaag and Akumpan in the list of Nokia 5130 XpressMusic winners!</p><p>You will be contacted soon.</p>';

var fbphotoCompetitionInfoText = '<img src = "images/fbphotobanner.png"/>' + 
"<p>This competition is global, open to everyone and happens on Facebook. All you need to do to enter is post any photo that makes you think of Barking Seed - it can be anything, a drawing, a photo of merchandise, a photo of a Barking dog, a seed... at the end of three months whoever has the most likes on their photo will win a Creative D100 bluetooth speaker!</p>"+
"<p>These speakers are awesome, we have one and listen to the Ninjani soundtrack on it all the time. These speakers connect to almost any bluetooth audio device, just hook up your device over bluetooth and stream your music from your pocket!</p>"+
"<p>There will be 3 prizes for this competition, consisting of a speaker and some sweet Barking Seed swag!</p>"+
"<p>Good Luck! Full rules <a href = '#info_fbphoto'>here</a>, and our facebook page is <a href = 'http://www.facebook.com/barkingseed'>here!</a></p>";

var triviaCompetitionInfoText = '<img src = "images/triviabanner.png"/>'+
"<p>How much do you know about Barking Seed? 6 Shiny new Nokia devices (3 Nokia N8 devices, and 3 Nokia E5 devices!) are up for grabs depending on your answers, 2 each month!"+
"<p>For this competition you need to keep an eye on the shoutbox, and every time you see a question pop up asked by \"bark bot\", all you need to do is reply to the question in the shoutbox. We aren't saying how many questions there are or when a question is asked, up to you to find them! ;) The questions will be asked across all games.</p>"+
"<p>At the end of each month, whoever has the most correct answers in that month will win! The first prize each month is a Nokia N8 and Barking Seed Swag, and the 2nd Prize is an E5 and Barking seed swag. If there is a tie in the number of questions answered correctly, whoever answered quickest overall will be the final winner. The questions are based on Barking Seed and our games so make sure you have them all downloaded, you can find them all <a href = 'http://store.ovi.com/publisher/Breakdesign/'>here!</a> ;)</p>"+
"<p>This competition is only available to those in the SEAP region. Full rules can be found <a href = '#info_trivia'>here!</a></p>";

var fancyBoxDefaults = {
			'overlayOpacity'	: 0.6,
			'overlayColor'		: "#555",
			'centerOnScroll'	: true,
			'showCloseButton'	: false,
			'titleShow'         : false,
			'scrolling'			: 'no',
			'onStart'			: fbOpened,
			'onClosed'			: fbClosed
};

function fbOpened(){
	
	keyScrolling = false;
}

function fbClosed(){
	
	keyScrolling = true;
}

var keyScrolling = true;

function setupLinks(){
	
   $(".link_login_body").click(function(event){
	 $("#div_Register").hide();
	 $("#div_Login").show();
	 $("#div_Forgot").hide();	   	 
     event.preventDefault();
   });
   
   $(".link_register_body").click(function(event){
	   $("#div_Login").hide();
	   $("#div_Register").show();	
	   $("#div_Forgot").hide();	   
	   event.preventDefault();
   });   	
	
   $(".link_login_body").fancybox(fancyBoxDefaults);		
   $(".link_register_body").fancybox(fancyBoxDefaults);	
}

function setupPage(destination){

	if (destination == "arena_game_0")
		destination = "arena_games";	

	//Thailand shortcut
	if (destination == "thailand")
		destination = "competition_nokiaThailand";
	
	//Generic arena
	if (destination=="arena"){
		
		if (userId != 0)
			setupPage("arena_stats");
		else
			setupPage("arena_players");
			
		return;
	}
	
	//Cannot go to profile if not logged in
	if (destination == "arena_stats" && userId == 0) {
		
		$("#link_login").click();
		return;
	}
	
	//If it's a log out
	if (destination == "logout"){
	
		eraseCookie('sessionKey');	
		createCookie("currentPage","latestnews",1);
   		userId = 0;
		doLoginChanges();
		setupPage("latestnews");
   		return;
	}
	
	//Remember the current destination
	createCookie("currentPage",destination,1);
	
	if (destination != "arena_games"){
		
		$("#arena_games").slideUp("slow");		
	}
	
	//For competition, or arena, show arena menu
	if (destination.substr(0,5) == "arena" || destination.substr(0,11) == "competition"){
		
		$("#arena_menu").slideDown("slow");				
	} else {

		$("#arena_menu").slideUp("slow");		
	}
	
	//Hide competition menu
	if (destination != "competition"){
		
		$("#arena_competitions").slideUp("slow");	
	}
	
	//Remove all current boxes, changing scene
	eventhook.closeAllBoxes();
	
	//Move to the left and stay there
	eventhook.moveTo(0);
	eventhook.setAddMoveTo(false);	
	
	//Tell other content items inside the content div to vanish and remove itself
	$("#layout_page_content .content_wrapper").hide("slow",function(){$(this).remove();});
	
	if (destination == "latestnews"){
		
		$("#layout_page_content").hide();
		$("#layout_content_wrapper").hide();
		$("#layout_latestnews").show("slow");		
	} else if (destination == "faq" || destination == "terms" || destination == "privacy" || destination.substr(0,5) == "info_") {
		
		$("#layout_page_content").show();
		$("#layout_content_wrapper").hide();
		$("#layout_latestnews").hide();	
	} else {
		
		$("#layout_page_content").hide();
		$("#layout_content_wrapper").show("slow");
		$("#layout_latestnews").hide();	
	}
	
	if (destination == "profile"){
		
		var profile = new Profile;
		profile.setUserId(userId).addTo("#layout_content");
	} else if (destination == "games"){
		
		for (var i = 0; i < gameInfo.game.length; i++){
		
			var game = new Game;
			game.setGameId(gameInfo.game[i].gameId).addTo("#layout_content");
		}
		
	} else if (destination == "arena_games"){
		
		$("#arena_games").slideDown("slow");
	} else if (destination == "competition") {
		
		$("#arena_competitions").slideDown("slow");			
	} else if (destination.substr(0,10) == "arena_game"){	
		
		var gameId = destination.split("_")[2];
		
		var scores = new Scores;
		scores.setType("top").setGameId(gameId).addTo("#layout_content");
		
		if (userId != 0) {
			scores = new Scores;
			scores.setType("mine").setUserId(userId).setGameId(gameId).addTo("#layout_content");
			scores = new Scores;
			scores.setType("myCountry").setUserId(userId).setGameId(gameId).addTo("#layout_content");			
		}

		var countries = new Countries;
		countries.setGameId(gameId).addTo("#layout_content");
				
		var shouts = new Shouts;
		shouts.setGameId(gameId).addTo("#layout_content");
		
	} else if (destination.substr(0,11) == "arena_stats"){
	
		var bits = destination.split("_");
		if (bits.length == 3){
			var profileId = bits[2];
		} else {
			var profileId = userId;
		}
		
		var profile = new Profile;
		profile.setUserId(profileId).addTo("#layout_content");	
		var stats = new UserStats;
		stats.setUserId(profileId).addTo("#layout_content");
		
		if (profileId == userId) {
		
			$.getJSON("interface/json.php", {
				action: "userGameStats"
			}, function(data){
			
				for (var i = 0; i < data.game.length; i++) {
				
					var scores = new Scores;
					scores.setType("mine").setUserId(userId).setGameId(data.game[i].gameId).addTo("#layout_content");
					scores = new Scores;
					scores.setType("myCountry").setUserId(userId).setGameId(data.game[i].gameId).addTo("#layout_content");					
				}
			});
		}
	} else if (destination == "arena_countries"){
	
		for (var i = 0; i < gameInfo.game.length; i++){
					
			var countries = new Countries;
			countries.setGameId(gameInfo.game[i].gameId).addTo("#layout_content");				
		}		
	
	} else if (destination == "arena_players"){
			
		for (var i = 0; i < gameInfo.game.length; i++){
			
			var scores = new Scores;
			scores.setType("top").setGameId(gameInfo.game[i].gameId).addTo("#layout_content");
		}
	} else if (destination == "competition_nokiaSeap") {
		
		var profile = new Profile;
		profile.setUserId(userId).addTo("#layout_content");
		
		var textBox = new TextBox;
		textBox.setText(competitionInfoText).setTitle("Competition Info").addTo("#layout_content");
						
/*
		var competitionStats = new CompetitionStats;
		var targetDate = new Date();
		targetDate.setUTCFullYear(2010);
		targetDate.setUTCHours(16);
		targetDate.setUTCMinutes(0);
		targetDate.setUTCSeconds(0);
		targetDate.setUTCMonth(7,31);				
		competitionStats.setCompetitionId(5).setTargetDate(targetDate).setTitle('Competition stats: August').addTo("#layout_content");

		competitionStats = new CompetitionStats;
		targetDate.setUTCDate(30);
		targetDate.setUTCMonth(5);				
		competitionStats.setNumEntriesVar('numEntries2').setTargetDate(targetDate).setTitle('Competition stats: June').addTo("#layout_content");
*/		
		var competitionLeaderboard = new CompetitionLeaderboard;
		competitionLeaderboard.setCompetitionId(4).setTitle('Competition winners: August').addTo("#layout_content");		
/*		
		var scores = new LatestScores;
		scores.setGameId(0).setNumber(5).setTitle("Latest Entries").setCountry("competition1").addTo("#layout_content");				
*/				
	} else if (destination == "arena_blog") {
		
		var scores = new Scores;
		scores.setType("top").setGameId(3).setCountry("blog").setNumber(20).addTo("#layout_content");
		scores = new Scores;
		scores.setType("top").setGameId(4).setCountry("blog").setNumber(20).addTo("#layout_content");		
		scores = new Scores;
		scores.setType("top").setGameId(8).setCountry("blog").setNumber(20).addTo("#layout_content");	
		
	//Thai competitions ----------------------------------------------------------------------------------------------
	} else if (destination == "competition_nokiaThailand") {

		//User profile
		//var profile = new Profile;
		//profile.setUserId(userId).addTo("#layout_content");
				
		//Competition rules
		var textBox = new TextBox;
		textBox.setText(thaiCompetitionInfoTextThai).setTitle("Master Of Games").addTo("#layout_content");				
		textBox = new TextBox;
		textBox.setText(thaiCompetitionInfoText).setTitle("Master Of Games").addTo("#layout_content");
		textBox = new TextBox;
		textBox.setText(thaiCompetitionMostActiveText).setTitle("5th Weekly Winner").addTo("#layout_content");
		
				
		//Eligibility and countdown timer
		var competitionStats = new CompetitionStats;
		var targetDate = new Date();
		targetDate.setUTCFullYear(2010);
		targetDate.setUTCHours(16);
		targetDate.setUTCMinutes(0);
		targetDate.setUTCSeconds(0);
		targetDate.setUTCMonth(8,20);				
		competitionStats.setCompetitionId(4).setTargetDate(targetDate).setTitle('Your competition stats').addTo("#layout_content");
				
		//Scoreboards for each game
		var scores = new Scores;
		scores.setType("top").setGameId(3).setGameImage().setCountry("competition4").addTo("#layout_content");
		scores = new Scores;
		scores.setType("top").setGameId(4).setGameImage().setCountry("competition4").addTo("#layout_content");		
		scores = new Scores;
		scores.setType("top").setGameId(8).setGameImage().setCountry("competition4").addTo("#layout_content");
		scores = new Scores;
		scores.setType("top").setGameId(9).setGameImage().setCountry("competition4").addTo("#layout_content");
		scores = new Scores;
		scores.setType("top").setGameId(10).setGameImage().setCountry("competition4").addTo("#layout_content");
				
		//Participation leaderboards for universities
		var schools = new CompetitionSchools;
		schools.setTitle("Leading Schools").addTo("#layout_content");

//Roach Madness competitions ----------------------------------------------------------------------------------------------
	} else if (destination == "competition_roachMadness"){
		
		var textBox = new TextBox;
		textBox.setText(roachCompetitionInfoText).setTitle("Roach Madness").addTo("#layout_content");	
		
/*		
		//Scoreboards for each game
		var scores = new Scores;
		scores.setType("top").setGameId(3).setGameImage().setCountry("competition6A").setTitle('Week Leaders: TRGSA').setBanner('images/roachmadness_trgsa.png').addTo("#layout_content");
		scores = new Scores;
		scores.setType("top").setGameId(13).setGameImage().setCountry("competition6A").setTitle('Week Leaders: TRGSEA').setBanner('images/roachmadness_trgsea.png').addTo("#layout_content");		
		scores = new Scores;
		
		scores = new LatestScores;
		scores.setGameId(0).setNumber(5).setTitle("Latest Entries").setCountry("competition6A").addTo("#layout_content");				
*/		
	} else if (destination == "competition_fbphoto"){

		var textBox = new TextBox;
		textBox.setText(fbphotoCompetitionInfoText).setTitle("Facebook Photo").addTo("#layout_content");

		var competitionStats = new CompetitionStats;
		var targetDate = new Date();
		targetDate.setUTCFullYear(2011);
		targetDate.setUTCHours(16);
		targetDate.setUTCMinutes(0);
		targetDate.setUTCSeconds(0);
		targetDate.setUTCMonth(5,30);				
		competitionStats.setCompetitionId(6).setTargetDate(targetDate).setTitle('Competition Stats').addTo("#layout_content");

	} else if (destination == "competition_trivia"){

		var textBox = new TextBox;
		textBox.setText(triviaCompetitionInfoText).setTitle("Barking Seed Trivia").addTo("#layout_content");

		var competitionStats = new CompetitionStats;
		var targetDate = new Date();
		targetDate.setUTCFullYear(2011);
		targetDate.setUTCHours(16);
		targetDate.setUTCMinutes(0);
		targetDate.setUTCSeconds(0);
		targetDate.setUTCMonth(5,30);				
		competitionStats.setCompetitionId(7).setTargetDate(targetDate).setTitle('Competition stats: June').addTo("#layout_content");

		var shouts = new Shouts;
		shouts.addTo("#layout_content");
		
	} else if (destination == "arena_allshouts"){
		
		var shouts = new LatestShouts;
		shouts.setGameId(0).setNumber(10).setTitle("Latest Shouts: All Games").addTo("#layout_content");		
		
		for (var i = 0; i < gameInfo.game.length; i++){
			
			var shouts = new Shouts;
			shouts.setGameId(gameInfo.game[i].gameId).addTo("#layout_content");
		}		
	} else if (destination == "latestnews"){
		
		get_rss_feed();
		var scores = new LatestScores;
		$("#layout_latest_scores").empty();
		scores.setGameId(0).setNumber(5).setDrawBox(false).addTo("#layout_latest_scores");
		
		var shouts = new LatestShouts;
		$("#layout_latest_shouts").empty();
		shouts.setGameId(0).setNumber(5).setDrawBox(false).addTo("#layout_latest_shouts");
				
	} else if (destination == "faq"){

		$("#div_faqs").clone().appendTo("#layout_page_content").show("slow");	
	} else if (destination == "terms"){

		$("#div_terms").clone().appendTo("#layout_page_content").show("slow");		
	} else if (destination == "privacy"){

		$("#div_privacy").clone().appendTo("#layout_page_content").show("slow");		
	} else if (destination.substr(0,5) == "info_"){
		
		var infoNames = destination.split("_");
		var infoName = infoNames[infoNames.length-1];
		$("#div_info_" + infoName).clone().appendTo("#layout_page_content").show("slow");
	}
	
	//Track new boxes again
	eventhook.setAddMoveTo(true);
	
	//Analytics track page view

	//Setup analytics object only here so that it has most likely loaded	
	if (typeof(pageTracker) == "undefined"){
		
		if (typeof(_gat) != "undefined"){
			
			pageTracker = _gat._getTracker("UA-9355678-4");
			pageTracker._trackPageview("/" + destination);									
		}
	} else {
		
		pageTracker._trackPageview("/" + destination);				
	}	
}

function doLoginChanges()
{
	if (userId==0){
		
		$(".show_loggedIn").slideUp("slow", function() {$(".show_loggedOut").slideDown("slow");});
	} else {
	
	eventhook.triggerEvent("loggedIn");
 	$.getJSON("interface/json.php",{action: "getUserDetails"},
		        function(data){
				
					$("#logged_in_name").html(data.userName);
					$("#logged_in_image").attr("src","images/avatars/playerpics" + data.picture + ".png");
					$(".show_loggedOut").slideUp("slow",function(){ $(".show_loggedIn").slideDown("slow");});							
				});
		
	}
}

//-----------------------------------------------------------------------------------------------------------------	
// Startup
//-----------------------------------------------------------------------------------------------------------------	

$(document).ready(function(){
	
	//Cache sounds
	//var snd = new Audio("audio/beep.wav");
	
	//Event manager
	eventhook = new EventHook;
	
	//Links
	setupLinks();
	
   $("#link_login").fancybox(fancyBoxDefaults);		
   $("#link_register").fancybox(fancyBoxDefaults);	
			
   $(".link_login").click(function(event){
	 $("#div_Register").hide("slow");
	 $("#div_Login").show("slow");
	 $("#div_Forgot").hide("slow");	   	 
     event.preventDefault();
   });
   
   $(".link_register").click(function(event){
	   $("#div_Login").hide("slow");
	   $("#div_Register").show("slow");	
	   $("#div_Forgot").hide("slow");	   
	   event.preventDefault();
   });

   $(".link_forgot").click(function(event){
	   $("#div_Login").hide("slow");
	   $("#div_Register").hide("slow");
	   $("#div_Forgot").show("slow");	   
	   event.preventDefault();
   });		

	//Hash changing for location changes including back button / history
	$(window).hashchange( function(){
		splitString = location.hash.split("#");
		dest = splitString[1];
		setupPage(dest);
	});
	
			
//-----------------------------------------------------------------------------------------------------------------	
// Login
//-----------------------------------------------------------------------------------------------------------------	
	
   $("#button_login").click(function(event){

	   $("#button_login").attr("disabled", "true");
	   $("#userName").attr("disabled", "true");
	   $("#password").attr("disabled", "true");
	   $("#notice_login_error").hide("fast");
	   $.fancybox.showActivity();
	   
	   $.getJSON("interface/json.php",{action: "login", userName: $("#userName").val(), password: $("#password").val()},
		        function(data){
					
				  $.fancybox.hideActivity();
		   			$("#button_login").removeAttr("disabled");
		   			$("#userName").removeAttr("disabled");
		   			$("#password").removeAttr("disabled");		  
		   		  if (data.success == "1"){
				  	
		   			  createCookie('sessionKey',data.sessionKey);
		   			  createCookie('login_userName',$("#userName").val());
					  $("#password").val("");
		   			  $.fancybox.close();
					  userId = data.userId;
					  doLoginChanges();
		   		  } else {

		   			$("#notice_login_error").show("slow");
					$.fancybox.resize();		   			  
		   		  }
		          });
   });	
   
   $("#div_Login").find('input').keypress(function(e) {
       if(e.which == 13) {
    	   e.preventDefault();
           $(this).blur();
           $('#button_login').focus().click();
       }
   });   
   
   $("#button_register").click(function(event){
	   
	   $("#notice_register_error").hide("slow");	   	   
	   
	   if ($("#password_register").val() != $("#password2_register").val()){
		   
		   $("#notice_register_error").html("Passwords do not match");
		   $("#notice_register_error").show("slow");
		   return;
	   }
	   
	   if ($("#div_Register .email").val() == "") {
	   	
		   $("#notice_register_error").html("You must enter an email address to register");
		   $("#notice_register_error").show("slow");
		   return;		
	   }
	   
	   $.fancybox.showActivity();
	   	   
	   $("#button_register").attr("disabled","true");
	   	   
	   $.getJSON("interface/json.php",{action: "register", email: $("#div_Register .email").val(), userName: $("#userName_register").val(), password: $("#password_register").val(), gender: $("#div_Register .gender").val(), 
		   								dob: $("#div_Register .dobYear").val() + '-' + $("#div_Register .dobMonth").val() + '-' + $("#div_Register .dobDay").val(), country: $("#div_Register .country").val()},
		        function(data){

				  $("#button_register").removeAttr("disabled");				  			   		
				  $.fancybox.hideActivity();											
		   		  if (data.success == "1"){
		   			  createCookie('sessionKey',data.sessionKey);		   			  
		   			  $.fancybox.close();
					  userId = data.userId;
					  doLoginChanges();
		   		  } else {
		   			  
		   			$("#notice_register_error").html(data.errorMessage);
		   			$("#notice_register_error").show("slow");		   			  
		   		  }
		         });
   });
   
   $("#div_Register").find('input').keypress(function(e) {
       if(e.which == 13) {
    	   e.preventDefault();
           $(this).blur();
           $('#button_register').focus().click();
       }
   });   
   
   $("#button_forgot").click(function(event){
	   
	   $("#button_forgot").attr("disabled","true");
	   $("#notice_forgot").hide("slow");	   
	   $.getJSON("interface/json.php",{action: "forgotPassword", email: $("#email_forgot").val()},function(data){
		   
		   $("#button_forgot").removeAttr("disabled");
		   $("#notice_forgot").show("slow");	   
	   });   
   });
   
   $("#div_Forgot").find('input').keypress(function(e) {
       if(e.which == 13) {
    	   e.preventDefault();
           $(this).blur();
           $('#button_forgot').focus().click();
       }
   });      
   
   $("#div_login_popup .box_close").click(function(event){
   	
		event.preventDefault();
		$.fancybox.close();
   });	
	
			
//-----------------------------------------------------------------------------------------------------------------	
// Content scrolling
//-----------------------------------------------------------------------------------------------------------------	

	$("#content_scrollleft").click(function(event){

		event.preventDefault();		
		eventhook.moveLeft();		
	});
	
	$("#content_scrollright").click(function(event){
		
		event.preventDefault();
		eventhook.moveRight();		
	});
	
	$(document).keydown(function(e){
		
		if (!keyScrolling)
			return;
		
		switch (e.keyCode)
		{
			case 37:
				$("#content_scrollleft").click();
				break;
			case 39:
				$("#content_scrollright").click();
				break;
			default:
				break;
		}
	});
	
//-----------------------------------------------------------------------------------------------------------------	
// Profile search popup
//-----------------------------------------------------------------------------------------------------------------		

	$("#content_show_profile_search").click(function(event){

		event.preventDefault();		
		profileSearch = new ProfileSearch;
		var afterId = eventhook.getBoxAt(eventhook.getContentPosition()).id;
		profileSearch.addTo("#layout_content",afterId);
	});

//-----------------------------------------------------------------------------------------------------------------	
// Get competition details
//-----------------------------------------------------------------------------------------------------------------		

	var comp = $("#template_arena_competition").clone().css("display","").appendTo("#arena_competitions");
	comp.find("img").attr("id","").attr("src","images/competitions/roachmadness.png");
	//comp.find("a").attr("href","#competition_roachMadness");	
	
	var comp = $("#template_arena_competition").clone().css("display","").appendTo("#arena_competitions");
	comp.find("img").attr("id","").attr("src","images/competitions/seap.png");
	//comp.find("a").attr("href","#competition_nokiaSeap");

	comp = $("#template_arena_competition").clone().css("display","").appendTo("#arena_competitions");
	comp.find("img").attr("id","").attr("src","images/competitions/masterofgames.png");
	//comp.find("a").attr("href","#competition_nokiaThailand");

	comp = $("#template_arena_competition").clone().css("display","").appendTo("#arena_competitions");
	comp.find("img").attr("id","").attr("src","images/competitions/trivia.png");
	comp.find("a").attr("href","#competition_trivia");

	comp = $("#template_arena_competition").clone().css("display","").appendTo("#arena_competitions");
	comp.find("img").attr("id","").attr("src","images/competitions/fbphoto.png");
	comp.find("a").attr("href","#competition_fbphoto");



//-----------------------------------------------------------------------------------------------------------------	
// Get game details
//-----------------------------------------------------------------------------------------------------------------			
	
	$.getJSON("interface/json.php",{action: "getGameDetails", order: "reverse"}, function(data){
		
		gameInfo = data;
		
		for (var i = 0; i < gameInfo.game.length; i++){
		
			var game = $("#template_arena_game").clone().css("display","").appendTo("#arena_games");
			game.css("background-image","url(images/games/game" + gameInfo.game[i].gameId + ".png)");
			game.find(".page_link").html(gameInfo.game[i].gameName).attr("href","#arena_game_" + gameInfo.game[i].gameId);
		}
		
		doLoginChanges();		
		
		//Show to deep link or default latestnews
		urlBits = window.location.href.split("#");
		if (urlBits.length == 1)
			setupPage("latestnews");
		else 
			setupPage(urlBits[1]);
			
/*		//Reload memory doesn't exist at the moment		
		if (0 && readCookie("currentPage") && readCookie("currentPage") != ""){
			setupPage(readCookie("currentPage"));
		} else {
			setupPage("latestnews");
		}
*/		
	});

//-----------------------------------------------------------------------------------------------------------------	
// Animations
//-----------------------------------------------------------------------------------------------------------------	
	
	function animateFly(){
	
		for (var i = 0; i < numFlys; i++){

			flys[i][1] += (Math.random()*4)-2;
			flys[i][0] += flys[i][2];
			if (flys[i][1] < 0)
				flys[i][1] = 0;

			if (flys[i][0] > animateMaxWidth){
				flys[i][0] = -50;
				flys[i][1] = (Math.random()*$(document).height())-100;
				flys[i][2] = (Math.random()*2.5)+1.25;
			}

			$("#overlay_fly_" + i).css("top",Math.round(flys[i][1]) + "px").css("left",Math.round(flys[i][0]) + "px");

		}
		
		flyAnimation += 30;
		if (flyAnimation > 100){

			flyAnimation %= 100;
			if (++flyFrame > 5)
				flyFrame = 1;

			$(".flys").find("img").attr("src","images/fly/fly" + flyFrame + ".png");
		}

		window.setTimeout(animateFly,30);
	}	

	$(window).resize(function(){
	
		animateMaxWidth = $(window).width();
	});
	
	numFlys = 3;
	flyAnimation = 0;
	flyFrame = 1;
	animateMaxWidth = $(window).width();	
	
	flys = new Array(new Array(0,100,3,0),new Array(0,500,1.5,0),new Array(0,700,2,0));		
	roaches = new Array(new Array(-40,100,1,2), new Array(-40,200,2,1), new Array(-40,300,4,1));
	
	//animateRoach();
});

