
/// -------------------------------------------------------------------
/// --- 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;

	if ( urlParams )
	{
		ajaxUrl += "?" + urlParams;
	}

	$( "#" + container ).load( ajaxUrl, "",
			function( responseText, textStatus, xmlHttpRequest )
			{
				EnableAjaxForm( formUrl, "" );

				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()
		{
			$( 'body' ).removeClass( 'ajax-in-progress' );
			EnableAjaxForm( formUrl, container );
		},
		beforeSubmit: function()
		{
			$( 'body' ).addClass( 'ajax-in-progress' );
		},
		// other available options:
		url:       '/ajax/form' + formUrl + '?ct=' + container
	};

    $( "#" + container + " form" ).ajaxForm( options );
	$( "#" + container + " form" ).unbind( "submit.form-plugin" );

	$( "#" + container + " form" ).bind( "submit.form-plugin", function( eventObject )
			{
				if ( !ajaxFunctionButton )
				{
					var result = true;

					if ( result )
					{
						options.data = {};

						var appKey = $( this ).attr( 'appKey' );

						if ( window.ajaxObjects[ appKey ] )
						{
							//options.data[ 'app-session-data' ] = window.ajaxObjects[ appKey ];
							//options.data[ 'app-session-key' ] = appKey;
						}

						options.data.stepObjectId = $( this )[0].id.replace( 'form', '' );

						$(this).ajaxSubmit(options);
					}

					return false;
				}

				return false;
			} );

	var ajaxFunctionButton = false;

	$( "#" + container + " input[type=submit]" ).unbind( "click.ajax-form" );
	$( "#" + container + " input[type=submit]" ).bind( "click.ajax-form", function()
	{
		ajaxFunctionButton = ( $( this ).attr( 'ajax' ) == '1' ) ? true : false;
	});
}
