/// <reference path="jQuery.intellisense.js"/>
/// <reference path="xeko.js"/>
/// <reference path="messaging.js"/>

$(document).ready(function() 
{
	xeko.widgets.arcadeGames.renderGames();
		
	$(".arcadegamesContent>a").click(function(e) {
		if (!xeko.forceLogin(xeko.messaging.alert.GAMES_LOGIN_REQUIRED)) {
			e.preventDefault();
		}
	});
	
	// Boxes must be re-rendered upon login
	xeko.events.notify("xeko.widgets.arcadeGames.renderGames", "login");
	
});

xeko.widgets.arcadeGames = {
	"renderGames" : function() {
		$(".arcadegamesItem").each(function()
		{
			var guid = $(this).attr("id").substr("arcadegamesItem".length);
			xeko.widgets.arcadeGames.getAgentGame(guid);
		});
	},
	"getAgentGame" : function(guid)
	{
		$.ajax({
			type: "GET",
			url : "/widgets/widget.ArcadeGame.handler.php?gameid=" + guid,
			beforeSend: function() {  },
			complete: function() { $("#arcadegamesItem" + guid + " .arcadegamesInfoLoading").hide() },
			success : function(xml)
			{
				if ($("agentgame", xml).length == 1) xeko.widgets.arcadeGames.renderbox(xml, guid);
			},
			error : function()
			{
				// don't show points/plays box
			}
		});
	},
	"renderbox" : function(xml, guid)
	{
		var highscore = $("highscore", xml).text();
		highscore = xeko.utilities.formatPoints(isNaN(parseInt(highscore)) ? 0 : parseInt(highscore));
		var plays = $("remainingsessionstoday", xml).text();
		plays = isNaN(parseInt(plays)) ? "0" : parseInt(plays);
		var s = (plays == 1) ? "play" : "plays";
		
		var infoBox = $(".arcadegamesInfoBox", "#arcadegamesItem" + guid);
		$(".div1>.points", infoBox).text(highscore);
		
		// Unlimited plays begins at 99,999 -- different grid structure
		if (plays > 1000) {
			$(".div2", infoBox).text("");
			$(".div3>.daysText", infoBox).text("unlimited");
			$(".div3>.text", infoBox).text("plays today");
		} else {
			$(".div2>.days", infoBox).text(plays);
			$(".div3>.daysText", infoBox).text(s);
			$(".div3>.text", infoBox).text("left today");
		}
		
		infoBox.show();
	}
};