﻿function TropicosButton( options )
{
	var button = $( "#" + options.buttonId );
	var externalClickMethod = "";
	
	button.click( function()
	{
		if ( button.attr( "stopPostBack" ) == "true" )
		{
			return false;
		}
		if ( options.preventDoubleClicking == "1" )
		{
			if ( options.disableButtonsOnClick == "1" )
			{
				$( "input" ).each( function()
				{
					if ( $( this ).attr( "type" ) == "submit" || $( this ).attr( "type" ) == "button" )
					{
						$( this ).attr( "disabled", "disabled" );
					}
				} );
			}
			button.attr( "disabled", "disabled" );
		}
		
		if ( externalClickMethod.length > 0 )
		{
			externalClickMethod();
		}
	} );

	button.keydown( function( ev )
	{
		if ( options.enterKeyClick == "1" )
		{
			if ( ev.keyCode == 13 )
			{
				this.click();
				//__doPostBack( button.attr( "name" ), "" );
				if ( button.attr( "onclick" ).length > 0 )
				{
					button.attr( "onclick" )();
				}
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{
			if ( ev.keyCode == 13 )
			{
				return false;
			}
			else
			{
				return true;
			}
		}
	} );

	// Reset to enable on postback -- this might be a problem if we want the button to be disabled
	if ( options.disableButtonsOnClick == "1" )
	{
		$( "input" ).each( function()
		{
			if ( $( this ).attr( "type" ) == "submit" || $( this ).attr( "type" ) == "button" )
			{
				$( this ).removeAttr( "disabled" );
			}
		} );
	}
	button.removeAttr( "disabled" );
	button.removeAttr( "onkeydown" );
	if ( button.attr( "onclick" ) && button.attr( "onclick" ).length > 0 )
	{
		externalClickMethod = button.attr( "onclick" );
		button.removeAttr( "onclick" );
	}
}

TropicosButton.create = function( id, options )
{
	if ( !this._instances )
	{
		this._instances =
		{
		};
	}

	this._instances[ id ] = new TropicosButton( options );
};

TropicosButton.getInstance = function( id )
{
	return this._instances[ id ];
};