
window.addEvent('domready', function(e){
	var busy = false, loadedImages = [], gallery = $('gallery'), progress = $('progress'), bar = $$('#progress .bar'); 
	var dirs = ["training", "gym", "soccer", "sport_icons", "waterfall", "sunflower", "field_tree"];
	var random_dir = dirs[Math.floor(Math.random()*7)];

	var path = "/images/center_imgs/" + random_dir + "/";
	var images = [];
	for(x=1; x<=18;x ++){
		images[x-1] = path + "center_img_" + (x < 10 ? "0" : "") + x + ".jpg";
	}
	gallery.setStyles({'opacity': 0, 'display': 'none'});
	progress.setStyle('display', 'none');

	if (!busy) {
	
		var galleryImgs = $$('#gallery img');
		if (galleryImgs.length > 0) galleryImgs.each(function(image) {	image.remove();	});
	
		busy = true;
		progress.setStyle('display', 'block');
		gallery.setStyle('display', 'none');
		new Asset.images(images, {
			onProgress: function(i) {
				this.setStyles({
					'display': "block"					
				});
				loadedImages[i] = this;
				var percent = ((i + 1) * progress.getStyle('width').toInt()) / images.length;
				if(progress.getStyle('width').toInt() < percent.toInt()){
					percent = 200;	
				}
				bar.setStyle('width', percent.toInt()).set('html', i + 1 + ' / ' + images.length);
			},
			onComplete: function() {
				progress.setStyle('display','none');
				images.each(function(image, i) {
				// instead of using the loadedImages array, create a new img element for each part to maintain order					 
					im = new Element('img', {'src': image});
					im.inject(gallery);
				});
				gallery.setStyle('display', 'block');
				var fx = new Fx.Tween('gallery', {'duration': 1000});
				fx.start('opacity', 0, 0.999);
			}
		});
	}
});
