var timeOutEvent;

function SettingsBox()
{
	this.SettingsContainer = "settings-box";
	this.Button = null;
	this.Url = null;

	this.AddSettingsContainer = function()
	{
		if( null == $( this.SettingsContainer ) )
		{
			$( "site_container" ).insert(
				new Element( "div", { id: this.SettingsContainer, style: 'display: none;' } )
			);
		}
		else
			$( this.SettingsContainer ).update();
	};

	this.Hide = function()
	{
		$( this.SettingsContainer ).hide();
	};

	this.GetSettingsContainer = function()
	{
		return $( this.SettingsContainer );
	};

	this.SetButton = function( element )
	{
		this.Button = element;
	};

	this.SetAjaxUrl = function( url )
	{
		this.Url = url;
	};

	this.Initialize = function()
	{
		if( $( this.SettingsContainer ).readAttribute( "rel" ) == $( this.Button ).readAttribute( "id" ) && $( this.SettingsContainer ).visible() )
		{
			SettingsBoxFade();
		}
		else
		{
			clearTimeout( timeOutEvent );

			$( this.SettingsContainer ).writeAttribute( { rel: $( this.Button ).readAttribute( "id" ) } );

			if( null != this.Url )
			{
				new Ajax.Updater( $( this.SettingsContainer ), this.Url, {
					onCreate: this.InitializeLoader(),
					onComplete: function(){ timeOutEvent = setTimeout( "SettingsBoxFade()", 3000 ) }
				} );
			}

			var position = this.Button.positionedOffset();
			var positionX = position[0];
			var positionY = position[1] + this.Button.getHeight() + 1;

			$( this.SettingsContainer ).setStyle( { left: positionX + "px", top: positionY + "px", opacity: 1 } );
			$( this.SettingsContainer ).show();
		}
	};

	this.InitializeLoader = function()
	{
		$( this.SettingsContainer ).update(
			new Element( "div", { style: "text-align: center; padding: 5px 50px;" } ).insert(
				new Element( "img", { src: "/gfx/theme_default/site/ico_wait_anim.gif" } )
			)
		);
	}

	this.AddSettingsContainer();
}

function SettingsBoxFade()
{
	$( "settings-box" ).fade( { duration: 0.5 } );
}

function InitializeSettingsBoxes()
{
	settings = new SettingsBox();

	$$( "[rel=settings]" ).each( function( obj )
	{
		$( obj.identify() ).observe( "click", function( event )
		{
			settings.SetButton( this );
			settings.SetAjaxUrl( this.href );
			settings.Initialize();

			event.stop();
		} );
	} );
}

Event.observe( window, 'load', function()
{
	InitializeSettingsBoxes();
} );
