/**
 * Class legend:
 * - validatable: Allows the form to be validated.
 *
 * - invalid:     Indicates a field in invalid.
 * - inputHolder: Indicates the element is a container for a field.
 * - required:    Indicates the field must be validated. 
 *                If applied to a container field with class "checkboxGroup", then it represents that at least one checkbox in the container must be ticked.
 *
 * - integer:     Validates for integers.
 * - email:       Validates for email addresses.
 */

$(document).ready(function()
{
	$('.validatable').submit(function(e)
	{
		$this = $(this);
		$this.find('*').removeClass('invalid');
		var fields = $this.find(':input:not(:disabled)');
		
		var invalid = Array();
		
		// Required.
		var invalidRequired = $(fields).filter('.required').filter(function()
		{
			$field = $(this);
			if($field.hasClass('checkbox'))
				return $field.filter(':checked').size() == 0;
			else
			{
				// Check for input focused fields for the true value.
				var value;
				if($field.data('init') == $field.val())
					value = '';
				else
					value = $field.val();
				return value.length == 0;
			}
		});
		invalid = $.merge(invalid, invalidRequired);
		
		// Required Checkbox group.
		var invalidRequiredGroup = $('.checkboxGroup.required', $this).filter(function()
		{
			return $(this).find(':input:checked').size() == 0;
		});
		invalid = $.merge(invalid, invalidRequiredGroup);
		
		// Email validation.
		var invalidEmail = $(fields).filter('.email').filter(function()
		{
			$field = $(this);
			
			// Check for input focused fields for the true value.
			var value;
			if($field.data('init') == $field.val())
				value = '';
			else
				value = $field.val();
			
			var regex = /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,5}$/;
			return !regex.test(value) && value != '';
		});
		invalid = $.merge(invalid, invalidEmail);
		
		// Integer validation.
		var invalidInteger = $(fields).filter('.integer').filter(function()
		{
			$field = $(this);
			
			// Check for input focused fields for the true value.
			var value;
			if($field.data('init') == $field.val())
				value = '';
			else
				value = $field.val();
			
			var regex = /^[+-]?\d+$/;;
			return !regex.test(value) && value != '';
		});
		invalid = $.merge(invalid, invalidInteger);
		
		// Mark elements as invalid.
		if($(invalid).size() > 0)
		{
			e.preventDefault();
			
			// Add invalid class to all fields.
			$(invalid).addClass('invalid').each(function()
			{
				$field = $(this);
				$inputHolder = $field.parents('.inputHolder');
				
				// Add invalid class to current field holder.
				if($inputHolder.size() > 0)
					$inputHolder.addClass('invalid');
			});
			
			alert('Please complete all fields correctly.');
		}
	});
});
