jQuery.fn.dotSlideshow = function(settings){
	settings = jQuery.extend({
		'target': null, //the jquery selector or elements that should be used for the list of dots
		'duration': 10000, //how many ms do we stay on a slide
		'transitionDuration': 500, //how many ms does it take to transition from one slide to the next
		'autoStart': true //if true will show the first slide when loaded
	},settings);

	return this.each(function(k,v){
		var el = $(v);
		var target = $(settings.target);

		el.html('<ul class="dot-slideshow-list"/>');
		var ul = el.find('ul');

		target.each(function(kk,vv){
			var li = $('<li/>');
			li.data('target.dotSlideshow',$(vv));
			li.data('slot.dotSlideshow',kk);
			ul.append(li);
		});

		var showSlide = function(li){
			var li = $(li);
			var lastActive = li.parent().find('.active');
			lastActive.removeClass('active');
			li.addClass('active');
			var target = li.data('target.dotSlideshow');
			var lastTarget = lastActive.data('target.dotSlideshow');

			//if we had a previous slide showing, crossfade, else just show it
			if(typeof lastTarget != 'undefined' && lastTarget){
				lastTarget.stop().css('opacity',1).fadeOut(settings.transitionDuration);
				target.stop().css('opacity',1).fadeIn(settings.transitionDuration,function(){
					$(this).attr('style','display: block');
				});
			} else {
				target.show();
			}
		};

		var stopSlideshow = function(){
			var timeout = el.data('timeout.dotSlideshow');
			if(timeout){
				window.clearTimeout(timeout);
			}
		}

		var startSlideshow = function(){
			var list = el.find('li');
			var cycleImage = function(){
				var activeEl = el.find('li.active');
				var nextEl = null;
				if(activeEl.length <= 0){
					nextEl = el.find('li:first');
				} else {
					nextEl = list.get(list.index(activeEl)+1);
					if(!nextEl || nextEl.length <= 0){
						nextEl = activeEl.parents('ul:first').find('li:first');
					}
				}

				showSlide(nextEl);
				var timeout = window.setTimeout(cycleImage,settings.duration);
				el.data('timeout.dotSlideshow',timeout);
			}

			cycleImage();
		}

		//bind the click event to the element
		ul.find('li').bind('click.dotSlideshow',function(){
			stopSlideshow();
			showSlide(this);
		});

		//auto start with the first element if set
		if(settings.autoStart){
			startSlideshow();
		}
	});
};


