﻿$(function() {
	
	var	$images = $("#mainImage img"),
			index = 0, gallery = [], preLoader = null,
			timer = null,
			delay = 8000, fadeSpeed = 2000;


	function animate() {
		var next = index + 1;
		if (next >= $images.length) { next = 0; }

		$images.eq(index).fadeOut(fadeSpeed);

		$images.eq(next).fadeIn(fadeSpeed, function() {
			timer = setTimeout(function() {
				animate();
			}, delay);
		});

		index = next;
	}



	function startAnimation() {
		$images.slice(1).hide();
		timer = setTimeout(function() {
			animate();
		}, delay);
	}



	if ($images.length > 1) {
		$images.each(function() {
			gallery.push({ src: this.src, alt: this.alt });
		});
		
		preLoader = new Abl.UI.ImagePreLoader({
			onComplete: function() {
				startAnimation();
			}
		});
		preLoader.loadImages(gallery);
	}



	$(window).unload(function() {
		if (timer) { clearTimeout(timer); }
		if (preLoader) { preLoader.dispose(); }
	});

});
