$(document).ready(function() {
	xeko.widgets.agentAccount.getAgent();
	$("#agentAccountEditSaveChanges").click(function(e) {
		e.preventDefault();
		if (xeko.widgets.agentAccount.validate()) xeko.widgets.agentAccount.save();
	});
});

xeko.widgets.agentAccount =
{
	"password": "",
	"firstname": "",
	"postalcode": "",
	"products": "",
	"emailType" : "",
	"email": "",
	"altereco": "",
	"optin": "",
	"save": function() {
		var queryString = "firstname=" + xeko.widgets.agentAccount.firstname + "&" +
				"postalcode=" + xeko.widgets.agentAccount.postalcode + "&" +
				"emailaddress=" + xeko.widgets.agentAccount.email + "&" +
				"getsnewsletter=" + xeko.widgets.agentAccount.optin + "&" +
				"password=" + xeko.widgets.agentAccount.password + "&" +
				"avatarid=" + xeko.widgets.agentAccount.altereco + "&" +
				"products=" + xeko.widgets.agentAccount.products + "&";

		$.ajax({
			type: "GET",
			url: "/widgets/widget.AgentInfo.handler.php?request=agentupdate",
			data: queryString,
			beforeSend: function() {
				// lightbox while the POST is in progress
				xeko.lightbox.show("Please wait while we update your account.", true, "agentAcount");
			},

			success: function(xml) {
				// success?
				if ($(xml).find("agent").length == 0) {
					xeko.widgets.agentAccount.throwError(xeko.messaging.error.ACCOUNT_UPDATE_ERROR);
				}
				else {
					flashObj = document.getElementById("headerflash");
					flashObj.passLoginFromJS();
				
					// update agent obj
					xeko.debug.trace("updating...");
					xeko.widgets.logIn.updateUser();
					xeko.debug.trace("updated");
					
					$("#myAccount").hide();
					$("#myAccountThanks").show();
				}
			},
			error: function(xmlHttpRequest, status, err) {
				if (xmlHttpRequest.status > 0) xeko.widgets.agentAccount.throwError(xeko.messaging.error.ACCOUNT_UPDATE_ERROR);
			},
			complete: function() {
				// hide lightbox
				xeko.lightbox.hide("agentAcount");
			}
		});
	},
	"getAgent": function() {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=agentwithparent",
			success: function(xml) {
				// Check for existence of <agent> node for this Agent ID
				if ($(xml).find("agent").length == 1) {
					xeko.widgets.agentAccount.parseAgentXml(xml);
				}
			},
			error: function(xmlHttpRequest, status, err) {
				// this usually means it can't find the agent
			}
		});
	},
	"parseAgentXml": function(xml) {
		var hotspot = xeko.utilities.removeSpaces($("card>hotspot", xml).text());
		var number = $("card>number", xml).text();
		var avatarImg = "/images/cardart/" + hotspot + "/altereco/" + number + ".png";
		var agentid = $("userid", xml).text();
		var firstname = $("firstname", xml).text();
		var postalcode = $("postalcode", xml).text();
		var email = $("emailaddress", xml).text();
		var parentemail = $("parent>emailaddress", xml).text();
		var avatarid = $("avatar", xml).attr("id");
		var optin = ($("getsnewsletter", xml).text() == "1");

		$(".alterEco img").attr("src", avatarImg);
		$("div.agentName").text(agentid);
		$("#agentAccountEditFirstName").val(firstname);
		$("#agentAccountEditZipCode").val(postalcode);
		
		if (parentemail.length > 1) {
			$("#agentAccountEditEmail").val(parentemail);
			$("#agentAccountEditEmailLabel").text("Your Parent's Email Address");
			xeko.widgets.agentAccount.emailType = "parent";
		} else {
			$("#agentAccountEditEmail").val(email);
			$("#agentAccountEditEmailLabel").text("Your Email Address");
			xeko.widgets.agentAccount.emailType = "user";
		}
		
		xeko.widgets.agentAccount.products = ",";
		$("agentproducts>product", xml).each(function() {
			xeko.widgets.agentAccount.products += $(this).attr("id") + ",";
		});
		
		xeko.widgets.agentAccount.getAvatars(avatarid);
		xeko.widgets.agentAccount.getProducts();
	},
	"getAvatars": function(avatarid) {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=avatars",
			success: function(xml) {
				$("#agentaccountAvatarSelect").html("");
				var count = 1;

				//##TODO Get latin name
				$("avatar", xml).each(function() {
					var avatarName = $("name:eq(0)", this).text();
					var guid = $(this).attr("id");
					var hotspot = xeko.utilities.removeSpaces($("card>hotspot:eq(0)", this).text());
					var cardNo = $("card>number:eq(0)", this).text();
					var src = "/images/cardart/" + hotspot + "/altereco/" + cardNo + ".png";
					var latinName = "";	// TODO "<br/><span class='latinName'>(latin name)</span>";
					$("#agentaccountAvatarSelect").append("<div class='avatarrow'><input type=\"radio\" value=\"" + guid + "\" name=\"agentAccountAlterEco\" id=\"agentAccountAlterEco" + count + "\" /><label class=\"checkbox\" for=\"agentAccountAlterEco" + count + "\"><img src=\"" + src + "\" /></label><div style='padding-top: 8px;'><strong> " + avatarName + "</strong>" + latinName + "</div></div>");
					count++;
				});

				$("#agentaccountAvatarSelect div.avatarrow").click(function(e) {
					$("div#agentaccountAvatarSelect div.avatarrow").removeClass("selected");
					$(this).addClass("selected");
					$("input", this).attr("checked", "checked");
					xeko.debug.trace("clicked me");
				});
				
				// auto-select the current avatar
				$("input[value=" + avatarid + "]").parent().trigger("click");
			},
			error: function(xmlHttpRequest, status, err) {
				if (xmlHttpRequest.status > 0) xeko.widgets.register.throwError(xeko.messaging.error.AVATAR_SERVICE_ERROR);
			}
		});
	},
	"getProducts": function() {
		$.ajax({
			method: "get",
			url: "/widgets/widget.AgentInfo.handler.php?request=productsBlended",
			success: function(xml) {
				$("#agentAccountXekoProductsContainer>p:first").remove();

				$("product", xml).each(function() {
					var productName = $("name", this).text();
					var guid = $(this).attr("id");
					var isOwned = ($(this).attr("owned") == "true");
				
					var itemDiv = $("#agentAccountProduct").clone().appendTo("#agentAccountXekoProductsContainer");
					xeko.utilities.appendGuidToId(itemDiv, guid);
					$("input", itemDiv).attr("id", "agentAccountProductCheck" + guid);
					$("input", itemDiv).get(0).checked = isOwned;
					$("input", itemDiv).val(guid);
					$("label", itemDiv).attr("for", "agentAccountProductCheck" + guid);
					$("label", itemDiv).text(productName);
					
					// Previously selected products
					if (xeko.widgets.agentAccount.products.indexOf("," + guid + ",") > -1) $("input", itemDiv).get(0).checked = true;
				});
				
				//##TODO auto-select previously selected
			},
			error: function(xmlHttpRequest, status, err) {
				if (xmlHttpRequest.status > 0) xeko.widgets.register.throwError(xeko.messaging.error.PRODUCTS_SERVICE_ERROR);
			}
		});
	},
	"validate": function() {
		var isValid = false;
		
		if ($("input[name='agentAccountAlterEco']:checked").length > 0) {
			var alterEco = $("input[name='agentAccountAlterEco']:checked").val();
			xeko.validation.clearMessage("agentAccountAvatarSelect");
			isValid = true;
			xeko.widgets.agentAccount.altereco = $("input[name='agentAccountAlterEco']:checked").attr("value");
		}
		else {
			xeko.validation.showMessage("agentAccountAvatarSelect", xeko.messaging.alert.ALTER_ECO_MUST_SELECT);
			xeko.widgets.agentAccount.altereco = "";
		}
		
		// If password is specified, it must be at least five non-whitespace characters
		xeko.widgets.agentAccount.password = $("#agentAccountEditPassword").val();
		if (xeko.widgets.agentAccount.password.length > 0) {
			if (!xeko.validation.validatePassword($("#agentAccountEditPassword").val())) {
				xeko.validation.showMessage("agentAccountEditPasswordLabel", xeko.messaging.alert.PASSWORD_INVALID);
				isValid = false;
			}
			else xeko.validation.clearMessage("agentAccountEditPasswordLabel");

			// Passowrds must match
			if (xeko.widgets.agentAccount.password != $("#agentAccountEditPasswordConfirm").val()) {
				xeko.validation.showMessage("agentAccountEditPasswordConfirmLabel", xeko.messaging.alert.PASSWORDS_DO_NOT_MATCH);
				isValid = false;
			}
			else xeko.validation.clearMessage("agentAccountEditPasswordConfirmLabel");
		}

		// First name is required
		xeko.widgets.agentAccount.firstname = $("#agentAccountEditFirstName").val();
		if (xeko.widgets.agentAccount.firstname.length < 1) {
			xeko.validation.showMessage("agentAccountEditFirstNameLabel", xeko.messaging.alert.FIRST_NAME_MISSING);
			isValid = false;
		}
		else xeko.validation.clearMessage("agentAccountEditFirstNameLabel");

		// Postal code is required
		xeko.widgets.agentAccount.postalcode = $("#agentAccountEditZipCode").val();
		if (xeko.widgets.agentAccount.postalcode.length < 1) {
			xeko.validation.showMessage("agentAccountEditZipCodeLabel", xeko.messaging.alert.ZIP_CODE_MISSING);
			isValid = false;
		}
		else xeko.validation.clearMessage("agentAccountEditZipCodeLabel");

		// Xeko products checkboxes are optional
		xeko.widgets.agentAccount.products = "";
		$("input[name='agentAccountXekoProducts']").each(function() {
			if (this.checked) xeko.widgets.agentAccount.products += $(this).val() + ",";
		});
		if (xeko.widgets.agentAccount.products == "") xeko.widgets.agentAccount.products = -1;

		// Email address required
		if (xeko.widgets.agentAccount.emailType == "parent") {
			// Validate parent's email address
			xeko.widgets.agentAccount.email = $("#agentAccountEditEmail").val();
			if (!xeko.validation.validateEmail(xeko.widgets.agentAccount.email)) {
				xeko.validation.showMessage("agentAccountEditEmailLabel", xeko.messaging.alert.PARENT_EMAIL_INVALID);
				isValid = false;
			}
			else xeko.validation.clearMessage("agentAccountEditEmailLabel");
		} else {
			// Validate user's email address
			xeko.widgets.agentAccount.email = $("#agentAccountEditEmail").val();
			if (!xeko.validation.validateEmail(xeko.widgets.agentAccount.email)) {
				xeko.validation.showMessage("agentAccountEditEmailLabel", xeko.messaging.alert.USER_EMAIL_INVALID);
				isValid = false;
			}
			else xeko.validation.clearMessage("agentAccountEditEmailLabel");
		}
		
		// Opt-in
		xeko.widgets.agentAccount.optin = $("#agentAccountOptIn").get(0).checked;
		
		return isValid;
	},
	"throwError": function(msg) {
		$("div#myAccount p.error").text(msg).show();
	},
	"hideError": function() {
		$("div#myAccount p.error").hide();
	}
};