/*
	Toggler - object for handling the state and callbacks for a toggle widget.
	
	© Scott Ziegler, OSU Chemistry Dept. - Jan 2006
	
	Supports following options:
		invert - if set (preferably to true), inverts the toggle start state
		onToggleEvent - function to override default behavior
		eventOver - function to handle widget mouseover
		eventClick - function to capture 'toggle' event
	
	Need to Test:
		- eventClick -> onClick bind and call
		- eventOver -> onmouseover bind and call
		
	Future:
		- should there be a stronger observer pattern for event binding?
	
*/

//declaring the class
var Toggler = Class.create();

//defining the rest of the class implmentation
Toggler.prototype = 
{
	initialize: function (widget_id, functionOn, functionOff)
	{
		// Downgrade Detection
		if (document.getElementById)
		{
			this.options = arguments[3] || {};
			
			this.toggle = (this.options.invert ? false : true);
			
			// Add custom properties
			this.fnOn = functionOn || function () {};
			this.fnOff = functionOff || function () {};
			
			if (widget_id != '')
			{
				this.widget = document.getElementById(widget_id);
				
				// Add Toggle-necessary event listeners
				Event.observe(this.widget, 'mouseup', 
					(this.options.onToggleEvent 
						? this.options.onToggleEvent.bindAsEventListener(this)
						: this.onToggleEvent.bindAsEventListener(this)), false);
				
				if (this.options.eventOver && this.widget.onmouseover)
				{
					Event.observe(this.widget, 'mouseover', 
						this.options.eventOver.bindAsEventListener(this), false);
				}
			}
			
			if (this.options.eventClick)
			{
				this.onClick = this.options.eventClick;
			}
		}
	},
	
	setOptions: function (options)
	{
		Object.extend(this.options, options);
	},
	
	onToggleEvent: function ()
	{
	//	alert('onToggleEvent');
		if (this.onClick) this.onClick();
		//	if toggle, then on - turn off, else off - turn on
		(this.toggle ? this.fnOff() : this.fnOn())
		//	reverse the toggle "polarity"
		this.toggle = !this.toggle;
	},
	
	toggleEvent: function ()
	{
		if (this.options.onToggleEvent)
		{
			this.options.onToggleEvent();
		}
		else
		{
			this.onToggleEvent();
		}
	}
}