dojo.ready(function(){
	var bannerNodes  = dojo.query(".slide", dojo.byId("slideshow")),
		menuNodes    = dojo.query(".shelfTab", dojo.byId("slideshow")),
		maxIndex     = menuNodes.length - 1,
		currentIndex = 0,
		duration     = 600,
		wait         = 9001, // what 9000!!!
		isHovered    = false,
		timeout;

	menuNodes.forEach(function(node, index){
		dojo.connect(node, "mouseenter", function(){
			isHovered = true;
			run(index);
		});
		dojo.connect(node, "mouseleave", function(){
			isHovered = false;
			runTimer();
		});
	});

	function runTimer(duration){
		// Gecko passes timer skew as a final argument to the function passed to setTimeout which breaks
		// if we just pass run directly to it
		clearTimeout(timeout);
		timeout = setTimeout(function(){
			run();
		}, wait - (duration || 0));
	}

	function run(newIndex){
		clearTimeout(timeout);

		if(newIndex === currentIndex){
			return;
		}

		dojo.removeClass(menuNodes[currentIndex], "active");
		dojo.style(bannerNodes[currentIndex], "display", "none");

		currentIndex = newIndex != null ? newIndex : currentIndex === maxIndex ? 0 : currentIndex + 1;

		dojo.addClass(menuNodes[currentIndex], "active");
		dojo.style(bannerNodes[currentIndex], { display: "block", opacity: 0.01 });

		dojo.fadeIn({
			node: bannerNodes[currentIndex],
			duration: duration,
			onEnd: function(){
				!isHovered && runTimer(duration);
			}
		}).play();
	}

	runTimer();
});
