function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) return false;
	else return true;
}

function bookmarksite(title, url) {
	if (document.all)
		window.external.AddFavorite(url, title);
	else if (window.sidebar) {
		window.sidebar.addPanel(title, url, "");
	}
}

// Size method
var Get = new Object;
Get.size = function(obj) {
	var size = 0, key;
	for(key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
}


	
$(document).ready(function() {
	
	$('#gallery a').lightBox({fixedNavigation:true});
	$('#zoomFoto').lightBox({fixedNavigation:true});

	// Voltar ao topo
	$(".voltarTopo").click(function() {
		$.scrollTo(0, 800 );
	});

	// zoom image
	$('.zoom').zoomimage();
	




	
	// Username
	$("#username").focus(function() {
		var val = $(this).val();
		if(val == "utilizador") $(this).val("");
	});
	$("#username").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("utilizador");
	});
	// Password
	$("#password").focus(function() {
		var val = $(this).val();
		if(val == "chave") $(this).val("");
	});
	$("#password").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("chave");
	});
	
	// Newsletter
	$("#emailNewsletter").focus(function() {
		var value = $(this).attr("value");
		if(value == "newsletter e-mail") $(this).attr({"value":""});
	});
	$("#emailNewsletter").blur(function() {
		var email = $(this).attr("value");
		if(checkEmail(email) == false) $(this).attr({"value":"newsletter e-mail"});
	});

	// Procurar
	$("#pesquisar").focus(function() {
		var val = $(this).val();
		if(val == "procurar") $(this).val("");
	});
	$("#pesquisar").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("procurar");
	});

	// Recomendar amigo - seu nome
	$("#seuNome").focus(function() {
		var val = $(this).val();
		if(val == "seu nome") $(this).val("");
	});
	$("#seuNome").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("seu nome");
	});
	$("#emailAmigo").focus(function() {
		var value = $(this).attr("value");
		if(value == "e-mail de amigo") $(this).attr({"value":""});
	});
	$("#emailAmigo").blur(function() {
		var email = $(this).attr("value");
		if(checkEmail(email) == false) $(this).attr({"value":"e-mail de amigo"});
	});


	// Regular hover
	$(".hover").hover(function() {
		var img = $(this).attr("src");
		var hover = img.replace(".png","-hover.png");
		$(this).attr({"src":hover});
	}, function() {
		var img = $(this).attr("src");
		var hover = img.replace("-hover.png",".png");
		$(this).attr({"src":hover});
	});

	// preload images
	$(".hover").each(function() {
		var img = this.src;
		$("body").append('<img id="deleteThis" src="'+img.replace(".png","-hover.png")+'" style="display:none">');
		$("#deleteThis").remove();
	});


	// Hover em boxs
	$(".box-darker").hover(function() {
		$(this).css({"background-color":"#fcb52b"});
	}, function() {
		$(this).css({"background-color":"#638dac"});
	});


	// Contactos form
	$("#contactos-form-nome").focus(function() {
		var val = $(this).val();
		if(val == "nome") $(this).val("");
	});
	$("#contactos-form-nome").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("nome");
	});
	
	$("#contactos-form-email").focus(function() {
		var value = $(this).attr("value");
		if(value == "e-mail") $(this).attr({"value":""});
	});
	$("#contactos-form-email").blur(function() {
		var email = $(this).attr("value");
		if(checkEmail(email) == false) $(this).attr({"value":"e-mail"});
	});


	$("#contactos-form-assunto").focus(function() {
		var val = $(this).val();
		if(val == "assunto") $(this).val("");
	});
	$("#contactos-form-assunto").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("assunto");
	});
	
	$("#contactos-form-mensagem").focus(function() {
		var val = $(this).val();
		if(val == "mensagem") $(this).val("");
	});
	$("#contactos-form-mensagem").blur(function() {
		var val = $(this).val();
		if(val == "") $(this).val("mensagem");
	});


	
	// Recuperar password
	recuperarPassword = function() {
		var email = $("#recuperarPasswordEmail").val();
		$.ajax({
			type: "POST",
			url: "/requests/recuperar-password.php",
			data: "email="+email,
			success: function(msg){
				if(msg == true) {
					alert("Password enviada com sucesso.");
					$("#popupNoFixedChave").hide();
				}
				else alert("Ocorreu um erro, por favor tente novamente");
			}
		});
		
	}
	$("#recuperarPasswordBtn").click(function() {
		recuperarPassword();
	});

	
	
	// Login && Submit on enter
	submitLogin = function() {		
		var username = $("#username").val();
		var password = $("#password").val();
		//var grupo = $("#grupo").val();
		$.ajax({
			type: "POST",
			url: "/requests/login.php",
			data: "username="+username+"&password="+password,
			success: function(msg){
				if(msg == true) {
					window.location=location.href;
				}
				else alert("A autenticação falhou!");
			}
		});
	}
	$("#username, #password").keypress(function(e) {
		if(e.which == 13) submitLogin();
	});
	$("#login").click(function() {
			submitLogin();
	});
	$("#logout").livequery('click', function() {
		$.ajax({
			url: "/requests/logout.php",
			success: function(msg){
				if(msg == true) {
					//window.location=location.href;
					window.location='/';
				}
			}
		});		
	});







	/* CARRINHO */
	// Verificação de login para encomenda
	$("#cart-continuar").click(function() {
		$.ajax({
			type: "POST",
			url: "/requests/checkLogin.php",
			success: function(msg){
				if(msg != "true") {
					alert("Necessita de efectuar login para continuar a encomenda.");
					window.location='/novo-registo';
				}
				else document.f.submit();
			}
		});
	});

	// Selecção da morada pretendida
	$(".radioEndereco").click(function() {
		//$("#novoEnderecoWrapper").toggle();
		if($(this).attr("value") == 1) $("#novoEnderecoWrapper").show();
		else $("#novoEnderecoWrapper").hide();

		// Repor os valores originais caso seja selecionado utilizar o endereço da conta
		if($(this).val() == 0) {
			var id = $(this).val();
			var peso = $("#pesoCarrinho").val();
			var stotal = $("#totalCarrinhoItems").val();
			$.ajax({
				dataType: "json",
				contentType: "application/json; charset=utf-8",
				url: "/requests/carrinho.php?request=portesAccount&peso="+peso+"&stotal="+stotal,
				success: function(result){
					$("#portesEnvio").html(result);
					Total(id, embrulho);
				}
			});
			document.getElementById("distrito").selectedIndex = 0;
			$("#novoEnderecoTextArea").val("");
			$("#cp01").val("");
			$("#cp02").val("");
			$("#cidade").val("");

			var detalhesMorada = document.getElementById("detalhes-morada");
			detalhesMorada.style.display='none';
		}
	});

	// Selecção de distritos
	$("#distrito").change(function() {
		var id = $(this).val();
		var peso = $("#pesoCarrinho").val();
		var stotal = $("#totalCarrinhoItems").val();
		$.ajax({
			dataType: "json",
			contentType: "application/json; charset=utf-8",
			url: "/requests/carrinho.php?request=portes&distrito="+id+"&peso="+peso+"&stotal="+stotal,
			success: function(result){
				$("#portesEnvio").html(result);
				Total(id, embrulho);


				var detalhesMorada = document.getElementById("detalhes-morada");
				if(detalhesMorada.style.display == 'none') detalhesMorada.style.display='block';
				if(detalhesMorada.style.display == 'block' && id == 0) detalhesMorada.style.display='none';

				/*
				var detalhesMorada = $("#detalhes-morada");
				if($(detalhesMorada).css("display") == 'none') $(detalhesMorada).css({"display":"block"});
				if($(detalhesMorada).css("display") == 'block' && id == 0) $(detalhesMorada).css({"display":"none"});
				*/
			}
		});
	});
	
	// Actualiza o total do carrinho
	Total = function(id, embrulho) {
		$.ajax({
			dataType: "json",
			contentType: "application/json; charset=utf-8",
			url: "/requests/carrinho.php?request=actualizaTotal&distrito="+id+"&embrulho="+embrulho,
			success: function(result){
				$("#totalValue").html(result);
			}
		});
	}
	
	
	// Embrulhos
	var embrulho = false;
	$("#embrulho").change(function() {
		var id = document.getElementById("distrito").selectedIndex;
		$("#embrulhoWrapper").toggle();

		if(embrulho == false) {
			Total(id, "true");
			embrulho = true;
		} else {
			Total(id, "false");
			embrulho = false;
		}
	});






	UpdateDom = function() {
		$(".hover").hover(function() {
			var img = $(this).attr("src");
			var hover = img.replace(".png","-hover.png");
			$(this).attr({"src":hover});
		}, function() {
			var img = $(this).attr("src");
			var hover = img.replace("-hover.png",".png");
			$(this).attr({"src":hover});
		});
		$("#pesquisar").focus(function() {
			var val = $(this).val();
			if(val == "procurar") $(this).val("");
		});
		$("#pesquisar").blur(function() {
			var val = $(this).val();
			if(val == "") $(this).val("procurar");
		});
	}
	/*
	setLogOut = function(){
		$("#logout").click(function() {
			$.ajax({
				url: "/requests/logout.php",
				success: function(msg){
					if(msg == true) {
						window.location=location.href;
					}
				}
			});		
		});
	}
	setLogOut();
	*/








	// Inscrever em newsletter
	$("#emailNewsletter").keypress(function(e) {
		if(e.which == 13) {
			var email = $("#emailNewsletter").val();
			$.ajax({
				type: "POST",
				url: "/requests/newsletter.php",
				data: "email="+email,
				success: function(msg){
					alert(msg);
					window.location=location.href;
				}
			});
		}
	});
	
	$("#InscreveNewsletter").click(function() {
		var email = $("#emailNewsletter").val();
		$.ajax({
			type: "POST",
			url: "/requests/newsletter.php",
			data: "email="+email,
			success: function(msg){
				alert(msg);
				window.location=location.href;
			}
		});
	});










	// request pedido de informações
	$("#info-btn").click(function() {
		data = new Object();
		$("#popup-info-text-wrapper input, textarea").each(function(obj,i) {
			data[$(i).attr("name")] = $(i).val();
		});
		//JSON Informações request aqui
		$.ajax({
			type: "GET",
			url: "/requests/info.php",
			data: data,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg){
				if(msg == null) {
					alert("Mensagem enviada com sucesso");
					$("#popup-info-outside-wrapper").fadeOut("fast");
					$("#popup-info-text-wrapper label").css({"color":"#333333"});
					$("#popup-info-text-wrapper input, textarea").val("");
					popupInfo = false;
				} else {
					var key;
					for(key in msg.error) {
						if(msg.error[key] == true) $("#popup-info-text-wrapper label[name='"+key+"']").css({"color":"red"});
						else $("#popup-info-text-wrapper label[name='"+key+"']").css({"color":"#333333"});
					}
				}
			}
		});
	});






	// Request recomendar a amigo
	$("#recomentarAmigo").click(function() {
		data = new Object();
		$("#recomendar-amigo-wrapper input").each(function(obj,i) {
			data[$(i).attr("name")] = $(i).val();
		});
		var url = location.href.split("/");
		data["tipo"] = url[3];
		//JSON recomendar amigo
		$.ajax({
			type: "GET",
			url: "/requests/recomendar-amigo.php",
			data: data,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg){
				if(msg == "ok") {
					alert("Mensagem enviada com sucesso");
					if(popupOpen == true) {
						popup.fadeOut("normal");
						popupOpen = false;
					}
					//var key;
					//for(key in data) $("input[name='"+key+"']").val("");
				} else {
					alert("Preencha os campos correctamente.");
				}
			}
		});		
	});
	
	
	

	/*
	<name>Generic Popup</name>
	<usage>
		<a class="genericPopup" rel="popupTeste">Clique aqui</a>
		<div id="popupTeste">CONTEUDO DA POPUP</div>
	</usage>
	*/
	var popupOpen = false;
	var popupRel = null;
	var popup = null;
	var popupWidth = 0;
	var popupHeight = 0;
	$(".genericPopup").click(function(e) {
		var width = $(window).width();
		var height = $(window).height();
		var xPos = e.pageX;
		var yPos = e.pageY;
		popupRel = $(this).attr("rel");
		popup = $("#"+popupRel);
		popupWidth = parseInt(popup.width());
		popupHeight = parseInt(popup.height());

		if(xPos + popupWidth > width) popup.css({"left":xPos-popupWidth});
		else popup.css({"left":xPos+10});
		if(yPos + popupHeight > height) popup.css({"top":yPos-popupHeight});
		else popup.css({"top":yPos+10});
		popup.fadeIn("normal", function() {
			popupOpen = true;
		});
	});
	// close popup
	$(document).click(function(e) {
		if(popupOpen == true) {
			var offsetX = parseInt(popup[0].offsetLeft);
			var offsetY = parseInt(popup[0].offsetTop);
			if(e.pageX < offsetX || e.pageX > (offsetX+popupWidth) || e.pageY < offsetY || e.pageY > (offsetY+popupHeight)) {
				popup.fadeOut("normal");
				popupOpen = false;
			}
		}
	});
	
	
	
	
	// Personalized
	//not(:checked)
	$(".categoria").click(function(e) {
		//$(this).children(".subcategoria").toggle("normal");
		if(e.target.className != "slide-no-toggle")
			$(this).children(".subcategoria").animate({height:'toggle'},350);
	});
	$(".categoria").hover(function() {
		$(this).css({"background-color":"#e7f1f9"});
		$(this).children("ul").css({"background-color":"#FFFFFF"});
	}, function() {
		$(this).css({"background-color":"#FFFFFF"});
	});
	$(".subcategoria li").hover(function() {
		$(this).css({"background-color":"#e7f1f9"});
	}, function() {
		$(this).css({"background-color":"#FFFFFF"});
	});
	
	
	// Bullets
	$(".hover-bullet").hover(function() {
		$(this).children("img").attr({"src":"/images/bullet-blue-hover.png"});
	}, function() {
		$(this).children("img").attr({"src":"/images/bullet-blue.png"});
	});
	
	
	// Hover na listagem de molduras de categorias
	$(".moldura-categorias-wrapper").hover(function() {
		$(this).children(".moldura-categorias-title").css({"background-color":"#ee9219"});
	}, function() {
		$(this).children(".moldura-categorias-title").css({"background-color":"#638dac"});
	});
	
	
	// SELECT
	$(".selectTrigger, .selectTriggerMeses, .selectTriggerAnos").click(function() {
		$(this).next().slideToggle("fast");
	});
	
	$(".selectListagemResult, .selectListagemResultMeses, .selectListagemResultAnos").hover(function() {
		$(this).css({"background-color":"#fcb52b", "color":"white"});
	}, function() {
		$(this).css({"background-color":"white", "color": "#808080"});
	});





	// VERIFICAR QUAIS FORAM SELECCIONADOS E APLICAR FILTROS
	var mes = 1;
	var ano = 2010;
	$(".selectListagemResultMeses").click(function() {
		$(this).parent().parent().slideUp("fast");
		$(".selectTriggerMeses").html($(this).html());
		mes = $(this).attr("rel");
	});
	$(".selectListagemResultAnos").click(function() {
		$(this).parent().parent().slideUp("fast");
		$(".selectTriggerAnos").html($(this).html());
		ano = $(this).attr("rel");
	});
	
	$("#filtrosNoticias").click(function() {
		url = "/noticias/" + mes + "/" + ano;
		window.location=url;
	});





	// Listagem de dicas
	$(".listagem-dicas").hover(function() {
		$(this).css({"background-color":"#e7f1f9"});
		$(this).children("ul").css({"background-color":"#FFFFFF"});
	}, function() {
		$(this).css({"background-color":"#FFFFFF"});
	});
	
	




	// CRIAR WISHLIST
	$("#wishlistCreate").click(function() {
		var wishlistName = $("#wishlistName").val();
		$.ajax({
			type: "POST",
			url: "/requests/wishlist.php",
			data: "request=Create&name="+wishlistName,
			success: function(msg){
				if(msg == "true") {
					alert("Wishlist criada com sucesso.");
					$("#wishlistName").attr({"value":""});
					if(popupOpen == true) {
						popup.fadeOut("normal");
						popupOpen = false;
					}
					window.location=location.href;
				} else {
					var JSONobj =  eval('('+msg+')');
					alert(JSONobj.msg);
				}
			}
		});
	});
	



	/*
	 * Adicionar à wishlist
	 *
	 */
	$(".listagemWishlistsAdd").click(function() {
		var wishlist = $(this).attr("rel");
		var url = location.href.split('/');
		var type = url[3];
		var item = url[4];
		$.ajax({
			type: "POST",
			url: "/requests/wishlist.php",
			data: "request=AddItem&wishlist="+wishlist+"&type="+type+"&item="+item,
			success: function(msg){
				if(msg == "true") alert('Inserido com sucesso na wishlist.');
				else {
					var JSONobj =  eval('('+msg+')');
					alert(JSONobj.msg);
				}
				$("#ListWishlist").slideToggle("fast");
			}
		});
	});


	

	/*
	 * Enviar wishlist
	 *
	 */	
	$("#sendWishlist").click(function() {
		var email = $("#sendWishlistEmailAmigo").val();
		var url = location.href.split("/");
		var id_wishlist = url[5];
		$.ajax({
			type: "POST",
			url: "/requests/wishlist.php",
			data: "request=Send&email="+email+"&id_wishlist="+id_wishlist,
			success: function(msg){
				if(msg == "true") alert('Email enviado com sucesso.');
				else {
					var JSONobj =  eval('('+msg+')');
					alert(JSONobj.msg);
				}
			}
		});
	});



	/*
	 * Remover ItemWishlist
	 *
	 */
	$(".DeleteItem").click(function() {
		var remover = window.confirm("Deseja realmente eliminar este item?");
		if (remover) {
			var id_item = $(this).attr("id").replace("wishlistItem-","");
			var wrapper = $(this).parent().parent();
			wrapper.fadeOut("normal");
			$.ajax({
				type: "POST",
				url: "/requests/wishlist.php",
				data: "request=DeleteItem&id_item="+id_item,
				success: function(msg){
					if(msg == "true") {
						//alert('Item eliminado com sucesso.');
						wrapper.fadeOut("normal");
					}
					else {
						var JSONobj =  eval('('+msg+')');
						alert(JSONobj.msg);
					}
				}
			});
		} else return false;
	});





	/*
	 * Listagem com hover da wishlist
	 *
	 */
	$(".listagemWishlists, .listagemWishlistsAdd").hover(function() {
		$(this).css({"background-color":"#fcb52b", "color":"white"});
	}, function() {
		$(this).css({"background-color":"white", "color":"#808080"});
	});


	



	/*
	 * SelectBox list
	 *
	 */
	$(".ListWishlistTrigger").click(function() {
		$("#ListWishlist").slideToggle("fast");
	});







	// Hover nas novidades homepage
	$(".hover-novidades").hover(function() {
		var imgSrc = $(this).children("a").children("img");
		$(imgSrc).attr({"src":$(imgSrc).attr("src").replace(".png","-hover.png")});
		$(this).children("a").css({"color":"#ee9219"});
	}, function() {
		var imgSrc = $(this).children("a").children("img");
		$(imgSrc).attr({"src":$(imgSrc).attr("src").replace("-hover.png",".png")});
		$(this).children("a").css({"color":"#435e73"});
	});
	
	
	
	
	// Hover na listagem de resultados encontrados
	$(".pesquisa-hover").hover(function() {
		$(this).css({"background-color":"#e7f1f9"});
	}, function() {
		$(this).css({"background-color":"#FFFFFF"});
	});
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*
	 * LOJA DAS CRIANÇAS
	 *
	 */
	$(".hover-menu").hover(function() {
		$(this).css({"background-color":"white"});
		$(this).children("a").css({"color":"#e65a8d"});
	}, function() {
		$(this).css({"background-color":"transparent"});
		$(this).children("a").css({"color":"white"});
	});
	$(".hover-menu:first").hover(function() {
		$(this).children("#bullet-produtos").children("img").attr({"src":"/images/bullet-medium-hover.png"});
		$("#popup-menu").show();
	}, function() {
		$(this).children("#bullet-produtos").children("img").attr({"src":"/images/bullet-medium.png"});
		$("#popup-menu").hide();
	});




	$(".listagem-categorias li").hover(function() {
		if($(this).attr("id") != "categoria-activa") {
			$(this).css({"background-color":"#db2462"});
			$(this).children("span").children("a").css({"color":"#ffffff"});
			$(this).children("img").attr({"src":"/images/bullet-white.png"});
		}
	}, function() {
		if($(this).attr("id") != "categoria-activa") {
			$(this).css({"background-color":"white"});
			$(this).children("span").children("a").css({"color":"#404041"});
			$(this).children("img").attr({"src":"/images/bullet-pink.png"});
		}
	});
	
	
	
	
	/*
	 * Hover molduras
	 *
	 */
	$(".hover-molduras").hover(function() {
		$(this).children(".border-moldura").css({"border":"1px solid #db2462"});
		$(this).children(".titulo-produto-wrapper-moldura").children("h1").css({"color":"#db2462"});
	}, function() {
		$(this).children(".border-moldura").css({"border":"1px solid #929396"});
		$(this).children(".titulo-produto-wrapper-moldura").children("h1").css({"color":"#404041"});
	});
});

