
function apagarsub (codigo) {
	if (confirm("Deseja apagar?"))
		window.location = "listar_sub.php?apagar=true&codigo=" + codigo;
}
var pedido;

function mostrarOferta(codigo, marcado) {
	var div = document.getElementById("divOferta");
	if(marcado){
		div.style.display = "block";
		div.innerHTML = "carregando...";
		pedido = getHttpRequest(tratarOferta);
		pedido.open("GET", "mostrarOferta.php?codigo=" + codigo + "&x="+ Math.random(), true);
		pedido.send(null);
	}
	else{
		div.style.display = "none";
		document.getElementById("precoOferta").value = "";
		document.getElementById("dataIni").value = "";
		document.getElementById("dataTer").value = "";
		document.getElementById("modoPagamento").value = "";
	}
}

function tratarOferta() {
	var div = document.getElementById("divOferta");
	if (pedido.readyState == 4) {
		div.innerHTML = pedido.responseText;
	}
}

function ajustarData (input) {
	if ((event.keyCode < 48) || (event.keyCode > 57)) {
		event.returnValue = false; 
	}
	else { 
		if (input.value.length == 2)
			input.value += "/" ;
		if (input.value.length == 5)
			input.value += "/" ;
	}
}

function validar(form){
	var ret = false;
	with (form) {
		if(categoria.value == "0") {
			alert("Voce deve escolher uma categoria de produto.");
		}
		else if(titulo.value == ""){
			alert("Voce deve escolher um nome.");
		}
		else if ((destcheck.value == "S") && (precodestaque.value == "")) {
			alert("Cláudio, você esqueceu de preencher o preço do Destaque!!!!");
		}
			else if ((promocheck.value == "S") && (precopromocao.value == "")) {
			alert("Cláudio, você esqueceu de preencher o preço da Promoção da Semana!!!!");
		}
		else{ 
		ret = true;
		}
	}
	return ret;
}

function verifica_check(tipo) {

if (tipo=="promocao") {

if (document.form.promocao.checked==true) {

document.form.promocheck.value="S";
document.getElementById('divpromocao').style.display='block';
}
else {
document.form.promocheck.value="";
document.getElementById('divpromocao').style.display='none';
}

}

if (tipo=="destaque") {

if (document.form.destaque.checked==true) {

document.form.destcheck.value="S";
document.getElementById('divdestaque').style.display='block';
}
else {
document.form.destcheck.value="";
document.getElementById('divdestaque').style.display='none';
}

}
}

function validaCadastro() {

 varForm = document.cadastro;

	  if (varForm.nome.value.length == 0) {
		alert("Favor informar o nome ");
        varForm.nome.focus();
        return false;
     } 

		if (varForm.cnpj.value.length < 11 ) {
			  alert("Favor informar o CPF corretamente!");
			  varForm.cnpj.focus();
			  return false;
	

			if (!VerificaCPF(varForm.cnpj.value))
			{
				alert("O número de CPF inválido!");
				varForm.cnpj.focus();
				return false;
			}
	    }

   	 if (varForm.email.value.length == 0) {
		alert("Favor informar um e-mail para contato");
        varForm.email.focus();
        return false;
     }

    if (!VerificaEmail(varForm.email.value)) {
		alert("Email inválido!");
        varForm.email.focus();
        return false;
     }


	  if (varForm.endereco.value.length == 0) {
		alert("Favor informar o endereço ");
        varForm.endereco.focus();
        return false;
     }

     if (varForm.numero.value.length == 0) {
		alert("Favor informar o número ");
        varForm.numero.focus();
        return false;
     }
 
    if (varForm.bairro.value.length == 0) {
		alert("Favor informar o bairro ");
        varForm.bairro.focus();
        return false;
     }
	   if (varForm.cidade.value.length == 0) {
		alert("Favor informar a cidade ");
        varForm.cidade.focus();
        return false;
     }
	 

	  if (varForm.estado.selectedIndex == 0) {
		alert("Favor informar o estado ");
        varForm.estado.focus();
        return false;
     }
	
	   if (varForm.cep.value.length == 0) {
		alert("Favor informar o CEP ");
        varForm.cep.focus();
        return false;
       }
	

 	 
	 if (varForm.dddtel.value.length == 0){ 
		alert("Favor informar DDD ");
        varForm.dddtel.focus();
        return false;
     }
	 
	 if (varForm.telefone.value.length == 0) {
		alert("Favor informar telefone ");
        varForm.telefone.focus();
        return false;
     }
	 

		
  
	 

	 
	 if (varForm.senha.value.length == 0) {
		alert("Favor informar a senha ");
        varForm.senha.focus();
        return false;
     }
	 
	 if (varForm.senha2.value.length == 0) {
		alert("Favor informar a confirmação de senha ");
        varForm.senha2.focus();
        return false;
     }else{
			 if (varForm.senha2.value != varForm.senha.value){
			 alert("Favor confira a senha e confirmação ");
			 return false;
			 }
		 }
  
	
    resp=confirm("Deseja concluir o cadastro?");
    
	if (!resp) 
	{
		return false;
    }

	varForm.submit();
}

function modulo(str) 
{
   	soma=0;
   	ind=2;
   	for(pos=str.length-1;pos>-1;pos=pos-1) 
	{
   		soma = soma + (parseInt(str.charAt(pos)) * ind);
   		ind++;
   		if(str.length>11) 
		{
   			if(ind>9) ind=2;
   		}
	}
   	
	resto = soma - (Math.floor(soma / 11) * 11);
   	
	if(resto < 2) 
	{
    	return 0
   	}
   	
	else 
	{
   		return 11 - resto
   	}
}

function VerificaEmail(email) 
{
	if (!email) return false;
		var  BadChars = "*|,\":<>[]{}`\';()&$#% ";
		var  GoodChars = "@.";   
		
		for (var i = 0; i < email.length; i++) {
			if (BadChars.indexOf(email.charAt(i)) != -1) 
			{
				return false;
			}
		}
		
		for (var i = 0; i < GoodChars.length; i++) 
		{
			if (email.indexOf(GoodChars.charAt(i)) == -1) 
			{
				return false;
			}
		}
	 	
		if (email.indexOf ('@.',0) != -1 || email.indexOf ('.@',0) != -1) 
		{
			return false;
		}
	return true;
} 

function SomenteNum(Campo)
{
	var checkOK = '0123456789';
	var checkStr = Campo.value;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
			break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
		if (ch != " ")
		allNum += ch;
	}
	
	if (!allValid)
	{
		alert("Somente números!") 
		Campo.value=allNum
		Campo.focus();
		return false;
	}
	return true;
}

function VerificaCPF(valor) 
{
	primeiro=valor.substr(1,1);
	falso=true;
	size=valor.length;
	if (size!=11)
	{
		return false;
	}
	size--;
	
	for (i=2; i<size-1; ++i)
	{
		proximo=(valor.substr(i,1));
		
		if (primeiro!=proximo) 
		{
			falso=false
		}
	}
	
	if (falso)
	{
		return false;
	}
   	
	if(modulo(valor.substring(0,valor.length - 2)) + "" + modulo(valor.substring(0,valor.length - 1)) != valor.substring(valor.length - 2,valor.length)) 
	{
   		return false;
   	}
   	return true
}

function valida(){

	if (document.form1.nom.value=="") {
				  
				   alert("É obrigatório preencher seu nome!\n\nPor favor, preencha corretamente!");
				   document.form1.nom.style.backgroundColor = "#FFFFCC";
				   document.form1.nom.focus();
				   return false;
	}

	if (document.form1.email.value=="") {
				  
				   alert("É obrigatório preencher seu e-mail!\n\nPor favor, preencha corretamente!");
				   document.form1.email.style.backgroundColor = "#FFFFCC";
				   document.form1.email.focus();
				   return false;
	}
	if (document.form1.email.value!="") 
	{
	   //validar email(verificao de endereco eletrônico)
		parte1 = document.form1.email.value.indexOf("@");
		parte2 = document.form1.email.value.indexOf(".");
		parte3 = document.form1.email.value.length;
		if (!(parte1 >= 3 && parte2 >= 6 && parte3 >= 9)) 
		{
			alert ("O campo E-mail deve conter um endereço válido!");
			document.form1.email.focus();
			return false;
		}
	}
	if (document.form1.assunto.value=="") {
				  
				   alert("É obrigatório preencher o assunto!\n\nPor favor, preencha corretamente!");
				   document.form1.assunto.style.backgroundColor = "#FFFFCC";
				   document.form1.assunto.focus();
				   return false;
	}
	if ((document.form1.telefone.value=="") || (document.form1.telefone.value=="(")) {
				  
				   alert("É obrigatório preencher seu telefone!\n\nPor favor, preencha corretamente!");
				   document.form1.telefone.style.backgroundColor = "#FFFFCC";
				   document.form1.telefone.focus();
				   return false;
	}
	if (document.form1.cidade.value=="") {
				  
				   alert("É obrigatório preencher sua cidade!\n\nPor favor, preencha corretamente!");
				   document.form1.cidade.style.backgroundColor = "#FFFFCC";
				   document.form1.cidade.focus();
				   return false;
	}
	if (document.form1.estado.value=="") {
				  
				   alert("É obrigatório preencher seu estado!\n\nPor favor, preencha corretamente!");
				   document.form1.estado.style.backgroundColor = "#FFFFCC";
				   document.form1.estado.focus();
				   return false;
	}
	if (document.form1.comentario.value=="") {
				  
				   alert("É obrigatório preencher seu comentário!\n\nPor favor, preencha corretamente!");
				   document.form1.comentario.style.backgroundColor = "#FFFFCC";
				   document.form1.comentario.focus();
				   return false;
	}

	document.form1.submit();


}

function valida_pedido(){

if (document.pedido.nome.value=="") {
			  
			   alert("É obrigatório preencher seu nome!\n\nPor favor, preencha corretamente!");
			   document.pedido.nome.style.backgroundColor = "#FFFFCC";
			   document.pedido.nome.focus();
			   return false;
}
if (document.pedido.telefone.value=="") {
			  
			   alert("É obrigatório preencher o telefone!\n\nPor favor, preencha corretamente!");
			   document.pedido.telefone.style.backgroundColor = "#FFFFCC";
			   document.pedido.telefone.focus();
			   return false;
}
if (document.pedido.email.value=="") {
			  
			 alert("É obrigatório preencher seu e-mail!\n\nPor favor, preencha corretamente!");
			  document.pedido.email.style.backgroundColor = "#FFFFCC";
			 document.pedido.email.focus();
			  return false;
}
if (document.pedido.email.value!="") {
   //validar email(verificao de endereco eletrônico)
parte1 = document.pedido.email.value.indexOf("@");
parte2 = document.pedido.email.value.indexOf(".");
parte3 = document.pedido.email.value.length;
if (!(parte1 >= 3 && parte2 >= 6 && parte3 >= 9)) {
alert ("O campo E-mail deve conter um endereço válido!");
document.pedido.email.focus();
return false;
}
}
document.pedido.submit();


}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function tel(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

function correctPNG() 
   {
   for(var i=0; i<document.images.length; i++)
      {
	  var img = document.images[i]
	  var imgName = img.src.toUpperCase()
	  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	     {
		 var imgID = (img.id) ? "id='" + img.id + "' " : ""
		 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		 var imgStyle = "display:inline-block;" + img.style.cssText 
		 if (img.align == "left") imgStyle = "float:left;" + imgStyle
		 if (img.align == "right") imgStyle = "float:right;" + imgStyle
		 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle		
		 var strNewHTML = "<span " + imgID + imgClass + imgTitle
		 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	     + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
		 img.outerHTML = strNewHTML
		 i = i-1
	     }
      }
   }

function esqueci() {
	if (document.restrito.login.value == "") {
		alert("Informe o seu login e clique em Esqueci minha senha!");
	}
	else
	{
		document.restrito.target = 'janela';
		document.restrito.action = 'enviar_senha.php';
		document.restrito.submit();
	}
}

//POPUP centralizado
function popup(caminho1,nome1,largura1,altura1,rolagem1) {
	var esquerda1 = (screen.width - largura1) / 2;
	var cima1 = (screen.height - altura1) / 2 -50;
	window.open(caminho1,nome1,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem1 + ',resizable=no,copyhistory=no,top=' + cima1 + ',left=' + esquerda1 + ',width=' + largura1 + ',height=' + altura1);
}

function buscar(valor,caminho) {
	if (valor=="") {
		alert("Por favor, digite o nome do produto \n\nou categoria que deseja consultar!");
		}
			else {
location.href= caminho+"pesquisa/"+valor; // //////////////////////////////// ALTERAR O CAMINHO AQUI "index2.php?pesquisa=ok&busca="+valor
		}
}

function busca_cat(valor) {
	
	if (valor=="") {
		alert("Por favor, selecione uma categoria!");
		}
	else if (valor=="0000") {
		location.href="index.php";
		} 		
		else {
	
location.href="index2.php?categoria="+valor;
		}
}
	
var tecla;
function capturaTecla(e) 
    {
        if(document.all)
            tecla=event.keyCode;
        else
        {
            tecla=e.which; 
        }
     if(tecla==13)
        {
			if (document.getElementById('enter').value=="1") {
				
				document.restrito.action='login.php';
				document.restrito.target = 'janela';
				document.restrito.submit();
				} else {
			
			if (document.getElementById('tipo').value=="pesquisa") {
			
                buscar(document.getElementById('busca').value);
				
			} else if (document.getElementById('tipo').value=="calculo") {
				
				valida();
				
				}
				
			}
			
        }
    }  

document.onkeydown = capturaTecla;

	
	//Formata moeda e verifica se só números são digitados.
function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
		if (j == 3) {
			aux2 += milSep;
			j = 0;
		}
		aux2 += aux.charAt(i);
		j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}



function Mascara (formato, keypress, objeto){
campo = eval (objeto);

// cep
if (formato=='cep'){
separador = '-';
conjunto1 = 5;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador;}
}

// cpf
if (formato=='cpf'){
separador1 = '.'; 
separador2 = '-'; 
conjunto1 = 3;
conjunto2 = 7;
conjunto3 = 11;
if (campo.value.length == conjunto1)
  {
  campo.value = campo.value + separador1;
  }
if (campo.value.length == conjunto2)
  {
  campo.value = campo.value + separador1;
  }
if (campo.value.length == conjunto3)
  {
  campo.value = campo.value + separador2;
  }
}

// nascimento
if (formato=='nascimento'){
separador = '/'; 
conjunto1 = 2;
conjunto2 = 5;
if (campo.value.length == conjunto1)
  {
  campo.value = campo.value + separador;
  }
if (campo.value.length == conjunto2)
  {
  campo.value = campo.value + separador;
  }
}

// telefone
if (formato=='telefone'){
separador1 = '(';
separador2 = ') ';
separador3 = '-';
conjunto1 = 0;
conjunto2 = 3;
conjunto3 = 9;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador1;
}
if (campo.value.length == conjunto2){
campo.value = campo.value + separador2;
}
if (campo.value.length == conjunto3){
campo.value = campo.value + separador3;
}
}


}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//Função para criar Máscaras de Dados em Formulários.
Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,
Acentos: /[À-ÿ]/i,
Num: /[0-9]/,
carregar: function(parte){
 var Tags = ['input','textarea'];
 if (typeof parte == "undefined") parte = document;
 for(var z=0;z<Tags.length;z++){
  Inputs=parte.getElementsByTagName(Tags[z]);
  for(var i=0;i<Inputs.length;i++)
   if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
    this.aplicar(Inputs[i]);
 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50)
   tamanho = 10;
  if (!casasdecimais)
   casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
 }
 if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
  campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; return true;
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');
 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
aplicarMascara: function(campo, valor){
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-") 
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0"; 
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
}
};

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//-->
function abrir(valor, container) {

if (valor=="1") {

alert("Por favor, selecione um link corretamente!");

}
else if (valor=="2") {

MM_openBrWindow('produtos/lista_produtos.php','','scrollbars=yes,width=419,height=400');

document.getElementById(container).selectedIndex = 0;

}
else if (valor=="3") {

MM_openBrWindow('abre_webmail.php','','scrollbars=yes,width=790,height=500');

document.getElementById(container).selectedIndex = 0;
}

else {

parent.frame.location.href = valor;

document.getElementById(container).selectedIndex = 0;
}

}
function apagar (codigo) {
	if (confirm("Deseja realmente apagar?\n\nTudo que está relacionado a este item(Categorias, Sub-categorias e Produtos) também será deletado."))
		window.location = "listar.php?apagar=true&codigo=" + codigo;
}


function publicar(status, codigo){
	if(confirm("Deseja alterar status?")){
		window.location = "listar.php?status="+ status +"&publicar=true&codigo=" + codigo;
	}		
}