var ajaxLoad;
var temporizador = 10;
var imgActual = 0;

$(document).ready(function() {
	$("#newsletter").focus(function(){ if( $(this).val() == $(this).attr('title')) $(this).val(''); }).blur(function(){ if( $(this).val() == '') $(this).val($(this).attr('title')); });
	
	$('#fundo img').load(function(){
		actualizaDim();
		$('#fundo img').eq(imgActual).fadeIn(1500);
	});
	
	setInterval('mudaImagem()', temporizador * 1000);
	$("#fundo img").load(function(){ $("#fundo").stop(true,true).fadeIn(1000); });
	actualizaJS(true);
	
});
$(window).resize(function(){actualizaDim();actualizaJS(false);});
$.ajaxSetup ({ cache: false });

function actualizaJS(jCarouselLite){
	var altura = $("#header").height() + $("#contentor").height() + $("#rodape").height() + $("#rodape").height();
	//if(altura < $(window).height()) $('#rodape').css('position','fixed'); else $('#rodape').css('position','relative');
	$("#conteudo-contacts .obrigatorio").focus(function(){ if( $(this).val() == $(this).attr('title')) $(this).val(''); }).blur(function(){ if( $(this).val() == '') $(this).val($(this).attr('title')); });
	
	if($("#mapa").exists()) setMapa();
	if($("#rss-feed").exists() && $("#rss-feed").html() == '') getFeed();
	
	/*$('#conteudo-history').masonry({
		itemSelector: 'li',
		columnWidth: 220,
		gutterWidth: 20
	});*/
	
	if(jCarouselLite == true){
		$(".auto .jCarouselLite").jCarouselLite = null;
		$(".auto .jCarouselLite").jCarouselLite({
			visible: 1,
			auto: 3000,
			speed: 2000
		});
	}
	
	$("a[rel^='prettyPhoto']").prettyPhoto({show_title:false, deeplinking: false, social_tools:false, hideflash:true});
	
	if($("#pass-collections").exists()){
		$("#pass-collections").focus(function(){
			if($("#pass-collections").val() == "Buyer’s password here")
				$("#pass-collections").val('');
		}).blur(function(){
			if($("#pass-collections").val() == '')
				$("#pass-collections").val("Buyer’s password here");
		});
	}
}
function openDownload(){
	var vars = {f:'verifyPass', pass:$("#pass-collections").val()}; 
	$.ajax({ type: "POST", url: "php/ajax.php", data: vars, success: function(msg){
		if(strIsNull(msg)){
			SWFAddress.setValue('catalog');
		} else {
			debug(msg);
			toggleLoading(false);
		}
	},	error: function(xhr, ajaxOptions, thrownError){ debug('missing file!'); } });
}
// GERAL
function actualizaURL(){
	var url = SWFAddress.getValue();
	if(url.substr(0,1) == '/') url = url.substr(1,url.length);
	if($.isFunction(toggleMenu)){
		if(url == "" || url == undefined || url == '/') toggleMenu([]); else toggleMenu(url.split("/"));
	}
}
function getFeed(){
	$.ajax({
		url: "php/getrss.php",
		dataType: "html",
		success: function(html) { 
			$("#rss-feed").html(html).fadeIn(300,function(){actualizaJS(true);});
		}
	});
}
function toggleMenu(lista){
	var pagina;
	if(lista.length > 0){
		pagina = lista[0];
		$("#menu li a").each(function(){ if($(this).attr('rel') == lista[0]) $(this).addClass('inactivo'); else $(this).removeClass('inactivo'); });
		$("#rodape-menu li a").each(function(){ if($(this).attr('rel') == lista[0]) $(this).addClass('inactivo'); else $(this).removeClass('inactivo'); });
	} else {
		pagina = 'home';
		$("#menu li a").each(function(){ if($(this).attr('rel') == '') $(this).addClass('inactivo'); else $(this).removeClass('inactivo'); });
		$("#rodape-menu li a").each(function(){ if($(this).attr('rel') == '') $(this).addClass('inactivo'); else $(this).removeClass('inactivo'); });
	}
	var extra = '';
	if(!strIsNull(lista[1])) extra = '?i='+lista[1];
	$("#conteudo").stop(true,false).animate({'opacity':0},500,function(){
		$("#conteudo-ajax").load('pg/'+pagina+'.php'+extra, function(){
			$("#conteudo").stop(true,false).animate({'opacity':1},500);
			actualizaJS(true);
		});
	});
}

function registaEmail(){
	if( emailValido($('#newsletter').val()) ){
		$('#newsletter').css('border-color','#404040');
		var vars = {f:'registaEmail', email:$("#newsletter").val()}; 
		$.ajax({ type: "POST", url: "php/ajax.php", data: vars, success: function(msg){
			if(strIsNull(msg)){
				debug('Your email was successfully registered!');
				$('#newsletter').val($('#newsletter').attr('title')).css('border-color','#404040');
			} else {
				debug(msg);
				toggleLoading(false);
			}
		},	error: function(xhr, ajaxOptions, thrownError){ debug('missing file!'); } });
	} else {
		$('#newsletter').css('border-color','#60c4d7');
	}
}
function sendContacto(){
	var erro = false;
	$("#conteudo-contacts .obrigatorio").each(function(){
		if($(this).val() == $(this).attr('title') || $(this).val().length < 2){erro = true;$(this).css('border-color','#60c4d7');} else $(this).css('border-color','#404040');
	});
	
	if(!emailValido($("#contacts-email").val())) {erro = true;$("#contacts-email").css('border-color','#60c4d7');} else $("#contacts-email").css('border-color','#404040');
	
	if(erro == false){
		var vars = {f:'sendContacto', email:$("#contacts-email").val(), nome:$("#contacts-nome").val(), assunto:$("#contacts-assunto").val(), mensagem:$("#contacts-mensagem").val()}; 
		$.ajax({ type: "POST", url: "php/ajax.php", data: vars, success: function(msg){
			if(strIsNull(msg)){
				$("#contacts-alerta").html('Your email was successfully sent');
				$("#contacts-email").val($("#contacts-email").attr('title'));
				$("#contacts-nome").val($("#contacts-nome").attr('title'));
				$("#contacts-assunto").val($("#contacts-assunto").attr('title'));
				$("#contacts-mensagem").val($("#contacts-mensagem").attr('title'));
				$("#conteudo-contacts .obrigatorio").each(function(){$(this).css('border-color','#404040');});
			} else {
				$("#contacts-alerta").html(msg);
				toggleLoading(false);
			}
		},	error: function(xhr, ajaxOptions, thrownError){ debug('missing file!'); } });
	} else
		$("#contacts-alerta").html('Please complete the marked fields correctly!');
}

//
function mudaImagem(){
	$('#fundo img').eq(imgActual).stop(true,true).fadeOut(1500);
	imgActual++;
	if(imgActual >= $('#fundo img').length) imgActual = 0;
	$('#fundo img').eq(imgActual).stop(true,true).fadeIn(1500);
}

function actualizaDim(){
	var altura = $('#fundo img').height();
	var largura = $('#fundo img').width();
	
	var escala = $(window).height() / $('#fundo img').height();
	$('#fundo img').css("height",(altura*escala)+"px").css("width",(largura*escala)+"px");
	if($('#fundo img').width() < $(window).width()){
		escala = $(window).width() / largura;
		$('#fundo img').css("width",(largura*escala)+"px").css("height",(altura*escala)+"px");
	}
	// centrar
	$('#fundo img').css("left",( $(window).width() - $('#fundo img').width() ) / 2 );
	$('#fundo img').css("top",( $(window).height() - $('#fundo img').height() ) / 2);
}

function setMapa(){
	var latlng = new google.maps.LatLng( 41.149538,-8.620094 );
	var myOptions = {
		zoom: 16,
		center: latlng,
		streetViewControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var 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 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(on==true)$("#loading").stop(true,false).delay(0.5).animate({'bottom':0});else $("#loading").stop(true,false).animate({'bottom':-40})*/}
jQuery.fn.exists = function(){return this.length>0;}
//function fileExists(urlFile){ $.ajax({ url:urlFile, type:'HEAD',  error: function(){  return 'false';  }, success: function(){ return 'true'; } }); }
