/*
 * jQuery FCSlider Plugin
 *
 * A very basic image slider plugin. v0.3-alpha
 *
 * Copyright (c) 2011, Gregory Plüss (gpluess@fconnection.com)
 */

(function($)
{
	var version = '0.3-alpha';

	$.fn.fc_slider = function(options)
	{
		var defaults = {
			fade: '400',
			interval: '4000',
			autoplay: false,
			handleContainer: false
		};

		var options = $.extend(defaults, options);

		return this.each(function()
		{
			$slider = $(this);

			// create the handle
			var handle = $('<ul>', {
				id: 'image-slider-handles'
			}).insertBefore($slider);

			// collect the slider items
			slider_items = $slider.find('li');
			
			// we only need this if we have more than one item
			if (slider_items.length > 1)
			{
				// collect the slider items and create the image browser
				slider_items.each(function(index)
				{
					var parent = $('<li>');
	
					var child = $('<a>', {
						href: '#',
						text: index+1,
						click: function(e)
						{
							e.preventDefault();

							$slider.find('li:visible')
								.hide()
								.show()
								.fadeOut(options.fade)
								.removeClass('active')
								.addClass('hidden');

							$(slider_items[index]).fadeIn(options.fade)
								.removeClass('hidden')
								.addClass('active');
							
							handle.find('.active').removeClass('active');
							handle.find('li').eq(index).addClass('active');
							
						}
					}).prependTo(parent);
	
					parent.appendTo(handle);
				});
				
				handle.find('li').first().addClass('active');
				
				if (options.autoplay === true)
				{
					// private function
					function fade()
					{
						var $current = $slider.find('.active');
						var $next = ($slider.find('.active').next().length > 0) ? $slider.find('.active').next() : $slider.find('li').first();
						
						var $current_handle = handle.find('.active');
						var $next_handle = (handle.find('.active').next().length > 0) ? handle.find('.active').next() : handle.find('li').first();
		
						$current.hide()
							.show()
							.fadeOut(options.fade)
							.removeClass('active')
							.addClass('hidden');
							
						$next.fadeIn(options.fade)
							.removeClass('hidden')
							.addClass('active');
						
						$current_handle.removeClass('active');
						$next_handle.addClass('active');
					};
					
					var timer = setInterval(fade, options.interval);
		
					// pause the slideshow on hover
					$slider.hover(function() {
						timer = clearInterval(timer);
					}, function() {
						timer = setInterval(fade, options.interval);
					});
				};
			};
		});
	};

	$.fn.fc_slider.version = function() { return version; };

})(jQuery);
