
/// -------------------------------------------------------------------
/// --- 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 + '?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 ( $( this ).attr( "validationfunction" ) != "" )
					{
						result = eval( $( this ).attr( 'validationfunction' ) + "()" );
					}

					if ( result )
					{
						$(this).ajaxSubmit(options);
					}

					return false;
				}

				return false;
			} );

	var ajaxFunctionButton = false;

	$( "#" + container + " input[type=submit]" ).bind( "click.ajax-form", function()
	{
		ajaxFunctionButton = ( $( this ).attr( 'ajax' ) == '1' ) ? true : false;
	});
	
	// This may seen a strange place for this call, however its necessary as if the buttons
	// are moved before the call to EnableAjaxForm() then the jquery ajax plugin can't find
	// the buttons!
	MovePageletsButtons();
}