$(document).ready(function() {
  xeko.widgets.agentpoints.getAgent();
  xeko.widgets.agentpoints.renderPoints();

  $("#pointsPopup").click(function(e) {
    e.preventDefault();
    $(".postItOpen").show();
    $(".postItClosed").hide();
  });

  $("#closePointsPopup").click(function(e) {
    e.preventDefault();
    $(".postItOpen").hide();
    $(".postItClosed").show();
  });
});

xeko.widgets.agentpoints =
{
  "renderPoints": function() {
    $.ajax
		({
		  type: "GET",
		  url: "/widgets/widget.AgentInfo.handler.php?request=agentpointstotal",
		  success: function(xml) {
		    $("ul#agentpointslist").show();
		    $("div#pointtotals").html("");
		    //var totalpoints = $("totalpoints", xml).text();
		    //$("#agenttotalpoints").html(xeko.utilities.formatPoints(totalpoints));
		    $("missions mission", xml).each(function() {
		      var mission = $("name", this).text();
		      $("div#pointtotals").append("<div class='pointtotal'><img src='/images/btn/btn_closed.png' id='openCloseButton" + xeko.utilities.removeSpaces(mission) + "' class='openCloseButton' /><h2>" + mission + "</h2><div class='totalPoints'>" + xeko.utilities.formatPoints($("points", this).text()) + " pts</div><div class='clear'></div></div>");
		    });

		    $("agentpoints", xml).each(function() {
		      var dateawarded = xeko.utilities.formatShortDate($("dateearned", this).text());
		      var pointtype = $("type", this).text();
		      var pointevent = $("earnedfor", this).text();
		      var points = xeko.utilities.formatPoints($("value", this).text());
		      $("ul#agentpointslist").append("<li><span class='date'>" + dateawarded + "</span><span class='desc'>" + pointtype + "</span><span class='desc'>" + pointevent + "</span><span class='pts'>" + xeko.utilities.formatPoints(points) + " pts</span></li>");
		    });

		  },
		  error: function(xmlHttpRequest, status, err) {}
		});
  },
  "getAgent": function() {
    $.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.agentpoints.parseAgentXml(xml);
		    }
		  },
		  error: function(xmlHttpRequest, status, err) {
		    // this usually means it can't find the agent
		  }
		});
  },
  "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);
  }
};