/*
 * JavaScript file for the reference platform form mailer. Can either validate
 * the form, submit it or both. It takes these arguments:
 * 
 *	form_id		ID of the HTML form element
 *	validate	True if this should validate the form as the user goes along, false otherwise
 *	submit		True if this should submit the form, false otherwise
 *
 * JQuery is required for this script to work.
 *
 * $Id: mi_forms.js 603 2008-03-26 18:39:40Z pboyd $
 */

function miForm (form_id, validate, submit) {
	var form_sel = '#' + form_id;

	var pre_validated = false;

	if (validate)
	{
		// validate fields with the server whenever a field looses focus
		$(form_sel + ' .validate').blur (function () {
			var args = Object ();

			var name = $(this).attr ('name');

			args[name] = $(this).val ();

			args['output'] = 'json';
			args['mode'] = 'validate';
			args['form'] = $(form_sel + ' #form_id').val ();

			var url = $(form_sel).attr ('action');

			$.getJSON (url, args, function (data) {
				$('#' + name + '_container .errors').text ('');
				if (data.errors)
				{
					if (name in data.errors)
					{
						$('#' + name + '_container .errors').text (data.errors[name]);
					}
				}
			});
		});

		// if any changes are made the validation needs to be done again
		$(form_sel + ' :input').change (function () { pre_validate = false; });
	}

	this.send = function () {
		// if we've already validated the form, just return so the form
		// can be processed without javascript
		if (pre_validated)
			return true;

		var args = Object ();

		$(form_sel).find (':input').each (function () {
			var type = $(this).attr ('type');

			if (type == "submit" || type == "reset" || type == "button")
				return;

			args[$(this).attr ('name')] = $(this).val ();
		});

		args['output'] = "json";

		if (!submit)
			args['mode'] = 'validate';

		var url = $(form_sel).attr ('action');

		$.getJSON (url, args, function (data) {
			$(form_sel + '.errors').text ('');
			if (submit)
				$('#form_results').text (data.message);
			else
				$('#form_results').text ('');

			if (data.errors)
			{
				// show the errors
				for (var key in data.errors)
				{
					$('#' + key + '_container .errors').text (data.errors[key]);
				}
			}
			else if (submit)
			{
				// No errors, so the e-mail should have been
				// sent and the message is displayed. So just
				// hide the form to avoid confusing the user.
				$(form_sel).hide ();
			}
			else if (!submit)
			{
				// The form has been validated, but not
				// submitted. We need to submit via the regular
				// (non-javascript) method.  Just calling
				// form.submit() would re-validate the form, so
				// set pre_validated first, which will cause
				// this function to just return true.
				pre_validated = true;
				$(form_sel).submit ();
			}
		});

		return false;
	}

	$(form_sel).submit (this.send);
}

