var slideshow = {
	SLIDE_FADE_SPEED: 1000,
	TIME_BETWEEN_SLIDES: 7000,
	TIME_BETWEEN_RETRIES: 10,
	slideshow_timer: null,
	retry_timeout: null,
	current_slide: null,
	
	init: function() {
		//show first slide
		jQuery('#slideshow_slide_container .slideshow_slide:first-child').show();
		
		//make first button active
		jQuery('#slideshow_container .slideshow_button:first-child').addClass('active');

		//start timer
		this.startSlideshow();
		
		//button behavior
		jQuery('.slideshow_button').click(function() {
			slideshow.showSlide(jQuery(this).index());
		});
		
		// redirect behavior on text-box click
		jQuery('.slideshow_slide_text').click(function() {
			window.location = jQuery(this).siblings('.slideshow_slide_url').html();
		});
	},
	
	startSlideshow: function() {
		this.slideshow_timer = setInterval('slideshow.nextSlide()', this.TIME_BETWEEN_SLIDES);
	},
	
	stopSlideshow: function() {
		clearInterval(this.slideshow_timer);
	},
	
	getCurrentSlide: function() {
		if(this.current_slide) {
			return this.current_slide;
		} else {
			return jQuery('#slideshow_slide_container .slideshow_slide:visible');
		}
	},
	
	nextSlide: function() {
		var current_slide = this.getCurrentSlide();
		var next_slide = current_slide.next();
		if(!next_slide.length) {
			next_slide = jQuery('#slideshow_slide_container .slideshow_slide:first-child');
		}
		
		var next_slide_num = next_slide.index();
		
		this.showSlide(next_slide_num);
	},
	
	showSlide: function(num) {
		// ignore request if the current slide is already displayed
		var current_slide = this.getCurrentSlide();
		if(current_slide.index() == num) {
			return;
		}
		
		// If an animation's in progress, wait until finished
		var animated_slides = jQuery('#slideshow_slide_container .slideshow_slide:animated');
		if(animated_slides.length) {
			clearTimeout(this.retry_timeout);
			this.retry_timeout = setTimeout('slideshow.showSlide('+num+')', this.TIME_BETWEEN_RETRIES);
			
		// Otherwise, change the slide
		} else {
			this.stopSlideshow();
		
			var next_slide = jQuery('#slideshow_slide_container .slideshow_slide:eq('+num+')');
			if(next_slide.length) {
				next_slide.fadeIn(this.SLIDE_FADE_SPEED);
				current_slide.fadeOut(this.SLIDE_FADE_SPEED);
			}
			
			var active_button = jQuery('#slideshow_container .slideshow_button.active');
			var next_button = jQuery('#slideshow_container .slideshow_button:eq('+num+')');
			active_button.removeClass('active');
			next_button.addClass('active');
			
			// update the current_slide variable
			this.current_slide = next_slide;
			
			this.startSlideshow();
		}
	}
};

Drupal.behaviors.slideshow = {
	attach: function(context) {
		slideshow.init();
	}
};
