/// <reference path="jQuery.intellisense.js"/>
/// <reference path="xeko.js"/>
/// <reference path="messaging.js"/>

$(document).ready(function() {

	xeko.widgets.myagentfiles.getAgent(xeko.agentinfo.agentGUID);
	xeko.widgets.myagentfiles.getSavedActivities();
	xeko.widgets.myagentfiles.getAgentActivities();
	xeko.widgets.myagentfiles.getRecentPoints();
	xeko.widgets.myagentfiles.getRecentMission();
	xeko.widgets.myagentfiles.getOtherAgentActivity();

	$("div#agentsummarynav button").click(function(e) {
		e.preventDefault();
		xeko.widgets.myagentfiles.summary.navclick($(this).attr("id"));
		this.blur();
	});

	xeko.widgets.myagentfiles.summary.navclick("activitiessaved");
});

xeko.widgets.myagentfiles = {
	"votedLoaded" : false,
	"voted" : {},
	"challengeState" : {
		"open" : 1,
		"agentVoting" : 2,
		"creatorVoting" : 3,
		"hallOfFame" : 4
	},
	"summary": {
		"navclick": function(objId) {
			$("div#agentsummarynav").removeClass();
			$("div#agentsummarynav").addClass(objId);

			// Show detail tab
			$("div.activityDetail").hide();
			$("div#" + objId + "Detail").show();
		}
	},
	"getAgent": function(guid) {
		$.ajax(
		{
			method: "get",
			url: "widgets/widget.AgentInfo.handler.php",
			success: function(xml) {
				// Check for existence of <agent> node for this Agent ID
				if ($(xml).find("agent").length == 1) {
					xeko.widgets.myagentfiles.parseAgentXml(xml);
				}
			},
			error: function(xmlHttpRequest, status, err) {
				// this usually means it can't find the agent
			}
		});
	},
	"getSavedActivities": function() {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=agentfavorites&filter=challenge",
			success: function(xml) {
				$("#activitiessavedDetail>*:not(#agentsummarySavedActivity)").remove();
				if ($("agentfavorite", xml).length == 0) {
					$("#activitiessavedDetail").html("<p>No saved activites were found.</p>");
				}
				else {
					$("agentfavorite", xml).each(function() {
						var hotspot = xeko.utilities.removeSpaces($("challenge>card>hotspot", this).text());
						var cardnum = $("challenge>card>number", this).text();
						var title = $("challenge>title", this).text();
						var byagent = $("challenge>createdbyuserid", this).text();
						var points = $("challenge>pointvalue", this).text();
						var favoriteGuid = $(this).attr("id");
						var challengeGuid = $("favoriteitemid", this).text();
						
						var src = "/images/cardart/" + hotspot + "/activities_medium/" + cardnum + ".jpg";
						var href = "/challenges/" + challengeGuid;
				
						// Days left is # of days between closedate & now
						var responseCloseDate = xeko.utilities.parseDate($("responseclosedate", this).text());
						var now = new Date();
						var daysLeft = xeko.utilities.daysBetween(responseCloseDate, now);
						var s = (daysLeft == 1) ? "" : "s";
						
						// Clone the template div and append to the container
						var challengediv = $("#agentsummarySavedActivity").clone().appendTo("#activitiessavedDetail");
						xeko.utilities.appendGuidToId(challengediv, challengeGuid);
						
						$("img.cardImg", challengediv).attr("src", src);
						$("div.detailContainer>h2", challengediv).text(title);
						$("div.detailContainer>div.agent>strong", challengediv).text(byagent);
						$("div.detailContainer>a", challengediv).attr("href", href);
						$("div.openChallengeInfo>div.div1>span.points", challengediv).text(points);
						$("div.openChallengeInfo>div.div2>span.days", challengediv).text(daysLeft);
						$("div.openChallengeInfo>div.div3>span.daysText", challengediv).text("day" + s);
						
						$("div.detailContainer>div.removeBookmark", challengediv).click(function(e) {
							e.preventDefault();
							xeko.widgets.myagentfiles.removeBookmark(favoriteGuid, challengeGuid);
						});
					});
				}
			}
		});
	},
	"getAgentActivities": function() {
		// Reset
		xeko.widgets.myagentfiles.votedLoaded = false;
		xeko.widgets.myagentfiles.voted = {};

		$.ajax({
			method: "get",
			url: "/widgets/widget.Challenges.handler.php",
			data: "type=getvoted",
			success: function(xml) {
				// success?
				if ($("error", xml).length > 0) {
					//##TODO how to handle this error?
					xeko.debug.trace('Unable to load voted: ' + err);
				}
				else if ($("agentchallengeresponsevote", xml).length > 0) {
					$("agentchallengeresponsevote", xml).each(function() {
						// Agent's votes are stored as a name-value pair with the challenge id as the index
						xeko.widgets.myagentfiles.voted[$("challengeid", this).text()] = $("agentchallengeresponseid", this).text();
					});
				}
					
				// Votes are loaded; now load and render created challenges
				xeko.widgets.myagentfiles.getCreatedChallenges();

			},
			error: function(xmlHttpRequest, status, err) {
				//##TODO how to handle this error?
				xeko.debug.trace('Unable to load voted: ' + err);
			},
			complete: function() {
				xeko.widgets.myagentfiles.votedLoaded = true
			}
		});
	},
	"getCreatedChallenges" : function() {
		$.ajax({
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=agentcreated",
			success: function(xml) {
				$("#activitiescreatedDetail>p:first").hide();
				if ($("challenge", xml).length == 0) {
					$("#activitiescreatedDetail").html("<p>No created activites were found.</p>");
				} else {
					$("challenge", xml).each(function() {
						var hotspot = xeko.utilities.removeSpaces($("card hotspot", this).text());
						var cardnum = $("card number", this).text();
						var title = $("title", this).text();
						var byagent = $("createdbyuserid", this).text();
						var points = $("pointvalue", this).text();
						var guid = $(this).attr("id");
						var winnerUserId = $("winninguserid", this).text();
						
						var src = "/images/cardart/" + hotspot + "/activities_medium/" + cardnum + ".jpg";
				
						// Determine the state of this Challenge
						var expirationDate = xeko.utilities.parseDate($("expirationdate", this).text());
						var responseCloseDate = xeko.utilities.parseDate($("responseclosedate", this).text());
						var creatorVoteDate = xeko.utilities.parseDate($("creatorvotedate", this).text());
						var votingCloseDate = xeko.utilities.parseDate($("votingclosedate", this).text());
						var now = new Date();
						var thisChallengeType;
						if (responseCloseDate > now) thisChallengeType = xeko.widgets.myagentfiles.challengeState.open;
						if (responseCloseDate <= now && creatorVoteDate > now) thisChallengeType = xeko.widgets.myagentfiles.challengeState.agentVoting;
						if (creatorVoteDate <= now && votingCloseDate > now) thisChallengeType = xeko.widgets.myagentfiles.challengeState.creatorVoting;
						if (votingCloseDate <= now) thisChallengeType = xeko.widgets.myagentfiles.challengeState.hallOfFame;
						
						// Clone the template div and append to the container
						var challengediv = $("#agentsummaryCreated").clone().appendTo("#activitiescreatedDetail");
						xeko.utilities.appendGuidToId(challengediv, guid);
						
						$("img.cardImg", challengediv).attr("src", src);
						$("div.detailContainer>h2", challengediv).text(title);
						$("div.detailContainer>div.agent>strong", challengediv).text(byagent);
						$("div.openChallengeInfo>div.div1>span.points", challengediv).text(points);
						
						// Challenge is open: points/days remaining
						// Agent Voting: days until voting/"see votes" link
						// Creator Voting: days left to vote/"vote now" link
						// Hall of Fame: "challenge closed"/winner
						switch (thisChallengeType) {
							case xeko.widgets.myagentfiles.challengeState.open:
								$("div.detailContainer>a", challengediv).attr("href", "/challenges/" + guid);
								$("div.detailContainer>a", challengediv).text("View");
								
								// Days left is # of days between closedate & now
								var daysLeft = xeko.utilities.daysBetween(responseCloseDate, now);
								var s = (daysLeft == 1) ? "" : "s";
								$("div.openChallengeInfo>div.div2>span.days", challengediv).text(daysLeft);
								$("div.openChallengeInfo>div.div3>span.daysText", challengediv).text("day" + s);
								$("div.openChallengeInfo", challengediv).show();
								break;
							case xeko.widgets.myagentfiles.challengeState.agentVoting:
							case xeko.widgets.myagentfiles.challengeState.creatorVoting:
								$("div.detailContainer>a", challengediv).attr("href", "/challengesvote/" + guid);
								$("div.detailContainer>a", challengediv).text("Vote");
								
								if (xeko.widgets.myagentfiles.voted[guid]) {
									// user or owner has already voted
									$("div.votingChallengeInfo a", challengediv).remove();
									$("div.votingChallengeInfo>div.div2", challengediv).append("<span class=\"vote\">voted</span>");
									
									// Days left is # of days between votingCloseDate & now
									var daysLeft = xeko.utilities.daysBetween(votingCloseDate, now);
									var s = (daysLeft == 1) ? "" : "s";

									$("div.votingChallengeInfo span.days", challengediv).text(daysLeft + " day" + s);
									$("div.votingChallengeInfo span.text", challengediv).text("until close");
									$("div.votingChallengeInfo", challengediv).show();
								}
								else if (creatorVoteDate > now) {
									// Challenge owners cannot vote until creatorVoteDate has passed
									var daysLeft = xeko.utilities.daysBetween(creatorVoteDate, now);
									var s = (daysLeft == 1) ? "" : "s";
									
									$("div.votingChallengeInfo a", challengediv).text("see votes");
									$("div.votingChallengeInfo a", challengediv).attr("href", "/challengesvote/" + guid);

									$("div.votingChallengeInfo span.days", challengediv).text(daysLeft + " day" + s);
									$("div.votingChallengeInfo div.text", challengediv).text("until voting");
									$("div.votingChallengeInfo", challengediv).show();
								}
								else {
									// owner can vote
									$("div.votingChallengeInfo a", challengediv).attr("href", "/challengesvote/" + guid);

									// Days left is # of days between votingCloseDate & now
									var daysLeft = xeko.utilities.daysBetween(votingCloseDate, now);
									var s = (daysLeft == 1) ? "" : "s";

									$("div.votingChallengeInfo span.days", challengediv).text(daysLeft + " day" + s);
									$("div.votingChallengeInfo span.text", challengediv).text("left to vote");
									$("div.votingChallengeInfo", challengediv).show();
								}
								$("div.votingChallengeInfo", challengediv).show();
								break;
							case xeko.widgets.myagentfiles.challengeState.hallOfFame:
								$("div.detailContainer>a", challengediv).attr("href", "/challengeshalloffame/" + guid);
								$("div.detailContainer>a", challengediv).text("See Results");
								
								if (winnerUserId.length > 0) {
									$("div.hallOfFameChallengeInfo>div.div2>div.chosen", challengediv).text(winnerUserId);
									$("div.hallOfFameChallengeInfo>div.div2", challengediv).show();
								}
								$("div.hallOfFameChallengeInfo", challengediv).show();
								break;
						}
						
					});
				}
			}
		});
	},
	"parseAgentXml": function(xml) {
		// Avatar
		var avatarImg = "/images/cardart/" + xeko.utilities.removeSpaces($("card>hotspot", xml).text()) + "/altereco/" + $("card>number", xml).text() + ".png";

		$(".alterEco img").attr("src", avatarImg);
		$(".agentName").text($("userid", xml).text());
	},
	"getRecentPoints": function() {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=agentpointstotal",
			success: function(xml) {
				$("#agentSummaryRecentPoints").empty();
				if ($("agentpoints", xml).size() == 0) {
					$("#agentSummaryRecentPoints").html("<p>No points yet!</p>");
				}
				else {
					$("agentpoints", xml).each(function(i) {
						if (i < 3) {
							var points = $("value", this).text();
							var earnedfor = $("earnedfor", this).text();
							$("#agentSummaryRecentPoints").append("<div><span class='points'>" + points + "</span> Points | " + earnedfor + "</div>");
						}
					});
					$("#agentSummaryRecentPoints").append("<a href='/mypoints'>See points detail</a>");
				}
			}
		});
	},
	"getOtherAgentActivity": function() {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.Challenges.handler.php?type=recentresponse",
			success: function(xml) {
				$(".recentActivityAgentName").empty();
				$(".recentActivityName").empty();
				if ($("agentchallengeresponse ", xml).size() == 0) {
					$("#agentSummaryAgentActivity").hide();
				} else {
					var title = $("title", xml).text();
					if (title.length > 32) title = title.substr(0, 32) + "...";
					$("span.recentActivityAgentName").text($("agent>userid", xml).text());
					$("#recentActivityName").text(title);
					$("a.recentActivity").attr("href", "/challenges/" + $("challengeid", xml).text());
					$("#agentSummaryAgentActivityDetail").show();
				}
			}
		});
	},
	"getRecentMission": function() {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.Missions.handler.php?type=getfavorites",
			success: function(xml) {
				if ($("agentfavorite", xml).size() == 0) {
					$("#agentSummaryRecentMissions").empty();
					$("#agentSummaryRecentMissions").html(xeko.messaging.alert.MISSIONS_SAVED_NONE);
				}
				else {
					var fave = $("agentfavorite:first", xml);

					// Mission Name
					$("#agentSummaryRecentMissions h2").text($("name:first", fave).text() + ":");

					// Show links
					$("#recentMissionLinks").show();
					$("#recentMissionLinks a#completeMission").attr("href", "/missions");
					//$("#recentMissionLinks a#completeMission").attr("href", "/missions/" + $("mission", fave).attr("id"));
					$("#recentMissionLinks a#seeMission").attr("href", "/mymissions");
					//$("#recentMissionLinks a#seeMission").attr("href", "/mymissions/" + $("mission", fave).attr("id"));

					// Rewards
					var rewardsDiv = $(".missionItemRewards");
					var highestPointValue = 0;
					var reward = {};
					var numberOfRewardsBoxes = 0;
					$("rewards>reward", fave).each(function() {
						// Total points for this mission will be whichever reward has the highest point value
						var thisPointValue = parseInt($("triggervalue", this).text());
						if (thisPointValue > highestPointValue) highestPointValue = thisPointValue;

						// If this reward type is a badge, add it to the collection
						if ($("rewardtype", this).text() == "Badge") {
							var badgeId = $("badge>imageidentifier", this).text();
							var imgSrc = "/images/badges/g_badge_" + badgeId + ".png"
							reward[numberOfRewardsBoxes] = "<div class=\"missionItemReward\"><img src=" + imgSrc + " alt=\"\" /></div>";
							numberOfRewardsBoxes++;
						}

						// If this reward type is a digital card, add it to the collection
						if ($("rewardtype", this).text() == "Digital Card") {
							// Not supported yet
						}
					});

					// Add points, if applicable
					if (highestPointValue > 0) {
						rewardsDiv.append(
						"<div class=\"missionItemPoints\">" +
						xeko.utilities.formatPoints(highestPointValue) +
						"<small>points</small>" +
						"</div>"
						);
					}

					// Add rewards, if applicable
					for (var i = 0; i < numberOfRewardsBoxes; i++) {
						// add separator if there is already content in the div
						if (rewardsDiv.children().length > 0) {
							rewardsDiv.append(
							"<img " +
							"src=\"/images/g/g_mission_box_divider.gif\" " +
							"alt=\"\" " +
							"class=\"missionItemRewardDivider\" " +
							"/>"
							);
						}

						// add the reward
						rewardsDiv.append(reward[i]);
					}

					// Mission objectives
					var numObjectives = 0;
					var totalPercent = 0;
					$("missionobjectives>missionobjective", this).each(function() {
						var objectivePercent = parseInt($("percentcomplete", this).text());
						objectivePercent = isNaN(objectivePercent) ? 0 : objectivePercent;

						totalPercent += objectivePercent;
					});

					//$("#agentSummaryRecentMissions").append(totalPercent + "%");


				}
			},
			error: function(xmlHttpRequest, status, err) {
				if (xmlHttpRequest.status > 0) $("#agentSummaryRecentMissions").html(xeko.messaging.error.MISSIONS_SAVED_LOAD_ERROR);
			}
		});
	},
	"removeBookmark" : function(favoriteGuid, challengeGuid) {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.Challenges.handler.php?type=deletefavorite&guid=" + favoriteGuid,
			beforeSend: function() { xeko.lightbox.show(xeko.strings.CHALLENGE_FAV_DELETE_WAIT, true, "removeBookmark") },
			complete: function() { xeko.lightbox.hide("removeBookmark"); },
			success: function(xml) {
				if ($("success", xml).length > 0) {
					$("#agentsummarySavedActivity" + challengeGuid).hide("fast", function() {
						$("#agentsummarySavedActivity" + challengeGuid).remove();
					});
				} else {
					//##TODO
				}
			}
		});
	}
};