var NewsletterSubscription = function(container)
{

	this.container = $(container);

	this.postUrl = 'ajax/postNewsletterSubscription.php';

	this.subscribe = function(name, email) {
		if (name.empty() || email.empty()) { this.showError('Please fill in all values.'); }
		else {
			this.getFormElement().disable();

			var self = this;
			new Ajax.Request(this.postUrl, {
				method: 'post',
				parameters: { name: name, email: email },

				onSuccess: function(transport) {
					self.getFormElement().enable();
					if (!transport.responseText.strip().empty()) { self.showError('Something went wrong: ' + transport.responseText); }
					else { self.subscribed(); }
				},
				onFailure: function() { self.showError('Something went wrong... sorry'); }
			});
		}
	};


	this.subscribed = function() {
		this.showSuccess('Thank you for subscribing to our newsletter.<br><a href="javascript:newsletterSubscription.hide();">Close this window.</a>');
		this.getErrorElement().hide();
		this.getFormElement().hide();
	};

	this.show = function() { this.getContainerElement().show(); };
	this.hide = function() { this.getContainerElement().hide(); this.reactivateForm(); };


	this.reactivateForm = function()
	{
		var formElement = this.getFormElement();
		formElement.show();
		formElement.enable();
		formElement.getElements().each(function(element) { element.clear(); });
		this.getSuccessElement().hide();
	};


	this.toggleVisibility = function()
	{
		if (this.getContainerElement().visible()) { this.hide(); }
		else { this.show(); }
	};

	this.showError = function(error)
	{
		var theElement = this.getErrorElement();
		theElement.update(error);
		theElement.show();
	};

	this.showSuccess = function(success)
	{
		var theElement = this.getSuccessElement();
		theElement.update(success);
		theElement.show();
	};



	this.getContainerElement = function() { return this.container; }
	this.getFormElement      = function() { return this.container.select('.form form').first() };
	this.getErrorElement     = function() { return this.container.select('.form .error').first(); };
	this.getSuccessElement   = function() { return this.container.select('.form .success').first(); };

};


document.observe('click', function(evt) { var element = evt.element(); if (element.id != 'newsletter' && !element.descendantOf('newsletter')) { $('newsletter').hide(); } });
