// JavaScript Document
window.addEvent('domready', function() {
	var thumbcont = $$('#thumbs');
	var thumButton = $$('.thumButton');
	var thumbImages = $$('#slider > div ');
	var slider = $$('#slider');

	// init morphing e stili
	thumbImages.each(function(a){ a.setStyle('opacity','.5'); });
	thumButton.setStyle('opacity','.4');
	thumbcont.set('morph', {'duration' : 200});
	thumButton.set('morph', {'duration' : 200});
	thumbImages.set('morph', {'duration' : 200});
	slider.set('morph', {'duration' : 800});
	
	//inizializzazione immagini
	var images = $$('.image');
	var nimmagini = images.length-1;
	var imgIniziale = Math.random()*nimmagini;
	imgIniziale = Math.round(imgIniziale, 10);
	images.set('morph', {'duration':1000});
	images[imgIniziale].setStyle('opacity','1');
	images[imgIniziale].setStyle('display','block');
	for(c=imgIniziale;c<images.length;c++) {
		zindex = images.length - (c - imgIniziale);
		images[c].setStyle('z-index', zindex);
	}
	if (imgIniziale != 0) {
		for(c=0;c<imgIniziale;c++) {
			zindex = imgIniziale - c;
			images[c].setStyle('z-index', zindex);
		}
	}
	
	//gestione slide miniatura
	var sxButton = $$('.sx');
	var dxButton = $$('.dx');
	//inizializzo la posizione dello slider
	var margine = 0;
	marginemax = 177 * (images.length - 4);
	//gestisco gli eventi
	sxButton.addEvents({
		'click':function() {
			margine = margine + 177;
			if (margine >= 0) { margine = 0; }
			slider.morph({'left':margine});
		}
	});
	dxButton.addEvents({
		'click':function() {
			margine = margine - 177;
			if (margine <= ((-1)*marginemax)) { margine = ((-1)*marginemax); }
			slider.morph({'left':margine});
		}
	});
	
	//gestione div miniature
	i=1;
	thumButton.addEvents({
		'click':function(){
			if (!i) {
				thumbcont.morph({'top':'-85px', 'opacity':'.4'});
				thumButton.morph({'top':'-85px', 'opacity':'.4'});
				i=1;
			} else {
				thumbcont.morph({'top':'0px', 'opacity':'.8'});
				thumButton.morph({'top':'0px', 'opacity':'.8'});
				i=0;
			}
		}
	});

	//gestione miniature
	thumbImages.each(function(el, f){
		el.addEvents({
			'mouseover':function(){
				el.morph({'opacity':'1'});
			},
			'mouseleave':function(){
				el.morph({'opacity':'.5'});
			},
			'click':function(){
				h = f-1; 
				if (h<0) {h = 0;}
				if (f==3) {h = 3;} 
				images.morph({'opacity':'0'});
				images[f].morph({'opacity':'1'});
				Site.counter = h;
				thumbcont.morph({'top':'-85px', 'opacity':'.4'});
				thumButton.morph({'top':'-85px', 'opacity':'.4'});
				i=1;
			}
		});
	});
	
	// numero casuale Math.round((Math.random()*images.length),10)
	
	
	//slideshow immagini grandi
	var Site = { counter: imgIniziale };
	var addCount = function(){
		images[this.counter].morph({'opacity':'0'});
		this.counter++; 
		if (this.counter >= images.length ) { this.counter = 0; }
		images[this.counter].morph({'opacity':'1'});
	};
	addCount.periodical(8000, Site); 
});	