(function() {
	jQuery.fn.tkCycle = function(settings) {

		var config = {
			'slides':{},
			'delay':4000,
			'fadeTime':1000,
			'height':false,
			'includeContents':true
		};
		if( settings ) {
			$.extend(config, settings);
		}
		
		if( config.slides.length === 0 ) {
			return;
		}

		return this.each( function() {

			var index = 0;
			var timer = false;
			
			var $obj = $(this);
			var width = $obj.width();
			if( !config.height ) {
				config.height = $obj.height();
			}
			
			if( config.includeContents ) {
				config.slides.unshift( $obj.html() );
			}
			
			// modify markup
			var $top = $('<div>' + config.slides[ nextIndex() ] + '</div>');
			$top.
				css({"position":"absolute", "z-index":"2001", "opacity":0.0, "display":"none"}).
				width( width ).
				height( config.height ).
				html( config.slides[1] );
			var $bottom = $('<div>' + config.slides[index] + '</div>');
			$bottom.
				css({"position":"absolute", "z-index":"2000"}).
			width( width ).
				height( config.height ).
				html( config.slides[0] );
			$obj.
				css({"height":config.height + 'px'}).
				html('').
				append($top).append($bottom);
			
			function nextIndex() {
				return ( index < (config.slides.length - 1) ? index + 1 : 0 );
			}
			function prevIndex() {
				return ( index > 0 ? index - 1 : config.slides.length - 1 );
			}
			
			function advance() {
				$top.stop().css({"display":"block"}).animate({"opacity": 1.0}, config.fadeTime, function() {
					index = nextIndex();
					$bottom.html( $top.html() );
					$top.css({"display":"none", "opacity": 0.0});
					$top.html( config.slides[ nextIndex() ] );
				});
			}
			
			function goBack() {
				$top.html( config.slides[ prevIndex() ] );
				$top.stop().css({"display":"block"}).animate({"opacity": 1.0}, config.fadeTime, function() {
					index = prevIndex();
					$bottom.html( $top.html() );
					$top.css({"display":"none", "opacity": 0.0});
					$top.html( config.slides[ nextIndex() ] );
				});
			}
			
			timer = setInterval(function() { advance(); }, config.delay);
			
		});
		
	};
})(jQuery);

