var Tox = {
	current_node : 0,
	img_nodes : null,
	p_nodes : null,
	controls_node : null,
	pe : null,
	running : false,
		
	initialize : function () { },
		
	setupSlideShow : function() {
		this.img_nodes = $$('#slideshow_inner img');
		this.p_nodes = $$('#slideshow_caption p');
		this.controls_node = $('slideshow_controls');
		this.drawControls();
	},
	
	drawControls : function() {
		if (this.controls_node) {
			controls = new Array(this.img_nodes.length + 1);
			
			for (i = 0; i < this.img_nodes.length; i++) {
				if (this.current_node == i )
					controls[i] = '<span>' + (i + 1) + '</span>';
				else
					controls[i] = '<a href="" onclick="Tox.stopSlideShow(); Tox.goToSlide(' + i + '); return false">' + (i + 1) + '</a>'
			}
			start_stop =  this.running ? '<a href="" onclick="Tox.stopSlideShow(); return false"><img src="/toxicology/images/pause_button.gif" /></a>' :  '<a href="" onclick="Tox.startSlideShow(); return false"><img src="/toxicology/images/start_button.gif" /></a>'
			this.controls_node.innerHTML = start_stop + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + controls.join("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		}
	},
	
	cycleForward : function(pe) {
		this.pe = pe;
		// prevent case where link is clicked before the first execution and slideshow runs anyway
		if (!this.running)
			this.pe.stop();
		else
			this.goToNextSlide();
	},
	
	goToNextSlide : function() {
		this.goToSlide(this.current_node < this.img_nodes.length - 1 ? this.current_node + 1 : 0);
	},
	
	goToSlide : function(slide) {
		if (this.img_nodes.length > 1) {
			if (slide <= this.img_nodes.length) {
				Effect.Fade(this.img_nodes[this.current_node], { duration: 1.0 } );
				Effect.Fade(this.p_nodes[this.current_node], { duration: 1.0 } );
				//if (this.current_node < this.img_nodes.length - 1) this.current_node++; else this.current_node = 0;
				this.current_node = slide;
				this.drawControls();
				Effect.Appear(this.img_nodes[slide], { duration: 1.0 });
				Effect.Appear(this.p_nodes[slide], { duration: 1.0 });
			}
		}
	},
	
	startSlideShow : function() {
		new PeriodicalExecuter(this.cycleForward.bind(this), 10);
		this.running = true;
		this.drawControls();
	},
	
	stopSlideShow : function() {
		if (this.pe) this.pe.stop();
		this.running = false;
		this.drawControls();		
	}
	
}

Event.observe(window, 'load', function() {
	Tox.initialize();
	if (document.location.href.match(/toxicology$|toxicology\/$|toxicology\/index.html$/)) {
		Tox.setupSlideShow();
		Tox.startSlideShow();
	}
});