var Fading = new Class({
	
	initialize: function(div_id, img_id)
	{
		this.element = $(div_id);
		this.img = img_id;
	},
	
	init: function(nomi, dir, time, random)
	{
		//prima fermo eventuali altri loop
		this.stop();
		
		this.arrFoto = nomi;
		this.dir = dir;
		this.time = time;
		this.random = random;
	},
	
	work: function()
	{
		var obj = this;
		var json = this.arrFoto;
		if (this.count >= json.length) this.count=0;
		
		var fxFade = new Fx.Tween(this.element,{'property':'opacity', 'duration': 'long'});
		
		fxFade.start(0).chain(function(){
			if ($(obj.img)!=null)
			{
				var nomeold = $(obj.img).get('nome');
				$(obj.img).dispose();
			}
			if(!obj.random)
			{
				var nome = json[obj.count];
				obj.count++;
			}
			else
				var nome = obj.scegliRandom(json, nomeold);
			
			var img;
			if ($type(nome)=='string')
				img = new Element('img',{'src': obj.dir+"/"+nome, 'id': obj.img, 'nome':nome, 'alt':''});
			else img = nome;
			img.inject(obj.element);
			return this.callChain();
		}).chain(function(){fxFade.start(1);});
		
	},

	
	start: function()
	{
		this.count = 0;
		var obj = this;
		var f = function(){obj.work();}
		this.work();
		if (this.arrFoto.length>1)
		{
			this.preLoadImg();
			this.go = f.periodical(this.time);
		}
	},
	
	stop: function()
	{
		$clear(this.go);	
	},
	
	preLoadImg: function()
	{
		var obj = this;
		this.arrFoto.each(function(el, index){
				obj.arrFoto[index] = new Element('img',{'src': obj.dir+"/"+el, 'id': obj.img, 'nome':el, 'alt':''});
		});
	},
	
	scegliRandom: function(nomi, nome)
	{
		var nomenew;
		var loop = true;
		do
		{
			nomenew = nomi.getRandom();
			if ($type(nome)=='element') nome = nome.get('nome');
			
			if ($type(nomenew)=='string')
			{
				if (nomenew != nome) loop = false;
			}
			else
			{
				if (nomenew.get('nome') != nome) loop = false;
			}
		}while(loop);
		return nomenew;
	}
});