//ajax
function ajaxInit() {
	var req;
	try {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(ex) {
			try {
				req = new XMLHttpRequest();
			} catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				req = null;
			}
		}
	}
	return req;
}

//procura
function busca(valor){
	valor=valor.toLowerCase();
	ajax = ajaxInit(); 
	if(valor.length > 2){
		document.getElementById("pesquisa").style.background = '#FFF url(../images/loading.gif) no-repeat right center';
	}
	ajax.open("GET", "ajaxpesquisa.asp?vale="+escape(valor), true);
	ajax.onreadystatechange=function() {
		if(ajax.readyState==4){
			if(ajax.responseText.length > 0){
				if(ajax.responseText=='vazio'){
					document.getElementById("contentor").style.display = 'none';
					document.getElementById("pesquisa").style.background = '#FFF';
				}
				else{
					document.getElementById("contentor").style.display = '';
					document.getElementById("pesquisa").style.background = '#FFF';
					document.getElementById('contentor').innerHTML = ajax.responseText;
				}
			}
		}
	}
	ajax.send(null);
}

//ao clicar limpar a pesquisa em ajax
function limpatudoaoclicar(){
	document.getElementById("contentor").style.display = 'none';
}
document.onclick = limpatudoaoclicar;

//menus
function novobot(iden,nome){
	eval("document.getElementById('"+iden+"').src='images/"+nome+".gif';")
}
function velhobot(iden,nome){
	eval("document.getElementById('"+iden+"').src='images/"+nome+".gif';")
}

//innerhtml
function escreve(msg){
	document.getElementById('osresultados').innerHTML=msg;
}

//form
function mudar2(accao){
	document.ord2.action = accao;
	document.ord2.submit();
}

//imprimir carrinho
function imprimir(){
	var w = 700;
	var h = 600;
	var lado = (screen.width - w) / 2;
	var topo = (screen.height - h) / 2;
	var ca = window.open('carrinhoimp.asp','carrinho','scrollbars=yes, width='+w+', height='+h+', top='+topo+', left='+lado+'');
	ca.focus();
}

//imprimir produto
function impri(val){
	var w = 700;
	var h = 600;
	var lado = (screen.width - w) / 2;
	var topo = (screen.height - h) / 2;
	var im = window.open("imprime.asp?id="+val+"","imprime"+val+"","scrollbars=yes, width="+w+", height="+h+", top="+topo+", left="+lado+"")
	im.focus();
}

//confirmar
function perguntaconfirmar(dados){
	var per = window.confirm(dados);
	if(per){
		return true;
	}
	else{
		return false;
	}
}

//actualizar
function actualizar(){
	erro=0
	erromsg=""
	var elementos = document.carrinho.elements;
	for(var i=0; i< elementos.length; i++){
		if(elementos[i].getAttribute("type")=="text"){
			if(elementos[i].getAttribute("obrigatorio")=="outro"){
				if(!/^\d+$/.test(elementos[i].value)){
					erro+=1
				}    
			}
		}  
	} 
	if(erro > 0){
		erromsg="Atenção, os valores da quantidade têm que ser inteiros."
		alert(erromsg) 
	}
	else{
		document.carrinho.action = "./alteraquantidade.asp";
		document.carrinho.submit();
	}
}

//continuar
function continuar(){
	document.carrinho.action = "./forma.asp";
	document.carrinho.submit();
}

//metodo
function metodo(){
	document.formas.action = "./metodo.asp";
	document.formas.submit();
}

//confirmar
function confirmar(){
	document.metodos.action = "./confirmar.asp";
	document.metodos.submit();
}

//concluir
function concluiencomenda(){
	document.observa.action = "./conclusao.asp";
	document.observa.submit();
}

//???
function pag(des){
	window.location.href=des;
}

//suporte
function suporte(){
	var w = 400;
	var h = 400;
	var lado = (screen.width - w) / 2;
	var topo = (screen.height - h) / 2;
	var su = window.open('http://settings.messenger.live.com/Conversation/IMMe.aspx?invitee=bf98cde169f7fa3c@apps.messenger.live.com&mkt=pt-PT','suporte','top='+topo+',left='+lado+',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width='+w+',height='+h+'');
	su.focus();
}

//modals
function modalOpen (dialog) {
	dialog.overlay.fadeIn('slow', function () {
		dialog.container.fadeIn('slow', function () {
			dialog.data.hide().slideDown('slow');	 
		});
	});
}
function modalClose (dialog) {
	dialog.data.fadeOut('slow', function () {
		dialog.container.hide('slow', function () {
			dialog.overlay.slideUp('slow', function () {
				$.modal.close();
			});
		});
	});
}

//registo
function copiando(){
	var copiaractiva = document.oregisto.copiaractiva;
	if(copiaractiva.checked==true){
		document.oregisto.moradacobranca.value=document.oregisto.morada.value;
		document.oregisto.postalcobranca.value=document.oregisto.postal.value;
		document.oregisto.localidadecobranca.value=document.oregisto.localidade.value;
	}
}
function levarvalores(){
	var copiaractiva = document.oregisto.copiaractiva;
	if(copiaractiva.checked==true){
		document.oregisto.moradacobranca.value=document.oregisto.morada.value;
		document.oregisto.postalcobranca.value=document.oregisto.postal.value;
		document.oregisto.localidadecobranca.value=document.oregisto.localidade.value;
	}
	else{
		document.oregisto.moradacobranca.value='';
		document.oregisto.postalcobranca.value='';
		document.oregisto.localidadecobranca.value='';
	}
}

//validar registo
$(function() {
	$("#oregisto").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("td").next("td"));
			//$('.tool').tipsy({gravity: 'w', live: true});
		},
		rules: {
			nome: {
				required: true
			},
			email: {
				required: true,
				email: true
				//remote: "duplicado.asp"
			},
			morada: {
				required: true
			},
			postal: {
				required: true
			},
			localidade: {
				required: true
			},
			moradacobranca: {
				required: true
			},
			postalcobranca: {
				required: true
			},
			localidadecobranca: {
				required: true
			},
			telefone: {
				required: true,
				minlength: 9
			},
			username: {
				required: true,
				minlength: 4,
				remote: "duplicado.asp"
			},
			passe: {
				required: true,
				minlength: 4
			},
			passe2: {
				equalTo: "#passe"
			}
		},
		//set messages to appear inline
		messages: {
			nome: "<div class='error-registo'>Nome inválido.</div>",
			email:{
				required:"<div class='error-registo'>Email inválido.</div>",
				email:"<div class='error-registo'>Email inválido.</div>"
			},
			morada: "<div class='error-registo'>Morada inválida.</div>",
			postal: "<div class='error-registo'>Código postal inválido.</div>",
			localidade: "<div class='error-registo'>Localidade inválida.</div>",
			moradacobranca: "<div class='error-registo'>Morada inválida.</div>",
			postalcobranca: "<div class='error-registo'>Código postal inválido.</div>",
			localidadecobranca: "<div class='error-registo'>Localidade inválida.</div>",
			telefone: "<div class='error-registo'>Telefone inválido.</div>",
			username:{
				required: "<div class='error-registo'>Mínimo 4 caracteres.</div>",
				minlength: "<div class='error-registo'>Mínimo 4 caracteres.</div>",
				remote: "<div class='error-registo'>Username indisponível.</div>"
			},
			passe: "<div class='error-registo'>Mínimo 4 caracteres.</div>",
			passe2:{
				equalTo: "<div class='error-registo'>Confirmação inválida.</div>"
			}
		}
	});
});

//validar editar registo
$(function() {
	$("#oregisto2").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("td").next("td"));
			//$(error).tooltip(".tooltip");
		},
		rules: {
			nome: {
				required: true
			},
			email: {
				required: true,
				email: true
				//remote: "duplicado.asp"
			},
			morada: {
				required: true
			},
			postal: {
				required: true
			},
			localidade: {
				required: true
			},
			moradacobranca: {
				required: true
			},
			postalcobranca: {
				required: true
			},
			localidadecobranca: {
				required: true
			},
			telefone: {
				required: true,
				minlength: 9
			},
			passe: {
				required: true,
				minlength: 4
			},
			passe2: {
				equalTo: "#passe"
			}
		},
		//set messages to appear inline
		messages: {
			nome: "<div class='error-registo'>Nome inválido.</div>",
			email:{
				required:"<div class='error-registo'>Email inválido.</div>",
				email:"<div class='error-registo'>Email inválido.</div>"
			},
			morada: "<div class='error-registo'>Morada inválida.</div>",
			postal: "<div class='error-registo'>Código postal inválido.</div>",
			localidade: "<div class='error-registo'>Localidade inválida.</div>",
			moradacobranca: "<div class='error-registo'>Morada inválida.</div>",
			postalcobranca: "<div class='error-registo'>Código postal inválido.</div>",
			localidadecobranca: "<div class='error-registo'>Localidade inválida.</div>",
			telefone: "<div class='error-registo'>Telefone inválido.</div>",
			passe: "<div class='error-registo'>Mínimo 4 caracteres.</div>",
			passe2:{
				equalTo: "<div class='error-registo'>Confirmação inválida.</div>"
			}
		}
	});
});

//jquery
$(document).ready( function() {
	// preload images
	var img = ['ocupado.png','Paginainicial2.gif','apresentacao2.gif','faq.gif','servicos2.gif','contactos2.gif'];
	$(img).each(function () {
		var i = new Image();
		i.src = '/images/' + this;
	});
	
	//banner
	$('#s3slider').s3Slider({ 
		timeOut: 15000 
	});
	
	//screen mais procurados
	screenshotPreview();
	
	//adicionar ao carrinho
	$("a[rel=carrinho]").click(function() {
		$.post('inserproduto.asp',
		{ produtoid : $(this).attr("valor") },
		function(resposta_carrinho){
			dividecarro=resposta_carrinho.split(";");
			if(dividecarro[2]=='carrinho.asp' || dividecarro[2]=='forma.asp' || dividecarro[2]=='metodo.asp' || dividecarro[2]=='confirmar.asp' || dividecarro[2]=='conclusao.asp'){
				window.location.href='carrinho.asp';
			}
			else{
				$('#ositensdocarrinho').html(dividecarro[0]+" itens");
				$('#ototaldocarrinho').html(dividecarro[1]+" €");
				$('#botaocarrinho').removeAttr('disabled'); 
				$.prompt('O artigo foi adicionado ao carrinho com sucesso.',{prefix:'jqismooth'});
			}
		});
	return false;
	});
	
	//login
	$("#logon").submit(function() {
		$("#botaologin").val("Aguarde por favor");
		var options = {
			url: "login.asp",
			type: "post",
			success: function(resposta_login) {
				desarr=resposta_login.split(";");		
				if(desarr[0]=="1"){
					$.prompt(desarr[1],{prefix:'jqismooth'});
					$("#botaologin").val("Entrar");
				}
				else{
					window.location.href=desarr[1];
				}
			}
		}
		$(this).ajaxSubmit(options);
	return false;
	});
	
	//newsletter
	$("#news").submit(function() {
		$("#botaonews").val("Aguarde por favor");
		var options = {
			url: "newsletter.asp",
			type: "post",
			success: function(resposta_news) {
				$("#botaonews").val("Subscrever");
				$.prompt(resposta_news,{prefix:'jqismooth'});
			}
		}
		$(this).ajaxSubmit(options);
	return false;
	});
	
	//osmodals
	//recpasse
	$("#recpasse").click(function() {
		$("#basicModalContent").modal({onOpen: modalOpen, onClose:modalClose});
		$("#formpasse").submit(function() {
			$("#botaopasse").val("Aguarde por favor");
			var options = {
				url: "recuperar.asp",
				type: "post",
				success: function(resposta_passe) {
					desarr=resposta_passe.split(";");		
					if(desarr[0]=="1"){
						$("#botaopasse").val("Enviar");
						$("#ajaxrespostaerro1").html(desarr[1]);
					}
					else{
						$("#ajaxefeito1").animate({height: 'hide', opacity: 'hide'}, 'slow');
						$("#ajaxrespostaok1").html(desarr[1]);
					}
				}
			}
			$(this).ajaxSubmit(options);
		return false;
		});
	return false;
	});
	
	//sugira site
	$("#sugirabotao").click(function() {
		$("#basicModalContent2").modal({onOpen: modalOpen, onClose:modalClose});
		$("#formsugira").submit(function() {
			$("#botaosugira").val("Aguarde por favor");
			var options = {
				url: "recuperar.asp",
				type: "post",
				success: function(resposta_sugira) {
					desarr=resposta_sugira.split(";");		
					if(desarr[0]=="1"){
						$("#botaosugira").val("Enviar");
						$("#ajaxrespostaerro2").html(desarr[1]);
					}
					else{
						$("#ajaxefeito2").animate({height: 'hide', opacity: 'hide'}, 'slow');
						$("#ajaxrespostaok2").html(desarr[1]);
					}
				}
			}
			$(this).ajaxSubmit(options);
		return false;
		});
	return false;
	});
	
	//duvida
	$("#duvidabotao").click(function() {
		$("#basicModalContent3").modal({onOpen: modalOpen, onClose:modalClose});
		$("#formduvida").submit(function() {
			$("#botaoduvida").val("Aguarde por favor");
			var options = {
				url: "recuperar.asp",
				type: "post",
				success: function(resposta_duvida) {
					desarr=resposta_duvida.split(";");		
					if(desarr[0]=="1"){
						$("#botaoduvida").val("Enviar");
						$("#ajaxrespostaerro3").html(desarr[1]);
					}
					else{
						$("#ajaxefeito3").animate({height: 'hide', opacity: 'hide'}, 'slow');
						$("#ajaxrespostaok3").html(desarr[1]);
					}
				}
			}
			$(this).ajaxSubmit(options);
		return false;
		});
	return false;
	});
	
	//sugerir produto a amigo
	$("#produtobotao").click(function() {
		$("#basicModalContent4").modal({onOpen: modalOpen, onClose:modalClose});
		$("#formproduto").submit(function() {
			$("#botaoproduto").val("Aguarde por favor");
			var options = {
				url: "recuperar.asp",
				type: "post",
				success: function(resposta_produto) {
					desarr=resposta_produto.split(";");		
					if(desarr[0]=="1"){
						$("#botaoproduto").val("Enviar");
						$("#ajaxrespostaerro4").html(desarr[1]);
					}
					else{
						$("#ajaxefeito4").animate({height: 'hide', opacity: 'hide'}, 'slow');
						$("#ajaxrespostaok4").html(desarr[1]);
					}
				}
			}
			$(this).ajaxSubmit(options);
		return false;
		});
	return false;
	});
	
	//forms
	$(".osforms input[type='text'],input[type='password'],textarea").each(function(){
		$(this).focus(function(){
			$(this).css({"border":"1px solid #63ABC7"});
		});
		$(this).blur(function(){
			$(this).css({"border":"1px solid #8F8F8F"}); 
		});
	});   
	
	//comparação
	$("#selectcompara").change(function() {
		$("#recebeconteudo").html("<br /><br /><img src='images/lightbox-ico-loading.gif' />");
		var idprod = $(this).val();
		$.post('comparar.asp',
			{ oid : $(this).val() },
			function(resposta_comparar){
				var escolha = $('#selectcompara :selected').text();
				if(escolha!='Comparar com'){
					$('#nomecompara').html("<a href='produtodetalhe.asp?id="+idprod+"'>"+escolha+"</a>");
				}else{
					$('#nomecompara').html("&nbsp;");
				}
				$('#recebeconteudo').html(resposta_comparar);
		});
	});
	
	//acordion
	$("#accordion").accordion({
		autoHeight: false
	});
	
	//tabelas
	$('#tabelacompras').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "two_button",
		"bAutoWidth": false,
		"aaSorting": [[0,'desc']] ,
		"aoColumns": [ 
			{ "sWidth": "15%", "sType": "numeric" },
			{ "sWidth": "28%", "bSortable": false },
			{ "sWidth": "32%", "bSortable": false },
			{ "sWidth": "20%", "sType": "numeric" },
			{ "sWidth": "5%", "bSortable": false }
		],
		"oLanguage": {
			"sProcessing": "A processar...",
			"sLengthMenu": "Mostrar _MENU_ registos",
			"sZeroRecords": "Nenhum registo encontrado",
			"sInfo": "Mostrar _START_ a _END_ de _TOTAL_ registos",
			"sInfoEmpty": "Mostrar 0 a 0 de 0 registos",
			"sInfoFiltered": "(filtrado de _MAX_ registos totais)",
			"sSearch": "Procurar:",
				"oPaginate": {
					"sFirst":    "Pri.",
					"sPrevious": "Anterior",
					"sNext":     "Seguinte",
					"sLast":     "Últ."
				}
		}
	});
	
	//pretyfoto
	$("a[rel^='prettyPhoto']").prettyPhoto({
			opacity: 0.60,
			overlay_gallery: false
	});
	
	//tooltips
	$("span[rel='tooltipdesconto']").tipsy({gravity: 'e'});
	
});
