(function($){
	
	$.fn.slideshow = function(options) {
		
		var defaults = {
			timeout: 5000,
			controls: ".controls",
			element: "li",
			start: 1
		};
		
		var options = $.extend(defaults, options);
		
		return this.each( function() {
			var $obj = $(this);
			
			var interval;

			function slideSwitch(override) {
			    var $active = $("> .active", $obj);

			    if ( $active.length == 0 ) $active = $(":last", $obj);
				
			    // use this to pull the divs in the order they appear in the markup
			    var $next =  $active.next().length ? $active.next() : $(":first", $obj);

				if( override )
				{
					$next = $("> " + options.element + ":nth-child("+override+")", $obj);
					reset();
				}
				var slideIndex = $("> " + options.element, $obj).index($next);
			    $active.addClass('last-active');
				if( options.colors )
				{
					$next.css({opacity: 0.0});
					$(options.$colors,$next).css({"background-color": options.colors[slideIndex]});
				}
				var speed = 0;
				if( $("> " + options.element, $obj).length > 1)
				{
					speed = 1000;
				}
				$("> " + options.element, $obj).animate({opacity: 0.0}, speed);
				$next.stop().css({opacity: 0.0})
					.addClass('active')
					.animate({opacity: 1.0}, speed, function() {
						$active.removeClass('active last-active');
						//$obj.height($next.height());
					});
				$obj.animate({height:$next.height()}, speed);
				var $controls = $(options.controls, $obj.parent());
				if( $controls.size() > 0)
				{
					$("a",$controls).removeClass('active');
					$("a:eq("+slideIndex+")",$controls).addClass('active');
				}
			}

			function reset() {
				clearInterval(interval);
				if( options.timeout > 0)
					interval = setInterval(function() { slideSwitch(); }, options.timeout);
			}

			var $controls = $(options.controls, $obj.parent());
			if( $controls.size() > 0)
			{
				var index = 1;
				$(" > "+options.element, $obj).each( function() {
					var $button = $("<a href=\"#\">"+index+"</a>");
					$controls.append($button);
					$button.bind("click", function() {
						reset();
						slideSwitch($(this).text());
						return false;
					});
					index++;
				});
			}
			
			slideSwitch(options.start);
		});
		
	};
	
})(jQuery);
