$(document).ready(function(){
	$('a.button, button').button();
	$('form.newsletter-signup input:text').bind('focus', function(){
		if ($(this).val() == 'Email Address') {
			$(this).val('').addClass('focus');
		}
	}).bind('blur', function(){
		if ($(this).val() == '') {
			$(this).removeClass('focus').val('Email Address');
		}
	});
	$('form.newsletter-signup button[type=submit]').bind('click', function(event){
		event.preventDefault();
		var parentForm = $(this).parents('form');
		parentForm.children('div.newsletter-result').fadeOut(function(){
			$(this).removeClass('error');
		});
		$.ajax({
			type: 'POST',
			url: '/newsletters/subscribe.json',
			data: parentForm.serialize(),
			dataType: 'json',
			success: function(data) {
				if (data.success) {
					parentForm.children('div.newsletter-input').fadeOut(function(){
						parentForm.children('div.newsletter-result').html('Thanks for subscribing! Please check your email<br />to confirm your subscription.').fadeIn();
					});
				} else {
					if (data.error.code == 502) {
						parentForm.children('div.newsletter-result').addClass('error').html('Please enter a valid email address!').fadeIn();
					} else {
						parentForm.children('div.newsletter-result').addClass('error').html('We\'re sorry but we cannot process<br />subscriptions right now. Please try again later.');
					}
				}
			}
		});
	});
});
