﻿var CarouselViewer = {

	init : function () {
		var	imgIdx = -1,
			imgs = $$('#carousel > img'),
			
			timerId = null,
			startTimer = function () {
				if (timerId) { clearTimeout(timerId); }
				timerId = setTimeout(function (){ selectImage(imgIdx + 1); }, 4000);
			},

			selectImage = function (i) {
				var nav = $('carousel-nav').hide();

				if (imgIdx >= 0) //hide previous
					{ $(imgs[imgIdx]).fade({ duration: 0.4, queue: 'front' }); }

				if (i >= imgs.length) { i = 0; } //turn the corner, go back to 1st

				$(imgs[i]).appear({ queue: 'end', afterFinish: function (){ nav.show(); } });
				imgIdx = i;
				
				startTimer();
			};

		if (imgs.length == 0) { return; }

		$$('#carousel-nav a').each(function (a){
			var idx = parseInt(a.innerHTML, 10) - 1;
			Event.observe(a, 'click', function (e){ selectImage(idx); Event.stop(e); });
		});

		//select the first img to begin with
		selectImage(0);
	}
}