function textCounter(field, countfield, maxlimit) 
{
	if (field.value.length > maxlimit)
		field.value = field.value.substring(0, maxlimit);
	else 
		countfield.value = maxlimit - field.value.length;
}

function FormataCampo(Campo,teclapres,mascara)
{
	//pegando o tamanho do texto da caixa de texto com delay de -1 no event
	//ou seja o caractere que foi digitado não será contado.
	strtext = Campo.value
	tamtext = strtext.length
	//pegando o tamanho da mascara
	tammask = mascara.length
	//criando um array para guardar cada caractere da máscara
	arrmask = new Array(tammask)	
	//jogando os caracteres para o vetor
	for (var i = 0 ; i < tammask; i++){
		arrmask[i] = mascara.slice(i,i+1)
	} 
	//alert (teclapres.keyCode)
	//começando o trabalho sujo
	if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9")))))
	{
		if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13))
		{
			Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)		
		}
		else{
			Detona_Event(Campo,strtext)
		}
	}
	else{//Aqui funcionaria a mascara para números mas eu ainda não implementei
		if ((arrmask[tamtext] == "A"))	{
			charupper = event.valueOf()
			//charupper = charupper.toUpperCase()
			Detona_Event(Campo,strtext)
			masktext = strtext + charupper 
			Campo.value = masktext
		}
	}
}

function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){
	if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){
		separador = arrpos
		masktext = strtext + separador
		Campo.value = masktext
	}
}

function Detona_Event(Campo,strtext){
	event.returnValue = false
	if (strtext != "") {
		Campo.value = strtext
	}
}   

/*
FIM
*/

function ValidaBusca(frm)
{

   if(frm.palavrabusca.value == false){
    alert("Digite uma palavra para efetuar a busca.");
	frm.palavrabusca.focus();
	return false;
   }

   var tam = frm.palavrabusca.value;
   var re = /((\s*\S+)*)\s*/;
   tam = tam.replace(re, "$1");
   
   if(tam.length < 3){
    alert("Digite no mínimo 3 caracteres.");
	frm.palavrabusca.focus();
	return false;
   }
   
   
   return true;
}
  
function ExibicaoConteudo(id,ids)
{

var quebra = ids;
quebra = quebra.split(",");

var btn = '';
var conteudo = '';
var obj = '';

for(i=0;i<quebra.length;i++){
  btn = "btn_"+quebra[i];
  conteudo = "conteudo_"+quebra[i];
  obj = document.getElementById(btn);
  if(quebra[i] != id){
   obj.src = "images/btn_baixo.gif";
   document.getElementById( conteudo ).style.display = 'none';   
  }
}

  btn = "btn_"+id;
  conteudo = "conteudo_"+id;
  obj = document.getElementById(btn);
  if(document.getElementById( conteudo ).style.display == 'none'){
    document.getElementById( conteudo ).style.display = (navigator.appName == "Netscape") ? 'table-row' : 'block';  
    obj.src = "images/btn_cima.gif";
  }
  else{
    document.getElementById( conteudo ).style.display = 'none';
    obj.src = "images/btn_baixo.gif";	
  }
}

function ExibicaoMaisMenos(id,ids)
{

var quebra = ids;
quebra = quebra.split(",");

var btn = '';
var conteudo = '';
var obj = '';

for(i=0;i<quebra.length;i++){
  btn = "btn_"+quebra[i];
  conteudo = "conteudo_"+quebra[i];
  obj = document.getElementById(btn);
  if(quebra[i] != id){
   obj.src = "images/btn_mais.gif";
   document.getElementById( conteudo ).style.display = 'none';   
  }
}

  btn = "btn_"+id;
  conteudo = "conteudo_"+id;
  obj = document.getElementById(btn);
  if(document.getElementById( conteudo ).style.display == 'none'){
    document.getElementById( conteudo ).style.display = (navigator.appName == "Netscape") ? 'table-row' : 'block';  
    obj.src = "images/btn_menos.gif";
  }
  else{
    document.getElementById( conteudo ).style.display = 'none';
    obj.src = "images/btn_mais.gif";	
  }
}

function ExibicaoProduto(id,ids)
{
	
var quebra = ids;
quebra = quebra.split(",");

var btn = '';
var conteudo = '';
var obj = '';

for(i=0;i<quebra.length;i++){
  btn = "btn_"+quebra[i];
  conteudo = "produto_"+quebra[i];
  obj = document.getElementById(btn);
  if(quebra[i] != id){
   obj.src = "images/btn_mais.gif";
   document.getElementById( conteudo ).style.display = 'none';   
  }
}

  btn = "btn_"+id;
  conteudo = "produto_"+id;
  obj = document.getElementById(btn);
  if(document.getElementById( conteudo ).style.display == 'none'){
    document.getElementById( conteudo ).style.display = (navigator.appName == "Netscape") ? 'table-row' : 'block';  
    obj.src = "images/btn_menos.gif";
  }
  else{
    document.getElementById( conteudo ).style.display = 'none';
    obj.src = "images/btn_mais.gif";	
  }
}


function swap_content(span)
{
 displayType = ( document.getElementById( span ).style.display == 'none' ) ? ((navigator.appName == "Netscape") ? 'table-row' : 'block') : 'none';

document.getElementById( span ).style.display = displayType;
}

function votar(frm, enquete, votar)
{
	var f = document.forms[frm];
	var tam = f.length;
	var opcao;
	var voted = false;
	for (var i=0; i<tam; i++)
	{
	
		if (f.elements[i].name == 'resposta')
		{
			if (f.elements[i].checked == true)
			{
				opcao = f.elements[i].value;
				voted = true;
			}
		}
	}
	if(!voted && votar) alert("Selecione uma resposta, por favor !!!");
	else
	 {
	  w = (screen.width/2)-140;
	  h = (screen.height/2)-165;
      window.open("enquete.php?enq_id="+enquete+"&resp_id="+opcao+"&votar="+votar,"Enquete","width=280, height=330, left="+w+", top="+h+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=1,resizable=no");
	 }
}

function val_cnpj(numero) {
	//numero = numero1.value;
	dig_1 = 0;
	dig_2 = 0;
	controle_1 = 5;
	controle_2 = 6;

if ( (numero.length != 18)  || (numero.substring(2, 3) != ".") || (numero.substring(6, 7) != ".") || (numero.substring(10, 11) != "/") || (numero.substring(15, 16) != "-") ) {
     return false;
}else{ 
  	   numero = (numero.substring(0, 2)) + "" + (numero.substring(3, 6)) + "" + (numero.substring(7, 10))+ "" + (numero.substring(11, 15)) + "" + (numero.substring(16, 18)) 
	   for ( i=0 ; i < 12 ; i++) {
	        dig_1 = dig_1 + parseFloat(numero.substring(i, i+1) * controle_1);
	          controle_1 = controle_1 - 1;
	        if (i == 3) {
	           controle_1 = 9;
	        }
	   }
	   
	   resto = dig_1 % 11;
	   dig_1 = 11 - resto;
	   
	   if ((resto == 0) || (resto == 1)){
	        dig_1 = 0;
	   }
	   
	   for ( i=0 ; i < 12 ; i++) {
	        dig_2 = dig_2 + parseInt(numero.substring(i, i+1) * controle_2);
	          controle_2 = controle_2 - 1;
	        if (i == 4) {
	           controle_2 = 9;
	        }
	   }
	   
	   dig_2 = dig_2 + (2 * dig_1);
	   resto = dig_2 %11;
	   dig_2 = 11 - resto;
	   
	   if ((resto == 0) || (resto == 1)){
	        dig_2 = 0;
	   }
	   
	   dig_ver = (dig_1 * 10) + dig_2;
	   
	   if (dig_ver != parseFloat(numero.substring(numero.length-2,numero.length))) {
	          return false;
	   }
 }
 return true;
}

//formata cnpj
function FormataCNPJ(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

//Valida o cpf 
function val_cpf(numero2) {
  dig_1 = 0;
  dig_2 = 0;
  controle_1 = 10;
  controle_2 = 11;
  lsucesso = 1;
  
  var numero = numero2.substr(0,3) + numero2.substr(4,3) + numero2.substr(8,3) + numero2.substr(12,2);
  
  if (numero == "00000000000" || numero == "11111111111" || numero == "22222222222" || numero == "33333333333" || numero == "44444444444" || numero == "55555555555" || numero == "66666666666" || numero == "77777777777" || numero == "88888888888" || numero == "99999999999") {
  	return false;
  }
  
  if ((numero.length != 11) && (numero.length != 0)) {
     return false;
  }
  else {
     for ( i=0 ; i < 9 ; i++) {
        dig_1 = dig_1 + parseInt(numero.substring(i, i+1) * controle_1);
          controle_1 = controle_1 - 1;
     }
    
     resto = dig_1 % 11;
     dig_1 = 11 - resto;
     if ((resto == 0) || (resto == 1)) {
          dig_1 = 0;
     }
     for ( i=0 ; i < 9 ; i++) {
          dig_2 = dig_2 + parseInt(numero.substring(i, i + 1) * controle_2);
        controle_2 = controle_2 - 1;
     }
     dig_2 = dig_2 + 2 * dig_1;
     resto = dig_2 % 11;
     dig_2 = 11 - resto;
     if ((resto == 0) || (resto == 1)) {
        dig_2 = 0;
     }
     dig_ver = (dig_1 * 10) + dig_2;
     if (dig_ver != parseFloat(numero.substring(numero.length-2,numero.length))) {
          return false;
        }
  }

return true;
}

function FormataCEP(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace("-", "");
	tam = vr.length + 1 ;
    
	if (tecla != 9 && tecla != 8)
	 if(tam > 5)
	  Campo.value = vr.substr(0, 5) + '-' + vr.substr(5, tam);
}

function FormataFone(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace("-", "");
	tam = vr.length + 1 ;
    
	if (tecla != 9 && tecla != 8)
	 if(tam > 4)
	  Campo.value = vr.substr(0, 4) + '-' + vr.substr(4, tam);
}

function FormataCPF(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam >= 10 && tam < 12) {
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
		} else if (tam >= 7 && tam < 10) {
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
		} else if (tam > 3 && tam < 7) {
			Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
		}
		
	}
		
}

// Não permite digitar letras em um input type=text
function evita_letra(tecla) {
	if (tecla.keyCode < 48 || tecla.keyCode > 57) 
		tecla.returnValue = false;
}

function FormataData(campo,formname,teclapres) { // Máscara para os campos de data
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			document[formname][campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); 
	}
}


//Utilização: onkeypress="evita_letra(event)" onKeydown="FormataHora(this,event)" maxlength="5"
function FormataHora(campo,formname,teclapres){
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;
	
	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 ){
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
		}
	}
}

function testa_data2(data)
{
 tipo = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
 return tipo.test(data);
}

function testa_hora(hora)
{
 tipo = /^([0-1]\d|2[0-3]):[0-5]\d$/;
 return tipo.test(hora);
}

function testa_email(email)
{
 tipo = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
 return tipo.test(email);
}

function upper(str) {
	var texto = str.toUpperCase();
	return texto;
}

function ToggleAll(checked, tf) {
    len = tf.elements.length;
    var i = 0;
    for(i = 0; i < len; i++) {
        tf.elements[i].checked = checked;
    }
}

function ToggleAll2(checked, tf, field) {
	len = tf.elements.length;
    var i = 0;
    for(i = 0; i < len; i++) {
        if (tf.elements[i].name == field) tf.elements[i].checked = checked;
    }
}

function verificaData(Data)
 {
  var dma = -1;
  var data = Array(3);
  var ch = Data.charAt(0); 
  for(i=0; i < Data.length && (( ch >= '0' && ch <= '9' ) || ( ch == '/' && i != 0 ) ); ){
   data[++dma] = '';
   if(ch!='/' && i != 0) return false;
   if(i != 0 ) ch = Data.charAt(++i);
   if(ch=='0') ch = Data.charAt(++i);
   while( ch >= '0' && ch <= '9' ){
    data[dma] += ch;
    ch = Data.charAt(++i);
   } 
  }
  if(ch!='') return false;
  if(data[0] == '' || isNaN(data[0]) || parseInt(data[0]) < 1) return false;
  if(data[1] == '' || isNaN(data[1]) || parseInt(data[1]) < 1 || parseInt(data[1]) > 12) return false;
  if(data[2] == '' || isNaN(data[2]) || ((parseInt(data[2]) < 0 || parseInt(data[2]) > 99 ) && (parseInt(data[2]) < 1900 || parseInt(data[2]) > 9999))) return false;
  if(data[2] < 50) data[2] = parseInt(data[2]) + 2000;
  else if(data[2] < 100) data[2] = parseInt(data[2]) + 1900;
  switch(parseInt(data[1])){
   case 2: { if(((parseInt(data[2])%4!=0 || (parseInt(data[2])%100==0 && parseInt(data[2])%400!=0)) && parseInt(data[0]) > 28) || parseInt(data[0]) > 29 ) return false; break; }
   case 4: case 6: case 9: case 11: { if(parseInt(data[0]) > 30) return false; break;}
   default: { if(parseInt(data[0]) > 31) return false;}
  }
  return true; 
 }

function busca_quantidade2(str) {
	var vetor = str.split(",");
	var vetor_final = new Array();
	var contador = 0;
	for (var i = 0; i < vetor.length; i++) {
		if (vetor[i].search("-") != -1) {
			var sequencia = vetor[i].split("-");
			if (sequencia[1] < sequencia[0]) {
				for (var j = sequencia[0]; j >= sequencia[1]; j--) {
					vetor_final[contador] = j;
					contador++;
				}
			} else {
				for (var k = sequencia[0]; k <= sequencia[1]; k++) {
					vetor_final[contador] = k;
					contador++;
				}
			}
		} else {
			vetor_final[contador] = vetor[i];
			contador++;
		}
	}
	return(vetor_final.length);
}

function abre_ajuda(des_id) {
	window.open("pop_ajuda.php?des_id="+des_id,"pop_ajuda","top=0, left=0, width=330, height=400, scrollbars=yes")
}

function limitatext(str,maximo) {
		if (str.length >= maximo) {
			return false;
		} else return true;
	}

function testa_data(dta, formname, campo) { // função complementar para testar a validade da data
	if(!verificaData(dta)) {
       if(document[formname][campo].value != '')
        {
	 	 document[formname][campo].value = '';
		 alert("Data inválida");
		}
	  else
  	   document[formname][campo].value = ''; 
		return false;
	}
	
	if(!isdate(dta)) {
       if(document[formname][campo].value != '')
        {
	 	 document[formname][campo].value = '';
		 alert("Data inválida");
		} 
	   else	
   	 	 document[formname][campo].value = '';
		return false;
	}
	return true;
}

function isdate2(obj){
var mes, ano;
var retval = false;
ano=obj.substring(3,7);
if (obj != ""){
   if (obj.length != 7 || obj.substring(2,3)!="/") {         
   		retval = false;
   }
   else {     
      mes = obj.substring(0,2);
      if (nochars(mes) && parseInt(mes,10) > 0 && parseInt(mes,10) <= 12){
         mes = parseInt(mes,10);
         if (nochars(ano) && parseInt(ano,10) >= 0000) {
            if ((parseInt(ano,10) % 4) == 0) {
               bissexto = 1;
            }
            else {
               bissexto = 0;
            }
			retval = true;
         } else {
		 	retval = false;
		 }
      } else {
	  		retval = false;
	  }
   }
}
else {
     retval = true;
}
return retval;
}

//Verifica se é uma data válida
function isdate(obj){
var mes, dia, ano;
var retval = false;
ano=obj.substring(6,10);
if (obj != ""){
   if (obj.length != 10 || obj.substring(2,3)!="/" || obj.substring(5,6)!="/") {         
   }
   else {     
      mes = obj.substring(3,5);
      if (nochars(mes) && parseInt(mes,10) > 0 && parseInt(mes,10) <= 12){
         mes = parseInt(mes,10);
         if (nochars(ano) && parseInt(ano,10) >= 0000) {
            if ((parseInt(ano,10) % 4) == 0) {
               bissexto = 1;
            }
            else {
               bissexto = 0;
            }
            dia = obj.substring(0,2);
            if (nochars(dia)){
               dia = parseInt(dia,10);
               if (((mes==1 || mes==3 || mes==5 || mes==7 || mes==8 || mes==10 || mes==12) && (dia >= 1 && dia <= 31)) ||
                  ((mes==4 || mes==6 || mes==9 || mes==11) && (dia >= 1 && dia <= 30)) ||
                  (mes==2 && dia >= 1 && dia <= (28 + bissexto))) {
                  retval=true;
               }
            }
         }
      }
   }
}
else {
     retval = true;
}
return retval;
}

// Verifica se existem letras na variavel
function nochars(strval){
  var retval = true;
  for (var i = 0; i < strval.length; i++){
     if (strval.substring(i,i+1) < "0" || strval.substring(i,i+1) > "9"){
        retval=false;
        break;
     }
  }
  return retval;
}

//Utilização: onkeypress="evita_letra(event)" onKeydown="FormataHora(this,event)" maxlength="5"
function FormataHora(campo,formname,teclapres){
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;
	
	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 ){
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
		}
	}
}

// Não permite digitar quantidades maiores que o especificado
function qtdcampo(qtd,valor,tecla) {
	valor = valor + String.fromCharCode(tecla.keyCode);
	var int_valor = parseInt(valor);
	var int_qtd = parseInt(qtd);
	if (int_valor > int_qtd) {
		tecla.returnValue = false;	
	}
}

// Não permite digitar letras em um input type=text
function evita_letra(tecla) {
	if (tecla.keyCode < 45 || tecla.keyCode > 57 || tecla.keyCode == 47 || tecla.keyCode == 45 || tecla.keyCode == 46)
		tecla.returnValue = false;	
}

// Não permite digitar letras em um input type=text
function evita_letra2(tecla) {
	if (tecla.keyCode < 48 || tecla.keyCode > 57) 
		tecla.returnValue = false;
}

//Funçao para deixar digitar o ponto
function evita_letra3(tecla) {
	if (tecla.keyCode < 45 || tecla.keyCode > 57 || tecla.keyCode == 47 || tecla.keyCode == 45)
		tecla.returnValue = false;	
}

// FUNÇÃO PARA LIBERAR SÓ NÚMEROS
function EvitaLetra(e) {

  if (e.keyCode) tecla = e.keyCode;  	
  else if (e.which) tecla = e.which; // Netscape 4.?
  else if (e.charCode) tecla = e.charCode; // Mozilla

  if (tecla != 8 && tecla != 46 && (tecla < 48 || tecla > 57))
   return false;
   
}

// só permite digitar letras em um input type=text
function testa_alfa(tecla) {
	if (tecla.keyCode < 65 || tecla.keyCode > 122 || (tecla.keyCode > 90 && tecla.keyCode < 97)) 
		tecla.returnValue = false;
}

function FormataValor2(tammax,teclapres, tf) { // formata os campos com a máscara valor
	var tecla = teclapres.keyCode;
	vr = tf.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		tf.value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		tf.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		tf.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		tf.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		tf.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		tf.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
	}
}


function isANumber(number) {
  answer = 1;

  if (!parseFloat(number)) {
    //the first digit wasn't numeric
    answer = 0;
  } else {
    //the first digit was numeric, so check the rest
    for (var i=0; i<number.length; i++) {
      if ((number.charAt(i) != "0")
        && (!parseFloat(number.charAt(i)))) {
          answer = 0;
          break;
      }
    }
  }
  if (answer == 1) {
    orderPlaced = true;
  }
  if (number == 0) answer = 1;
  return answer;
}


function fixWin() {
			 var x = 400;
			 var y = 150;
			 window.moveTo(parseInt((screen.availWidth - x) / 2),parseInt((screen.availHeight - y) / 2));
}
		
//Checa o campo E-Mail
function verifica_mail(email){
var campo = email;
   if (campo != "") {
   		if (campo.indexOf("@") == -1) return false;
        else {
            if (campo.indexOf(".") == -1) return false;
        }
   }
	return true;
}

function isANumber(number) {
  answer = 1;

  if (!parseFloat(number)) {
    //the first digit wasn't numeric
    answer = 0;
  } else {
    //the first digit was numeric, so check the rest
    for (var i=0; i<number.length; i++) {
      if ((number.charAt(i) != "0")
        && (!parseFloat(number.charAt(i)))) {
          answer = 0;
          break;
      }
    }
  }
  if (answer == 1) {
    orderPlaced = true;
  }
  if (number == 0) answer = 1;
  return answer;
}

function FormataIE(Campo, teclapres){
  if(Campo.value.length < 12) {	
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5) {
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		}
		
		if (tam > 5 && tam < 7) {
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2,4) + '.' + vr.substr(5,tam-4);
		}
		
		if (tam >= 9) {
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,6) + '-' + vr.substr(8,tam-4);
		}
	}
  }
}

function formataValorMonetario(campooriginal,decimais)
{
  var posicaoPontoDecimal;
  var campo = '';
  var resultado = '';
  var pos,sep,dec;

  campo = campooriginal.replace(".",",");
//Retira possiveis separadores de milhar
/*  for (pos=0; pos < campooriginal.length; pos ++)
  {
    if (campooriginal.charAt(pos)!='.')
        campo = campo + campooriginal.charAt(pos);
  }     */

//Formata valor monetário com decimais
  posicaoPontoDecimal = campo.indexOf(',');
  if (posicaoPontoDecimal != -1)
   {
      sep = 0;
      for (pos=posicaoPontoDecimal-1;pos >= 0;pos--)
      {
        sep ++;
        if (sep > 3)
        {
           resultado = '.' + resultado;
           sep = 1;
        }

        resultado = campo.charAt(pos) + resultado;   
      }

      // Trata parte decimal
      if (parseInt(decimais) > 0 )
      {
         resultado = resultado + ',';
      
         pos=posicaoPontoDecimal+1;
         for (dec = 1;dec <= parseInt(decimais); dec++)
         {
           if (pos < campo.length)
           {
              resultado = resultado + campo.charAt(pos);
              pos++;
           }
           else
              resultado = resultado + '0';   
         }

      } // trata decimais
   }
   // Trata valor monetário sem decimais
   else
   {
      sep = 0;
      for (pos=campo.length-1;pos >= 0;pos--)
      {
        sep ++;
        if (sep > 3)
        {
           resultado = '.' + resultado;
           sep = 1;
        }
        resultado = campo.charAt(pos) + resultado;   
      }
      // Trata parte decimal
      if (parseInt(decimais) > 0 )
      {
         resultado = resultado + ',';
         for (dec = 1;dec <= parseInt(decimais); dec++)
         {
              resultado = resultado + '0';   
         }
      } // trata decimais
   }

   return resultado;
}


function MarcarTodos(estado)
{
	 var tam = document.cadastro.elements.length;
   for(i = 0; i < tam; i++){
		 if(document.cadastro.elements[i].name == 'sub_id[]'){
		   document.cadastro.elements[i].checked = estado;
			 xajax_MarcaDesmarca(estado, document.cadastro.elements[i].value);
		 }
	 }
}

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

function desabilitar(){
    alert ("Função Desabilitada.")
    return false
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    v_obj.value=v_fun(v_obj.value);
}

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

function FormataDataDM(v){
    v=v.replace(/\D/g,"");                 //Remove tudo o que não é dígito
    v=v.replace(/(\d{2})(\d)/,"$1/$2");    //Coloca hífen entre o quarto e o quinto dígitos
    v=v.replace(/(\d{2})(\d)/,"$1/$2");    //Coloca hífen entre o quarto e o quinto dígitos		
    return v;
}

function FormataValor(v){
 v=v.replace(/\D/g,"");                 //Remove tudo o que não é dígito
var ponto = '.';
  v=v.replace(/(\d{1,})(\d{2})/,"$1,$2");
  while (ponto && v.search(/[0-9]{4}/) > -1) {
    v = v.replace(/([0-9])([0-9]{3})([^0-9])/,'$1'+ponto+'$2$3');
	}
	return v;
}

function ValorKg(linha)
{
	var peso = 0, valor = 0, res = 0;
	for(i = 0; i < document.cadastro.length; i++){

	  if(document.cadastro.elements[i].name == 'res_peso['+linha+']')	
		  peso = document.cadastro.elements[i].value;

		if(document.cadastro.elements[i].name == 'res_valor['+linha+']')	
		  valor = document.cadastro.elements[i].value;

     if(peso && valor && document.cadastro.elements[i].name == 'res_valkg['+linha+']'){
			 valor = valor.replace("\.","");
			 valor = valor.replace("\,","\.");			 
			 xajax_FormataMoeda(parseFloat(valor / peso),i);
			 peso = 0;
			 valor = 0;			 
		 }		 
	}
}