function Bloqueia_Caracteres(evnt){
 //Função permite digitação de números
 	if (clientNavigator == "IE"){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false
 		}
 	}else{
 		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
 			return false
 		}
 	}
}

function Bloqueia_Car_Espciais(evnt){
 	if (clientNavigator == "IE"){
  		if ((evnt.keyCode < 40 || evnt.keyCode > 122) || (evnt.keyCode == 94 || evnt.keyCode == 96)){
		  if (evnt.keyCode == 32 || evnt.keyCode == 33 || evnt.keyCode == 13)
		    return true
		  else 
 			return false
 		}
 	}
}

function EnviarPressEnter(tecla){
  if(tecla==13) 
    document.forms[0].submit();
}

function vai (url){
  location.replace(url);
}

function msgRetorno (msg,url){
  alert(msg);		
  location.replace(url);
}

// JavaScript Document
/////////////////////////////////////////////////////////////////////////////////////////////////////
function validaData(str) { 

	dia = (str.value.substring(0,2)); 
    mes = (str.value.substring(3,5)); 
	ano = (str.value.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		alert("Preencha a data somente com números."); 
		str.value = "";
		str.focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) { 
		alert("A data inserida não é válida: " + str.value); 
		str.value = "";
		str.focus(); 
		return false;
	} 
}

/////////////Valores em dinheiro
function Limpar(valor, validos){
// retira caracteres invalidos da string
   var result = "";
   var aux;
   for(var i=0; i < valor.length; i++){
      aux = validos.indexOf(valor.substring(i, i+1));
      if(aux>=0){
         result += aux;
      }
   }
return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal){
   var tecla = teclapres.keyCode;
   vr = Limpar(campo.value,"0123456789");
   tam = vr.length;
   dec = decimal;
   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 <= dec ){
         campo.value = vr ;
      }
      if((tam > dec) && (tam <= 5)){
         campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 6) && (tam <= 8)){
         campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 9) && (tam <= 11)){
         campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 12) && (tam <= 14)){
         campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 15) && (tam <= 17)){
         campo.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 ) ;
      }
   }
}

// Seleciona todos os checkbox
function checkAll(field) {
	for (i = 0; i < field.length; i++) {
		field[i].checked = true;
	}
}
// Deseleciona todos os checkbox
function uncheckAll(field) {
	for (i = 0; i < field.length; i++) {
		field[i].checked = false;
	}
}

function checkEmail(){
   var d = document.getElementById("email");
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(d.value)) || !d.value) 
     return false;
   else 
     return true;
}

function checkEmail2(email){
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}

function imprimir(){
/*  window.onbeforeprint = function() { 
    document.getElementById('lMenus').style.display="none";
  }
  window.onafterprint = function() { 
    document.getElementById('lMenus').style.display="block";
  } */
  document.getElementById('lMenus').style.display="none";  
  window.parent.focus();
  window.parent.print();
}

//----------------------------------------------------------
// Remove linha de qualquer tabelas pela qual foi criada 

function remLinha(tabela) {
    var table   = document.getElementById(tabela);
	if (table.rows.length-1 >0){
		var linha = table.rows.length; 
		table.deleteRow(linha-1);
	}
} // End deleteRows function

function Excluir(caminho,desc_nome,id,tabela,campo_tabela,op,urlRetorno,pasta,foto)
  {
    if(window.confirm("Confirma a exclusao de "+desc_nome))
      {
       location.href = caminho+"?id="+id+"&tabela="+tabela+"&campo_tabela="+campo_tabela+"&urlRetorno="+urlRetorno+"&op="+op+"&pasta="+pasta+"&foto="+foto;;
      } 
  } // Fim da Função 


function msgOpcao(msg,caminho,desc_nome,id,tabela,campo_tabela,op,urlRetorno){
    if(window.confirm(msg+desc_nome))
       location.href = caminho+"?id="+id+"&tabela="+tabela+"&campo_tabela="+campo_tabela+"&urlRetorno="+urlRetorno+"&op="+op;
} // Fim da Função 

function Verifica_Cep(cep, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	var cep    = document.getElementById(cep);
 	var strcep = cep.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strcep != "")){
 		if (strcep.length != 9){
 			alert("CEP informado inválido.");
 			cep.focus();
 			return false
 		}else{
 			if (strcep.indexOf("-") != 5){
 				alert("Formato de CEP informado inválido.");
 				cep.focus();
 				return false
 			}else{
 				if (isNaN(strcep.replace("-","0"))){
 					alert("CEP informado inválido.");
 					cep.focus();
 					return false
 				}
 			}
 		}
 	}	  
}

function janelaCenter(url, nome, parms, width, height) {
 	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	if (parms != "") {
		str += ", " + parms;
	}
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;

		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

	} else {
		var xc = 0, xy = 0;
	}
	str += ",left=" + xc + ",screenX=" + xc;
	str += ",top=" + yc + ",screenY=" + yc;
	return window.open(url, nome, str);
}

// Nova Janela com Retorno 
function janelaCenterCR(url, nome, parms, width, height,urlRetorno) {
 	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	if (parms != "") {
		str += ", " + parms;
	}
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;

		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

	} else {
		var xc = 0, xy = 0;
	}
	str += ",left=" + xc + ",screenX=" + xc;
	str += ",top=" + yc + ",screenY=" + yc;
	window.open(url, nome, str);
    if (urlRetorno)
     location.href = urlRetorno;   
}

function format_valor(valor){
  if (valor!='') 
	{
	  var valor   = valor.replace(".","");
	  var valor   = valor.replace(",",".");						   			  	
	  return valor;
	} else {
	  return 0;
	}
}									  

function totalOS(){
  var d = document;
  var tot = 0.00;
  var frete   = format_valor(document.getElementById("frete").value);	   
  var servico = format_valor(document.getElementById("servico").value);
  var sinal   = format_valor(document.getElementById("sinal").value);  
  tot  =  ((parseFloat(frete)+ parseFloat(servico)) - parseFloat(sinal));
  tot = new String(tot);
  d.getElementById('total').value  =  numberFormat(tot,20,2);
}

// Retorno o valor selecionado do Radio Button 
function valRadio(nomeCampo){ 
  var i;
  for (i=0; i < nomeCampo.length; i++){ 
    if (nomeCampo[i].checked) 
      return nomeCampo[i].value; 
  } 	
}

function valida_camposArray(campo,nome){
  var d = document;
  for (var i = 0;i<campo.length; i++){
  	 if (d.getElementById(campo[i]).value == ""){
    	alert ("Campo "+nome[i]+" esta em branco!");
	 	d.getElementById(campo[i]).focus();
	 	return false;
     }
	 if (campo[i] == "email" || campo[i] == "emailamigo"){
	 	if (!checkEmail2(d.getElementById(campo[i]).value)){
    		alert ("Campo "+nome[i]+" esta incorreto!");
	 		d.getElementById(campo[i]).focus();	 
			return false;
	 	}
	 }
  }
  return true;
}

// Fechar Janela 
function fechaJanela(){
  top.window.close();
}

function msgRetornoOpener(msg,url){
  alert(msg);		
  fechaJanela(); // Fecha a Janela Atual
  opener.location.href = url; // Carrega a janela que abriu o POPUP 
}
function msgFecha(msg){
  alert(msg);		
  fechaJanela(); // Fecha a Janela Atual
 }

function cancelar(){
   document.form1.reset();
}

function voltar(){
   history.back();
}

function $get(idElemento){
	return document.getElementById(eval(idElemento));
}
// Codificar Strings

function url_encode(str) {  
        var hex_chars = "0123456789ABCDEF";  
        var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
        var n, strCode, hex1, hex2, strEncode = "";  

        for(n = 0; n < str.length; n++) {  
            if (noEncode.test(str.charAt(n))) {  
                strEncode += str.charAt(n);  
            } else {  
                strCode = str.charCodeAt(n);  
                hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
                hex2 = hex_chars.charAt(strCode % 16);  
                strEncode += "%" + (hex1 + hex2);  
            }  
        }  
	return strEncode;  
}  

// Descodificar String 

function url_decode(str) {  
	var n, strCode, strDecode = "";  

	for (n = 0; n < str.length; n++) {  
		if (str.charAt(n) == "%") {  
			strCode = str.charAt(n + 1) + str.charAt(n + 2);  
			strDecode += String.fromCharCode(parseInt(strCode, 16));  
			n += 2;  
		} else {  
			strDecode += str.charAt(n);  
		}  
	}  

	return strDecode;  
} 
function $_get( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function validar_email(email){
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}
function valida_estado(estado){
	var estados = new Array('AC','AL','AP','AM','BA','DF','CE','ES','GO','MA','MT','MS','MG','PB','PR','PA','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO');
	for (var i = 0; i < estados.length; i++){
		if (estados[i] == estado.toUpperCase()){
			return true;
		}
	}
	return false;
}

function validaCPF(cpf){
	erro = new String;
	
	cpf = cpf.replace('.', '');
	cpf = cpf.replace('.', '');
	cpf = cpf.replace('-', '');

	if (cpf.length == 11){    
		var nonNumbers = /\D/;
		if (cpf == "00000000000" || 
				cpf == "11111111111" || 
				cpf == "22222222222" || 
				cpf == "33333333333" || 
				cpf == "44444444444" || 
				cpf == "55555555555" || 
				cpf == "66666666666" || 
				cpf == "77777777777" || 
				cpf == "88888888888" || 
				cpf == "99999999999") {
				
				return false;
		}
	
		var a = [];
		var b = new Number;
		var c = 11;
	
		for (i=0; i<11; i++){
				a[i] = cpf.charAt(i);
				if (i < 9) b += (a[i] * --c);
		}
	
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
	
		for (y=0; y<10; y++) b += (a[y] * c--); 
	
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])) {
			return false;
		}
	} else 
		return false;
	
    return true;    
}

function validaCNPJ(cnpj){
	var cnpj = cnpj.replace(".","").replace(".","").replace("-","").replace("/","");
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	
	if (cnpj.length < 14 && cnpj.length < 15)
		return false;
		
	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
			  digitos_iguais = 0;
			  break;
		}
		if (!digitos_iguais){
			tamanho = cnpj.length - 2
			numeros = cnpj.substring(0,tamanho);
			digitos = cnpj.substring(tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--){
				  soma += numeros.charAt(tamanho - i) * pos--;
				  if (pos < 2)
						pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(0))
				  return false;
			tamanho = tamanho + 1;
			numeros = cnpj.substring(0,tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2)
					pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(1))
				return false;
		
		return true;
	} else
		return false;
} 

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode; 
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
}

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
        if(arr[index] == ele)
            found = true;
        else
            index++;
        return found;
    }

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
			return index;
		}
	return true;
}
function number_format (number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = (number ? number.toString () : 0);
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

function trocaponto(valor){
	return (valor ? valor.replace(".", ",").replace(",",".") : 0);
}

