/*
 * 
 * Expander 0.1
 * Version 0.1
 * @requires jQuery v1.2.4
 * 
 * Copyright (c) 2008 Caleb Brown
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */
(function($) {
	$.extend({
		expander: new function() {
			
			this.defaults = {
				debug: false
			};
			
			/* debuging utils */
			function benchmark(s,d) {
				log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
			}
			
			this.benchmark = benchmark;
			
			function log(s) {
				if (typeof console != "undefined" && typeof console.debug != "undefined") {
					console.log(s);
				} else {
					alert(s);
				}
			}
			/* utils */
			function buildLists(ul){
				if(ul.config.debug) { var time = new Date(); }
				
				items = $(ul).children();
				
				items.each(function(index) {
					$(this).children().hide();
					this.items = $("li",this);
					
					this.items.each(function(index){
						$(this).children("div,ul,li").hide();
						this.items = $("div",this);
						if(index==0) expandFast(this);
					});
				});
				
				if(ul.config.debug) { benchmark("Built lists:", time); log(items); }
				
				return items;
			}
			function collapse(target){
				$(target).children().hide("fast");
				$(target).children("img").fadeIn("fast");
				$(target).removeClass("on");
			}
			function expand(target){
				$('html,body').animate({scrollTop: $(target).offset().top}, 400);
				$(target).children("div,ul,li").fadeIn("normal");
				$(target).children("img").fadeOut("normal");
				$(target).addClass("on");
			}
			function expandFast(target){
				$(target).children("div,ul,li").show();
				$(target).children("img").hide();
				$(target).addClass("on");
			}
			function toggle(target){
				$(target).is(".on") ? collapse(target) : expand(target);
			}
			/* public methods */
			this.construct = function(settings) {
				
				return this.each(function() {
					
					var $this, $document, $topLists, config;
					
					// store common expression for speed				
					$this = $(this);
					
					this.config = {};
					
					config = $.extend(this.config, $.expander.defaults, settings);
					
					// build headers
					$items = buildLists(this);
					
					$items.click(function(e) { 
						toggle(e.target); 
					}).mousedown(function() {
						this.onselectstart = function() {return false};
						return false;
					});
					//expandFast($items[0]);
				});
			};
		}
	});
	// extend plugin scope
	$.fn.extend({
        expander: $.expander.construct
	});
})(jQuery);
