/**
* Created by Paul Barton
* http://www.thisispaul.co.uk
*/

(function($) {

	$.fn.accordian = function(options){
		
		// default configuration properties
		var defaults = {
			speed:	800
		}; 
		
		var options = $.extend(defaults, options);
		
		this.each(function() {
			var clickable = true;
			var obj = $(this);
			init(); //initialising the shit out of it
			$('h3',obj).show();
			$('div.element',obj).hide();
			$('div.element:first',obj).show();
			
			$('h3',obj).click(function(){
				activate($(this));
			});
			
			function activate(comp) {
				if(clickable && comp.next('div.element',obj).css('display') == 'none') {
					clickable = false;
					hideAll();
					showSelected(comp);
				}
			}
			
			function hideAll() {
				$('div.element',obj).each(function() {
					if($(this).css('display') == "block") {
						var h = $(this).height();
						$(this).css('overflow','hidden')
						.animate({height: 0}, options.speed, function() {
							$(this).hide();
							$(this).css('overflow','').css('height', h);
						})
					}
				});
			}
			
			function showSelected(comp) {
				var h = comp.next('div.element',obj).height();
				comp.next('div.element',obj).height(0)
				.css('overflow','hidden')
				.animate({height: h}, options.speed, function() {
					clickable = true;
				});
			}
			
			function init() {
				$('div.element',obj).each(function() {
					var h = $(this).height();
					$(this).height(h);
				});
			}
		});
	};
 })(jQuery);