/**
 * @file
 *
 * A simple jQuery plug-in for making sections of documents disclosable.
 *
 * Options can be set globally by modifying the members of the object
 *     $.fn.minimize.defaults.anOption = 'aValue';
 * or per-call by passing in an options object:
 *     $('.stuff').minimize({anOption: 'aValue'});
 *
 * The supported options include:
 *		headSelector	jQuery selector for the heading. Default: '.hd'
 *		bodySelector	jQuery selector for the body. Default: '.bd'
 *		buttonPosition	End of the heading to insert the button. 'start' or 'end'. Default: 'start'
 *		defaultState	Default state of element. 'open' or 'closed'. Default: 'open'
 *
 * Note, though, that only the defaults have been tested.
 *
 * @author Thomas Sutton <thomas@bouncingorange.com>
 */
(function($){
	
	// Log debug messages
	debug = function() {}
	if (window.console && window.console.log) {
		debug = function(msg) {
			var m = "minimize: " + msg;
			window.console.log(m);	
		}
	}
	
	// Convert an element such that it can be minimized to a header
	$.fn.minimize = function(options) {
		var opts = $.extend({}, $.fn.minimize.defaults, options);
		
		return this.each(function(){
			debug("Minimizing element");
			
			// Find the element and its header and body.
			var $this = $(this);
			var $hd = $(opts.headSelector, $this);
			var $bd = $(opts.bodySelector, $this);
			
			// Add the classes and set the default state.
			$this.addClass('jquery-opener');
			if ('closed' == opts.defaultState) {
				$bd.hide();
			} else if ('open' == opts.defaultState) {
				$this.addClass('jquery-opener-open');
			} else {
				debug("Invalid default state: "+ opts.defaultState);
				return $this;	
			}
			
			// Create the button
			var $bt = $('<a href="#" class="jquery-opener-button">+</a>');
			$hd.click(function(){
				if ($this.hasClass('jquery-opener-open')) {
					$bd.slideUp("normal", function(){ $this.toggleClass('jquery-opener-open'); });
				} else {
					$this.toggleClass('jquery-opener-open');
					$bd.slideDown("normal");
				}
			
				return false;
			}).addClass('clickable');
			
			if ('start' == opts.buttonPosition) {
				$bt.prependTo($hd);
			} else if ('end' == opts.buttonPosition) {
				$bt.appendTo($hd);
			} else {
				debug('Invalid button position: '+ opts.buttonPosition);
			}
            $('<span class="clear"></span>').appendTo($hd);
		});
	};
	
	// Default values
	$.fn.minimize.defaults = 
		{ headSelector: '.hd'		// Any jQuery selector
		, bodySelector: '.bd'		// Any jQuery selector 
		, buttonPosition: 'start'	// '/start|end/'
		, defaultState: 'open'		// '/closed|open/' (default: open)
		};
})(jQuery);
