var Newsletter = {
	
	inputField: null,
	submitButton: null,
	inputDefault: 'Enter email address',
	
	init: function()
	{
		this.inputField = $('#subscribe input[type="text"]');
		this.submitButton = $('#subscribe a.newsletter-button');
		
		this.inputField.focus(function()
		{
			if ($(this).val() == Newsletter.inputDefault)
			{
				$(this).val('');
			}
		});
		this.inputField.blur(function()
		{
			if ($(this).val() == '')
			{
				$(this).val(Newsletter.inputDefault);
			}
		});
		this.submitButton.click(function(e)
		{
			Newsletter.subscribe();
			e.preventDefault();
		});
	},
	
	subscribe: function()
	{
		$('.newsletter').removeClass('err');
		
		switch (this.checkEmail())
		{
			case 'valid':
				$.ajax({
				   type: 'POST',
				   url: '/newsletter/add',
				   data: $('#subscribe').serialize(),
				   success: Newsletter.subscribeSucceeded,
				   error: Newsletter.subscribeFailed
				 });
				break;
			case 'invalid':
				this.showError('The email address you entered appears to be incorrect.');
				break;
			case 'empty':
				this.showError('Please enter a valid email address.');
				break;
		}
	},
	
	checkEmail: function()
	{
		var emailRegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		if ((this.inputField.val() == this.inputDefault) || (this.inputField.val() == ''))
		{
			return 'empty';
		}
		if (emailRegExp.test(this.inputField.val()))
		{
			return 'valid';
		}
		
		return 'invalid';
	},
	
	subscribeSucceeded: function(response)
	{
		if(response == 'OK') 
		{
			Newsletter.showConfirmation();
		}
		else if (response == '')
		{
			Newsletter.showError('An error occurred, please retry.');
		}
		else 
		{
			Newsletter.showError('Error on submitting, please enter another email address.');
		}
	},
	
	subscribeFailed: function(response)
	{
		this.showError('An error occurred, please retry.');
	},
	
	showError: function(message)
	{
		$('.newsletter').addClass('err');
		$('#subscribe em').html(message);
	},
	
	showConfirmation: function()
	{
		$('.newsletter').addClass('confirmed');
	}
	
};

jQuery(function() {
	
	Newsletter.init();
	
});

