(function($) {

	$.fn.cycle = function(options) {
	    
	    return this.each(function() {
	    	
	    	var gallery = $(this);
	    	var caption = $('<div id="slideshow-caption"><h2></h2><p></p></div>');
	    	var numOfImages = $('li', this).size();
	    	
	    		    	
	    	var timer;
	    	
	    	initView();
	    	initListener();
	    	
			function initView(){
				$('li:eq(0)', gallery).addClass('show');
				$('li:eq(0)', gallery).siblings().hide();
				triggerImage($('li:eq(0)', gallery));
				
				if( options.showCaption) gallery.append(caption);
			
			}
			
			function initListener(){
			
				if( options.autoCycle ){
					$(gallery).bind('mouseenter', onGalleryMouseEnter);
					$(gallery).bind('mouseleave', onGalleryMouseLeave);
				}else{
					$('li a', gallery).bind('click', onImageClick);
				}
			
			}
			
			function startSlideshow(){
				timer = setTimeout( function(){ triggerImage( getNextImage() ) }, options.speed);
			}
			
			function stopSlideshow(){
				clearTimeout(timer);
			}
	    	
	    	function getNextImage(){
	    	
	    		var current = $('li.show', gallery);
	    		var next = $('li:eq(0)', gallery);
	    		
	    		if( current.next().length && current.next().attr('id') != 'slideshow-caption'){
	    			next = current.next();
	    		}
	    			    			    		
	    		return next;
	    	
	    	}
	    	
	    	
	    	function triggerImage( image ){
	    		
	    		$(image).siblings().removeClass('show').fadeOut(300, function(){
	    			
	    		});
	    		
	    		$(image).addClass('show').delay(500).fadeIn(300, function(){
	    			$('h2', caption).html( $('img', image).attr('alt'));
	    			$('p', caption).html( $('p', image).text());
	    		});
	    		$(caption).delay(500).fadeIn();
	    		
	    		if(options.autoSize)
	    			$(gallery).css({ height: $(image).outerHeight() });
	    		
	    		if(options.autoCycle)
	    			startSlideshow();
	    	
	    	}
	    	
	    	
	    	function onGalleryMouseEnter(){
	    		stopSlideshow();
	    	}
	    	
	    	function onGalleryMouseLeave(){
	    		startSlideshow();
	    	}
	    	
	    	function onImageClick(){
	    		triggerImage( getNextImage());
	    		return false;
	    	}
	    	
	    });
	};


})(jQuery);
