$.fn.slideshow = function(options) {

	var settings = {
		timeout: '2000',
		type: 'sequence'
	}
	if(options)
		$.extend(settings, options);

	/*alert(settings.reloadSlides[0]);*/

	this.css('position', 'relative');

	var slides = $.slideshow.getSlides(this);
	var container = this;

	if(settings.reloadSlides){
		/* start loop to add slides */
		$.slideshow.addSlides(container, settings);
	}

	if ( settings.type == 'sequence' ) {
		setTimeout(function(){
			$.slideshow.next(container, settings, 1, 0);
		}, settings.timeout);
	}
	/* random is still buggy! */
	else if ( settings.type == 'random' ) {
		setTimeout(function(){
			do { current = Math.floor ( Math.random ( ) * ( slides.length ) ); } while ( current == 0 )
			$.slideshow.next(container, settings, current, 0);
		}, settings.timeout);
	}
	else {
		alert('type must either be \'sequence\' or \'random\'');
	}
};
$.slideshow = function() {}
$.slideshow.next = function (container, settings, current, last) {

	var slides = $.slideshow.getSlides(container);

	for (var i = 0; i < slides.length; i++) {
		$(slides[i]).css('display', 'none');
	}
	$(slides[last]).css('display', 'block').css('zIndex', '0');
	$(slides[current]).css('zIndex', '1').fadeIn('slow');

	if ( settings.type == 'sequence' ) {
		if ( ( current + 1 ) < slides.length ) {
			current = current + 1;
			last = current - 1;
		}
		else {
			current = 0;
			last = slides.length - 1;
		}
	}
	else if ( settings.type == 'random' ) {
		last = current;
		while (	current == last ) {
			current = Math.floor ( Math.random ( ) * ( slides.length ) );
		}
	}
	else {
		alert('type must either be \'sequence\' or \'random\'');
	}
	setTimeout((function(){$.slideshow.next(container, settings, current, last);}), settings.timeout);
}
$.slideshow.getSlides = function(container){
	var slides = container.find('a').get();
	for ( var i = 0; i < slides.length; i++ ) {
		$(slides[i]).css('zIndex', slides.length - i).css('position', 'absolute').css('top', '0').css('left', '0');
	}
	return slides;
}
$.slideshow.addSlides = function(container, settings){
	if(settings.reloadSlides.length > 0){
		container.append(settings.reloadSlides[0]);
		settings.reloadSlides.shift();
		if(settings.useImagebox == true){
			$.ImageBox.init({
					loaderSRC: 'images/imagebox/loading.gif',
					closeHTML: 'x'
			});
		}
		$.slideshow.getSlides(container);
		container.find("a:last img").load(function(){
			/*alert('loaded:'+container.find("a:last img").attr('src'));*/
			$.slideshow.addSlides(container,settings);
		});
	}

}