$.createNamespace('rainier.validation');
$(function() {
	rainier.validation.text = function(node) {
		if ($(node).attr('value')) {
			return true;
		}
		return false;
	};

	/**
	 * The handler dealing with the outcome after validation. This is
	 * convenient for setting how the validity of a field shows on html.
	 * @param {Boolean} result The result that is to be displayed.
	 * @param {DomNode} element The element that the result belongs to.
	 * @return The result that was passed in.
	 */
	var resultHandler = function(result, element, validation) {
		if (result) {
			validation.trueHandler(element);
		} else {
			validation.falseHandler(element);
		}
		return result;
	};
	
	/**
	 * The main logic of the form validation functionality. It will either set the
	 * validator for each field or check each field in a loop.
	 * @param {DomNode} form The domNode of the form.
	 * @param {Object} validation The object that contains validation type and functions.
	 * @param {Boolean} init True for initializing the form, false for checkign the form.
	 * @return {Boolean} Returns true if the form is valid, false otherwise.
	 */
	var validationHelper = function(form, validation, init) {
		var noErrors = true;
		
		// Get all of the required fields
		var elements = $('.field.required', form);
		for ( var i = 0; i < elements.length; ++i) {
			var el = elements[i];
			
			var handler;
			// Each field, check to see if it needs a certian validation.
			for (var type in validation) {
				if ($(el).is('.' + type)) {
					handler = validation[type];
					break;
				}
			}
			
			// If a handler was not defined, we define a default one.
			if (!handler) {
				handler = validation['default'];
			}
			
			if (init) {
				$(el).blur((function(elem) {
					// Note that we need to have closure here so that the right
					// element gets called. Otherwise, the handlers will only call
					// for the last element on the form.
					return function() {
						resultHandler(handler($(elem).attr('value')), elem, validation);
					};
				})(el));
			} else {
				noErrors &= resultHandler(handler($(el).attr('value')), el, validation);
			}
			
			return noErrors;
		}
	};
	
	/**
	 * Does the validation fo the form.
	 * @param {DomNode} form The domNode of the form.
	 * @param {Object} validation The object that contains validation type and functions.
	 * @return {Boolean} Returns true if the form is valid, false otherwise.
	 */
	rainier.validation.validate = function(form, validation) {
		return validationHelper(form, validation, false);
	};
	
	// 
	/**
	 * Initialize each field in the form with an onblur function.
	 * @param {DomNode} form The domNode of the form.
	 * @param {Object} validation The object that contains validation type and functions.
	 */
	rainier.validation.initialize = function(form, validation) {
		validationHelper(form, validation, true);
	};
});
