/*
 * Dropdown Menu jQuery plugin
 * 
 * Copyright 2011 KiwiCréation
 * Author: Michael Grenier
 *
 * Usage:
 * 
 * 		<div class="slideshow">
 *			<div></div>
 *			<div></div>
 *			<div></div>
 *			...
 *		</div>
 *
 * Call:
 * 
 * 		$('.slideshow').imageslider({
 * 			'speed': 1000,
 * 			'timeout': 10000
 * 		});
 */

(function ($){
	
	$.fn.extend({
		
		'imageslider': function (options) {
			
			options = $.extend({
				'speed': 1000,
				'timeout': 10000
			}, options);
			
			$(this).each(function (){
				var item = $(this);
				item.data('options', options);
				item.children().css('opacity', 0);
				item
				.children()
					.css('left', (-1*item.outerWidth())+'px');
				var childrens = item.children();
				$(childrens[0])
				.css({
						'left': '0px',
						'opacity': 1
					}
				);
				var timertemp = setTimeout(function(){
					$.imageslidernext(item, 1, options);
				}, options.timeout+options.speed);
			});
		}
	});
	
	var timer;
	
	$.imageslidernext = function(item, count, options) {
		var childrens = item.children();
		if (count == 0)
			$(childrens[childrens.length-1])
				.css('z-index', 150)
				.animate({
						'left':  item.outerWidth()+'px',
						'opacity': 0
					},
					options.speed, 'easeOutSine',
					function() {
						$(childrens[childrens.length-1])
						.css('left', (-1*item.outerWidth())+'px');
					}
				);
		else
			$(childrens[count-1])
				.css('z-index', 150)
				.animate({
						'left': item.outerWidth()+'px',
						'opacity': 0
						
					},
					options.speed, 'easeOutSine',
					function() {
						$(childrens[count-1])
						.css('left', (-1*item.outerWidth())+'px');
					}
				);
		$(childrens[count])
			.css('z-index', 200)
			.animate(
				{
					'left': '0px',
					'opacity': 1
				}, 
				options.speed, 'easeOutSine'
			);
		if (timer)
			clearTimeout(timer);
		timer = setTimeout(function(){
			if (childrens.length < count + 2)
				$.imageslidernext(item, 0, options)
			else
				$.imageslidernext(item, count+1, options)
		}, options.timeout+options.speed);
	}
	
})(jQuery);
