var speed = 315;

function drawRoundedCorners()
{
	// Allow Gecko and WebKit to display CSS3 features still implemented as browser
	// extensions... without breaking validation! I'm such a cheater :P
	$('#box')
		.css('-moz-border-radius', '15px')
		.css('-webkit-border-radius', '15px');
	
	$('#sub input[type="text"]')
		.css('-moz-border-radius', '5px')
		.css('-webkit-border-radius', '5px');
	
	$('#sub button')
		.css('-moz-border-radius', '20px')
		.css('-webkit-border-radius', '20px');
}

function showResult(html)
{
	$('#sub')
		.prepend(html)
		.find('.result')
		.hide()
		.animate({ height: 'show', opacity: 'show' }, speed);
}

function showErrors(errors)
{
	showResult('<ul class="result"><li>' + errors.join('</li><li>') + '</li></ul>');
	
	$('#sub .result')
		.idle(3000)
		.animate({ height: 'hide', opacity: 'hide' }, speed, function()
		{
			$('#sub-submit button').removeAttr('disabled');
			$(this).remove();
		});
}

function showSuccess(success)
{
	$('#box .intro + p').animate({ height: 'hide', opacity: 'hide' }, speed, function()
	{
		showResult('<p class="result">' + success + '</p>');
		$(this).remove();
	});
}

$(function()
{
	drawRoundedCorners();
	
	$('#sub-name input').defaultText('Your name').prev().text('');
	$('#sub-email input').defaultText('Your email address').prev().text('');
	
	$('#sub-form').submit(function()
	{
		if ($('#sub-submit button').attr('disabled') == 'disabled')
		{
			return false;
		}
		
		var name   = $('#sub-name input').val(), 
			email  = $('#sub-email input').val(), 
			key    = $('#sub-key').val(), 
			errors = [];
		
		$('#sub-submit button').attr('disabled', 'disabled');
		
		if (name == '')
		{
			$('#sub-name input').val('Your name');
			errors.push('Please enter your name.');
		}
		
		if (email == '')
		{
			$('#sub-email input').val('Your email address');
			errors.push('Please enter your email address.');
		}
		
		if (errors.length > 0)
		{
			showErrors(errors);
		}
		else
		{
			$('#sub-submit button').fadeOut(speed, function()
			{
				$('#sub-submit .ajax-spinner').fadeIn(speed).css('display', 'block');
			});
			
			$.post('subscribe_c.php', $('#sub-form').serialize(), function(response)
			{
				if (response.errors)
				{
					showErrors(response.errors);
				}
				else if (response.success)
				{
					showSuccess(response.success);
					
					$('#sub-submit button')
						.text('Thank you!')
						.attr('disabled', 'disabled')
						.addClass('disabled');
				}
				
				$('#sub-submit .ajax-spinner').fadeOut(speed, function()
				{
					$('#sub-submit button').fadeIn(speed);
				});
			}, 'json');
		}
		
		return false;
	});
});