
window.addEvent('domready', function() {
	
	var sections = ['home', 'bio', 'showreel', 'foto', 'press', 'links', 'contatti'];
	
	
	// impostazione del click delle voci di menu
	$$('.menu_link').each(function(el) {
		el.addEvent('click', function(evt) {
			evt.stop();
			changeContent(el.get('href'));
		});
	});
	
	/*
		CLICK PULSTANTE
		changeContent()
			|------> setContent()
			|				|------> loadContent()
			|				|				|------> showContent(true)
			|				|
			|				|------> resetContent()
			|
			|------> showContent(false)
							|------> setContent()
							|				|------> loadContent()
							|				|				|------> showContent(true)
							|				|
							|				|------> resetContent()
							|
							|------> resetContent()
	*/
	
	var content_container = $('content_container');
	var content = $('content');
	var showing = false;
	var section = 'home';
	
	// impostazione per la visualizzazione dei contenuti
	var content_show = new Fx.Morph(content_container, {
		duration: 'normal',
		transition: 'quad:out',
		link: 'ignore',
		onComplete: function(el) {
			showing = false;
		}
	});
	// impostazione per il nascondimento dei contenuti
	var content_hide = new Fx.Morph(content_container, {
		duration: 'normal',
		transition: 'quad:out',
		link: 'ignore',
		onComplete: function(el) {
			setContent(section);
		}
	});
	
	var height_limit = 390;
	// visualizza o nasconde la fascia dei contenuti
	var showContent = function(value) {
		
		var dim = content.getComputedSize({mode: 'vertical'});
		if (dim.height > height_limit) dim.height = height_limit;
		
		if (value) {
			content_show.start({
				'height': dim.height,
				//'height': [0, dim.height],
				'opacity': 1
			});
			
		} else {
			content_hide.start({
				'height': 0,
				//'height': [dim.height, 0],
				'opacity': 0
			});
		}
	}

	// imposta il contenuto caricando la pagina richiesta
	var setContent = function(value) {
		if (value && value!='home') {
			loadContent(value+'.html');
		} else {
			resetContent();
		}
	}

	// svuota il contenuto della pagina
	var resetContent = function() {
		content.empty();
		showing = false;
	}

	// chiede il cambiamento della pagina
	// viene controllato se la pagina richiesta è corretta
	// e se vi è già un'altra pagina in caricamento
	var changeContent = function(value) {
		if (sections.indexOf(value) < 0) {
			return false;
		}
		
		if (showing) {
			return false;
		}
		showing = true;
		
		var _section = section;
		setSection(value);
		if (_section == 'home' && _section != section) {
			setContent(section);
		} else {
			showContent(false);
		}
		
		SWFAddress.setValue(value);
		
		return true;
	}
	
	// carica la pagina richiesta
	// aggiornando il div dei contenuti
	var loadContent = function(page) {
		var HTMLRequest = new Request.HTML({
			url: page,
			evalScripts: true,
			evalResponse: true,
			update: content,
			timeout: 2000,
			method: 'get',
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				showContent(true);
			},
			onFailure:function(){
				console.log(page);
				//alert('page loading error - retry or refresh the page please!');
				resetContent();
			},
			onTimeout:function(){
			}
		});
		HTMLRequest.send();
	}
	
	// cambia la sezione corrente
	// aggiornando gli elementi del menu
	var setSection = function(id) {
		$(section+'_link').getElement('a').setStyle('display', 'inline');
		$(section+'_link').getElement('span').setStyle('display', 'none');
		
		section = id;
		$(section+'_link').getElement('a').setStyle('display', 'none');
		$(section+'_link').getElement('span').setStyle('display', 'inline');
		
		if (id == 'home') {
			setSlideshow(true);
		} else {
			setSlideshow(false);
			changeBackground(section);
		}
		
		resetResizeEvent();
	}
	
	
	
	var loadBg = function(value) {
		var loader = new Asset.image(value,	{
			onLoad: function() {
				var background = $('background');
				var bg_image = loader;
				
				bg_image.fade('hide');
				bg_image.inject(background);
				
				resizeBackground(bg_image);
				
				bg_image.set('tween', {
					duration: 'long',
					transition: 'quad:out',
					onComplete: function(el) {
						var bg_images = background.getElements('img');
						if (bg_images.length > 1) {
							bg_images[0].destroy();
						}
					}
				});
				bg_image.fade('in');
			}
		});
	}
	
	var changeBackground = function(value) {
		loadBg('./images/background/bg_'+value+'.jpg');
	}
	
	var resizeBackground = function(bg_image) {
		var background = $('background');
		if (typeof(bg_image) == 'undefined') bg_image = background.getElement('img');
		
		var window_size = window.getSize();
		var body_size = $$('body')[0].getComputedSize();
		var container_size = $('container').getComputedSize();
		
		var max_height = Math.max(window_size.y, body_size.height);
		var max_width = Math.max(window_size.x, container_size.width);
		var max_dim = {'height': max_height, 'width': max_width};
		
		background.setStyles(max_dim);
		
		if (bg_image) {
			var dim = bg_image.getDimensions();
			var new_dim = fillSize(max_dim.width, max_dim.height, dim.width, dim.height);
			
			bg_image.setStyles({'height':new_dim.height, 'width':new_dim.width});
			bg_image.setProperties({'height':new_dim.height, 'width':new_dim.width});
		}
		
		var scroll_value =  Math.min(window_size.y-body_size.height, 0);
		$('container').setStyle('bottom', scroll_value+'px');
		
		// resize del contenuto della sezione
		var dim = content.getComputedSize({mode: 'vertical'});
		if (dim.height > height_limit) dim.height = height_limit;
		content_container.setStyles({'height': dim.height});
	}
			
	var fillSize = function(maxW, maxH, currW, currH) {
		var max_ratio = maxH / maxW;
		var curr_ratio = currH / currW;
		
		if (curr_ratio <= max_ratio) {
			// più orizzontale
			// ridimensiono in altezza
			currH = maxH;
			currW = Math.round(currH / curr_ratio);
		} else {
			// più verticale
			// ridimensiono in larghezza
			currW = maxW;
			currH = Math.round(currW * curr_ratio);
		}
			
		return {width:currW, height:currH};
	}
	
	var resetResizeEvent = function() {
		window.removeEvents('resize');
		window.addEvent('resize', function() {
			resizeBackground();
		});
	}
	resetResizeEvent();

	/*window.addEvent('scroll', function() {
		//var scroll_value =  -window.getScroll().y;
		//$('container').setStyle('bottom', scroll_value+'px');
	});*/
	
	var slideshow = false;
	var slideshow_image = 0;
	var slideshow_timer = 0;
	var slideshow_images = [{url:'bg_home.jpg', delay:10}, {url:'bg_slide.jpg', delay:7}, 
		{url:'bg_showreel.jpg', delay:7}, {url:'bg_press.jpg', delay:7}, 
		{url:'bg_bio.jpg', delay:7}, {url:'bg_foto.jpg', delay:7}, 
		{url:'bg_links.jpg', delay:7}, {url:'bg_contatti.jpg', delay:7}];
		
	var setSlideshow = function(value) {
		if (value) {
			nextSlide();
			slideshow = true;
		} else {
			clearTimeout(slideshow_timer);
			slideshow_image = 0;
			slideshow = false;
		}
	}
	
	var nextSlide = function() {
		var image = slideshow_images[slideshow_image];
		loadBg('./images/background/'+image.url);
		
		slideshow_timer = nextSlide.delay(image.delay * 1000);
		
		slideshow_image++;
		if (slideshow_image >= slideshow_images.length) {
			slideshow_image = 0;
		}
	}
	
	function handleInit(event) {
		var path = event.pathNames[0];
		
		if (changeContent(path) == false) {
			changeContent('home');
		}
	}
	
	function handleChange(event) {
		var path = event.pathNames[0];
		changeContent(path);
		//SWFAddress.setTitle(formatTitle(event.path));
	}
		
	SWFAddress.addEventListener(SWFAddressEvent.INIT, handleInit);
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
	
	
	//changeContent(section);
});
