$(document).ready(function() {
	var getWorld = false;
	var mode = 'main';

	//build main menu
	var html = '';
	$.each(levels, function(i, item) {
		html += '<li id="' + item.LevelNumber + '">' +
			'<div style="float:left; margin-left: 2px; margin-top: 1px; background-position: 0px -' + (60 * parseInt(item.LevelNumber)) + 'px;" class="levelImage" />' +
			'<p>' + 
			'<span class="levelName">' + (parseInt(item.LevelNumber)+1) + '. ' + item.LevelName + '</span><br />' + 
			'<span class="topPlayerName">' + item.BestTime.Name + ' </span>' +
			'<img class="flag" src="images/flags/' + item.BestTime.Country + '.png" alt="' + item.BestTime.Country + '" title="' + item.BestTime.Country + '" />' +
			'<span class="playerTime"> - ' + item.BestTime.Time + ' s</span>' +
			
			'</p>' +
			'<a href="#' + i + '"><img src="images/arrow.png" alt="" class="arrow" /></a>' +
		'</li>';
	});
	$('div#highScoresInner ul.scores').append(html);
	
	function GetHighScores()
	{
		//make ajax call to get the top 30 (??) scores for this level
		$.ajax({
			type: 'POST',
			url: 'highscoresajax.php',
			dataType: 'json',
			data: {
				action: 'GetHighScores',
				getWorld: getWorld
			},
			success: function(data) {
				levels = data.scores;
				$.each(levels, function(i, item) {
					//update Flag
					$('li#' + item.LevelNumber + ' p img.flag').attr({'src': 'images/flags/' + item.BestTime.Country + '.png', 'alt': item.BestTime.Country, 'title': item.BestTime.Country});
					//update span.playerName
					$('li#' + item.LevelNumber + ' p span.topPlayerName').text((item.BestTime.Name != null ? item.BestTime.Name : 'unknown') + ' ');
					//update span.playerTime
					$('li#' + item.LevelNumber + ' p span.playerTime').text(' - ' + (item.BestTime.Time != null ? item.BestTime.Time : '???') + ' s');
				});
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//TODO: better error checking
			}
		});
	}
	
	//update high score
	//show updaing indication (where?)

	//when ajax returns
	//for each entry in returned array
	//find level we are talking about
	//update span.playerName
	//	$('li#' + item.LevelNumber + ' p span.playerName').text(item.BestPlayerName + ' -');
	//update span.playerTime
	//	$('li#' + item.LevelNumber + ' p span.playerTime').text(item.BestPlayerTime + ' s');

	//the active level id
	var selectedLevelID = null;
	//the single high scores AJAX response data
	var singleAJAXData;
	//if the single high scores AJAX request has completed
	var singleAJAXReturned = false;
	//if the single high scores animation has finished
	var singleAnimationFinished = false;
	
	//click on a high scores entry
	$('div#highScoresInner ul.scores li').click(function() {
		mode = 'single';
		selectedLevelID = this.id;
		//set the img#levelSS, img#levelTitle and span#localTime
		$('div#levelSS').css('background-position', '0px -' + (60 * parseInt(levels[selectedLevelID].LevelNumber)) + 'px');
		$('span#levelTitle').text((parseInt(levels[selectedLevelID].LevelNumber)+1) + ". " + levels[selectedLevelID].LevelName);
		//$('span#localTime').text('0.00 s'); //TODO add in local player best time
		
		singleAnimationFinished = false;
		GetSingleHighScores();
		
		singleAnimationFinished = true;
		if (singleAJAXReturned)
			BuildSingleHighScores();
		
		//Scroll to the top so when we slide across then we have something to slide to
		window.scrollTo(0, 1);

		//animates slide
		if (jQuery.browser.safari)
		{
			$('div#highScoresWrapper').addClass('out').removeClass('current in reverse')
				.one('webkitAnimationEnd', function(){ $('div#highScoresWrapper').hide() } );
			$('div#singleHighScoresWrapper').show().removeClass('out reverse').addClass('in current');
		}
		else
		{
			$('div#singleHighScoresWrapper').show().css('left', '320px').animate(
				{ left: '0px' },
				400,
				'swing'
			);

			$('div#highScoresWrapper').animate(
				{ left: '-320px' },
				400,
				'swing',
				function() {
					$('div#highScoresWrapper').hide();
				}
			);
		}

		
		//show the show search button
		$('a#btnShowSearch').fadeIn('medium');
		//show the back button
		$('a#btnBack').fadeIn('medium');
		//show the search wrapper
		$('div#searchBarWrapper').show();
	});
	
	function GetSingleHighScores()
	{
		//show div#progressIndicator
		$('div#progressIndicator').show();
		//reset vars
		singleAJAXData = null;
		singleAJAXReturned = false;
		//make ajax call to get the top 30 (??) scores for this level
		$.ajax({
			type: 'POST',
			url: 'highscoresajax.php',
			dataType: 'json',
			data: {
				action: 'GetLevelHighScores',
				level: levels[selectedLevelID].LevelNumber,
				getWorld: getWorld
			},
			success: function(data) {
				//check to see if the visiable level is the appropriate one (in case user clicked back, then on another level b4 ajax returned)
				//if (levels[selectedLevelID].LevelNumber == 
				singleAJAXData = data;
				singleAJAXReturned = true;
				//if the animation has finished build the single high scores list
				if (singleAnimationFinished)
					BuildSingleHighScores();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//TODO: better error checking
			}
		});
	}


	function BuildSingleHighScores() {
		//populate list with top 30 scores
		if(singleAJAXData.scores.length > 0)
		{
			$('div#noBestTimes').hide();
			$('div#singleHighScoresInner ul.scores').append(BuildScores(singleAJAXData.scores));
		}
		else
			$('div#noBestTimes').show();
		//hide div#progressIndicator
		$('div#progressIndicator').hide();
	}
	
	function BuildScores(scores)
	{
		var html = '';
		$.each(scores, function(i, item) {
			html += 
				'<li>' +
					'<p class="left"><span class="playerPosition">' + (i + 1) + '.</span> <span class="playerName">' + item.Name + '</span> <img src="images/flags/' + item.Country + '.png" alt="' + item.Country + '" title="' + item.Country + '" /></p>' +
					'<p class="right">' + item.Time + ' s</p>' +
					'<br style="clear: both" />' +
					'<p class="date">' + item.Date + '</p>' +
				'</li>';
		});
		return html;
	}

	$('div#bottomBar a#btnBack').click(function() {
		mode = 'main';
		//if we are on the first page then return
		//var animationWrapper = $('div#animationWrapper');
		//if (animationWrapper.css('left') == '0px')
		//	return;
		//make sure the search bar is hidden
		$('div#searchBar').animate({ top: '-40px' }, 'fast');
		
		//animate slide
		if (jQuery.browser.safari)
		{
			$('div#highScoresWrapper').show().addClass('in reverse current').removeClass('out');
			$('div#singleHighScoresWrapper').removeClass('in current').addClass('out reverse')
				.one('webkitAnimationEnd', function(){
					ResetSingleLevel();
					//hide the search wrapper
					$('div#searchBarWrapper').hide();
					$('div#singleHighScoresWrapper').hide()
				});
		}
		else
		{
			$('div#singleHighScoresWrapper').animate(
				{ left: '320px' },
				400,
				'swing'
			);
			$('div#highScoresWrapper').show().animate(
				{ left: '0px' },
				400,
				'swing',
				function() {
					ResetSingleLevel();
					//hide the search wrapper
					$('div#searchBarWrapper').hide();
					$('div#singleHighScoresWrapper').hide();
				}
			);
		}
		
		//levelHeader
		//show the show search button and reset the background position
		$('a#btnShowSearch').fadeOut('fast').css('backgroundPosition', '0 0');
		$('a#btnBack').fadeOut('fast');

		//reset the selected level
		selectedLevelID = null;
	});
	
	//switch mode (all time/24 hr)
	$('div#bottomBar a.toggle').click(function() {

		//if this is active ->return
		if ($(this).attr('class').indexOf('active') >= 0)
			return;

		//toggle classes for both buttons
		$('a#btnWorld').toggleClass('active');
		$('a#btnLast24').toggleClass('active');

		getWorld = $(this).attr('id') == 'btnWorld';

		//force AJAX call to update the high scores
		if ($('div#searchMsg').css('display') != 'none' || $('div#noQueryResults').css('display') != 'none')
		{
			//Search is open
			$('div#searchBar a').click();
		}
		else if (mode == 'single')
		{
			ResetSingleLevel();
			GetSingleHighScores();
		}
		else //main screen
		{
			GetHighScores();
		}
		
	});
	
	//toggle search
	$('div#bottomBar a#btnShowSearch').click(function() {
		//if search div is not showing then show it
		var search = $('div#searchBar');
		if (search.css('top') == '-40px')
		{
			$('input#tbSearch').val('');
			search.animate(
				{ top: '0px' },
				'medium',
				'swing',
				function() { $('input#tbSearch').focus(); }
			);
			$('a#btnShowSearch').css('backgroundPosition', '-42px 0');
		}
		else
		{
			search.animate({ top: '-40px' }, 'medium');
			$('a#btnShowSearch').css('backgroundPosition', '0 0');
		}
	});

	function ResetSingleLevel()
	{
		$('div#singleHighScoresInner ul.scores').empty();
		$('div#noQueryResults').hide();
		$('div#noBestTimes').hide();
		$('div#searchMsg').hide();
		$('div#progressIndicator').show();
	}
	
	//search for a name
	$('div#searchBar a').click(function() {
		var search = $('#tbSearch').val();
		if(search.length == 0)
			return;
		ResetSingleLevel();
		//clear scores
		$('div#singleHighScoresInner ul.scores').empty();
		//make ajax call to get the top 30 (??) scores for this level and search
		$.ajax({
			type: 'POST',
			url: 'highscoresajax.php',
			dataType: 'json',
			data: {
				action: 'Search',
				level: levels[selectedLevelID].LevelNumber,
				getWorld: getWorld,
				searchQuery: search
			},
			success: function(data) {
				//check to see if we are still in search state
				
				//build div#singlehighScoresInner ul.scores from returned array
				if(data.scores.length > 0)
				{
					$('div#searchMsg').show().find('span').html(data.scores.length);
					$('div#singleHighScoresInner ul.scores').append(BuildScores(data.scores));
				}
				else //show the 'no search results'
					$('div#noQueryResults').show();
				//hide div#progressIndicator
				$('div#progressIndicator').hide();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//TODO: better error checking
			}
		});
	});
	
	//clear the search
	$('a.reset').click(function() {
		//Reset some of our bits
		$('div#searchMsg').find('span').html('');
		$('input#tbSearch').val('');
		$('div#singleHighScoresInner ul.scores').empty();
		
		//Reget the high scores
		ResetSingleLevel();
		GetSingleHighScores();
	});
	
	//Scroll the page on screen (Move the location bar off the top)
	setTimeout(function() { window.scrollTo(0, 1) }, 1000);
});
