var setduration1 = 4000;
var setduration2 = 5000;

window.addEvent('domready', function(e){
	var busy = false, timer, loadedImages = [], gallery = $('fotoli'); 
	var path = 'http://demos.mootools.net/demos/Asset.images/';
	var images = [
		'/_common/random.php?width=174&height=130&rand='+ Math.random(),
		'/_common/random.php?width=174&height=130&rand='+ Math.random(),
		'/_common/random.php?width=174&height=130&rand='+ Math.random(),
		'/_common/random.php?width=174&height=130&rand='+ Math.random(),
		'/_common/random.php?width=174&height=130&rand='+ Math.random(),
		'/_common/random.php?width=174&height=130&rand='+ Math.random(),
		'/_common/random.php?width=174&height=130&rand='+ Math.random()
	];

	gallery.setStyles({'opacity': 0, 'display': 'none'});
	if (!busy) {
		var galleryImgs = $$('#fotoli img');
		if (galleryImgs.length > 0) galleryImgs.each(function(image) {	image.remove();	});

		busy = true;
		gallery.setStyle('display', 'block');
		new Asset.images(images, {
			onProgress: function(i) {
				this.setStyles({
					'position': 'absolute',
					'opacity': 0,
					'left': ((gallery.getCoordinates().width / 2) - (this.width / 2))-1,
					'top': ((gallery.getCoordinates().height / 2) - (this.height / 2))-1
				});
				loadedImages[i] = this;
			},
			onComplete: function() {
				var fx = $('fotoli').effect('opacity').start(1);
				timer = 0;
				loadedImages.each(function(image, i) {
					timer += setduration1;
					image.inject(gallery);
					fx = function() {
						var imgEffect = image.effect('opacity', {duration: setduration2});
						imgEffect.start(1).chain(function() {
							if (i < loadedImages.length - 1) {
								this.start(0).chain(function() {
									image.remove();
								});
							} else {
								busy = false;
							}
						});

					}.delay(timer * 2);
				});
			}
		});
	}
}); 
