
// fornece imagens em ordem aleatória (e cíclica)
function RandomSource() {
	this.itens=new Array;
	this.buffer=new Array;  //array com as imagens já processadas;
	this.ciclo=-1;
	this.onCycle;
	
	this.add=function (image){
		this.itens[this.itens.length]=image;
	};
	
	this.count=function(){
		return this.itens.length+1;
	};
	
	this.next=function(){
		if (this.buffer.length==0){
			for(var i=0;i<this.itens.length;i++){
				this.buffer[i]=this.itens[i];
			};
			this.ciclo++;
			if (this.onCycle){
				this.onCycle(this.ciclo);
			}
		}
		var index=this.buffer.length;
		var seed=Math.floor(Math.random()*index+1)-1;
		var img=this.buffer[seed] ;
		this.buffer.splice(seed,1);  //remove da fila;
		return img;
	};

}

function Mosaico(timerCallback){
	this.imgSource= new RandomSource(); 
	this.targets= new RandomSource();
	this.timerOFF=true;
	this.start=start;
	this.timer=5000;
	this.cellsDone=0;
	this.timerCallback=timerCallback;
	this.buildQuery;
	this.onShowImage;
	this.onTimer='';
	this.checkTimer=checkTimer;
	this.createImage=createImage;
	this.addImage=function (image){
		this.imgSource.add(image);
	};
	this.addTarget=function (target){
		this.targets.add(target);
	};
	this.nextImage=function(){
		return this.imgSource.next();
	};
	this.nextTarget=function(){
		return this.targets.next();
	};
	
	this.targets.onCycle=function(ciclo){
		if (ciclo==1){
			setTimeout(this.timerCallback,8000);
		}
	}
	
	function start(){
		//para carregamento imdediato!
		for (var i=0;i<this.targets.count();i++){
			this.createImage(this.nextTarget());
		}
	}
	
	function createImage(cell){
		if (this.buildQuery){
			var s=this.buildQuery(this.nextImage());
			var oImage     = new Image;
			o=this;
			oImage.onload  = function(){
				if (o.onShowImage){
					o.onShowImage(oImage.cell,oImage.outerHTML);
				};
				o.checkTimer();
			};
			oImage.onerror = this.checkTimer;
			oImage.onabort = this.checkTimer;
			oImage.cell    = cell;
			oImage.src     = s;
		}
	}

	function checkTimer(){
		this.cellsDone++;
		if (this.cellsDone>=(this.targets.count()-1)){
			this.cellsDone=0;
			if (this.timerOFF==true){
				setTimeout(this.timerCallback,1000);
				this.timerOFF=false;
			}
		}	
	}
}


