var Wouter = new Class({
	
	// Called from mootools
	initialize: function()
	{
		$('captcha_reload').addEvent('click', this.reloadCaptchaImage.create({'bind':this}));
		// Clear captcha field
		$('CaptchaCaptcha').set('value', '');
	},
	/*
	Validates the comment form.
	Form is also validate server-side, but this saves the server a little bit of work.
	*/
	validateCommentForm: function(event)
	{
		// Stop event propagation
		event = new Event(event);
		//event.stop();

		var errors = [];
		
		// Check if name, email & message are set
		this.mCommentFields.each(function(field)
		{
			var id = field.getProperty('id');
			var value = field.getProperty('value');
			
			value = value.toString();
			if (value.trim() == '')
			{
				errors.push(id);
			}
		}, this);

		
		// Check if valid email is provided
		// Note the element id and name, these are generated by cakephp
		if (!errors.contains('CommentEmail') && !$('CommentEmail').value.trim().test(/^[a-z0-9]+(?:[-._][a-z0-9]+)*@[a-z0-9]+(?:[-.][a-z0-9]+)*(?:[.-][a-z0-9]{2,4})$/i))
		{
			errors.push('CommentEmail');
		}
		
		// Reset labels
		$$('#commentform label').setStyle('color', '#ffffff');
		// Display errors
		errors.each(function(error)
		{
			var label = $$('label[for=' + error + ']');
			if (label)
			{
				label.setStyle('color', '#ff0000');
			}
		}, this);

		// Stop event if errors occured
		if (errors.length != 0)
		{
			event.stop();
		}
	},
	
	/* Called when user clicks on captcha image reload. */
	reloadCaptchaImage: function(event)
	{
		// Obtain new image
		$('captcha_image').set('src', '/posts/captcha/image.gif?' + Math.round(Math.random(0) * 1000) + 1);
		// Clear also the text in the captcha field
		$('CaptchaCaptcha').set('value', '');
	}
});

initialise = function()
{
	new Wouter();
}

window.addEvent('domready', initialise);
