
/**
 * Automatically iterate over all of the fields in rules_param and generate a 
 * rule for each
 *
 * Suitable for simple forms with no conditional sections
 *
 * Call this function before form_post and pass the result to form_post as the 
 * rules element of the object
 */
function form_rules(rules_param)//, validateCallback)
{
	var rules = {};

	// for each field
	for(field in rules_param)
	{
		// build rule
		var required = ((rules_param[field].required == 'true') || (rules_param[field].required === true)) ? 'required ' : '';
		var rule = required + field;
		
		// add to rules
		rules[field] = rule;
		
		// enforce rule
		J.validator.addMethod(
			field,
			function(value, element) {
				field = element.name;
				matched = this.optional(element) || value.match(new RegExp(rules_param[field].pattern, rules_param[field].options));
				valid = (matched == null) ? false : true;
				//validateCallback(value, field, valid);
				return matched;
			},
			rules_param[field].message
		);
	}
	
	return rules;
}


/**
 * Execute once and this function attaches itself to a form (as per config param)
 * and handles any and all validation and posts the form via ajax once validated
 *
 * @param config consists mostly of callback functions for related events (such
 *               as form returning, prior to form posting, ajax errors..)
 */
function form_post(config)
{
	// jquery validate object and setup
	var jForm = J(config.formSelector);
	var validate = jForm.validate({
	
		rules: config.rules,
		onkeyup: false,
		errorElement: config.errorElement,
		wrapper: config.errorWrapper,
		debug: true,
		
		submitHandler: function() {
			
			var okToSubmit = config.preAjaxRequestCallback();
			
			if(okToSubmit)
			{
				J.ajax({
					type: 'post',
					url: config.action,
					data: jForm.serialize(),
					
					success: function(data, status, xhr)
					{
						data = json_parse(data);
						if(data.status == 'OK')
						{
							config.okCallback(data);
						}
						else
						{
							config.warningCallback(data);
							for(field in data)
							{
								config.fieldCallback(field, data[field]);
							}
						}
					},
					
					error: function(xhr, status, error)
					{
						config.errorCallback(xhr, status, error);
					}
				});
			}
		}
		
	});
}
