/**
 * @file
 *
 * A simple jQuery plug-in for making sections of documents disclosable 
 * in the "accordian style" - that is, with only a single section disclosed
 * at a time.
 *
 * Options can be set globally by modifying the members of the object before
 * making an `accordionize()` call:
 * 
 *     $.fn.accordionize.defaults.anOption = 'aValue';
 *
 * or per-call by passing in an options object:
 *
 *     $('.stuff').accordionize({anOption: 'aValue'});
 *
 * The supported options include:
 * - event
 *     event to bind. Default: 'click'
 * - headSelector
 *     jQuery selector for the heading. Default: '.hd'
 * - bodySelector
 *     jQuery selector for the body. Default: '.bd'
 * - buttonPosition
 *     end of heading to insert button. 'start' or 'end'. Default 'start'
 *
 * Note, though, that only the defaults have been tested.
 *
 * @author Thomas Sutton <thomas@bouncingorange.com>
 * 
 */

(function($){
	
	/**
	 * Convert all matched elements into a single accordion.
	 *
	 * The elements matched by the jQuery object upon which this method is 
	 * will be converted into a single accordion. This is accomplised by 
	 * retaining a reference to both the selector and context used in the
	 * jQuery() call and using them in future calls to update the display.
	 */
	$.fn.accordionize = function(options) {
		opt = $.extend({}, $.fn.accordionize.defaults, options);
		var sel = this.selector;
		var con = this.context;
		
		return this.each(function(){
			var $this = $(this);
			var $hd = $(opt.headSelector, $this);
			var $bd = $(opt.bodySelector, $this);
			
			$this.addClass('jquery-accordion');

			// Add click handler
			var $bt = $('<a href="#" class="jquery-accordion-button">+</a>');
			$hd.bind(opt.event, function(){
				if ($this.hasClass('accordion-open')) return false;
				
				// Close any open panes
				var $open = $(sel +".accordion-open", con);
				$(opt.bodySelector, $open).slideUp();
				$open.removeClass('accordion-open');
				
				// Open the clicked pane
				$bd.slideDown();
				$this.addClass('accordion-open');
				
				return false;
			}).addClass('clickable');
			
			if ('start' == opt.buttonPosition) {
				$hd.prepend($bt);
			} else if ('end' == opt.buttonPosition) {
				$hd.append($bt);
			} else {
				debug('Invalid button position: '+ opts.buttonPosition);
			}
            $('<span class="clear"></span>').appendTo($hd);
			
			$(opt.bodySelector, $this).hide();
		});
	};

	$.fn.accordionize.defaults =
		{ event: "click"		// the event to bind
		, headSelector: ".hd"	// selector the the bit that is clickable.
		, bodySelector: ".bd"	// selector for the bit to show/hide.
		, buttonPosition: "end"	// "end"|"start"
		};

})(jQuery);
