/// <reference path="jQuery.intellisense.js"/>
/// <reference path="xeko.js"/>
/// <reference path="messaging.js"/>

$(document).ready(function() {
	xeko.widgets.activities.getChallenges();
	xeko.widgets.activities.renderArcadeGame();
	xeko.widgets.activities.getRandomQuizzle();
	
	// Login required for arcade games
	$("#activitiesGames a.playItNow").click(function(e) {
		if (xeko.forceLogin(xeko.messaging.alert.ARCADEGAMES_LOGIN_REQUIRED)) return true;
		else return false;
	});
});

xeko.widgets.activities = {
	"numberOfChallenges": 4,
	"currentChallenge": 1,
	"challengesXml": null,
	"getRandomQuizzle": function() {
		// Fetch a random Quizzle question
		$.ajax({
			type: "GET",
			url: "widgets/widget.Quizzles.handler.php?type=getrandomquizzle",
			beforeSend: function() { $("#activitiesQuizzles>div").hide(); },
			complete: function() {  },
			success: function(xml) {
				var question = $("quizzle:first>questiontext", xml).text();
				if (question.length > 100) question = question.substr(0, 100) + "...";
				$("#activitiesQuizzles>h2").text(question);
				$("#activitiesQuizzles>div.p2:first").text("Created by: " + $("quizzle:first>createdbyuserid", xml).text());
				$("#activitiesQuizzles>div").show();
			},
			error: function() {
				$("#activitiesQuizzles>h2").text("Unable to load Quizzle");
			}
		});
	},
	"getChallenges": function() {
		// Fetch most recent Challenges
		$.ajax({
			type: "GET",
			url: "/widgets/widget.Challenges.handler.php?type=getopenchallenges&sortby=datecreated,desc&amt=" + xeko.widgets.activities.numberOfChallenges,
			beforeSend: function() {  },
			complete: function() { $("#featuredChallengeLoading").hide() },
			success: function(xml) {
				xeko.widgets.activities.renderChallenges(xml);

				// Show the first Challenge
				$(".featuredChallengeCol2Content:eq(1)").show();
			},
			error: function() {
				//##TODO
			}
		});
	},
	"renderChallenges": function(xml) {
		// All Challenges are rendered out to the page (hidden by default)
		// Nav buttons merely show/hide divs on the page
		var i = 1;
		$("challenge", xml).each(function() {
			if (i <= xeko.widgets.activities.numberOfChallenges) {
				// Clone the template div
				var itemDiv = $("#featuredChallengeCol2Content").clone().removeAttr("id").appendTo("#featuredChallengeCol2");

				// Fetch values from nodes
				var guid = $(this).attr("id");
				var hotspot = xeko.utilities.removeSpaces($("card>hotspot", this).text())
				var cardNo = $("card>number", this).text();
				var pointvalue = $("pointvalue", this).text();
				var closedate = xeko.utilities.parseDate($("responseclosedate", this).text());
				var title = $("title", this).text();
				var agentid = $("createdbyuserid", this).text();
				var agentGuid = $("createdby", this).text();
				var description = $("questiontext", this).text();
				
				// Keep it within the bounds of the box
				if (description.length > 235) {
					description = description.substr(0, 235) + "...";
				}

				// Days left is # of days between closedate & now
				var now = new Date();
				var daysLeft = xeko.utilities.daysBetween(closedate, now);
				var s = (daysLeft == 1) ? "" : "s";

				// Card image
				var src = "/images/cardart/" + hotspot + "/activities_large/" + cardNo + ".jpg";
				$(".featuredChallengeImage", itemDiv).attr("src", src);

				// Info box
				$(".challengeInfoFrame .points", itemDiv).text(pointvalue);
				$(".challengeInfoFrame .days", itemDiv).text(daysLeft);
				$(".challengeInfoFrame .daysText", itemDiv).text("day" + s);

				// Title
				$(".featuredChallengeCol2b>h2", itemDiv).text(title);

				// Creator ID
				$(".featuredChallengeCol2b>h3", itemDiv).text(agentid);

				xeko.widgets.activities.setAlterEco(agentGuid, itemDiv);

				// Description
				$(".featuredChallengeCol2b>p", itemDiv).text(description);

				// Link
				$(".featuredChallengeTry", itemDiv).attr("href", "/challenges/" + guid);

				// Previous button
				if (i == 1) {
					$(".featuredChallengePrevious", itemDiv).attr("src", "/images/btn/btn_challenges_prevdisabled.png");
				}
				else {
				  $(".featuredChallengePrevious", itemDiv).attr("src", "/images/btn/btn_challenges_prev.png");
				  var prv = i - 1;
					$(".featuredChallengePrevious", itemDiv).click(function() {
						$(".featuredChallengeCol2Content").hide();
						$(".featuredChallengeCol2Content:eq(" + prv + ")").show();
					});
				}

				// Next button
				if (i == xeko.widgets.activities.numberOfChallenges) {
				  $(".featuredChallengeNext", itemDiv).attr("src", "/images/btn/btn_challenges_nextdisabled.png");
				}
				else {
				  $(".featuredChallengeNext", itemDiv).attr("src", "/images/btn/btn_challenges_next.png");
				  var nxt = i + 1;
					$(".featuredChallengeNext", itemDiv).click(function() {
						$(".featuredChallengeCol2Content").hide();
						$(".featuredChallengeCol2Content:eq(" + nxt + ")").show();
					});
				}
			}
			i++;
		});
	},
	"setAlterEco": function(guid, div) {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=avatarbyguid&guid=" + guid,
			success: function(xml) {
				// Check for existence of <agent> node for this Agent ID
				if ($("agentavatars>agentavatar", xml).length == 1) {
					// Avatar
					var card = $("agentavatars>agentavatar>avatar>card", xml)
					var avatarImg = "/images/cardart/" + xeko.utilities.removeSpaces($("hotspot", card).text()) + "/altereco/" + $("number", card).text() + ".png";

					$("img.featuredChallengeAlterEco", div).attr("src", avatarImg);
				}
			},
			error: function(xmlHttpRequest, status, err) {
				// this usually means it can't find the agent
			}
		});
	},
	"renderArcadeGame": function() {
		var games = new Array();
		games[0] = new Array("Hairy the Nibbler", "Hairy the lemur is craving a treat, but what on Earth does he like to eat?", "/hairy");
		games[1] = new Array("Squirrel Flight", "Glide from tree to tree to collect yummy snacks and Xeko Points.", "/squirrel");
		games[2] = new Array("Panda Maze", "The baby panda is hungry--help it get a meal of delicious bamboo.", "/panda");

		var id = Math.ceil(Math.random() * 3) - 1;
		var game = games[id];
		$("#activitiesGames h2").text(game[0]);
		$("#activitiesGames p").text(game[1]);
		$("#activitiesGames a.playItNow").attr("href", game[2]);
	}
};