$(main);

var pfg = {game: null,
           games: [],
		   leftbar: null,
		   statsbar: null};


/** Initialize process and startup everything
 *
 * This function went through several different names, none of which really seemed to fit to me. The
 * current name is, obviously, based on the C family of programming languages, in which the function
 * that starts up the process is always named main. This function doesn't really do anything per se,
 * but calls the other functions that starts the whole process off. (I guess you could call this the
 * George Jetson of functions).   
 */ 
function main()
{
	/*
	// DEBUG ONLY
	if($('#signout').length) {
		$('#signout').click(function(event){
			cookiejar.deleteCookie('js_game_id');
			cookiejar.deleteCookie('gsuser_cookiehash');
			
			window.location.reload();
		});
	}*/
	
	
	// Setup live events for some dynamic links
	
	 $("a.team").live("click", function(event){
	 	doTeamPage(event.target.getAttribute('href').substr('5'));
	 	
	 	return false;
	 });
	 
	 $("a.left_leaderboard").live("click", function(){
		updateStats();
	 	return false;
	 });
	 
	$("a.left_theme").live("click", function(){
		doThemeSidebar();
	 	return false;
	});
	
	$("a.left_instructions").live("click", function(){
		doInstructionsSidebar();
	 	return false;
	});
	 

	
	
	if($('#game_box').length)
	{
		doWelcomePage();
	}
	else
	{		
		if($('#left_column').html() == '') {
			doWelcomeSidebar();
		}
		doPotwStatsbar();
	
	}
	
	newAd();
}



/** Sets the appropriate welcome page based on user history
 *
 * Here we check for the last round played by the current user, if there is one. We then pull up the
 * game info, using the game last played if there was one, or the default game if not. If a previous
 * round was found, we show the "pause" page if it was since midnight last night, or the three trees
 * level select page if not.   
 */ 
function doWelcomePage(game_id)
{
	var game_id = game_id;
	
	$.getJSON('/ajax/lastround.ajax.json.php', {game_id: game_id}, function(round, status)
	{
		if(game_id) {
			var game = {game_id: game_id};
		} else {
			var game = round ? {game_id: round.game_id} : null;
		} 
		
		$.getJSON('/ajax/game.ajax.json.php', game, function(game, status)
		{
			// Set the global game param so everybody can access info on what game we're playing
			pfg.game = game;
			
			
			// See if the last round was today
			
			if(round)
			{
				var dToday = new Date();
				var dRound = new Date(round.date);
				
				if(dToday.getFullYear() == dRound.getFullYear() && dToday.getDate() == dRound.getDate())
				{
					doPausePage(round);
				}
				else
				{
					doLevelSelect(round);
				}
			}
			else
			{
				doLevelSelect();
			}				
		});	
	});
}



/** Sets the gamebox and sidebars to the "Pause" state.
 *
 * Loads the "Game instructions" blurb in the instructions (right) box, the user/game stats stuff in
 * the stats box, and the "game pause" thing in the game box. This is what you get if you reload the
 * page or click the tree logo while playing a game.   
 */
function doPausePage(lastround)
{
	doWelcomeSidebar();
	doPotwStatsbar();
	
	var level = Math.round(lastround.level * 10);
	
	var html =  "<p>You are playing: "+pfg.game.title+". Difficulty: "+level+"/10.</p>";
	html += "<p>Play for good remembers your scores and the question you're on. The difficulty ";
	html += "level automatically changes based on the accuracy of your answers.</p>";
	
	html += "<p><a id='game_resume' href='#'>Return to my Game</a>.</p>";
	html += "<p><a id='game_select' href='#'>Play a different game</a>.</p>";
	
	//html += "<p><a id='game_reset'  href='#'>Reset my scores and start over</a>.</p>";
	
	$('#game_box').html(html);
	
	
	$('#game_resume').click(function(event){
		startGame(pfg.game.id, lastround.level);
		event.preventDefault();
	});
	
	$('#game_select').click(function(event){
		doGameList();
		event.preventDefault();
	});
	
	/*
	$('#game_reset').click(function(event){
		??????
		event.preventDefault();
	});
	*/
}


/** Creates the list of games
 *
 */ 
function doGameList()
{
	doWelcomeSidebar();
	doPotwStatsbar();
	
	$.getJSON('/ajax/gamelist.ajax.json.php', null, function(list, status)
	{
		list_html =  "<p>The following games are currently available:</p>";
		list_html += "<table id='gamelist' style='color:#FFF;'>";
		list_html += "<tr><th style='text-align:left;'>Game</th><th>Rounds</th><th>Score</th><th>Difficulty</th></tr>";
		
		for(id in list)
		{
			var game = list[id];
			list_html += "<tr><td><p><a id='game_"+game.id+"' href='#'>"+game.title+"</a></p></td>";
			
			if(game.score.rounds)
			{
				var score = Math.round(game.score.game_points);
				list_html += "<td style='padding-left:30px'>"+game.score.rounds+"</td>";
				list_html += "<td style='padding-left:30px'><p>"+score+"</p></td>";
				list_html += "<td style='padding-left:30px'><p>"+Math.round(game.score.level*10)+"/10</p>";
			}
			else
			{
				list_html += "<td style='padding-left:30px'>0</td><td style='padding-left:30px'>0</td><td style='padding-left:30px'>-</td>";
			}

			list_html += "</tr>"; 
		}
	
		list_html += "</table>";
		
		$('#game_box').html(list_html);
		
		
		for(id in list)
		{
			var game = list[id];
			
			$('#game_'+game.id).data('game', game);
			$('#game_'+game.id).click(function(event)
			{
				doWelcomePage($(event.target).data('game').id);
				event.preventDefault();
			});
		}
	});
}



/** Creates the "Three trees" difficulty select screen in the game box, and the welcome sidebars
 *
 * Loads the "How to play" blurb in the instructions box, the simple "player of the week" box in the
 * stats box, and the "three trees" level select in the game box. The three tress box will be just a
 * bit different depending on whether we're doing a "Welcome to Play for Good" for a brand new user,
 * or a "Welcome Back" for an old user who has returned. In the latter case, we show info about what
 * game the user was previously playing and give a link to resume that game, in addition to the rest
 * of the trees page.
 */
function doLevelSelect(lastround)
{
	doWelcomeSidebar();
	doPotwStatsbar();
	
	var html = "";
	
	if(lastround)
	{
		html += "<p>You are playing: "+pfg.game.title+". Difficulty: "+lastround.level*10+". ";
		html += "<a id='game_resume' href='#'>Return to Game</a>.</p>";
	}
	else
	{
		html += "<p>Now Playing: "+pfg.game.title+".</p>";
	}	
	
	html += "<p><strong>Select a difficulty level to begin...</strong></p>";
	html += "<div id='difficulty' align='center'>";
	html += "  <table class='levels'><tr><td>";
	html += "    <a id='start_e' href='#'><img src='img/easy.jpg' alt='Easy'>";
	html += "    <br />Easy</a>";
	html += "  </td><td>";
	html += "    <a id='start_m' href='#'><img src='img/medium.jpg' alt='Medium'/>";
	html += "    <br />Medium</a>";
	html += "    </td><td>";
	html += "    <a  id='start_h' href='#'><img src='img/hard.jpg' alt='Hard'/>";
	html += "    <br />Hard</a>";
	html += "  </td></tr></table>";
	html += "</div>";
	html += "<p><br /></p>";
	html += "<p class='box'>...or you can <a id='othergames' href='#'>play a different game</a>.</p>";

	$('#game_box').html(html);
	
	
	$('#game_resume').click(function(event){
		if(pfg.newQuestionTimeout) {
			clearTimeout(pfg.newQuestionTimeout);
		}
		
		startGame(pfg.game.id, lastround.level);
		event.preventDefault();
	});
	
	$('#start_e').click(function(event){startGame(pfg.game.id, 0.15);event.preventDefault();});
	$('#start_m').click(function(event){startGame(pfg.game.id, 0.50);event.preventDefault();});
	$('#start_h').click(function(event){startGame(pfg.game.id, 0.84);event.preventDefault();});
	
	$('a#othergames').click(function(event){doGameList();event.preventDefault();});
}



/** Start playing the given game at the given difficulty level
 *
 * Sets up the basic "You are playing whatever. Play a different game" header, then loads a question
 * of the specified difficulty level into the question box. This is the only way to start a new game
 * so all of the different control paths have to go through here to actually start playing. You can,
 * when calling this function, call game.ajax and set pfg.game to the returned data first, or make a
 * call to here without doing so, whichever works best for the control flow you're working on.   
 *
 */ 
function startGame(game_id, level)
{
	// See if we already have info for this game; if not, load it via ajax
	
	if(pfg.game.id != game_id)
	{
		if(pfg.games[game_id])
		{
			pfg.game = pfg.games[game_id];
		}
		else
		{
			$.getJSON('/ajax/game.ajax.json.php', {game_id: game_id}, function(game, status) {
				pfg.game = game;
				startGame(game_id, level);
			});
			
			return;
		}
	}
	
	// Set the appropriate sidebars
	
	//doInstructionsSidebar();
	updateStats(level);
	
	
	// Setup the game header and gamelist link
	
	$('#game_box').html('<div id="game"></div><div id="question"></div><div id="explanation"></div>');
	$('#game').html("<p class='box'>Now Playing: "+pfg.game.title+". <a id='othergames' href='#'>Other games</a>.</p>");
	
	$('a#othergames').click(function(event){doGameList();event.preventDefault();});
	
	
	// Load the first question into the question box
	newQuestion(level);
}



/** Load a new question into the question box
 *
 * Gets the game id from the pfg.game global. Loads and displays a new question with the given level
 * or the current (automatic) level if none is specified. Sets the pfg.question global so others can
 * find out what question we're currently dealing with. 
 */ 
function newQuestion(level)
{
	var data = {game_id: pfg.game.id};
	if(level) {data.level = level;}

	$.getJSON('/ajax/question.ajax.json.php', data, function(question, status) 
	{
		pfg.question = question;
		pfg.timestart = new Date();
		
		var box = $('#question');
		box.html(null);
		box.append("<h2 tabindex='0'>" + question.prompt + "</h2>");
		
		
		var alist = $("<ul id='answers'>");
	
		for(answer in question.answers)
		{
			var ansli = $("<li>");
			
			var ansa  = $("<a href='#'></a>");
			ansa.append(question.answers[answer].text);
			ansa.data('answer', question.answers[answer]);
			ansa.click(answerQuestion);
			
			ansli.append(ansa);
			alist.append(ansli);
		}
		
		box.append(alist);
		$('#game_box h2').focus();
		
		$('#question').animate({opacity: 1}, 1000);
	});
}



/** Handle a click for a question answer
 *
 * Logs the answer ("round") with the php system so we can update scores and such. Updates the stats
 * on the statsbar, and calls the function that shows the solutions in the question box.  
 *
 */ 
function answerQuestion(event)
{
	event.preventDefault();
	
	event.target.parentNode.className = 'selected';

	var data = $(event.target).data('answer');
	
	$.getJSON('/ajax/answer.ajax.json.php', 
	             {game       : data.game_id, 
	              question   : data.question_id,
	              answer     : data.id,
	              difficulty : pfg.question.difficulty, 
	              duration   : new Date() - pfg.timestart}, 
    function(result, status)
	{
		showSolutions();
		updateStats();
	});
}



/** Show the solutions to a (just answered) question.
 *
 * Prints "right" and "wrong" next to the corresponding answers in the answer list. Sets the various
 * css classes that we use to style the solution data correctly. Sets an automatic timeout for a new
 * question to load. 
 */ 
function showSolutions()
{
	$('#answers a').each(function()
	{
		if($(this).data('answer').correct == '1')
		{
			this.parentNode.className += ' correct';
			$(this).after('<span class="solution"> - Right</span>');
		} else
		{
			this.parentNode.className += ' incorrect';
			$(this).after('<span class="solution"> - Wrong</span>');
		}
	});
	
	$('#explanation').html("<p>" + $('li.selected a').data('answer').explanation + "</p>");
	$('#explanation').append("<p class='box'><a id='flag' href='#'>Flag Question</a></p>");
	
	$('#flag').click(function(event){flagQuestion(event);event.preventDefault();});

	$('.solution, #explanation').animate({opacity: 1}, 500);
	
	pfg.newQuestionTimeout = setTimeout(hideQuestion, 3000);
	
	$('#answers a').unbind('click', answerQuestion);
	$('#answers a').bind('click', function(event){event.preventDefault();});
	
	$('#question').click(function(){
		clearTimeout(pfg.newQuestionTimeout);
		$('#question').unbind('click');
		
		$('#explanation').css('opacity', 0);
		
		newQuestion();
	});
}


/** Sets the flag on the current question to true
 *
 * Flag is something we invented to try to weed out crappy questions in the question pool. Basically
 * if a user doesn't like a question, he can hit flag and we don't show it to anybody else unless we
 * review it and either fix it or determine that it was flagged incorrectly.   
 */ 
function flagQuestion(event)
{
	var data = $('.selected a').data('answer');
	var params = {game: data.game_id, question: data.question_id};

	$.getJSON('/ajax/flag.ajax.json.php', params, function(result, status)
	{
		$('#flag').animate({opacity: 0}, 250, function(){
			$('#flag').replaceWith('<span id="flag" style="opacity: 0">This question has been flagged for review.</span>');	
			$('#flag').animate({opacity: 1}, 300);
		});
	});
}



/** Animate away a question, then call for a new question
 *
 * This is used when a user has seen the answers to a question for the determined length of time and
 * it's time to show a new question. Alternately, a user can get a new question by clicking anywhere
 * in the question box while the answers are showing. The exact time that should elapse between when
 * the solutions are shown and when they disappear is easily changable and has been the subject of a
 * serious debate or two among the developers and other stakeholders.  
 * 
 * This is also the place where we make sure that we're showing the theme sidebar on the left column
 * (instead of the game instructions). We do this here because we want to show the instructions only
 * on the first question and the theme for all subsequent questions, and this is the best way for us
 * to hook that up without some sort of crazy hack.     
 */ 
function hideQuestion()
{
	$('#question').unbind('click');
	
	$('#question').animate({opacity: 0}, 1000);
	$('#explanation').animate({opacity: 0}, 1000, newQuestion);
	
	doThemeSidebar();
}


/** Create the full leaderboard in the question box
 *
 * Calls the same ajax script that we use the create the basic stats sidebar, but uses data that the
 * sidebar ignores to create the full leaderbaord in the main question box. There is a link to go to
 * the question again inside the leaderboard box that we create.    
 */ 
function doFullLeaderboard()
{
	$.getJSON('/ajax/stats.ajax.json.php', {full: true}, function(data, status){
		var html = '';
		html += '<div id="full_leaderboard">';
		html += '<table>';
		
		html += '<tr><th colspan="3"><h3>Top Players this Week</h3></th></tr>';
		
		html += '<tr><td>'
		html += makeStatsList('Smartest', data.leaderboard.user.level, 'level', 1, true);
		html += '</td><td>';
		html += makeStatsList('Fastest', data.leaderboard.user.speed, 'speed', 1, true);
		html += '</td><td>';
		html += makeStatsList('Correct Answers', data.leaderboard.user.correct, 'correct', 0, true);
		html += '</td></tr>'
		
		html += '<tr><th colspan="3"><h3>Top Teams this Week</h3></th></tr>';
		
		html += '<tr><td>';
		html += makeStatsList('Smartest', data.leaderboard.team.level, 'level', 1, true);
		html += '</td><td>';
		html += makeStatsList('Fastest', data.leaderboard.team.speed, 'speed', 1, true);
		html += '</td><td>';
		html += makeStatsList('Correct Answers', data.leaderboard.team.correct, 'correct', 0, true);
		html += '</td></tr>';
		
		html += '</table>';
		html += '</div>';
		
		html += "<p><a id='game_return' href='#'>Return to my Game</a></p>";
	
		$('#game_box').html(html);
		
		$('#game_return').click(function(event){
			event.preventDefault();
			startGame(pfg.game.id);
		});
	});
}



/** Sets the left column sidebar to the default "Welcome to Play for Good" sidebar.
 *
 * Changing this text requires changing the actual code in this function, since it isn't something I
 * expect will happen very often. The other sidebars both get their data from other places.  
 */ 
function doWelcomeSidebar()
{
	if(pfg.leftbar != 'welcome')
	{
		var html = "<h2>Welcome...</h2>";
		html += "<p>to Play for Good. When you play any of our games, you help raise money for ";
		html += "programs serving people with disabilities and their families. The games on this site ";
		html += "have been developed by the Center for Persons with Disabilities at Utah State ";
		html += "University.</p>";
		html += "<br />";
		html += "<h2>How to Play</h2>";
		html += "<p>Play for Good hosts several games and game tracks. Either choose a difficulty ";
		html += "level or select a different game.</p>";
		html += "<p>Sponsors of the game will make a small donation to help fund the programs of the ";
		html += "Center for Persons with Disabilities at Utah State University.</p>";
		html += "<p>You can play any of the games as often as you like!</p>";
	
		$('#left_column').html(html);
		
		pfg.leftbar = 'welcome';
	}
}


/** Sets the left column sidebar to the game instructions for the current game
 *
 * The plan right now is to only show this sidebar during the first question of a new game, and then
 * show the "theme" sidebar for all subsequent questions.
 */
function doInstructionsSidebar()
{
	if(pfg.leftbar != 'instructions')
	{
		$('#left_column').html('<h2>'+pfg.game.title+'</h2><p>'+pfg.game.instructions+'</p>');
		
		pfg.leftbar = 'instructions';
	}
}


/** Sets the left column sidebar to the current theme or cause blurb
 *
 * The plan right now is to show the instructions sidebar for the first questions of a new game, and
 * this one for all subsequent questions.
 */
function doThemeSidebar()
{
	if(pfg.leftbar != 'theme')
	{
		$.get('/ajax/theme.ajax.json.php', null, function(theme, status)
		{
			$('#left_column').html(theme);
		});
	
		pfg.leftbar = 'theme';
	}
}



/** Set the left column sidebar to a team roster and center box to team stats
 */
function doTeamPage(team_id)
{
	$.getJSON('/ajax/team.ajax.json.php', {team_id: team_id}, function(team, status)
	{
		var leftbar = '';
		leftbar += '<div id="team_roster">';
		leftbar += '<p>Members of team</p>';
		leftbar += '<h2>'+team.name+'</h2>';
		leftbar += '<ul>';
		
		for(index in team.members)
		{
			var user = team.members[index];
			
			leftbar += '<li><p>'+user.username+'</p></li>';
		}
		
		leftbar += '</ul>';
		leftbar += '<p><a href="#" class="left_leaderboard">return to leaderboard</a></p>';
		
		leftbar += '</div>';
	
		$('#left_column').html(leftbar);
			
		pfg.leftbar = 'team';
	});
}



/** Put the player of the week (default) stats bar on the right hand column
 *
 * This is the simple clean sidebar we show when you aren't playing any game. It just shows the last
 * week's "Player of the Week" and maybe a few more things later.
 */  
function doPotwStatsbar()
{
	$.getJSON('/ajax/potw.ajax.json.php', function(potw, status)
	{
		$.get('/ajax/theme.ajax.json.php', null, function(theme, status)
		{
			var html = "";
			html += '<h2 style="text-align:right;">Player of the <br />';
			html += 'Week</h2>';
			html += '<p style="text-align:right; color:#555;"><strong>';
			html += jqueryEntities(potw[0].name);
			html += ' - ' + Math.round(potw[0].points) + ' points!';
			html += '</strong></p>';
			html += '<br /><br /><br />';
			html += theme;
			
			$('#right_column').html(html);
		});
	});
}


/** Update the game statistics on the right column sidebar
 *
 * The level parameter is kind of a hack, because when you first start playing a game, we load a new
 * question after we've already put the stats on the sidebar, so the level that comes back from that
 * (the very first) stats call is 0.5, the default, regardless of what difficulty you clicked on and
 * actually got. Passing the level parameter to updateStats just displays that value in place of the
 * returned value. Subsequent calls to updateStats should work with no further trouble.     
 */
function updateStats(level)
{
	$.getJSON('/ajax/stats.ajax.json.php', {game_id: pfg.game.id}, function(data, status){
		var mylevel = level ? level : data.score['level'];
	
		var stats = '<div id="stats">';
		
		stats += '<h2>Your Scores</h2>';
		stats += '<div id="scores">';
		
		
		//stats += '<h3 style="margin-top:5px;">Current Game</h3>';
		stats += '<div style="margin-bottom: 6px">';
		stats += '<strong>Total score:</strong> '+Math.round(data.score.total_points)+' points';
		stats += '</div>';
		
		stats += '<strong>Game score:</strong> '+Math.round(data.score.game_points)+' points<br>';

		stats += '<strong>Correct:</strong> '+data.score['correct']+'/'+data.score['rounds']+' ';
		stats += (data.score['rounds'] == 0 ? '-' : Math.round(data.score['correct'] / data.score['rounds'] * 100))+'%<br>';
		stats += '<strong>Difficulty level: '+Math.round(mylevel * 10)+'/10</strong>'
		
		stats += '<div style="margin-top: 6px;">';
		stats += '<strong>Total correct this week:</strong> '+data.score['correct_week'];
		stats += '</div>';
		
		
		var currentTree = parseInt(data.score['correct_week']);
		
		var bigtrees = "";
		while(currentTree >= 100)
		{
			bigtrees += "<img src='/img/tree/100.jpg'>";
			currentTree -= 100;
		}
		

		stats += "<img src='/img/tree/"+currentTree+".jpg'>";
		
		if(currentTree == 99) {
			stats += "<img width='0' height='0' src='/img/tree/0.jpg'>";
		} else {
			stats += "<img width='0' height='0' src='/img/tree/"+(currentTree+1)+".jpg'>";
		}
		
		stats += bigtrees;
		
		
		stats += '</div>';
		stats += "</div>";

		// This breaks if you do $('#right_column').html(stats);. I think it's a jquery bug
		$('#right_column').html(null);
		$('#right_column').append(stats);
		

		
		
		var leaders = '<div id="leaderboard">';	
		leaders += '<h2>Top Players</h2>';
		
		leaders += makeStatsList('Leaders this Week', data.leaderboard.user.points, 'points', 0);
		leaders += makeStatsList('Teams this Week',   data.leaderboard.team.points, 'points', 0);
		
		leaders += "<p><a id='full_leaderboard' href='#'>more game stats</a></p>";
		
		leaders += "<p>";
		leaders += "<a class='left_instructions' href='#'>game instructions</a>";
		leaders += "<br/>";
		leaders += "<a class='left_theme' href='#'>news/announcements</a>";
		leaders += "</p>";
		
		
		// This breaks if you do $('#right_column').html(stats);. I think it's a jquery bug
		$('#left_column').html(null);
		$('#left_column').append(leaders);
		
		$('#full_leaderboard').click(function(event){
			event.preventDefault();
			clearTimeout(pfg.newQuestionTimeout);
			doFullLeaderboard();
		});
		
	});
}



/** Print a leader list using the provided data
 *
 * We have several leaderboards that show up in the left sidebar, and several more that show up when
 * you load the full leaderboard in the game box, all of which are created the exact same way. Using
 * this function, we outsource the creation of those lists to a single place so we don't have to use
 * the same code copied and pasted over and over again    
 */  
function makeStatsList(title, data, item, round, center)
{
	var stats = '';
	
	if(data.length > 0)
	{
		if(center) {
			stats += '<center><h3>'+title+'</h3></center>';
		} else {
			stats += '<h3>'+title+'</h3>';
		}
		
		stats += '<ol>';
		
		for(index in data)
		{
			var row = data[index];
			
			var value = mult = Math.round(row[item] * Math.pow(10, round)) / Math.pow(10, round);
		
			if(row['current'] == '1' && (row['name'] == undefined || row['name'] == ""))
			{
				row['name'] = 'You';
			}
			
			if(row.type == 'team') {
				var name = "<a href='#team"+jqueryEntities(row['id'])+"' class='team'>"+jqueryEntities(row['name'])+"</a>";
			} else {
				var name = jqueryEntities(row['name']);
			}
			
			
			if(row['current'] == '1')
			{
				stats += "<li><p><strong>"+row['number']+'. '+name+" - "+value+"</strong></p></li>";
			}
			else
			{
				stats += "<li><p>"+row['number']+'. '+name+" - "+value+"</p></li>";
			}
		}
		
		stats += "</ol>";
	}
	
	return stats;
}


/** Swap out the ad banner for a new one
 *
 * Animates out the current ad banner, then animates in a new one. Automatically sets a timeout with
 * itself to replace the new ad at the specified time (set in the database with the other data about
 * the ad). Should only need to be called once at load time, after which point it does its thing for
 * the rest of the game with no further outside thought or direction.    
 */ 
function newAd()
{
	$.getJSON('/ajax/ad.ajax.json.php', function(ad, status)
	{
		var adImg = new Image();
		adImg.src = ad.src;
	
		$('#ad_box img').animate({opacity: 0}, 1000, function(){
			//$('#ad_box').animate({height: adImg.height}, 1000, function()
			//{
				if(ad.href) {
					$('#ad_box').html('<a href="'+ad.href+'"><img style="opacity:0" src="'+ad.src+'" alt="'+ad.alt+'"></a>');
				} else {
					$('#ad_box').html('<img style="opacity:0" src="'+ad.src+'" alt="'+ad.alt+'">');
				}
				
				
				$('#ad_box img').animate({opacity: 1}, 1000, function(){
					setTimeout(newAd, ad.seconds * 1000);	
				});
			//});
		});
	});
}



/** Like htmlentities, only for javascript via jquery
 *
 * Javascript, as it turns out, doesn't have any sort of native htmlentities function, a major issue
 * when you're trying to print arbitrary text strings to html code. Now, there may be another way of
 * doing this that's somehow better or more efficient, but this is what I came up with (well, what I
 * found on Google) and it does the trick.    
 */
function jqueryEntities(data)
{
	return $('<div/>').text(data).html();
}