/**
 * Validate is a generic form validation class. An instance of validate corresponds
 * to a single form on the page.
 */
TOOSite.formvalidate = function(formEl, rules, callback) {
	/**
	 * Initialize the Validate instance, set its member vars, and create a listener
	 * to the form submition
	 * @param {Object} formEl | the id or reference of the form element
	 * @param {Object} rules | an array of rules objects. a rules object has three
	 * parameters: 
	 * 	owner {Element} the form element that "owns" the rule. Since multiple elements
	 *  	can be affected by a rule, one must be designated as the primary field.
	 *  rule {Function} the rule that will be evaluated. Should be a function that
	 *      returns true or false OR a string of javascript that evaluates to true or false
	 *  error {String} an error message if the rule evaluates to false
	 *  
	 * @param {Object} callback | a method that is called at the end of the validate 
	 * 	 stage if there are errors. Gets passed an array of error objects with two parameters,
	 *   owner and error.
	 */
		
	rules = rules;
	callback = callback;
	formEl = $(formEl);
  
	/**
	 * Validate is called when the form is submitted. It will stop the submit event 
	 * and fire the callback if there are errors.
	 * @param {Object} evt | validate gets passed the event that calls it, usually
	 * 	a form submit event. 
	 */
  function validate(evt) {
  	var errors = [];
    $A(rules).each( function(rule, index) {
			try {
		  	var ruleVerify = false;
		  	if (typeof rule.rule == "string") {
					ruleVerify = eval(rule.rule);
				} else if (typeof rule.rule == "function") {
					ruleVerify = rule.rule();
				}
				if (!ruleVerify) {
			  	errors.push({
			  		owner: rule.owner,
			  		error: rule.error
			  	});
			  }
	    } catch(excp) {
	      console.log(excp);
	    }
    });
		
		if (callback) {
	  	if (errors.length > 0) {
	  		try {
	  			callback(errors);
	  			Event.stop(evt);
	  		} 
	  		catch (excp) {
	  			console.log(excp);
	  		}
	  	}
	  }
	  else {
	  	return errors;
	  }
  }
	
	return {
		validate: validate
	};
	
};

