(function ($) {
	
	// Init namespace
	if (!$.blue) {
		$.fn.blue = {};
		$.blue = {};
	}
		
	$.blue.slideshow = function (selector, options) {
		return $.blue.slideshow.impl.init(selector, options);
	};	
		
	$.fn.blue.slideshow = function (options) {
		return $.blue.slideshow.impl.init(this, options);
	};
	
	$.blue.slideshow.defaults = {
		loop: true,
		duration: 1000,
		transition_duration: 500,
		slide_selector: ".slide",
		oncomplete: function() {},
		transition: function() {
			if (this.current_slide) {
				this.current_slide.fadeOut(this.opts.transition_duration)
			}
		
			this.next_slide.fadeIn(this.opts.transition_duration)
		}
	};
	
	$.blue.slideshow.impl = {
		
		opts: null,
		slideshow: null,
		slides: null,
		current_slide: null,
		next_slide: null,
		i: 0,
		current_loop: 0,
		timer: null,

		init: function (selector, options) {
			
			// Merge Default Options
			this.opts = $.extend({}, $.blue.slideshow.defaults, options);

			this.slides = $(selector).find(this.opts.slide_selector);
			if (this.slides.length == 0)
			{
				return false
			}
			this.current_slide = $(this.slides.get(this.i++));
			this.current_slide.show();
			
			if (typeof this.opts.duration == 'object')
			{
				this.timer = [];
				var duration = 0;
				for(i = 0; i < this.slides.length; i++)
				{
					duration += this.opts.duration[i % this.opts.duration.length];
					this.timer[i] = $(this).everyTime(duration, this.next_slide, (this.opts.loop ? this.opts.loop : 0), true);
				}
			}	
			else
				this.timer = $(this).everyTime(this.opts.duration, this.next_slide, (this.opts.loop ? this.opts.loop : 0), true);
		},
		
		next_slide:function() {
			this.next_slide = $(this.slides.get(this.i));

			$(this).bind("transition", this.opts.transition);
			$(this).trigger("transition");
			
			this.current_slide = this.next_slide;
			this.i++;
			
			if (this.i == this.slides.length) {
				if (this.opts.loop == false || this.current_loop == this.opts.loop)
				{
					$(this).bind("complete", this.opts.oncomplete);
					$(this).trigger("complete");
					$(this).stopTime();
				}
				this.current_loop++;
				this.i = 0;
			}
		}
		
	
	};
	
})(jQuery);