function actualizaStock(idProduto,idCor,qt,prateleira,caixa,obs){	//newsletter -> template.asp
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=actualizaStock&idProduto=' + idProduto + '&idCor=' + idCor + '&qt=' + qt + '&prateleira=' + prateleira + '&caixa=' + caixa + '&obs=' + obs,
		success: function(msg) {
			//alert('Stock actualizado!');
		}
	});
}

function checkAll(obj,check){ //seleciona todos os checkboxs true ou false
	var sel = document.getElementsByName(obj);
	for(var i=0; i < sel.length; i++){
		if (check == true){
			sel[i].checked = true;
		}else{
			sel[i].checked = false;
		}
	}
}
		
function mudaCatalogo(idCatalogo,idNovoCatalogo){ 	//adm/catalogos/pedidos.asp
	if (idCatalogo > 0 && idNovoCatalogo >= 0){
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=mudaCatalogo&idCatalogo=' + idCatalogo + '&idNovoCatalogo=' + idNovoCatalogo,
			success: function(msg) {
				$("#divCatalogo" + idCatalogo).html("<img src='/adm/img/icon_visto.gif' width='14' height='14' align='middle' class='msgImg' />");
			}
		});
	}
}


function mudaEstadoCatalogo(idCatalogo,idEstado){ 	//adm/catalogos/pedidos.asp
	if (idCatalogo > 0 && idEstado >= 0){
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=mudaEstadoCatalogo&idCatalogo=' + idCatalogo + '&idEstado=' + idEstado,
			success: function(msg) {
				$("#divEstado" + idCatalogo).html("<img src='/adm/img/icon_visto.gif' width='14' height='14' align='middle' class='msgImg' />");
			}
		});
	}
}

function trocaLinha(camada){ //varios names a esconder/mostrar orcamentos.asp
    tr = document.getElementsByTagName('tr');
	for (i=0;i<tr.length;i++){
		if (tr[i].getAttribute(camada)){
			if ( tr[i].style.display=='none' ){
				tr[i].style.display = '';
			}
			else {
				tr[i].style.display = 'none';
			}
		}
	}
}

function actualizaTexto(xDiv,idBrinde,idNewsletter,texto){	//newsletter -> template.asp
	s = new String(texto);
	s = s.replace(/\n/g,"<br>");
	
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=actualizaTexto&idNewsletter=' + idNewsletter + '&idBrinde=' + idBrinde + '&texto=' + s,
		beforeSend: function() {$("#" + xDiv).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-left:5px' />")},
		success: function(resposta) {
			$("#" + xDiv).html(resposta)
		},
	});
}


function mostraMenu(idCategoria){	//colLeft.asp
	$("#submenu" + idCategoria).slideToggle();
	if($("#setaImg" + idCategoria).attr('src') == '/imagens/seta_up.gif'){
		$("#setaImg" + idCategoria).attr('src', '/imagens/seta_down.gif');
		$("#menu" + idCategoria).attr('style', '');
	}else{		
		$("#setaImg" + idCategoria).attr('src', '/imagens/seta_up.gif');
		$("#menu" + idCategoria).attr('style', 'color:#008DD2; text-decoration:none; border-bottom:1px solid #008DD2;');
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=mostraMenu&idCategoria=' + idCategoria,
			beforeSend: function() {$('#submenu' + idCategoria).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-left:5px' />")},
			success: function(resposta) {
				$('#submenu' + idCategoria).html(resposta)
			},
		});
	}
}


function verificaPedido(){ //orcamentos.asp
	var nome = document.form1.nome.value;
	var email = document.form1.email.value;
	if ((nome == '') || (nome == 'Nome (*)')){
		alert('Por favor, preencha o seu nome!')
		document.form1.nome.focus();
		return false;
	}
	if (validaEmail(email) == false){
		alert('Por favor, preencha corretamente o seu email!')
		document.form1.email.focus();
		return false;
	}
	document.form1.finalizar.value=1;
	document.form1.submit();
}


function actualizaBotao(){ //orcamento.asp
	btn = document.getElementById("btnFinalizarOrcamento");
	chkBox = document.getElementById("encomendarJa");
	if (chkBox.checked == true){
		btn.value = "Finalizar Encomenda";
	}else{
		btn.value = "Finalizar Orçamento";
	}
}



function recuperarEmail(email){
	if (validaEmail(email)){
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=recuperarDados&email=' + email,
			success: function(msg) {
				if (msg == 1) {
					alert("Email inexistente nos nossos Registos!");
				}
				if (msg == 2) {
					alert("Dados de Acesso enviados com sucesso. Consulte o seu email!");
				}
				if (msg == 3) {
					alert("Email inválido!");
				}
			}
		});
	}else{
		alert('Email inválido!');
	}
}


// Browser Detection Javascript
// copyright 1 February 2003, by Stephen Chapman, Felgall Pty Ltd

// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.

function detectBrowser() {
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("opera") != -1) return 'Opera';
if (agt.indexOf("staroffice") != -1) return 'Star Office';
if (agt.indexOf("webtv") != -1) return 'WebTV';
if (agt.indexOf("beonex") != -1) return 'Beonex';
if (agt.indexOf("chimera") != -1) return 'Chimera';
if (agt.indexOf("netpositive") != -1) return 'NetPositive';
if (agt.indexOf("phoenix") != -1) return 'Phoenix';
if (agt.indexOf("firefox") != -1) return 'Firefox';
if (agt.indexOf("safari") != -1) return 'Safari';
if (agt.indexOf("chrome") != -1) return 'Chrome';
if (agt.indexOf("skipstone") != -1) return 'SkipStone';
if (agt.indexOf("msie") != -1) return 'Internet Explorer';
if (agt.indexOf("netscape") != -1) return 'Netscape';
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
if (agt.indexOf('\/') != -1) {
if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
return navigator.userAgent.substr(0,agt.indexOf('\/'));}
else return 'Netscape';} else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0,agt.indexOf(' '));
else return navigator.userAgent;
}



// exporta o conteudo de uma textarea frmTabela de um formulario frmExport (para exportar tabelas para o excel)
function exporta(obj){
	obj = document.getElementById(obj);
	frmTabela = document.getElementById("frmTabela");
	frmTabela.value = '<table>' + obj.innerHTML + '</table>';
	document.frmExport.submit();
}


function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
		string = string.replace(token, newtoken);
	}
	return string;
}


function add2cart(source_id, target_id, callback) {
	var source = $('#' + source_id );
	var target = $('#' + target_id );
	
	var shadow = $('#' + source_id + '_shadow');
	if( !shadow.attr('id') ) {
		$('body').prepend('<div id="'+source.attr('id')+'_shadow" style="display:none; width:14px; height:10px; background:transparent url(/imagens/cart_cinza.png) 0px 0px no-repeat; position:static; top:0px; z-index:100000;"></div>');
		var shadow = $('#'+source.attr('id')+'_shadow');
	}

	if( !shadow ) {
		alert('Cannot create the shadow div');
	}

	shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 1).show();
	shadow.css('position', 'absolute');

	shadow.animate( { width:14, height:10, top: target.offset().top, left: target.offset().left }, { duration: 500 } )
	.animate({opacity: 0}, {duration:500,complete:callback});
}



function atribuiCampanha(idKeyword,idCampanha){
	if (idKeyword > 0 && idCampanha >= 0){
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=atribuiCampanha&idKeyword=' + idKeyword + '&idCampanha=' + idCampanha,
			success: function(msg) {
				$("#divOk" + idKeyword).html("<img src='/adm/img/icon_visto.gif' width='14' height='14' align='middle' class='msgImg' />");
			}
		});
	}
}


function isEmail(myEmail) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = myEmail;
	if(reg.test(address) == false) {
		return false;
	}else{
		return true;
	}
}


// chamado de divLogin.asp e login.asp
function recuperarDados(){
	email = $('[name=recEmail]').val();
	if (validaEmail(email)){
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=recuperarDados&email=' + email,
			success: function(msg) {
				if (msg == 1) {
					$("#divLogErro").slideDown();
					$("#divLogErro").html("<img src='/imagens/msgErro.png' width='20' height='19' class='msgImg' />Email inexistente na Base de Dados!");
					setTimeout(function () {
						$("#divLogErro").slideUp();
						$('[name=recEmail]').val('');
					}, 3000);
				}
				if (msg == 2) {
					$("#divLogSucesso").slideDown();
					$("#divLogSucesso").html("<img src='/imagens/msgSucesso.png' width='29' height='23' class='msgImg' />Dados de Acesso enviados com sucesso. Consulte o seu email!");
					setTimeout(function () {
						$("#divLogSucesso").slideUp();
					}, 3000);
				}
				if (msg == 3) {
					$("#divLogErro").slideDown();
					$("#divLogErro").html("<img src='/imagens/msgErro.png' width='20' height='19' class='msgImg' />Email inválido!");
					setTimeout(function () {
						$("#divLogErro").slideUp();
						$('[name=recEmail]').val('');
					}, 3000);
				}
			}
		});
	}else{
		alert('Email inválido!');
	}
}





function removeLinha(idLinha){
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=removeLinha&idLinha=' + idLinha,
		success: function() {
			$("#btnRemoveLinha" + idLinha).parent().parent().remove();
			// num. linhas do form passa para menos uma, por causa do form collections ao actualizar
			numLinhas = $('[name=numLinhas]').val();
			numLinhasActual = numLinhas - 1;
			if (numLinhasActual > 0){
				$('[name=numLinhas]').val(numLinhasActual)
				// actualizamos o carrinho no top.asp
				idOrcamento = $('[name=idOrcamento]').val();
				actualizaCarrinho(idOrcamento);
				
				$.notifyBar({html: "<img src='/imagens/msgSucesso.png' class='msgImg' />Produto removido com sucesso!"});
				
			}else{
				top.location='orcamento.asp?msg=O seu carrinho encontra-se vazio!';
			}
		}
	});
}


function actualizaCarrinho(idOrcamento){ //chamado no addToOrcamento
    $.ajax({
		url: '/include/ajax.asp',
		data: 'action=carrNumItens&idOrcamento=' + idOrcamento,
		success: function(numItens) {
            $('#carrNumItens').html(numItens);
			$('#carrNumItensFooter').html(numItens);	//actualiza tb no layer que corre verticalmente (footer.asp)
		},
	});
    $.ajax({
		url: '/include/ajax.asp',
		data: 'action=carrValor&idOrcamento=' + idOrcamento,
		success: function(valorOrcamento) {
            $('#carrValor').html(valorOrcamento);
			$('#carrValorFooter').html(valorOrcamento); //actualiza tb no layer que corre verticalmente (footer.asp)
		},
	});    
}


function addToOrcamento(idOrcamento,idProduto){ // home.asp | brinde.asp

	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=addToOrcamento&idOrcamento=' + idOrcamento + '&idProduto=' + idProduto,
		success: function(idOrcamento) {
			//$("#divProdAdicionado" + idProduto).slideDown();
            //setTimeout(function () { $("#divProdAdicionado" + idProduto).slideUp(); }, 3000);
			//faz movimento do carrinho:
			
			//add2cart('brinde' + idProduto,'divCart'); //afinal já nao é para fazer o movimento...
			
			//msg de sucesso
			//$.notifyBar({html: "<img src='/imagens/msgSucesso.png' class='msgImg' />Produto adicionado com sucesso! Clique <a href='orcamento.asp'>aqui</a> para gerir o seu Orçamento."});
			// outra...
			//$.jGrowl("<img src='/imagens/msgSucesso.png' class='msgImg' />Produto adicionado com sucesso!<br><br>» <a href='orcamento.asp' style='color:white'>Ver os produtos no Orçamento</a><span style='margin-left:20px'> » <a href='javascript:;' style='color:white' onClick='fechaGrowl()'>Continuar a ver produtos</a></span>");
			
			
			// mostramos msg de sucesso
			$.fancybox({
				'type': 'inline',
				'href': '#divAddProduto'
			});
			
			
			//actualizamos o carrinho top.asp:
            actualizaCarrinho(idOrcamento);
		}
	});
	
	
}


function fechaGrowl(){
	$("div.jGrowl").jGrowl("close");
}


function preencheTodos(sel,idProduto,qual){ //brindes.asp
    if (qual == 'Cores'){
        var accao = 'insereCor';
        var mydiv = 'divProdCor';
        var accaoRemove = 'removeCor';
    }
    if (qual == 'Ocasiao'){
        var accao = 'insereOcasiao';
        var mydiv = 'divProdOcasiao';
        var accaoRemove = 'removeOcasiao';
    }
    if (qual == 'Sector'){
        var accao = 'insereSector';
        var mydiv = 'divProdSector';
        var accaoRemove = 'removeSector';
    }
    if (qual == 'Personalizacao'){
        var accao = 'inserePersonalizacao';
        var mydiv = 'divProdPer';
        var accaoRemove = 'removePersonalizacao';
    }
    for(j=1;j<=sel.length-1;j++){
		if (sel(0).checked == true){
			sel(j).checked = true;
			$.ajax({
				url: '/include/ajax.asp',
				data: 'action=' + accao + '&idProduto=' + idProduto + '&id=' + sel(j).value,
				beforeSend: function() {$('#' + mydiv).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-top:7px' />")},
				success: function(valor) {
					$('#' + mydiv).html(valor)
				},
			});
		}else{
			sel(j).checked = false;
			$.ajax({
				url: '/include/ajax.asp',
				data: 'action=' + accaoRemove + '&idProduto=' + idProduto + '&id=' + sel(j).value,
				beforeSend: function() {$('#' + mydiv).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-top:7px' />")},
				success: function(valor) {
					$('#' + mydiv).html(valor)
				},
			});
		}
	}
}

function insereProp(checkado,idProduto,id,qual){	//brindes.asp insercao de cor individualmente
    if (qual == 'Cores'){
        var accao = 'insereCor';
        var mydiv = 'divProdCor';
        var accaoRemove = 'removeCor';
    }
    if (qual == 'Ocasiao'){
        var accao = 'insereOcasiao';
        var mydiv = 'divProdOcasiao';
        var accaoRemove = 'removeOcasiao';
    }
    if (qual == 'Sector'){
        var accao = 'insereSector';
        var mydiv = 'divProdSector';
        var accaoRemove = 'removeSector';
    }
    if (qual == 'Personalizacao'){
        var accao = 'inserePersonalizacao';
        var mydiv = 'divProdPer';
        var accaoRemove = 'removePersonalizacao';
    }
    if (checkado == true){	
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=' + accao + '&idProduto=' + idProduto + '&id=' + id,
			beforeSend: function() {$('#' + mydiv).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-top:7px' />")},
			success: function(valor) {
				$('#' + mydiv).html(valor)
			},
		});
	}else{
		$.ajax({
			url: '/include/ajax.asp',
			data: 'action=' + accaoRemove + '&idProduto=' + idProduto + '&id=' + id,
			beforeSend: function() {$('#' + mydiv).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-top:7px' />")},
			success: function(valor) {
				$('#' + mydiv).html(valor)
			},
		});
	}
}



function calculaTotal(linha){	// adm/orcamento.asp -> quando se altera todos os valores do orcamento
	var qt 				= document.getElementById('qt' + linha).value;
	var desconto		= document.getElementById('desconto' + linha).options[document.getElementById('desconto' + linha).selectedIndex].value;
	var preco			= document.getElementById('preco' + linha).value;
	var precoImpressao	= document.getElementById('precoImpressao' + linha).value;
	
	preco 			= preco.replace(".", ",");
	precoImpressao	= precoImpressao.replace(".", ",");
	
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=calculaSubTotal&desconto=' + desconto + '&preco=' + preco + '&precoImpressao=' + precoImpressao,
		success: function(valor) {  
			$('#divSubTotalProduto' + linha).html(valor)
		},
	});
	
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=calculaTotal&qt=' + qt + '&desconto=' + desconto + '&preco=' + preco + '&precoImpressao=' + precoImpressao,
		success: function(valor) {
			if(valor == 0){
				$('#divTotalProduto' + linha).html('consultar')
			}else{
				$('#divTotalProduto' + linha).html(valor)
			}
			
		},
	});
}


function calculaProduto(linha){		// adm/orcamento.asp -> quando se altera a qt de um produto
	var idProduto		= document.getElementById('idProduto' + linha).value;
	var qt 				= document.getElementById('qt' + linha).value;
	var desconto		= 0
	
	// vamos verificar a qt minima do produto, se for abaixo lancamos um alerta
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=verificaQtMinima&idProduto=' + idProduto + '&qt=' + qt,
		success: function(valor) {
			if (valor == 1) {
				alert('A quantidade inserida é inferior à quantidade mínima deste artigo!\n\nPreço sujeito a confirmação.');
			}
		},
	});
	
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=calculaPrecoUnitario&idProduto=' + idProduto + '&qt=' + qt + '&desconto=0',	// faremos os  calculos no backoffice com o desconto a 0 para nao influenciar o preco unitario....
		success: function(valor) {
			$('#preco' + linha).val(valor);
			calculaTotal(linha);
		},
	});
}


function calculaProdutoComDesconto(linha){		// adm/orcamento.asp -> quando se altera o preco unitario de um produto (NOVO PREÇO)
	var preco			= document.getElementById('preco' + linha).value;
	var qt 				= document.getElementById('qt' + linha).value;
	var desconto		= document.getElementById('desconto' + linha).options[document.getElementById('desconto' + linha).selectedIndex].value;
	
	preco 				= preco.replace(".", ",");
	
	//so para calcular o preco com o desconto e mostrá-lo no campo proprio
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=calculaPrecoUnitarioComDesconto&preco=' + preco + '&qt=' + qt + '&desconto=' + desconto,
		success: function(valor) {
			$('#divPrecoComDesconto' + linha).html(valor + " €");
		},
	});
}


function calculaImpressao(linha){		// adm/orcamento.asp -> quando se altera o tipo de impressao e/ou cores de um produto // orcamento.asp
	var qt 				= document.getElementById('qt' + linha).value;
	var idTipoImpressao = document.getElementById('idTipoImpressao' + linha).options[document.getElementById('idTipoImpressao' + linha).selectedIndex].value;
	var numCores 		= document.getElementById('numCores' + linha).options[document.getElementById('numCores' + linha).selectedIndex].value;
	
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=calculaPrecoUnitarioImpressao&qt=' + qt + '&idTipoImpressao=' + idTipoImpressao + '&numCores=' + numCores,
		success: function(valor) {
			$('#precoImpressao' + linha).val(valor);
			calculaTotal(linha);
		},
	});
}


function carregaCores(idProduto,idTipoImpressao,linha){		// orcamento.asp -> quando se altera o tipo de impressao
	var idProduto		= idProduto;
	var idTipoImpressao	= idTipoImpressao;
	var linha			= linha;
	$.ajax({
		url: '/include/ajax.asp',
		data: 'action=carregaCores&idProduto=' + idProduto + '&idTipoImpressao=' + idTipoImpressao + '&linha=' + linha,
		beforeSend: function() {$('#divCores' + linha).html("<img src='/adm/img/icon_waiting.gif' border='0' style='margin-left:5px' />")},
		success: function(resposta) {
			$('#divCores' + linha).html(resposta)
		},
	});
}




// imagens.asp -> copiar endereço da imagem para clipboard
function ClipBoard(txt){
    document.getElementById("holdtext").innerText = txt
    Copied = document.getElementById("holdtext").createTextRange();
    Copied.execCommand("RemoveFormat");
    Copied.execCommand("Copy");
    alert('Copiou com sucesso o endereço do ficheiro:\n\n' + txt + '\n\nPoderá agora usá-lo utilizando o comando «colar»/«paste» ou a combinação de teclas CTRL+V');
}


function addOption(selectbox,text,value)
{
	var selectMenu = document.getElementById(selectbox)
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectMenu.options.add(optn);
}


function chamaAjax(divDestino,qstring){
	var divDestino = divDestino;
	var qstring = qstring;
	urlApassar = '/include/ajax.asp' + qstring;
	//alert(urlApassar);
	ajaxRequest(divDestino,urlApassar,'<img src=/adm/img/icon_waiting.gif width=16 height=16 border=0>');
}

function ajaxRequest(DivId,Url,sWait){
	if( sWait != "" ) {
		document.getElementById(DivId).innerHTML = sWait;
	}
	var AJAX;
	try{
		AJAX = new XMLHttpRequest();
	}
	catch(e){
		try{
			AJAX = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e){
			try{
				AJAX = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e){
				alert("Your browser does not support AJAX.");
				return false;
			}
		}
	}
	
	AJAX.onreadystatechange = function(){
		if(AJAX.readyState == 4){
			if(AJAX.status == 200){
				document.getElementById(DivId).innerHTML = AJAX.responseText;
			}else{
				document.getElementById(DivId).innerHTML = "Error: "+ AJAX.statusText + ". Status: " + AJAX.status;
			}
		}
	}
	AJAX.open("get", Url, true);
	AJAX.send(null);
}


// start cookies
// The parameters of the function getCookie hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.
// In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire.
// After that we store the cookie name, cookie value and the expiration date in the document.cookie object.
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}
//If the document.cookie object holds some cookies, then check to see if our specific cookie is stored. 
//If our cookie is found, then return the value, if not - return an empty string.
function setCookie(c_name,value,expiredays){
	var exdate = new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie = c_name + "=" + escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + ';path=/';
}
function DeleteCookie(name) {
  var exp = new Date();
  exp.setTime (exp.getTime() - 1);
  var cval = getCookie(name);
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
// end cookies


function trocaDivImg(camada,imagem){
	obj = document.getElementById(camada)
	img = document.getElementById(imagem)
	if (obj.style.display == 'none'){
		obj.style.display = '';
		img.src='/adm/img/icon_menos.gif';
	}else{
		obj.style.display = 'none';
		img.src='/adm/img/icon_mais.gif';
	}
}


function trocaImg(camada,imagem){
	obj = document.getElementById(camada);
    obj.src=imagem;
}


function isNum(char) {
	if (char == 8) return true; //delete
	if (char == 9) return true; // tab
	if (char == 13) return true; // enter
	if (char == 46) return true; //delete lateral
	if (char == 110) return true; // . lateral
	if (char == 190) return true; // . normal
	if (char >= 48 && char <= 57) return true; //teclado superior
	if (char >= 96 && char <= 105) return true; //teclado  lateral
}

function isPreco(e){
	var charCode = (e.which) ? e.which : e.keyCode;
	if (charCode == 13){
		e.keyCode = 9;
	}else{
		if (!isNum(charCode)){
			e.returnValue=false;
		}else{
			return true;
		}
	}
}


//** TAB AS ENTER ** //
var cle;
function detect(Event) {
	// Event appears to be passed by Mozilla
	// IE does not appear to pass it, so lets use global var
	if(Event==null) {
		alert('null');
		Event=event;
	}
	cle = Event.keyCode;
}
function tabAsEnter(Event,quoi) {
	detect(Event);
	setTimeout('cle=""',100);
	if(cle=='13')
		while(quoi!=null) 
		{
			quoi = quoi.nextSibling;
			if(quoi.tagName=='INPUT') 
			{
				quoi.focus();
				// quoi.select();
				quoi=null;
			}
		}
	} 
	function ok() {
		if(cle != '13') return true;
		else return false;
	}
//** TAB AS ENTER ** //


function isNum2(char) { //so numeros inteiros
	//alert(char)
	if (char == 8) return true; //delete
	if (char == 9) return true; // tab
	if (char == 13) return true; // enter
	if (char == 46) return true; //delete lateral
	if (char >= 48 && char <= 57) return true; //teclado superior
	if (char >= 96 && char <= 105) return true; //teclado  lateral
}
function isNumero(e){
	var charCode = (e.which) ? e.which : e.keyCode;
	if (charCode == 13){
		e.keyCode = 9;
	}else{
		if (!isNum2(charCode)){
			e.returnValue=false;
		}else{
			return true;
		}
	}
}

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
 var oldonload = window.onload;
 if (typeof window.onload != 'function') {
   window.onload = func;
 } else {
   window.onload = function() {
     if (oldonload) {
       oldonload();
     }
     func();
   }
 }
}

function mostraResumo(){
	if ((document.formulario.destHome.checked == true) || (document.formulario.destCanal.checked == true)){
		//alert('true');
		document.getElementById("tabResumo").style.display = 'block';
		document.getElementById("tabResumo").style.visibility = 'visible';
	}else{
		//alert('false');
		document.getElementById("tabResumo").style.display = 'none';
		document.getElementById("tabResumo").style.visibility = 'hidden';
	}
}

function verificaFormulario(){
	if (document.formulario.titulo.value == ''){
		alert('Dê um Título a esta página!');
		document.formulario.titulo.focus();
		return false;
	}
	if ((document.formulario.destHome.checked == true) || (document.formulario.destCanal.checked == true)){
		//if (document.formulario.foto.value == ''){
		//	alert('Para Destacar esta página seleccione uma foto!');
		//	document.formulario.foto.focus();
		//	return false;
		//}
		if (document.formulario.resumo.value == ''){
			alert('Para Destacar esta página prencha o campo "Resumo"!');
			document.formulario.resumo.focus();
			return false;
		}
	}
	if (document.formulario.idCanal.selectedIndex == 0){
		alert('Indique o Canal desta notícia!');
		document.formulario.idCanal.focus();
		return false;		
	}else{
	 	document.formulario.submit();
	}
}

function verificaPedidoCatalogo(){
	if ((document.formulario.nome.value == '')||(document.formulario.nome.value == 'Nome')){
		alert('Por favor preencha o seu Nome!');
		document.formulario.nome.focus();
		return false;
	}
	if ((document.formulario.empresa.value == '')||(document.formulario.empresa.value == 'Empresa')){
		alert('Por favor preencha a sua Empresa/Organização!');
		document.formulario.empresa.focus();
		return false;
	}
	if (validaEmail(document.formulario.email.value) == false){
		alert('Por favor preencha o seu Email!');
		document.formulario.email.focus();
		return false;
	}
	/*
	if ((document.formulario.morada.value == '')||(document.formulario.morada.value == 'Morada Completa')){
		alert('Por favor preencha a sua Morada!');
		document.formulario.morada.focus();
		return false;
	}
	if ((document.formulario.codPostal.value == '')||(document.formulario.codPostal.value == 'Código Postal')){
		alert('Por favor preencha o seu Código Postal!');
		document.formulario.codPostal.focus();
		return false;
	}
	if ((document.formulario.localidade.value == '')||(document.formulario.localidade.value == 'Localidade')){
		alert('Por favor preencha a sua Localidade!');
		document.formulario.localidade.focus();
		return false;
		*/
	else{
		return true;
	 	document.formulario.submit();
	}
	return false;
}

function confirma(label,url){

	if(confirm(label))
	{
		self.location = url;
	}
}



function validaEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
		return false;
	}else{
		return true;
	}
}


function setImage(imagem){
	document.form.imagem.value = imagem;
}


function mudaClasse(obj,srv){
	//	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
	//	alert('IE');
	//	obj2 = document.getElementById(obj);
	//	obj2.className = srv;
	//	}else{
	//	alert('FF');
	//	if (document.getElementById(obj)){
	//		obj2 = document.getElementById(obj);
	//		obj2.className = srv; 
	//	}else{
			obj.className = srv; 
	//	}
	//}
} 


function mostraDiv(camada){
	obj = document.getElementById(camada)
	if (obj.style.display == 'none')
		{obj.style.display = ''}
}


function escondeDiv(camada){
	obj = document.getElementById(camada)
	if (obj.style.display == '')
		{obj.style.display = 'none'}
}


function trocaDiv(camada){
	
	obj = document.getElementById(camada)
	
	if (obj.style.display == 'none')
		{obj.style.display = ''}
	else
		{obj.style.display = 'none'}
}


function troca(camada)
{
	if (camada.style.visibility == "hidden")
		{camada.style.visibility = "visible"}
	else
		{camada.style.visibility = "hidden"}
}


function mostra(camada)
{
	if (camada.style.visibility == "hidden")
		{camada.style.visibility = "visible"}
	else
		{return false}
}


function esconde(camada)
{
	if (camada.style.visibility == "visible")
		{camada.style.visibility = "hidden"}
	else
		{return false}
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  if (selObj.options[selObj.selectedIndex].value != ''){
  	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  	if (restore) selObj.selectedIndex=0;
  }
}



function load(formName) {
  var list = document[formName].list;
  var str = list.options[list.selectedIndex].value;
  if (str != "") location.href = str;
}


function Maiusculas()
{
 	var cidade=document.form.CIDADE.value;
 	cid=cidade.toUpperCase();
 	document.form.CIDADE.value=cid;
}


function MM_displayStatusMsg(msgStr) //v1.0
{
  status=msgStr;
  document.MM_returnValue = true;
}


function are_cookies_enabled()
{
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;
	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	{ 
		document.cookie="testcookie";
		cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}
	return (cookieEnabled);
}



function MM_openBrWindow(theURL,winName,features, myWidth, myHeight, isCenter) { //v3.0
  if(window.screen)if(isCenter)if(isCenter=="true"){
    var myLeft = (screen.width-myWidth)/2;
    var myTop = (screen.height-myHeight)/2;
    features+=(features!='')?',':'';
    features+=',left='+myLeft+',top='+myTop;
  }
  window.open(theURL,winName,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
}


function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}


function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=args[i+1]; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' dever ser um endereço de email válido.\n';
      } else if (test!='R') {
        if (isNaN(val)) errors+='- '+nm+' deve ser um Número.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (val<min || max<val) errors+='- '+nm+' deve ser um Número entre '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é de preenchimento obrigatório.\n'; }
  } if (errors) alert('Ocorreram os seguintes erros:\n'+errors);
  document.MM_returnValue = (errors == '');
}


function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){alert('A informação está incompleta ou contém erros. Por favor corriga-os:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
