/*
*	Controls hide/show behaviour of fieldset boxes. Instantiate for each fieldset eg
*	 	new FieldsetController( myfieldset );
*	myfieldset can be the fieldset's id (string) or a handle to the object.
*
*	Fieldsets must be in the form:
*
*	<fieldset id='myfieldset'>
*		<legend>my title</legend>
*		<div class='liner'>
*			<span>
*			my field set contents.
*			</span>
*		</div>
*	</fieldset>
*
*	Spans fix bug in scriptaculous. liner div takes on shape of fieldset which is hidden. This way the
*	liner can be collapsed leaving just the legend visible as the clickable element.
*/

var FieldsetController = Class.create();
FieldsetController.prototype = {
	
	initialize: function (){
		
		var fieldset = arguments[0];

		if( arguments.length > 1 )
			this.callback = arguments[1];
		else
			this.callback = false;
		
		if( typeof( fieldset ) == 'object' )
			var fieldsetHandle = fieldset;
		else
			var fieldsetHandle = $( fieldset );
				
		
		this.owner = fieldsetHandle;
		this.liner = fieldsetHandle.getElementsByTagName( 'div' )[0];
		var legendHandle = fieldsetHandle.getElementsByTagName( 'legend' )[0];
		
		this.liner.style.display = "none";
			
		this.addOnclick( legendHandle );
			
		this.setNotBusy();
			
	},
		
	addOnclick: function ( legend ){
		
		var event1 = this.legendClick.bind( this );
		legend.onclick = function() { event1(); };  
			
	},
		
	legendClick: function (){
			
		if( !this.busy ){
			
			if( this.callback )
				this.callback.onCollapse( this );
			
			if( this.liner.style.display == 'none' )
				this.openFieldSet();
			else
				this.closeFieldSet();
					
		}
		
	},
		
	openFieldSet: function (){
		
		this.setBusy();
		var setInactiveBINDED = this.setNotBusy.bind(this);
		new Effect.SlideDown( this.liner, { scaleFrom:0, scaleTo:90, afterFinish:setInactiveBINDED } );
		
	},
		
	closeFieldSet: function (){
		
		this.setBusy();
		var setInactiveBINDED = this.setNotBusy.bind(this);
		new Effect.SlideUp( this.liner, { scaleFrom:90, scaleTo:0, afterFinish:setInactiveBINDED } );
		
	},
		
	setNotBusy: function (){
		
		this.busy = false;
		
	},

	setBusy: function (){
		
		this.busy = true;
		
	}
	
	
};

