//QueueLoader 1.0;
//Source code by Luca Reghellin - http://www.reghellin.com - email@reghellin.com

//Required: mootools.js 1.2 - http://www.mootools.net

//Options:
//loaderImage: String - path of the loader.gif
//backgroundColor: String - container divs background color

/* /// QueueLoader /// */

//var u = new Utils();

var QueueLoader = new Class({

	Implements:Options,
	
	options:{
		loaderImage:'images/loader.gif',
		backgroundColor:'#ffffff'
		//loaderId:null
	},

	initialize:function(imageList,options){
		
		this.setOptions(options);
		this.o = this.options;
		
		this.imageList = imageList;
		
		if(this.imageList.length%2 != 0){ return; }//se la lista non  pari, manca qualcosa.
		
		this.loadedImages = 0;
		this.imageIndex = 0;	
		this.loader = null;
		
		this.buildLoaderHTML();
		this.loadImage(this.imageIndex);
	},
	
	loadImage:function(i){
					
		var img = new Asset.image(this.imageList[i], { 
				onload:function(img){
				   
					$(this.imageList[i+1]).setStyles({'opacity':0}).grab(img).fade('in');
					this.loadedImages++;
					
					if(this.loadedImages < this.imageList.length/2){
						this.imageIndex += 2;
						this.loadImage(this.imageIndex);
					}

				}.bindWithEvent(this)//fine onload
			});//fine asset
	},
	
	buildLoaderHTML:function(){

		if(this.o.loaderImage){
			//uso asset in modo da poter controllare se effettivamente l'immagine c'.
			var img = new Asset.image(this.o.loaderImage, { 
				onload:function(img){
					this.loaderSize = $H(img.getProperties('width','height')).map(function(item, index){
						return item.toInt();
					});
					
					//se il path dell'immagine è sbagliato w/h == 0, dunque mi fermo:
					if(this.loaderSize.height == 0 && this.loaderSize.width == 0){ return; }
		
					for(var i=1; i<=this.imageList.length-1; i+=2){
						var box = $(this.imageList[i]);
						box.setStyles({
							'background-image':'url('+this.o.loaderImage+')',
							'background-position':'center',
							'background-repeat':'no-repeat'
						});
					}
					
				}.bindWithEvent(this)//fine onload
			});
		}//fine if
		
	}//fine buildLoaderHTML();
	
	///////
});//END QUEUELOADER

