
validation = {};

validation.validate = function(args)
{
	var messages = [];
	args = $.makeArray(args);
	$.each(args, function(index1, item) {
		$.each(item.validators, function(index2, validator) {
			var result = validator(item.name, item.value);
			if (result) {
				messages.push(result);
				return false; // only show one message per field
			}
		});
	});
	return {
		valid: !messages.length,
		messages: messages
	};
};


validation.NotEmpty = function(name, value)
{
	if (!value || !value.toString().replace(/^\s+/, '').replace(/\s+$/, '').length) {
		return name + ' is required';
	}
	return null;
}
validation.Email = function(name, value)
{
	if (!/^[^@]+@[^@]+$/.test(value)) {
		return name + ' is not a valid email address';
	}
	return null;
}
validation.Confirm = function(name, value, confirmName, confirmValue)
{
	if (value != confirmValue) {
		return name + " doesn't match " + confirmName;
	}
	return null;
}

validation.Validator = function()
{
	var args = [];
	
	var _field;
	
	function commitField()
	{
		if (_field) {
			args.push(_field);
			_field = null;
		}
	}
	this.field = function(name, value)
	{
		commitField();
		_field = {name:name, value: value, validators:[]};
		return this;
	}
	this.validate = function()
	{
		commitField();
		return validation.validate(args);
	}
	this.NotEmpty = function()
	{
		_field.validators.push(validation.NotEmpty);
		return this;
	}
	this.Email = function()
	{
		_field.validators.push(validation.Email);
		return this;
	}
	this.Confirm = function(confirmName, confirmValue)
	{
		_field.validators.push(function(name, value) {
			return validation.Confirm(name, value, confirmName, confirmValue);
		});
		return this;
	}
}



