var pgAtual = "index";

$(document).ready(function(){
	
	//site
	setSize();
	$(window).resize(function(){
		setSize();
	});
	
	//menu
	ajustaMenu();
	$('#menu > ul > li > div').mouseenter(function(){
		$(this).addClass('hover');
		$(this).stop(true).animate({height:75},100);
	}).mouseleave(function(){
		$(this).animate({height:42},100,function(){
			$(this).removeClass('hover');
		});
	});
	
	//submenu
	$('.submenu > ul > li').live('mouseenter',function(){
		$(this).stop(true).animate({backgroundPosition:0},200);
	}).live('mouseleave',function(){
		$(this).animate({backgroundPosition:-190},200);
	}).live('click',function(){
		abreProduto($(this).attr('linha'),"");
	});
	$('.up').live('mouseenter',function(){
		goUp();
	}).live('mouseleave',function(){
		$('.submenu > ul').stop(true);
	});
	$('.down').live('mouseenter',function(){
		goDown();
	}).live('mouseleave',function(){
		$('.submenu > ul').stop(true);
	});
	
	//galeria
	$('.thumbs > ul > li > img').live('click',function(){
		abreProduto($(this).attr('linha'),$(this).attr('produto'));
	});
	$('.left').live('mouseenter',function(){
		goLeft();
	}).live('mouseleave',function(){
		$('.thumbs').stop(true);
	});
	$('.right').live('mouseenter',function(){
		goRight();
	}).live('mouseleave',function(){
		$('.thumbs').stop(true);
	});
	$('.galeria > .ampliacao').live('click',function(){
		ampliaFoto($(this).children('img').attr('src'));
	});
	
	//downloads
	$('.pasta').live('click',function(){
		abrePasta($(this).attr('pasta'));
	});
	
	
	//contato
	$("#form_contato").live('submit',function() {
		var nome = $("#ipt_nome").val();
		var email = $("#ipt_email").val();
		var telefone = $("#ipt_telefone").val();
		var mensagem = $("#ipt_mensagem").val();
		var assunto = $("#ipt_assunto").val();
		if (nome == ""){
			alert("Por favor, informe o nome.");
			$("#ipt_nome").focus();
		}
		else if (!/[A-Za-z0-9_.-]+@([A-Za-z0-9_]+\.)+[A-Za-z]{2,4}/.test(email)){
				alert("Por favor, informe um e-mail válido.");
				$("#ipt_email").focus();
		}
		else if (telefone == ""){
			alert("Por favor, informe o telefone.");
			$("#ipt_telefone").focus();
		}
		else if (assunto == ""){
			alert("Por favor, informe o assunto.");
			$("#ipt_assunto").focus();
		}
		else if (mensagem == ""){
			alert("Por favor, informe a mensagem.");
			$("#ipt_mensagem").focus();
		}
		else{
			$('#layer').show();
			$.post('fale_conosco.php', {nome:nome, email:email, telefone:telefone, mensagem:mensagem, assunto:assunto}, function(resposta) {
				if (resposta == false) {
					alert("Ocorreu um erro ao enviar sua mensagem.");
				}
				else {
					$('#layer').hide();
					alert("Mensagem enviada com sucesso.");
					$("#ipt_nome").val("");
					$("#ipt_email").val("");
					$("#ipt_telefone").val("");
					$("#ipt_mensagem").val("");
					$("#ipt_assunto").val("");
				}
			});
		}
	});
	$('.form').live('focusin focusout',function() {
		$(this).toggleClass('formhover');
	});
	
	//empresa
	$('.empresa > li').live('mouseenter mouseleave',function(){
		$(this).toggleClass('hover');
	}).live('click',function(){
		abreEmpresa($(this).attr('texto'));
	});

});

function ampliaFoto(src){
	src = src.replace('thumb','');
	Shadowbox.open({
		content:	src,
		player:		'img'
	});
}

function abreMapa(src){
	Shadowbox.open({
		content:	'mapa.php?id='+src,
		player:		'iframe',
		width:		426,
		height:		370
	});
}

function goUp(){
	var tempo = 5 * ($('.submenu > ul').scrollTop());
	$('.submenu > ul').animate({scrollTop: 0} ,tempo,"linear");
}

function goDown(){
	var tempo = 5 * ($('.submenu > ul').height() - $('.submenu > ul').scrollTop());
	$('.submenu > ul').animate({scrollTop: $('.submenu > ul').height()},tempo,"linear");
}

function goLeft(){
	if (pgAtual=='imprensa')
		var tempo = 2 * ($('.thumbs').scrollLeft());
	else
		var tempo = 3 * ($('.thumbs').scrollLeft());
	$('.thumbs').stop(true).animate({scrollLeft: 0} ,tempo,"linear");
}

function goRight(){
	if (pgAtual=='imprensa')
		var tempo = 2 * ($('.thumbs > ul').width() - $('.thumbs').scrollLeft());
	else
		var tempo = 3 * ($('.thumbs > ul').width() - $('.thumbs').scrollLeft());
	$('.thumbs').stop(true).animate({scrollLeft: $('.thumbs > ul').width()},tempo,"linear");
}

$.changeImage = function(src, callback) {
	var img = new Image();
  $(img).load(function (){
		$('#back').append(this);
		$(this).height($('#container').height());
		$(this).width( ($('#container').height()*16) / 9 );
		if ($('#back > img').width() < $('#container').width()){
			$($(this)).width($('#container').width());
			$($(this)).height( ($('#container').width()*9) / 16 );
		}
		if (pgAtual == 'index') {
			$(this).fadeIn(400);
			$('#layer').hide();
		}
		if (typeof callback == 'function') {
			callback.call(this);
		}
	}).attr('src', src);
};

function abreIndex(pg,image){
	$('.'+pgAtual).remove(); //remove página atual
	pgAtual = pg; //atribui novo valor à página atual
	$('#back > img').remove(); //apaga imagem do fundo
	$('#content').append("<div class='" + pg + "'></div>"); //adiciona nova página
	$('#layer').show() //mostra layer de loading
	$.changeImage(image);
}

function abrePagina(pg,image){
	$('.'+pgAtual).remove(); //remove página atual
	pgAtual = pg; //atribui novo valor à página atual
	$('#back > img').remove(); //apaga imagem do fundo
	$('#content').append("<div class='" + pg + "'></div>"); //adiciona nova página
	$('#layer').show() //mostra layer de loading
	$.ajax({
		url: pg+".php",
		dataType: "html", //opera
		data: "pagina="+pg,
		success: function(data){
			$.changeImage(image,function(){		 
				var imgs = $(data).find('img').size();
				
				var cont = 0;
				if (imgs > 0){
					$(data).find('img').load(function(a){
						cont++;
						if (cont == imgs){
							$('.'+pg).html(data).fadeIn(400);
							if ((pg == "linha_basic") || (pg == "linha_exclusive")){
								var aux = 0;
								var hPossible = $('#container').height() - $('#menu').height() - (($('.submenu').offset().top - $('#container').offset().top)  *2);
								$('.submenu > ul > li').each(function(){
									aux += $(this).outerHeight()+1;
								});
								if (aux > hPossible){
									$('.submenu > ul').height(hPossible- ($('.up').height() *2)); //ajusta tamanho do submenu de acordo com o tamanho da página
								}
								else {
									$('.up,.down').remove();
								}
							}
							else if (pg=="imprensa"){
								if (imgs > 4){
									$('.galeria').append("<div class='left'></div>").append("<div class='right'></div>");
								}
								$(".thumbs > ul").width( (imgs) * ($('.thumbs > ul > li').width()+8));
							}
							$('#back > img').fadeIn(400); //imagem
							$('#layer').hide(); //esconde layer de loading
							return;
						}
					}).delay(100,function(){
						
					});
				}
				else {
					$('.'+pg).html(data).fadeIn(400);
					if ((pg == "linha_basic") || (pg == "linha_exclusive")){
						var aux = 0;
						var hPossible = $('#container').height() - $('#menu').height() - (($('.submenu').offset().top - $('#container').offset().top)  *2);
						$('.submenu > ul > li').each(function(){
							aux += $(this).outerHeight()+1;
						});
						if (aux > hPossible){
							$('.submenu > ul').height(hPossible- ($('.up').height() *2)); //ajusta tamanho do submenu de acordo com o tamanho da página
						}
						else {
							$('.up,.down').remove();
						}
					}
					else if (pg=="imprensa"){
						if (imgs > 4){
							$('.galeria').append("<div class='left'></div>").append("<div class='right'></div>");
						}
						$(".thumbs > ul").width( (imgs) * ($('.thumbs > ul > li').width()+8));
					}
					$('#back > img').fadeIn(400); //imagem
					$('#layer').hide(); //esconde layer de loading
					return;
				}
			});
		}
	});
}

function abreProduto(linha,produto){
	$('#back > img').remove(); //apaga imagem do fundo
	$('.produto').remove();
	$('.'+pgAtual).append("<div class='produto'></div>");
	$('.produto').css({marginLeft: (($('#container').width() - $('.submenu').outerWidth() - 15) - $('.produto').outerWidth())/2 }); //centraliza produtos
	$('.produto').html("<img src='media/loading.gif' alt='' class='loading' />"); //loading
	$.ajax({
		type: "POST",
		url: "produtos.php",
		data: "linha="+linha+"&produto="+produto,
		dataType: "html", //opera
		success: function(data){
			var imgs = $(data).find('img').size();
			var cont=0;
			$(data).find('img').load(function(a){
				cont++;
				if (cont == imgs){
					$('.produto').html(data);
					if ($('.ampliacao > img').height() < $('.ampliacao').height()){
						$('.ampliacao > img').css({marginTop: ($('.ampliacao').height() - $('.ampliacao > img').height())/2 });
					}
					$('.thumbs > ul').width( (imgs-1) * ($('.thumbs > ul > li').width()+4));
					if (imgs-1 > 5){
						$('.thumbs').css({width: 370, marginLeft: 15});;
						$('.galeria').append("<div class='left'></div>").append("<div class='right'></div>");
					}
				}
			});			
		}
	});
}

function abrePasta(pasta){
	$('.box').html("<img src='media/loading.gif' alt='' class='loading' />"); //loading
	$.ajax({
		type: "POST",
		url: "downloads_in.php",
		data: "id="+pasta+"&pagina=downloads",
		dataType: "html", //opera
		success: function(data){
			$('.'+pgAtual).html(data);
		}
	});
}

function abreEmpresa(texto){
	$('.box').html("<img src='media/loading.gif' alt='' class='loading' />"); //loading
	$.ajax({
		type: "POST",
		url: "quem_somos.php",
		data: "sub="+texto+"&pagina=quem_somos",
		dataType: "html", //opera
		success: function(data){
			$('.'+pgAtual).html(data);
			$('.empresa > li').each(function(){
				if ($(this).attr('texto')==texto){
					$(this).addClass('hover');
				}
				else {
					$(this).removeClass('hover');
				}
			});
		}
	});
}

function ajustaMenu(){
	var totalWidth = 0;
	
	// centraliza
	$('#menu > ul > li').each(function(i){
		totalWidth += $(this).outerWidth(true);
	});
	$('#menu > ul').width(totalWidth+1);
	
	// ajusta o tamanho dos botões
	$('#menu > ul > li > div').each(function(){
		$(this).width($(this).parent('li').outerWidth());
	});
}

function setSize(){
	var sCroll = 17; //right scroll
	
	//ajusta largura
	if ($(window).width() < 1024-sCroll){
		$('#container').width(1024-sCroll);
	}
	else if ($(window).width() > 1600-sCroll){
		$('#container').width(1600-sCroll);
	}
	else {
		$('#container').width($(window).width());
	}
	
	//ajusta altura
	if ($(window).height() < 576-sCroll){
		$('#container').height(576-sCroll);
	}
	else if ($(window).height() > 900-sCroll){
		$('#container').height(900-sCroll);
	}
	else {
		$('#container').height($(window).height());
	}
	
	//centraliza
	if ($('#container').height() < $(window).height()){
		$('#container').css({top: ($(window).height() - $('#container').height())/2})
	}
	else {
		$('#container').css({top: 0})
	}
	
	//muda largura da imagem baseado na altura
	$('#back > img').height($('#container').height());
	$('#back > img').width( ($('#container').height()*16) / 9 );
	// ou muda altura da imagem baseado na largura
	if ($('#back > img').width() < $('#container').width()){
		$('#back > img').width($('#container').width());
		$('#back > img').height( ($('#container').width()*9) / 16 );
	}
	
	//centraliza menu e muda posição confome tamanho
	if ($('#container').width() >= $(window).width()){
		if ($('#menu > ul').width() >= $(window).width())
			$('#menu').width($('#menu > ul').width());
		else
			$('#menu').width($(window).width());
	}
	else {
		$('#menu').width($('#container').width());
	}
	if ($('#container').height() < $(window).height())
		$('#menu').css({position: 'absolute'});
	else
		$('#menu').css({position: 'fixed'});
}

