var NewsletterForm = 
{
	initialize: function()
	{
		this.nums = new Array();
		this.nums.push(Math.floor(Math.random() * 10));
		this.nums.push(Math.ceil(Math.random() * 10));
		this.numSolution = this.nums[0] + this.nums[1];
		
		this.errors = new Array();		
	},
	
	writeQuestion: function()
	{
		document.write(this.nums[0] + ' + ' + this.nums[1] + ' = ? ');
	},
	
	check: function()
	{
		var errBox = document.getElementById('errors');
		errBox.style.display = 'none';

		this.errors = new Array();
		this.validateForm();
		
		if(this.errors.length > 0)
		{
			var errorHtml = '<p>Oops!  We couldn\'t subscribe you to our newsletter.  Please check the following:</p><ul><li>';
			errorHtml += this.errors.join('</li><li>');
			errorHtml += '</li></ul>';
			
			errBox.style.display = 'block';
			errBox.innerHTML = errorHtml;
			
			return false;
		}
		else
		{
			return true;
		}
		
	},
	
	validateForm: function()
	{
		var f = document.forms['newsletter-subscribe'];
		f.action = 'nlsubscribe.cgi';
		
		var errors = new Array();
		
		if(f.name.value == '')
		{
			errors.push('Please provide your name.');
		}
		
		if(f.email.value == '')
		{
			errors.push('Please enter your e-mail address.');
		}
		
		if(f.answer.value == '')
		{
			errors.push('Please enter the answer to the math question.');
		}
		else if(parseInt(f.answer.value,10) != this.numSolution)
		{
			errors.push('The answer to the math question is incorrect.');
		}
		
		this.errors = errors;

		return this.errors;
	}
}

NewsletterForm.initialize();
