// Finds all forms with class="signup"
// Expects a form element named "address" for the email
// Uses the original form action for POSTing
// Appreciates when there's an element with class="subscribe-message" in the
//   form for spewing feedback
// Will hide anything inside the form with class="hideonsuccess" and display
//   anything with class="showonsuccess" when subscription succeeds
// Will fade out & disable anything inside elements with
//   class="disablewhileprocessing"
// Requires at least jQuery 1.4

$(function() {
	$('form.signup').submit(subscribe).each(function() {
		$(this).data('oldaction', this.action);
	}).removeAttr('action').removeAttr('method');
});

function subscribe() {
	var form = $(this);
	var messageDiv = $('.subscribe-message, #subscribe-message', form);
	var disableWhileProcessing = $('.disablewhileprocessing', form);
	var address = $('input[name=address]', form);
	var cookieName = $('input[name=cookie]', form).val();

	if (address.val() == '') {
		if (messageDiv.length)
			messageDiv.html(
				'You left the email address field blank.'
			).removeClass('success').addClass('error').show();
		else
			alert('You left the email address field blank.');
		return false;
	}

	$.ajax({
		url: form.data('oldaction'),
		type: 'POST',
		data: {address: address.val(), ajax: 'true'},
		dataType: 'text',
		beforeSend: function(req) {
			$('input', disableWhileProcessing).attr('disabled', 'disabled');
			disableWhileProcessing.fadeTo('fast', 0.4);
			messageDiv.removeClass('error').html('<div style="text-align:center">'
				+ '<img src="/global/images/loading-32x32.gif" alt="Loading..." /></div>');
		},
		success: function(data, textStatus, req) {
			$('input', disableWhileProcessing).removeAttr('disabled');
			disableWhileProcessing.filter(':animated').stop(true);
			disableWhileProcessing.fadeTo('fast', 1);
			// Subscribed
			if (req.status == 201) {
				if (messageDiv.length)
					messageDiv.html(data).removeClass('error').addClass('success').show();
				else
					alert(data);

				var eventID = req.getResponseHeader('X-SubscriberEventID');
				var trackingBug = $('<img src="https://secure.augusthome.com/'
					+ 'global/email/signed-up/' + eventID + '/?ajax=true">');
				$(document.body).append(trackingBug);

				$('.hideonsuccess', form).hide();
				$('.showonsuccess', form).show();

				if (cookieName) {
					var date = new Date();
					date.setTime(date.getTime() + (5 * 365 * 24 * 60 * 60 * 1000));
					var expires = "; expires="+date.toGMTString();
					document.cookie = cookieName + "=" + address.val() + expires + "; path=/";
				}
			}
			// Errors
			else if (req.status == 200) {
				if (messageDiv.length)
					messageDiv.html(data).removeClass('success').addClass('error').show();
				else
					alert(data);
			}
		}
	});

	return false;
}
 
