//#################################################################################
function finalizaSessao(aParametros){
	if(aParametros=='a'){
		alert('Sua sess&atilde;o expirou ! Voc&ecirc; deve efetuar o login novamente !');
	} else {
		alert('Sua sessão expirou ! Você deve efetuar o login novamente !');
	}
	if(aParametros=='u'){
		window.open('../../../Default.asp','_top');
	} else {
		window.open('../../Default.asp','_top');
	}
}
//#################################################################################
var ultima = "0";
function pintaLinha(l) {
  var linha = String(l);
  
  if (ultima != 0) {
    document.getElementById(ultima).style.backgroundColor = ((parseInt(ultima.substr(1))) % 2 == 0) ? "#FFFFFF" : "#F9FFCA";
  }
  ultima = l;
  document.getElementById(ultima).style.backgroundColor = "#EF8A39";
  
}
//#################################################################################
function insereColuna(linha, idColuna, valor, alinhamento, classe, visibilidade, tamanho) {
	var tempCol;
	tempCol = linha.insertCell(linha.cells.length); 
	tempCol.id = idColuna;
	tempCol.innerText = valor;
	if (alinhamento) tempCol.style.textAlign = alinhamento;
	if (classe) tempCol.className = classe;
	//if (visibilidade) tempCol.style.display = visibilidade;
	if (tamanho) tempCol.style.width = tamanho;
	return tempCol;
}
//#################################################################################
//retorna o valor selecionado no radio group especificado
function pegaRegistro(radioGroup) {
	if (radioGroup) {
		if (radioGroup.length==undefined && radioGroup.checked) return radioGroup.value;
		for(var ii = 0; ii<radioGroup.length;ii++)
			if (radioGroup[ii].checked) return radioGroup[ii].value;
	}
	return null;	
}
//#################################################################################
function validaData(vr) {
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	if (vr.length<8) return false;
	if ((Math.abs(vr.substr(2,2)) == 1 || Math.abs(vr.substr(2,2)) == 3 || Math.abs(vr.substr(2,2)) == 5 || Math.abs(vr.substr(2,2)) == 7 || Math.abs(vr.substr(2,2)) == 8 || Math.abs(vr.substr(2,2)) == 10 || Math.abs(vr.substr(2,2)) == 12) && (Math.abs(vr.substr(0,2))>=1 && Math.abs(vr.substr(0,2))<=31) && (Math.abs(vr.substr(4,4))>=1900 && Math.abs(vr.substr(4,4))<=2300)) {
		return true;
	}		
	if ((Math.abs(vr.substr(2,2)) == 4 || Math.abs(vr.substr(2,2)) == 6 || Math.abs(vr.substr(2,2)) == 9 || Math.abs(vr.substr(2,2)) == 11) && (Math.abs(vr.substr(0,2))>=1 && Math.abs(vr.substr(0,2))<=30) && (Math.abs(vr.substr(4,4))>=1900 && Math.abs(vr.substr(4,4))<=2300)) {
		return true;
	}
	if ((Math.abs(vr.substr(2,2)) == 2) && ((Math.abs(vr.substr(0,2))>=1 && Math.abs(vr.substr(0,2))<=29 && AnoBissexto(Math.abs(vr.substr(4,4)))) || (Math.abs(vr.substr(0,2))>=1 && Math.abs(vr.substr(0,2))<=28 && !AnoBissexto(Math.abs(vr.substr(4,4))))) && (Math.abs(vr.substr(4,4))>=1900 && Math.abs(vr.substr(4,4))<=2300)) {
		return true;
	}
	return false;
}
//#################################################################################
function parseDecimal(numero) {
	return parseFloat(String(numero).replace(".","").replace(",","."));
}
//#################################################################################
function focusNext(atual) {
	for (var i = 0; i < document.forms[0].elements.length; i++)
		if (document.forms[0].elements[i].tabIndex >= (atual + 1) && document.forms[0].elements[i].style.visibility != 'hidden' && document.forms[0].elements[i].style.display != 'none') {
			try {
				document.forms[0].elements[i].focus();
				return true;
			} catch (ex) {}
		}
	return false;
}
//#################################################################################
function FormataHora(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var sel;
	var vr = new String(Campo.value);
	vr = vr.replace(":", "");
	tam = vr.length + 1;
	var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapres.keyCode = 0 ;
		tecla=0;
		return false;
	}
	if (tecla != 9 && tecla != 8) {
		if (tam >= 3)
			Campo.value = vr.substr(0,2) + ':' + vr.substr(2, tam);
			var hora = vr.substr(0,2)
			var minuto = vr.substr(2,1)
		if (vr.length >= 3 ) {
  		    if (vr.length<4) {
			  Campo.value = Campo.value + String.fromCharCode(teclapres.keyCode);
			  vr+=String.fromCharCode(teclapres.keyCode);
			}
			teclapres.keyCode = 0 ;
			if (tam >= 3){
				if(hora > 23 || minuto > 5){
				alert("Hora informada é inválida! Utilize o formato 00:00 a 23:59");
				teclapres.keyCode = 0 ;
				Campo.value = "";
				return false;
				}
			}
			focusNext(Campo.tabIndex);
			return true;
		}
		return true;
	}
}
//#################################################################################
function FormataData(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var sel;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	
	var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapres.keyCode = 0 ;
		tecla=0;
		return false;
	}
	if (tecla != 9 && tecla != 8) {
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4);
		//var tfinal = new String(Campo.value);
		if (vr.length >= 7 ) {
  		    if (vr.length<8) {
			  Campo.value = Campo.value + String.fromCharCode(teclapres.keyCode);
			  vr+=String.fromCharCode(teclapres.keyCode);
			}
			teclapres.keyCode = 0 ;
			var tdata = new Date(vr.substr(2,2) + '/' + vr.substr(0,2) + '/' + vr.substr(4,4));
			
			if (isNaN(tdata)) {
  				alert("Valor de data inválido"); 
				return false;
			}
			
			if (validaData(vr)) {
				focusNext(Campo.tabIndex);
				return true;
			}	
			
			alert("Valor de data inválido"); 
			return false;
		}
	}
	return false;
}
//#################################################################################
function AnoBissexto(ano) {
  if (ano % 4 == 0)  return true; else return false;
}
//#################################################################################
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 ;
    var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapres.keyCode = 0 ;
	}
   
   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);
      }
}
//#################################################################################
function FormataCPF(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1;
	var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapres.keyCode = 0 ;
	}
	if (tecla != 9 && tecla != 8){
		if (tam > 3 && tam < 7)
			Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
		if (tam >= 7 && tam <10)
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
		if (tam >= 10 && tam < 12)
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
	}

}
//#################################################################################
function FormataInscEst(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1;
	var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapres.keyCode = 0 ;
	}
	if (tecla != 9 && tecla != 8){
		if (tam > 3 && tam < 7)
			Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
		if (tam >= 7 && tam <10)
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
		if (tam >= 10 && tam < 12)
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '.' + vr.substr(9,tam-9);
	}

}
//#################################################################################
function FormataCEP(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1;
	var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapres.keyCode = 0 ;
	}
	if (tecla != 9 && tecla != 8){
		if (tam > 3 && tam < 7)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2, tam);
		if (tam >= 7 && tam <9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '-' + vr.substr(5,tam-6);
	}

}
//#################################################################################
function soNumero(teclapress) {
	var tecla = teclapress.keyCode;
	var chars = new String("0123456789");
	if (chars.indexOf(String.fromCharCode(tecla))<0)  {
		teclapress.keyCode=0;
		return false;
	}
	return true;
}
//#################################################################################
function FormataTel(Campo, teclapress){
	var tecla = teclapress.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1;
	var strValidos = "0123456789" 
	if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9 ) {
		teclapress.keyCode = 0 ;
	}
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 7)
			Campo.value = vr.substr(0,2) + '-' + vr.substr(2,tam);
		if (tam >= 7 && tam <10)
			Campo.value = vr.substr(0,2) + '-' + vr.substr(2,4) + '.' + vr.substr(6,tam-4);
			if (Campo.value.length >= 12){
				teclapress.keyCode = 0;
				focusNext(Campo.tabIndex);
			}
	}
}
//#################################################################################
function soLetra(teclapress) {
	var tecla = teclapress.keyCode;
	var chars = new String("qwertyuiopasdfghjklçzxcvbnm´`^~.¨QWERTYUIOPLÇKJHGFDSAZXCVBNM");
	if (chars.indexOf(String.fromCharCode(tecla))<0) 
		teclapress.keyCode=0;
}
//#################################################################################
function soLetraENumero(teclapress) {
	var tecla = teclapress.keyCode;
	var chars = new String("qwertyuiopasdfghjklçzxcvbnm´`^~.¨QWERTYUIOPLÇKJHGFDSAZXCVBNM0123456789");
	if (chars.indexOf(String.fromCharCode(tecla))<0) 
		teclapress.keyCode=0;
}
//#################################################################################
function isValidEmail(email, required) {
	if (required==undefined) {   // if not specified, assume it's required
		required=true;
	}
	if (email==null) {
		if (required) {
			return false;
		}
		return true;
	}
	if (email.length==0) {  
		if (required) {
			return false;
		}
		return true;
	}
	if (! allValidChars(email)) {  // check to make sure all characters are valid
		return false;
	}
	if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
		return false;
	} else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
		return false;
	} else if (email.indexOf("@") == email.length) {  // @ must not be the last character
		return false;
	}

	return true;
}
//#################################################################################
function allValidChars(email) {
	var parsed = true;
	var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
	for (var i=0; i < email.length; i++) {
		var letter = email.charAt(i).toLowerCase();
		if (validchars.indexOf(letter) != -1)
			continue;
			parsed = false;
			break;
	}
	return parsed;
}
//#################################################################################
/*function mascaraMoeda(campo, teclapress) {
	if (!soNumero(teclapress)) return false;
	
	var vr = new String(campo.value);
	vr = vr.replace(",","");
	vr+=String.fromCharCode(teclapress.keyCode);
	if (vr.length >=3 ) vr = vr.substring(0,vr.length-2) + ',' + vr.substr(vr.length-2);
	campo.value = vr;
	teclapress.keyCode=0;
	campo.focus();
	return true;
}*/
//#################################################################################
function mascaraMoeda(fld, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var milSep = '.';
	var decSep = ',';
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	fld.select();
	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);
	}
	fld.select();
	return false;
}
//#################################################################################
function formataMoeda(campo) {
	var t = formatCurrency(parseDecimal(campo.value));
	campo.value = t;
}		
//#################################################################################
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
	return ( num + ',' + cents);
}
//#################################################################################
//Verifica se os campos foram realmente preenchidos - passar um array com o nome dos campos
function checaCampos(campos_obrigatorios) {
	for (var cmp=0; cmp<campos_obrigatorios.length; cmp++) {
		if (document.forms[0].elements[campos_obrigatorios[cmp]].value == '' ) return false
	}
	return true;
}

//#################################################################################
//troca todas as ocorrencias de um texto em uma string por outro
function replaceAll(str, proc, subst) {
	if (subst.indexOf(proc)>=0) return str;
	while (str.indexOf(proc)>=0)
	  str = str.replace(proc,subst);
	return str;
}

//###################################################################################
// Funções AJAX
//###################################################################################
function createXMLHTTP() {
	var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
	"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
	"Microsoft.XMLHTTP"];
	for (var i=0; i < arrSignatures.length; i++) {
		try {
			var oRequest = new ActiveXObject(arrSignatures[i]);
			return oRequest;
		} catch (oError) {
		}
	}
	throw new Error("MSXML não está instalado em seu sistema.");
}


function recuperarInformação(sPagina, aParametros, oDestino)
{
	// criacao do objeto XMLHTTP
	var oHTTPRequest = createXMLHTTP(); 
	// Abrindo a solicitacao HTTP. o primeiro parametro informa o metodo post/get
	// o segundo parametro informa o arquivo solicitado que pode ser asp, php, txt, xml, etc
	// o terceiro parametro informa que a solicitacao nao assincrona, 
	// para solicitacao sincrona o parametro deve ser false
	//oHTTPRequest.open("post", sPagina, true);
	oHTTPRequest.open("post", "executa.asp", true);
	// para solicitacoes utilizando o metodo post deve ser acrescentado 
	// este cabecalho HTTP
	oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	// a funcao abaixo e executada sempre que o estado do objeto muda (onreadystatechange)
	oHTTPRequest.onreadystatechange=function()
	{
	    // o valor 4 significa que o objeto ja completou a solicitacao
		if (oHTTPRequest.readyState==4){
			// abaixo o texto do gerado no arquivo executa.asp e colocado no div
			oDestino = oHTTPRequest.responseText;
		}
	}
// abaixo e enviada a solicitacao. Note que a configuracao
// do evento onreadystatechange deve ser feita antes do send.
oHTTPRequest.send("tipo=" + aParametros);
}

//#################################################################################
//Confere o dígito de CNPJ e CNPF
function confCNPJF(valor){
	var tamCampo = String(valor.length);
	if(tamCampo == 14){
		var num01 = parseInt(valor.substr(0,1));
		var num02 = parseInt(valor.substr(1,1));
		var num03 = parseInt(valor.substr(2,1));
		var num04 = parseInt(valor.substr(4,1));
		var num05 = parseInt(valor.substr(5,1));
		var num06 = parseInt(valor.substr(6,1));
		var num07 = parseInt(valor.substr(8,1));
		var num08 = parseInt(valor.substr(9,1));
		var num09 = parseInt(valor.substr(10,1));
		var dv    = valor.substr(12,2);
		var somaDg1 	 = ((num01 * 10) + (num02 * 9) + (num03 * 8) + (num04 * 7) + (num05 * 6) + (num06 * 5) + (num07 * 4) + (num08 * 3) + (num09 * 2));
		var resultadoDg1 = 11 - (somaDg1 % 11);
		if (resultadoDg1 > 9){
			resultadoDg1 = 0;
		}
		var somaDg2		 = ((num01 * 11) + (num02 * 10) + (num03 * 9) + (num04 * 8) + (num05 * 7) + (num06 * 6) + (num07 * 5) + (num08 * 4) + (num09 * 3) + (resultadoDg1 * 2));
		var resultadoDg2 = 11 - (somaDg2 % 11);
		if (resultadoDg2 > 9){
			resultadoDg2 = 0;
		}
		var confDv = String(resultadoDg1) + String(resultadoDg2);
		if(dv != confDv){
			return false;
		}
		else {
			return true;
		}
	}
	else {
		var num01 = parseInt(valor.substr(0,1));
		var num02 = parseInt(valor.substr(1,1));
		var num03 = parseInt(valor.substr(3,1));
		var num04 = parseInt(valor.substr(4,1));
		var num05 = parseInt(valor.substr(5,1));
		var num06 = parseInt(valor.substr(7,1));
		var num07 = parseInt(valor.substr(8,1));
		var num08 = parseInt(valor.substr(9,1));
		var num09 = parseInt(valor.substr(11,1));
		var num10 = parseInt(valor.substr(12,1));
		var num11 = parseInt(valor.substr(13,1));
		var num12 = parseInt(valor.substr(14,1));
		var dv    = valor.substr(16,2);

		var somaDg1 	 = ((num01 * 5) + (num02 * 4) + (num03 * 3) + (num04 * 2) + (num05 * 9) + (num06 * 8) + (num07 * 7) + (num08 * 6) + (num09 * 5) + (num10 * 4) + (num11 * 3) + (num12 * 2));
		var resultadoDg1 = (11 - (somaDg1 % 11));
		if (resultadoDg1 > 9){
			resultadoDg1 = 0;
		}
		var somaDg2 	 = ((num01 * 6) + (num02 * 5) + (num03 * 4) + (num04 * 3) + (num05 * 2) + (num06 * 9) + (num07 * 8) + (num08 * 7) + (num09 * 6) + (num10 * 5) + (num11 * 4) + (num12 * 3) + (resultadoDg1 * 2));
		var resultadoDg2 = (11 - (somaDg2 % 11));
		if (resultadoDg2 > 9){
			resultadoDg2 = 0;
		}
		var confDv = String(resultadoDg1) + String(resultadoDg2);
		if(dv != confDv){
			return false;
		}
		else {
			return true;
		}
	}
}

//#################################################################################
//Formata os números de CNPJ e CNPF e confere o dígito
function ajustaCNPJF(Campo){
	if(Campo!=""){
		var tamCampo = String(Campo.length);
		var valor = '';
		if(tamCampo<=11){
			valor = Campo.substr(0,3) + '.' + Campo.substr(3,3) + '.' + Campo.substr(6,3) + '-' + Campo.substr(9,2);
			if(confCNPJF(valor)==false){
				alert('O CPF informado é inválido !');
				F1.nmCnpj.focus();
				return false;
			}
			F1.nmCnpj.value = valor;
			document.getElementById('Cnpj').disabled = true
		}
		else
		{
			if(tamCampo>=11){
				valor = Campo.substr(0,2) + '.' + Campo.substr(2,3) + '.' + Campo.substr(5,3) + '/' + Campo.substr(8,4) + '-' + Campo.substr(12,2);
				if(confCNPJF(valor)==false){
					alert('O CNPJ informado é inválido !');
					F1.nmCnpj.focus();
					return false;
				}
			}
			F1.nmCnpj.value = valor;
			document.getElementById('Cnpj').disabled = true
		}
	}
}
//#################################################################################
function mask(_mask, val) {
	var i, mki;
	var aux="";
	
	for(i=mki=0; i<val.length; i++, mki++) {
		if(_mask.charAt(mki)=='' || _mask.charAt(mki)=='#' || _mask.charAt(i)==val.charAt(i)) {
			aux+=val.charAt(i);
		} else {
			aux+=_mask.charAt(mki)+val.charAt(i);
			mki++;
		}
	}
	return aux;
}
//#################################################################################
function maskEvent(field, _mask, event) {
	var key        ='';
	var aux        ='';
	var len        =0;
	var i          =0;
	var strCheck   = '0123456789';
	var rcode      = (window.Event) ? event.which : event.keyCode;
	var tamMask    = _mask.length;
	if(rcode == 13) {
		event.keyCode = 0 ;
		focusNext(field.tabIndex);
		return true;
	}
	//Get key value from key code
	key=String.fromCharCode(rcode);
	if(strCheck.indexOf(key)==-1) {
		//Not a valid key
		return false;
	}
	aux=field.value+key;
	//window.alert(aux);
	aux=mask(_mask,aux);
	//window.alert(aux);
	field.value=aux;
	var Campo      = aux;
	var tamCampo   = aux.length;
	if(tamCampo >= tamMask){
		event.keyCode = 0 ;
		focusNext(field.tabIndex);
		return true;
	}
	else{
		return false;
	}
}
//#################################################################################
// Configuração para Utilização do JavaScriptUtil
//#################################################################################
/*        //Set up the date parsers
        var dateParser = new DateParser("dd/MM/yyyy HH:mm");
    
        //Set up the InputMask    
        var numericMask = new InputMask(JST_MASK_NUMBERS, "numeric");
        var decimalMask = new InputMask(JST_MASK_DECIMAL, "decimal");
        var upperMask = new InputMask(fieldBuilder.upperAll(), "upper");
        var lowerMask = new InputMask(fieldBuilder.lowerAll(), "lower");
        var capitalizeMask = new InputMask(fieldBuilder.capitalizeAll(), "capital");
        var dateMask = new InputMask(JST_MASK_DATE, "date");
        var dateTimeMask = new InputMask(JST_MASK_DATE_TIME, "dateTime");
        var dateTimeSecMask = new InputMask(JST_MASK_DATE_TIME_SEC, "dateTimeSec");
        var phoneMask = new InputMask("(##) ####-####", "phone");
        var customMask = new InputMask("AA.UU.LL.CC-##", "custom");
    
        //Set up the NumberMasks
        var decimalSeparator = ",";
        var groupSeparator = ".";
        
        var numParser1 = new NumberParser(0, decimalSeparator, groupSeparator, true);
        var numMask1 = new NumberMask(numParser1, "num1");

        var numParser2 = new NumberParser(-1, decimalSeparator, groupSeparator, true);
        numParser2.negativeParenthesis = true;
        var numMask2 = new NumberMask(numParser2, "num2");
        numMask2.leftToRight = true;
    
        var numParser3 = new NumberParser(3, decimalSeparator, groupSeparator, true);
        var numMask3 = new NumberMask(numParser3, "num3", 6);
        numMask3.allowNegative = false;
        numMask3.leftToRight = true;
    
        var numParser4 = new NumberParser(2, decimalSeparator, groupSeparator, true);
        numParser4.currencySymbol = "R$"
        numParser4.useCurrency = true;
        numParser4.negativeParenthesis = true;
        numParser4.currencyInside = true;
        var numMask4 = new NumberMask(numParser4, "num4", 6);
    
        //Set up the DateMasks
        var errorMessage = "Invalid date: ${value}. Expected format: ${mask}";
    
        var dateParser1 = new DateParser("dd/MM/yyyy");
        var dateMask1 = new DateMask(dateParser1, "date1");
        dateMask1.validationMessage = errorMessage;
    
        var dateParser2 = new DateParser("dd/MM/yyyy HH:mm");
        var dateMask2 = new DateMask(dateParser2, "date2");
        dateMask2.validationMessage = errorMessage;
    
        var dateParser3 = new DateParser("dd/MM/yyyy HH:mm", false);
        var dateMask3 = new DateMask(dateParser3, "date3");
        dateMask3.validationMessage = errorMessage;
        dateMask3.blurFunction = function(event, mask) {
            var control = mask.control;
            var valid = inArray(control.value.length, [0, 10, 16]);
            if (!valid) {
                alert("The date should be informed as dd/MM/yyyy or dd/MM/yyyy HH:mm");
                if (control.value.length < 10) {
                    control.value = "";
                } else {
                    control.value = left(control.value, 10);
                }
            }
            return valid;
        };
    
        var dateParser4 = new DateParser("HH:mm:ss");
        var dateMask4 = new DateMask(dateParser4, "date4");
        dateMask4.validationMessage = errorMessage;
    
        //Set up the SizeLimits
        function updateLimit4(control, size, max, left) {
            var gauge = getObject("limit4Gauge");
            var width = Math.round(size * 100 / max) + "%";
            gauge.style.width = width;
            gauge.style.backgroundColor = (width == '100%' ? 'red' : 'blue');
            gauge.innerHTML = width;
        }
        new SizeLimit("limit1", 50, "limit1Out");
        new SizeLimit("limit2", 50, "limit2Out", "${size} / ${max}");
        new SizeLimit("limit3", 50, "limit3Out", "You typed ${size} characters of a total of ${max}.<br>You have ${left} more characters to type.<br>This field only accepts alphanumeric characters and spaces.");
        new InputMask(new Input(JST_CHARS_ALPHA + JST_CHARS_WHITESPACE), "limit3");
        var limit = new SizeLimit("limit4", 50);
        limit.updateFunction = updateLimit4;
        limit.update();
*/
//#################################################################################
function formataNumero(campo,casasDecimais,grupo,decimal,negativo,moeda,simbolo) {
	//Set up the NumberMasks
	var decimalSeparator = decimal;
	var groupSeparator = grupo;
	var numParser = new NumberParser(casasDecimais, decimalSeparator, groupSeparator, true);
	numParser.negativeParenthesis = negativo;
	numParser.currencySymbol = simbolo;
	numParser.useCurrency = moeda;
	//numParser.currencyInside = false;
	var numMask = new NumberMask(numParser, campo, 12);
}
//#################################################################################
function formataContainer(Campo,teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	if (Campo.value.length > 14) {
		return false;
	}
	vr = vr.replace("-", "");
	vr = vr.replace("-", "");
	tam = vr.length + 1;
	
	var strValidos = "qwertyuiopasdfghjklçzxcvbnmQWERTYUIOPLÇKJHGFDSAZXCVBNM0"
	var cond = (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tam <= 4 && tecla != 8 && tecla != 9 );
	var strValidos = "1234567890"
	cond = cond || (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tam > 4 && tecla != 8 && tecla != 9 );
	if (cond) {
		teclapres.keyCode = 0 ;
		tecla=0;
	}
	
	if (tecla != 9 && tecla != 8) {
		if (tam > 4 && tam < 10)
			Campo.value = vr.substr(0, 4) + '-' + vr.substr(4, tam);
		if (tam > 10 && tam <=11)
			Campo.value = vr.substr(0,4) + '-' + vr.substr(4,6) + '-' + vr.substr(10,1);
		var tfinal = new String(Campo.value);
	}
}
//#################################################################################
function limitaCampo(campo,teclapres,limite){
	if (campo.value.length > limite) {
		return false;
	}
	var counter = 'counter'+campo.name;
	var totlen  = parseInt(document.getElementById(counter).innerText) + 0;
	if (teclapres.keyCode==0){
		totlen  = totlen  + 1;
	} else {
		totlen  = limite  - campo.value.length;
	}
	document.getElementById(counter).innerText = totlen;
}
//#################################################################################
function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
		} 
		else
		return true;
	}      
//#################################################################################
function obrigaEntrada() {
	var dataOK = ValidaPeriodo();
	var campoOK = true;
	if(document.forms[0].elements[2].name != "item") {
		var texto = new String(document.forms[0].elements[2].value);
		if (texto.length<=0) { alert("Preencha todos os campos."); campoOK = false; }
	} 
	if (dataOK && campoOK ) document.forms[0].submit();
}
//#################################################################################
function ValidaPeriodo() {
	var sdti = new String(document.forms[0].elements[0].value);
	sdti = sdti.replace("/", ""); sdti = sdti.replace("/", "");
	var sdtf = new String(document.forms[0].elements[1].value);
	sdtf = sdtf.replace("/", ""); sdtf = sdtf.replace("/", "");
	if (sdti.length == 8 && sdtf.length == 8) {
		var dti = new Date(sdti.substr(2,2) + '/' + sdti.substr(0,2) + '/' + sdti.substr(4,4));
		var dtf = new Date(sdtf.substr(2,2) + '/' + sdtf.substr(0,2) + '/' + sdtf.substr(4,4));
		if (Math.abs(sdtf.substr(2,2))>12 || Math.abs(sdtf.substr(2,2))<1 ||Math.abs(sdti.substr(2,2))>12 || Math.abs(sdti.substr(2,2))<1 || Math.abs(sdtf.substr(0,2))>31 || Math.abs(sdtf.substr(0,2))<1 || Math.abs(sdti.substr(0,2))>31 || Math.abs(sdti.substr(0,2))<1 || Math.abs(sdti.substr(4,4))<1900 || Math.abs(sdti.substr(4,4))>2050 || Math.abs(sdtf.substr(4,4))<1900 || Math.abs(sdtf.substr(4,4))>2050) { alert("Periodo inválido"); return false ;}
		if ((dtf-dti) >= 0) { return true; }
		else  { alert("Periodo inválido"); return false ;}
	}
	else {
		alert("Periodo inválido");
		return false;
	}
}
//#################################################################################
function Detalhar(pag) {
	window.open(pag,'Detalhes','titlebar=no,scrollbars=yes,status=no,menubar=no,location=no,left=0,top=0,height=535,width=780'); 
}
//#################################################################################
function formataPlaca(Campo,teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	if (Campo.value.length > 8) {
		return false;
	}
	vr = vr.replace("-", "");
	tam = vr.length + 1;
	
	var strValidos = "qwertyuiopasdfghjklçzxcvbnmQWERTYUIOPLÇKJHGFDSAZXCVBNM0"
	var cond = (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tam <= 3 && tecla != 8 && tecla != 9 );
	var strValidos = "1234567890"
	cond = cond || (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tam > 3 && tecla != 8 && tecla != 9 );
	if (cond) {
		teclapres.keyCode = 0 ;
		tecla=0;
	}
	
	if (tecla != 9 && tecla != 8) {
		if (tam > 3 && tam < 8)
			Campo.value = vr.substr(0, 3) + '-' + vr.substr(3, tam);
		var tfinal = new String(Campo.value);
	}
}
//#################################################################################
function LocalizaMotorista(campo){
	var texto = new String(campo.value);
	if (texto.length<3) alert("Digite pelo menos os 3 caracteres iniciais.")
	else {document.forms[0].Listar.value="true"; document.forms[0].submit();}
}
//#################################################################################
function LocalizaImportador(campo){
	var texto = new String(campo.value);
	if (texto.length<3) alert("Digite pelo menos os 3 caracteres iniciais.")
	else {document.forms[0].Listar.value="true"; document.forms[0].submit();}
}
//#################################################################################
// AC_RunActiveContent
//#################################################################################
//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}
//#################################################################################
function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';
alert(str)
  document.write(str);
}
//#################################################################################
function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
//#################################################################################
function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
//#################################################################################
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
//#################################################################################
//#################################################################################
