var posX;
var mapa;
var lat;
var lon;
var ajaxLoad;
var ficheiro = 'welcome';
var weMadeGal = 0;

$(document).ready(function() {
	$('#lista-news').masonry({
		itemSelector: '.bloco',
		columnWidth: 311,
		gutterWidth: 12
	});
	actualizaMenu();
	$("#marca-over, #marca-selecionado").css('opacity',1);
	
	$("#menu li a").mouseover(function(){
		posX = $(this).offset().left  - 35 + ($(this).width()/2);
		$("#marca-over").stop(true,true).animate({'left':posX},500);
	}).mouseout(function(){
		posX = $("#menu li .inactivo").offset().left - 35 + ($("#menu li .inactivo").width()/2);
		$("#marca-over").stop(true,true).delay(300).animate({'left':posX},500);
	});
	setTimeout('setFundo()',5000);
});
$(window).load(function(){actualizaMenu(ficheiro);});
$(window).resize(function(){actualizaFundo();});
$.ajaxSetup ({ cache: false });

function setFundo(){
	$("#fundo .inside").html('<div><img src="imagens/fundo1.jpg" alt="" /></div><div><img src="imagens/fundo2.jpg" alt="" /></div><div style="margin-top:1000px;"><img src="imagens/fundo4.jpg" alt="" /></div><div style="margin-top:1000px;"><img src="imagens/fundo5.jpg" alt="" /></div>');
	$("#fundo img").load(function(){ $("#fundo").stop(true,true).fadeIn(1000); });
	actualizaFundo();
}
function actualizaFundo(){ var posX = ( 2050 - $(window).width() ) / 2; $("#fundo img").css('left',-posX); }

function actualizaJS(){
	$("a[rel^='prettyPhoto']").prettyPhoto({show_title:false, deeplinking: false, social_tools:false, hideflash:true});
	
	if($('.auto .jCarouselLite').exists()) $(".auto .jCarouselLite").jCarouselLite = null;
	if($('#welcome-left .prev').exists()) $('#welcome-left .prev').unbind('click');
	if($('#welcome-right .prev').exists()) $('#welcome-right .next').unbind('click');
	$(".auto .jCarouselLite").jCarouselLite({
		btnNext: "#welcome-right .next",
		btnPrev: "#welcome-left .prev",
		visible: 1,
		auto: 5000,
    	speed: 1000,
		pause: true
	});
	
	setFocusBlur();
	setMapa();
	if($('#lista-galeria').exists()){
		var $container = $('#lista-galeria');

		$container.imagesLoaded( function(){
			$container.masonry({ itemSelector: '.bloco', columnWidth: function( containerWidth ) { return containerWidth / 5; }, gutterWidth: 10 });
		});
	}
	toggleLoading(false);
}
// GERAL
function toggleMenu(lista){
	ficheiro = 'welcome';
	if(lista[0] == 'about-us' || lista[0] == 'our-projects' || lista[0] == 'we-made' || lista[0] == 'news' || lista[0] == 'contact-us') ficheiro = lista[0];
	
	$("#conteudo").stop(true,true).fadeOut(500,function(){
		if(ajaxLoad) ajaxLoad.abort();
		toggleLoading(true);
		var vars = {id:lista[1]}; 
		ajaxLoad = $.ajax({ type: "POST", url: "pg/"+ficheiro+".php", data: vars, success: function(msg){ 
			$("#conteudo").stop(true,true).html(msg).fadeIn(500,function(){actualizaJS();});
		},	error: function(xhr, ajaxOptions, thrownError){ debug('missing file!'); } });
	})
	
	$("#menu li a").each(function(){ if($(this).attr('rel') == ficheiro) $(this).addClass('inactivo'); else $(this).removeClass('inactivo'); });
	actualizaMenu(ficheiro);
}
function actualizaMenu(ficheiro){
	posX = $("#menu li .inactivo").offset().left  - 35 + ($("#menu li .inactivo").width()/2); 
	$("#marca-selecionado, #marca-over").stop(true,true).animate({'left':posX},500); 
	
	var posY = 0;
	switch(ficheiro){
		case 'about-us': posY = 1*1000; break;
		case 'our-projects': posY = 2*1000; break;
		case 'we-made': posY = 3*1000; break;
		case 'news': posY = 4*1000; break;
		case 'contact-us': posY = 5*1000; break;
	}
	$("#fundo .inside div").each(function(){ if($(this).attr('title') == ficheiro) posY = $(this).offset().top });
	$("#fundo .inside").stop(true,true).animate({'top':-posY});
}

//
function setMapa(){
	if($("#mapa").exists()){
	var estilos = [ { featureType: "water", stylers: [ { saturation: -100 }, { lightness: 50 } ] },{ featureType: "landscape", stylers: [ { saturation: -100 }, { visibility: "off" }, { lightness: 85 } ] },{ stylers: [ { saturation: -99 } ] },{ featureType: "road.highway", stylers: [ { visibility: "on" }, { lightness: 55 } ] },{ featureType: "road.local", stylers: [ { visibility: "on" }, { lightness: 7 } ] },{ featureType: "transit.station", stylers: [ { visibility: "simplified" } ] },{ featureType: "poi", stylers: [ { visibility: "simplified" } ] },{ featureType: "landscape.man_made", stylers: [ { visibility: "on" } ] },{ featureType: "administrative.neighborhood", stylers: [ { visibility: "on" } ] },{ featureType: "road.arterial", stylers: [ { lightness: 35 } ] } ];
	
	var latlng = new google.maps.LatLng( lat, lon );
	var myOptions = {
		zoom: 15,
		center: latlng,
		streetViewControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		},
		styles: estilos
	};
	mapa = new google.maps.Map(document.getElementById("mapa"), myOptions);
	
	var imagem = new google.maps.MarkerImage('imagens/marcador.png', new google.maps.Size(20, 20), new google.maps.Point(0,0), new google.maps.Point(10, 10));
	var marcador = new google.maps.Marker({
		position: latlng,
		icon: imagem,
		draggable: false,
		map: mapa
	});
	}
}

function prjMudaPagina(up){
	var total = $("#we-made-gal ul li").length / 9;
	var pos = Number($("#we-made-gal ul").css('top').replace('px',''));
	if(up == true){
		if($("#seta-baixo").hasClass('inactivo') == false){
			weMadeGal++;
			pos = -(weMadeGal*334);
			$("#we-made-gal ul").stop(true,true).animate({'top':pos},500);
		}
	} else if($("#seta-cima").hasClass('inactivo') == false) {
		weMadeGal--;
		pos = -(weMadeGal*334);
		$("#we-made-gal ul").stop(true,true).animate({'top':pos},500);
	}
	if(weMadeGal <= 0) $("#seta-cima").addClass('inactivo'); else $("#seta-cima").removeClass('inactivo');
	if(weMadeGal >= (total-1)) $("#seta-baixo").addClass('inactivo'); else $("#seta-baixo").removeClass('inactivo');
}
//
function sendContacto(){
	$("#contacto .alerta").stop(true,true).fadeOut(300, function(){
		$("#contacto .alerta").stop(true,true).html('');
		var erro = false;
		if($("#contacto-nome").val().length < 2 || $("#contacto-nome").val() == $("#contacto-nome").attr('title')){erro=true;$("#contacto-nome").css('border-color','#fff');} else $("#contacto-nome").css('border-color','transparent');
		if(!emailValido($("#contacto-email").val())){erro=true;$("#contacto-email").css('border-color','#fff');} else $("#contacto-email").css('border-color','transparent');
		if($("#contacto-assunto").val().length < 2 || $("#contacto-assunto").val() == $("#contacto-assunto").attr('title')){erro=true;$("#contacto-assunto").css('border-color','#fff');} else $("#contacto-assunto").css('border-color','transparent');
		if($("#contacto-mensagem").val().length < 2 || $("#contacto-mensagem").val() == $("#contacto-mensagem").attr('title')){erro=true;$("#contacto-mensagem").css('border-color','#fff');} else $("#contacto-mensagem").css('border-color','transparent');
		
		if(erro == false){
			toggleLoading(true);
			var vars = {f:'sendContacto', nome:$("#contacto-nome").val(), email:$("#contacto-email").val(), assunto:$("#contacto-assunto").val(), mensagem:$("#contacto-mensagem").val()}; 
			$.ajax({ type: "POST", url: "php/ajax.php", data: vars, success: function(msg){ 
				if(strIsNull(msg)){
					$("#contacto .alerta").stop(true,true).html('Message sent!').fadeIn();;
					$("#contacto-nome").val($("#contacto-nome").attr('title'));
					$("#contacto-email").val($("#contacto-email").attr('title'));
					$("#contacto-assunto").val($("#contacto-assunto").attr('title'));
					$("#contacto-mensagem").val($("#contacto-mensagem").attr('title'));
					toggleLoading(false);
				} else
					$("#contacto .alerta").stop(true,true).html(msg).fadeIn();
			},	error: function(xhr, ajaxOptions, thrownError){ debug('missing file!'); } });
		} else
			$("#contacto .alerta").stop(true,true).html('error').fadeIn();
	});
}

function actualizaURL(){ var url = SWFAddress.getValue(); if(url.substr(0,1) == '/') url = url.substr(1,url.length); if($.isFunction(toggleMenu)){ if(strIsNull(url) || url == '/') toggleMenu([]); else toggleMenu(url.split("/")); } }
function mudaLingua(lg){ if(lg != $("#linguas .inactivo").attr('rel')){ var vars = {f:'mudaLingua', lingua:lg}; ajaxLoad = $.ajax({ type: "POST", url: "php/ajax.php", data: vars, success: function(msg){ if(strIsNull(msg)) window.location.reload(); else debug(msg); },	error: function(xhr, ajaxOptions, thrownError){ debug('missing file!'); } }); } }
function goTop(){$('html, body').animate({scrollTop:0}, 'slow');}
/* ÚTIL */
function inputON(obj,valor){ if($(obj).val() == valor) $(obj).val(""); }
function inputOFF(obj,valor){ if(strIsNull($(obj).val())) $(obj).val(valor); }
function debug(txt){ toggleLoading(false); alert(txt);}
function strIsNull(str){ if(str == null || str == "" || str == undefined) return true; else return false; }
function emailValido(email){ var er = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/; return er.test(email); }
function toggleLoading(on){if(ajaxLoad) ajaxLoad.abort();if(on==true)$("#loading").stop(true,true).delay(0.5).slideDown();else $("#loading").stop(true,true).slideUp();}
function setFocusBlur(){$(".focus-blur").each(function(){$(this).focus(function(){if($(this).val() == $(this).attr('title')) $(this).val('');}).blur(function(){if($(this).val() == '')$(this).val($(this).attr('title'));});});}
jQuery.fn.exists = function(){return this.length>0;}
//function fileExists(urlFile){ $.ajax({ url:urlFile, type:'HEAD',  error: function(){  return 'false';  }, success: function(){ return 'true'; } }); }
