// JavaScript Document
var originalWidth = -1;
var originalHeight = -1;
var projetos = [];
var atual = 0;
var tempo = 4;

$(function(){
	adjustHomeMenu();
	$(window).resize(adjustHomeMenu);
	$(window).resize(adjustHomeImagem);
	
	$.post(baseurl + 'site/home/loadProjetos', null, function(json){
		projetos = json;
		startSlideshow();
	},'json');
	
	$('#home-imagem-projeto').css('display','none');
	
});

function adjustHomeMenu(){
	$('#menu-baixo-home')
		.css('top', $(document.body).height() - $('#menu-baixo-home').height() - 110);
}

function adjustHomeImagem(){
	var h = parseFloat($(window).height());
	var w = parseFloat($(window).width());
	
	var iw = originalWidth;
	var ih = originalHeight;
	
	var nw = (h/ih) * iw;
	var nh = h;
	
	if(nw < w){
		nw = w;
		nh = (w/iw) * ih;
	}
	
	$('#home-imagem-projeto')
		.height(nh).width(nw)
		.css('left', w/2 - nw/2)
		.css('top', h/2 - nh/2);
	
}

function startSlideshow(){
	var rec = projetos[ atual++ ];
	
	$('#home-imagem-projeto').attr('title', '')
		.attr('alt', '')
		.parent()
		.attr('href', baseurl + 'site/projetos/fotos/' + rec.idprojeto + '/' + rec.permalink)
		.attr('title', rec.titulo);
	
	var img = new Image();
	$(img).hide();
	$(document.body).append(img);
	
	$(img).load(function(){
		
		originalWidth = $(img).width();
		originalHeight = $(img).height();
		
		$('#home-imagem-projeto').attr('src', img.src)
			.fadeIn('slow');
		
		adjustHomeImagem();
		
		$(document.body).remove(img);
		
		// preload da proxima foto
		var preload = new Image();
		$(preload).load(function(){
			$(this).remove();
		}).css('display', 'none')
			.appendTo(document.body);
			
		preload.src = projetos[ atual >= projetos.length ? 0 : atual ].arquivo;
							 
		setTimeout(encerraSlideshow, tempo * 1000);
		
	}).attr('src', baseurl + rec.arquivo);

}

function encerraSlideshow(){
	atual = atual >= projetos.length ? 0 : atual;
	$('#home-imagem-projeto').fadeOut('slow', startSlideshow);
}
