/// <reference path="jQuery.intellisense.js"/>
/// <reference path="xeko.js"/>
/// <reference path="messaging.js"/>

$(document).ready(function() {
	xeko.drawers.items.inviteDrawer = { "id": "inviteDrawer", "closed": "-900px", "open": "0px", "onopenevent": "invitedraweropen" };

	xeko.events.notify("xeko.widgets.inviteAFriend.setAgentInfo", "invitedraweropen");
	xeko.events.notify("xeko.widgets.inviteAFriend.setAgentInfo", "login");

	$(".inviteForm").submit(function(e) { e.preventDefault(); });

	// Use the labels of the recipient boxes as the hint text
	$(".inviteRecipient").each(function() {
		var id = $(this).attr("id");
		var label = $("label[for=" + id + "]");
		var text = $.trim(label.text());

		$(this).val(text);
		$(this).addClass("instructional");

		// remove prompt text on field focus
		$(this).focus(function(e) {
			if (this.value == text) {
				this.value = "";
				$(this).removeClass("instructional");
			}
		});

		// re-add prompt text as necessary
		$(this).blur(function(e) {
			if (this.value == "") {
				this.value = text;
				$(this).addClass("instructional");
			}
		});
	});

	// Send Email button handler
	$(".inviteSendEmail").click(function(e) {
		e.preventDefault();
		if (xeko.forceLogin(xeko.messaging.alert.INVITE_LOGIN_REQUIRED)) {
			// find out which instance (page or drawer) the click originated from
			var instance = $(this).attr("id").substr("inviteSendEmail".length);
			if (xeko.widgets.inviteAFriend.validate(instance)) xeko.widgets.inviteAFriend.submit(instance);
		}
	});

	$("#inviteafriendClose").click(function(e) {
		e.preventDefault();
		xeko.drawers.slideDrawer("inviteDrawer", false);
	});
});



xeko.widgets.inviteAFriend = {
	"validate": function(instance) {
		var isValid = true;
		var validEmail = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;

		// First name is required
		xeko.validation.clearMessage("inviteFirstNameLabel" + instance);
		if ($("#inviteFirstName" + instance).text().length < 1) {
			xeko.validation.showMessage("inviteFirstNameLabel" + instance, xeko.messaging.alert.INVITE_NAME_MISSING);
			isValid = false;
		}

		// Validate sender email address
		xeko.validation.clearMessage("inviteEmailLabel" + instance);
		if (!validEmail.test($("#inviteEmail" + instance).text())) {
			xeko.validation.showMessage("inviteEmailLabel" + instance, xeko.messaging.alert.INVITE_SENDER_EMAIL_INVALID);
			isValid = false;
		}

		// Validate recipient email addresses
		var validEmailAddressFound = false;
		xeko.validation.clearMessage("inviteRecipientsLabel" + instance);
		$(".inviteRecipient").each(function() {
			var elmId = $(this).attr("id");
			var instructionText = $.trim($("label[for=" + elmId + "]").text());
			var email = $(this).val();

			// Only validate fields for this instance
			if (elmId.indexOf(instance) > -1) {
				// Only validate fields that are not blank
				if (email.length > 0 && email != instructionText) {
					if (validEmail.test(email)) {
						validEmailAddressFound = true;
					}
					else {
						xeko.validation.showMessage("inviteRecipientsLabel" + instance, xeko.messaging.alert.INVITE_RECP_EMAIL_INVALID);
						isValid = false;
					}
				}
			}
		});

		// Is there at least one valid recipient email?
		if (!validEmailAddressFound) {
			xeko.validation.showMessage("inviteRecipientsLabel" + instance, xeko.messaging.alert.INVITE_RECP_EMAIL_INVALID);
			isValid = false;
		}
		
		return isValid;
	},
	"submit": function(instance) {
		var senderName = $("#inviteFirstName" + instance).text();
		var senderEmail = $("#inviteEmail" + instance).text();
		var recipients = "";

		// Recipient email addresses are comma-delimited
		$(".inviteRecipient").each(function() {

			// Only use fields for this instance that have been filled in
			var elmId = $(this).attr("id");
			var instructionText = $.trim($("label[for=" + elmId + "]").text());
			var email = $(this).val();
			if (elmId.indexOf(instance) > -1 && email.length > 0 && email != instructionText) {
				recipients += email + ",";
			}
		});

		// Strip out last comma
		recipients = recipients.substr(0, recipients.length - 1)
		
		$.ajax(
		{
			type: "GET",
			url: "/widgets/widget.InviteAFriend.handler.php?type=submit"
					+ "&sendername=" + escape(senderName)
					+ "&senderemail=" + escape(senderEmail)
					+ "&recipients=" + escape(recipients)
			,
			beforeSend: function() { xeko.lightbox.show(xeko.strings.INVITE_SENDING, true, "inviteSubmit" + instance); },
			complete: function() {
				xeko.lightbox.hide("inviteSubmit" + instance);
			},
			success: function(xml) {
				if ($("invitation", xml).length > 0) {
					$("#inviteForm" + instance).hide();
					$("#inviteThanks" + instance).show();
				}
				else {
					xeko.widgets.inviteAFriend.hideError(instance);
					xeko.widgets.inviteAFriend.throwError(xeko.messaging.error.INVITE_SEND_ERROR, instance);
				}
			},
			error: function(xmlHttpRequest, status, err) {
				if (xmlHttpRequest.status > 0) {
					xeko.widgets.inviteAFriend.hideError(instance);
					xeko.widgets.inviteAFriend.throwError(xeko.messaging.error.INVITE_SEND_ERROR, instance);
				}
			}
		});
	},
//	"setAgentInfo": function(instance) {
	"setAgentInfo": function() {
		var instance = "Drawer";
		if ($("#inviteFirstName" + instance).text().length == 0) {
			$("#inviteFirstName" + instance).text(xeko.agentinfo.agentName);
		}
		if ($("#inviteEmail" + instance).text().length == 0) {
			$("#inviteEmail" + instance).text("invite@xeko.com");
		}
	},
	"throwError": function(msg, instance) {
		$("#inviteForm" + instance + ">div>p.error").text(msg);
		$("#inviteForm" + instance + ">div>p.error").show();
	},
	"hideError": function(instance) {
		$("#inviteForm" + instance + ">div>p.error").hide();
	}
};