/**
 * accordion 2.0
 * combined accordion and panel collapse
 * Copyright (c) Simon Neaves <simon@aerian.com>
 * Licensed like jQuery, see http://docs.jquery.com/License.
 *
 *	SETUP
 * add .accordion class to HTML node. Add one or more pairs of .accordion_title/.accordion_content HTML elements
 *
 * OPTIONS
 * add .start_open to any .accordion_title element to stop it being closed on startup
 *
 * CHANGELOG
 * added support for nested lists
 * simplified default closed behaviour
*/

jQuery.accordion = {
	titleClick : function($accordionTitle){
		if($accordionTitle.hasClass('closed')){
			jQuery.accordion.open($accordionTitle.next('.accordion_content'));
		} else {
			jQuery.accordion.close($accordionTitle.next('.accordion_content'));
		}
	},
	
	open : function($accordionContent, options){
		var defaults = {speed : 200};
		var options = jQuery.extend({}, defaults, options);
		if($accordionContent.parent().hasClass('accordion')){
			var $siblingContentNodes = $accordionContent.siblings('.accordion_content');
		} else {
			var $siblingContentNodes = $accordionContent.parents('.accordion:eq(0)').children().children('.accordion_content');//fix for lists. Get the grandparent, and then get it's grandchildren
		}
		$siblingContentNodes.each(function(){jQuery.accordion.close(jQuery(this));});//close siblings
		$accordionContent.slideDown(options.speed).removeClass('closed');
		$accordionContent.prev('.accordion_title').removeClass('closed');
	},
	
	close : function($accordionContent, options){
		var defaults = {speed : 200};
		var options = jQuery.extend({}, defaults, options);
		$accordionContent.slideUp(options.speed).addClass('closed');
		$accordionContent.prev('.accordion_title').addClass('closed');
	},
	
	init : function(){
		jQuery.fn.reverse = function() {return this.pushStack(this.get().reverse(), arguments);};//define function for iterating through a nodeset in reverse
		
		jQuery('.accordion_title').reverse().each(function(){//itterate in reverse to make sure nested accordions are properly closed
			jQuery(this).each(function(){
				var $accordionTitle = jQuery(this);
				$accordionTitle.wrapInner(jQuery('<a></a>')).click(function(){
					jQuery.accordion.titleClick($accordionTitle);
				});
				
				if(!$accordionTitle.hasClass('start_open')){//close any accordions that are not set to start_open
					jQuery.accordion.close($accordionTitle.next('.accordion_content'), {speed: 0});
				}
				
			});
		});		
	}
}

jQuery(document).ready(function(){
	jQuery.accordion.init();
});