
/// -------------------------------------------------------------------
/// --- form-ajax.js
/// ---
/// --- Allows PgForms to be loaded and submitted using javascript.
/// ---
/// --- Requires the jQuery prototype library.
/// ---
/// --- Author: Andrew Cuthbert
/// --- Date:	16/02/2009
/// --------------------------------------------------------------------

function LoadFormToContainer( formUrl, container, urlParams, onLoad )
{
	var ajaxUrl = "/ajax/form" + formUrl + "/" + container;

	if ( urlParams )
	{
		ajaxUrl += "?" + urlParams;
	}

	$( "#" + container ).load( ajaxUrl, "",
			function( responseText, textStatus, xmlHttpRequest )
			{
				EnableAjaxForm( formUrl, container );

				if ( onLoad )
				{
					onLoad();
				}
			}
	 );
}

function EnableAjaxForm( formUrl, container )
{
    // Change the form tag to submit to us instead.
    var options = {
		target:        '#' + container,   // target element(s) to be updated with server response
		success:       function()
		{
			EnableAjaxForm( formUrl, container );
		},

		// other available options:
		url:       '/ajax/form' + formUrl + '/' + container
		//type:      type        // 'get' or 'post', override for form's 'method' attribute
		//dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
		//clearForm: true        // clear all form fields after successful submit
		//resetForm: true        // reset the form after successful submit

		// $.ajax options can be used here too, for example:
		//timeout:   3000
	};

    $( "#" + container + " form" ).ajaxForm( options );
	$( "#" + container + " form" ).unbind( "submit.form-plugin" );
	$( "#" + container + " form" ).bind( "submit.form-plugin", function()
			{
				var result = eval( $( this ).attr( 'validationfunction' ) + "()" );

				if ( result )
				{
					$(this).ajaxSubmit(options);
				}

				return false;
			} );
}