/*
 * jQuery Toggler
 * 
 * Copyright (c) 2010 Tomislav Mesic
 *
 * HTML structure sample
 * ---------------------
 * <div class="content">
 * 	<h1>Toggle title 1</h1>
 * 	<div>Content 1</div>
 * 	<h1>Toggle title 2</h1>
 * 	<div>Content 2</div>
 * </div>
 * 
 * jQuery code sample
 * ------------------
 * $("div.content").toggler();
 * or
 * $("div.content").toggler({
 * 	
 * });
 */

(function($){

$.fn.toggler = function(options) {

	var opts = $.extend("", $.fn.toggler.defaults, options);
	
	var args = (arguments.length > 0) ? arguments[0] : null;
	
	return this.each(function(e){
							  
		var $toggler = $(this);
		
		var o = $.meta ?  $.extend({}, opts, $this.data()) : opts;
		
		$toggler.find(o.header).each(function(i){
			var $title = $(this);
			var $content = $title.next();
			
			if (args != "expand") {
				$content.filter(":visible").prev().toggleClass("selected");	
			
				$content.data("height", $content.height());
				
				if (i != o.active) {
					$content.css({height: "0"}).hide();
					$title.toggleClass("selected");
				};
				
				$title.bind("click", function(){
					$title.toggleClass("selected");
					if ($content.css("display") != "none") {
						$content.css("overflow", "hidden").animate({height: "0"}, 500, function(){$content.hide()});
					}
					else {
						$content.show(0, function(){$content.css("overflow", "visible").animate({height: $content.data("height")}, 500)});
						$content.find('input:visible:enabled:first').focus();		
					};
				});
			}
			else {
				$title.addClass("selected");
				
				$content.show().css({
					overflow: "visible",
					height: "auto"
				});			
			};
		});
	});
};

$.fn.toggler.defaults = {
	header: 'h2',
	defaultOpen: true,
	active: 0
};

})(jQuery);
