var iexplorer = (navigator.appName.indexOf("Microsoft") >= 0)	? true : false;

//alert(iexplorer+ " // " +navigator.appName+ "\n" +navigator.appVersion);



function getKeyCode(e)
{
	if (window.event)
		return window.event.keyCode;
	else if (e)
		return e.which;
	else
		return null;
}

function geralFormatarTexto(e)
{
	var key = "", keychar = "";
	key = getKeyCode(e);
	validchars = "0123456789zxcvbnmasdfghjklqwertyuiop-";
	
	if (key == null) return true;
	
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	validchars = validchars.toLowerCase();
	
	if (validchars.indexOf(keychar) != -1)
		return true;
	if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 
			|| key==39 || key==192 || key==189 || key==32
			&& (key!=46 || key!=44) )
		return true;
	return false;
}


/**
 * Verificar entrada de caracter numerico e exeções e formatar Data automaticamente
 * Hugo Rogério - 15/10/2008
 */
function geralFormatarData(campo, evento)
{
	var tam, descricao ,i, letra, caracteres;
	var obj = campo.value;
	tam = parseInt(obj.length,10);
	caracteres = "0123456789";
  
  
  if (iexplorer) // Internet Explorer
  {
  	if ((caracteres.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13)) {
  		window.event.returnValue = false;
  		return false;
  	}
	}
	else // Firefox
	{
    if ((caracteres.indexOf(String.fromCharCode(evento.which)) == -1) 
      && (evento.which != 13) && (evento.which != 0) && (evento.which != 8))
    {
      return false;
    } 
  }
	

	for (i = 0; i < tam; i++)
	{
		descricao = obj.charAt(i)
		
		if ((descricao >= '0' && descricao <= '9')||(descricao == '/'))
		{
		  //inclusao das barras.
			if (((i==1)||(i==4))&&((tam==2)||(tam==5)))
			{
				campo.value = obj.substring(0, (i + 1)) + '/';
				i++;
			}
		}
	 }
	 return true;
}


/**
 * Verificar entrada de caracter numerico e exeções e formatar CEP automaticamente
 * Hugo Rogério - 30/10/2008
 */
function geralFormatarCEP(campo, evento)
{
	var tam, descricao ,i, letra, caracteres;
	var obj = campo.value;
	tam = parseInt(obj.length,10);
	caracteres = "0123456789";
  
  
  if (iexplorer) // Internet Explorer
  {
  	if ((caracteres.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13)) {
  		window.event.returnValue = false;
  		return false;
  	}
	}
	else // Firefox
	{
    if ((caracteres.indexOf(String.fromCharCode(evento.which)) == -1) 
      && (evento.which != 13) && (evento.which != 0) && (evento.which != 8))
    {
      return false;
    } 
  }
	

	for (i = 0; i < tam; i++)
	{
		descricao = obj.charAt(i)
		
		if ((descricao >= '0' && descricao <= '9')||(descricao == '/'))
		{
		  //inclusao traço.
      if (tam==5)
			{
				campo.value = obj.substring(0, (i + 1)) + '-';
			}
			i++;
		}
  }
  
  return true;
}

/**
 * Verificar entrada de caracter numerico e exeções e formatar CPF automaticamente
 * Hugo Rogério - 30/10/2008
 */
function geralFormatarCPF(campo, evento)
{
	var tam, descricao ,i, letra, caracteres;
	var obj = campo.value;
	tam = parseInt(obj.length,10);
	caracteres = "0123456789";
  
  
  if (iexplorer) // Internet Explorer
  {
  	if ((caracteres.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13)) {
  		window.event.returnValue = false;
  		return false;
  	}
	}
	else // Firefox
	{
    if ((caracteres.indexOf(String.fromCharCode(evento.which)) == -1) 
      && (evento.which != 13) && (evento.which != 0) && (evento.which != 8))
    {
      return false;
    } 
  }
	

	for (i = 0; i < tam; i++)
	{
		descricao = obj.charAt(i)
		
		if ((descricao >= '0' && descricao <= '9')||(descricao == '-'))
		{
			if (tam==3 || tam==7)
			{
				campo.value = obj.substring(0, (i + 1)) + '.' ;
			}
			else if (tam==11)
			{
				campo.value = obj.substring(0, (i + 1)) + '-';
			}
			i++;
		}
  }
  return true;
}


/**
 * Verificar entrada de caracter numerico e exeções e formatar CNPJ automaticamente
 * Hugo Rogério - 30/10/2008
 */
function geralFormatarCNPJ(campo, evento)
{
	var tam, descricao ,i, letra, caracteres;
	var obj = campo.value;
	tam = parseInt(obj.length,10);
	caracteres = "0123456789";
  
  if (iexplorer) // Internet Explorer
  {
  	if ((caracteres.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13))
    {
  		window.event.returnValue = false;
  		return false;
  	}
	}
	else // Firefox
	{
    if ((caracteres.indexOf(String.fromCharCode(evento.which)) == -1) 
      && (evento.which != 13) && (evento.which != 0) && (evento.which != 8))
    {
      return false;
    } 
  }
	
	
  if(window.event) // IE
  {
    tecla = window.event.keyCode;
  }
  else // Firefox
  {
    tecla = evento.which;
  }
	
  var vr = new String(campo.value);
  vr = vr.replace(".", "");
  vr = vr.replace(".", "");
  vr = vr.replace("/", "");
  vr = vr.replace("-", "");

  tam = vr.length + 1;
  
  //mascara CNPJ
  //##.###.###/####-##
  
  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);
  }

	
  /*
	for (i = 0; i < tam; i++)
	{
		descricao = obj.charAt(i)
		
    //##.###.###/####-##
		
		if ((descricao >= '0' && descricao <= '9')||(descricao == '/'))
		{
		  
			if (tam==2)
			{
				campo.value = obj.substring(0, 2) + '.';
			}
			else if (tam==6)
			{
				campo.value = obj.substring(0, (i + 1)) + '.';
			}
			else if (tam==10)
			{
				campo.value = obj.substring(0, (i + 1)) + '/';
			}
      else if (tam==16)
			{
				campo.value = obj.substring(0, 15) + '-';
			}
			i++;
		}
  }
  */
  
  return true;
}
















// Formata primeira letra do nome UPPER
// Ex.: formatarNome(document.forms.nomedocampo)
function formatarNome(campo){
	  var texto			 = "";
	  var textoFinal = "";
	  var caracter	 = "";
	  var proxUP		 = false;
	  
	  texto	= campo.value;
	  texto	= texto.toLowerCase();
	  
	  //Primeira Letra Maiuscula
	  texto	= texto.substr(0,1).toUpperCase() + texto.substr(1,texto.length);
	  
	  //Busca o caracter vazio em todo texto e colocar caracter seguinte em UPPER
	  for (i=0; i < texto.length; i++){
	    caracter = texto.substr(i,1);
	    if(proxUP){caracter = caracter.toUpperCase();}
	    if(caracter == " "){proxUP = true;} else{proxUP = false;}
	    textoFinal = textoFinal + caracter;
	  }
	  
	  //Busca artigo especiais (de, da, do, e, das, dos)
	  if(textoFinal.indexOf(" De ") > 0 ){textoFinal = textoFinal.replace(" De "," de ")}
	  if(textoFinal.indexOf(" Da ") > 0 ){textoFinal = textoFinal.replace(" Da "," da ")}
	  if(textoFinal.indexOf(" Do ") > 0 ){textoFinal = textoFinal.replace(" Do "," do ")}
	  
	  if(textoFinal.indexOf(" E ") > 0 ){textoFinal = textoFinal.replace(" E "," e ")}
	  	  
	  if(textoFinal.indexOf(" Das ") > 0 ){textoFinal = textoFinal.replace(" Das "," das ")}
	  if(textoFinal.indexOf(" Dos ") > 0 ){textoFinal = textoFinal.replace(" Dos "," dos ")}
	  
    campo.value = textoFinal;
}

function mostraPub(item){
  var atual = item.style.display =='none';
  subMenu1Pub.style.display='none';
  if (atual){
    item.style.display='';
  }
}

function mostraSubMenu(item, objImg, nomImgOff, nomImgOn){
	var i, a; 
	var atual = item.style.display =='none';
	
	var urlOn, urlOff;
	
	if(eval(objImg)){
		strPathTemp = objImg.src;
		strReverse = reverse(objImg.src);
		i = strReverse.indexOf("/");
		strDesReverse = reverse(strReverse.substring(0,i));
		urlOn = replace(strPathTemp, strDesReverse, nomImgOn);
		urlOff = replace(strPathTemp, strDesReverse, nomImgOff);
	}
	
	for(i=0; (a = document.getElementsByTagName("span")[i]); i++) { 
		if(a.id!=''){
			if(a.id.substring(0,7)=='subMenu'){
				a.style.display='none';
				//alert(a.id);
			}
		}
	}
	
	for(i=0; (a = document.getElementsByTagName("img")[i]); i++) { 
		if(a.id!=''){
			if(a.id.substring(0,10)=='menuBullet'){
				if(eval(objImg))a.src = urlOff;
			}
		}
	}
	
	
	if (atual){
	  item.style.display='';
	  if(eval(objImg))objImg.src = urlOn;
	}
}

function reverse(objValor) {
	forwards = "";
	backwards = "";
	forwards = objValor;
	for (i = 0; i < forwards.length; i++) {
	backwards = forwards.charAt(i) + backwards; 
	}
	return backwards; 
}

function replace(string,text,by) {
    // Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);

    if ((!i) && (text != string.substring(0,txtLength))) return string;
        if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength) newstr +=replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}


function SearchAndReplace(Content, SearchFor, ReplaceWith) {

   var tmpContent = Content;
   var tmpBefore = new String();   
   var tmpAfter = new String();
   var tmpOutput = new String();
   var intBefore = 0;
   var intAfter = 0;

   if (SearchFor.length == 0)
      return;


   while (tmpContent.toUpperCase().indexOf(SearchFor.toUpperCase()) > -1) {
   
      // Get all content before the match
      intBefore = tmpContent.toUpperCase().indexOf(SearchFor.toUpperCase());
      tmpBefore = tmpContent.substring(0, intBefore);
      tmpOutput = tmpOutput + tmpBefore;

      // Get the string to replace
      tmpOutput = tmpOutput + ReplaceWith;


      // Get the rest of the content after the match until
      // the next match or the end of the content
      intAfter = tmpContent.length - SearchFor.length + 1;
      tmpContent = tmpContent.substring(intBefore + SearchFor.length);

   }

   return tmpOutput + tmpContent;

}

function link(url) {
	document.location.href = url;
}

function statusBar(url){
	window.status = url;
}

//Formata CEP
function FormataCep(campo){
    if(campo.value.length=='5'){
      campo.value = campo.value + "-";
    }
}

function FormataCPF(pForm,pCampo,pTamMax,pPos1,pPos2,pPosTraco,pTeclaPres){
 var wTecla, wVr, wTam;
 
       //alert(pForm[pCampo].value);
  
 wTecla = pTeclaPres.keyCode;
 wVr = pForm[pCampo].value;
 wVr = wVr.toString().replace( "-", "" );
 wVr = wVr.toString().replace( ".", "" );
 wVr = wVr.toString().replace( ".", "" );
 wVr = wVr.toString().replace( "/", "" );
 wTam = wVr.length ;

 if (wTam < pTamMax && wTecla != 8) { 
    wTam = wVr.length + 1 ; 
 }

 if (wTecla == 8 ) { 
    wTam = wTam - 1 ; 
 }
   
 if ( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105 ){
  if ( wTam <= 2 ){
    pForm[pCampo].value = wVr ;
  }
  if (wTam > pPosTraco && wTam <= pTamMax) {
        wVr = wVr.substr(0, wTam - pPosTraco) + '-' + wVr.substr(wTam - pPosTraco, wTam);
  }
  if ( wTam == pTamMax){
        wVr = wVr.substr( 0, wTam - pPos1 ) + '.' + wVr.substr(wTam - pPos1, 3) + '.' + wVr.substr(wTam - pPos2, wTam);
  }
  pForm[pCampo].value = wVr;
 
 }

}

/*****************************/
//formata CNPJ
 function FormatarCNPJ(objeto)
 {
 	var obj = objeto.value;
 	var lcRetorno = objeto.value;
 	
 	if ( obj.length == 3 ) {
 		if ( obj.substr(2,1) == "." )
 			lcRetorno = obj.substr(0,2);			
 		else
 			lcRetorno = obj.substr(0,2) + "." + obj.substr(2,1);
 	}
 	if ( obj.length == 7 ) {
 		if ( obj.substr(6,1) == "." )
 			lcRetorno = obj.substr(0,6);			
 		else
 			lcRetorno = obj.substr(0,6) + "." + obj.substr(6,1);
 	}
 	if ( obj.length == 11 ) {
 		if ( obj.substr(10,1) == "/" )
 			lcRetorno = obj.substr(0,10);			
 		else
 			lcRetorno = obj.substr(0,10) + "/" +
 obj.substr(10,1);
 	}
 	if ( obj.length == 16 ) {
 		if ( obj.substr(15,1) == "-" )
 			lcRetorno = obj.substr(0,15);			
 		else
 			lcRetorno = obj.substr(0,15) + "-" +
 obj.substr(15,1);
 	}
 	objeto.value = lcRetorno;
 }


/*****************************/
function validarCPF(campo){
 CPF = campo.value 

 if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
  CPF == "22222222222" || CPF == "33333333333" || CPF == "44444444444" ||
  CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
  CPF == "88888888888" || CPF == "99999999999"){
 alert("CPF Inválido !");
 campo.focus();
 return false;
 }

 soma = 0;
 for (i=0; i < 9; i ++)
 soma += parseInt(CPF.charAt(i)) * (10 - i);
 resto = 11 - (soma % 11);
 if (resto == 10 || resto == 11)
 resto = 0;
 if (resto != parseInt(CPF.charAt(9))){ 
  alert("CPF Inválido !");
  campo.focus();
  return false;
 }
 soma = 0;
 for (i = 0; i < 10; i ++)
 soma += parseInt(CPF.charAt(i)) * (11 - i);
 resto = 11 - (soma % 11);
 if (resto == 10 || resto == 11)
 resto = 0;
 
 if (resto != parseInt(CPF.charAt(10))){
   alert("CPF Inválido !")
   campo.focus();
   return false;
 }
 
}

function MudaCor(id,css) {
    document.all[id].className = css;
}

///
/*
function MudaCor(id,estado) {
 document.all[id].style.cursor = "hand";
 if(estado=='liga'){
	document.all[id].bgColor = "#CFD8E0";
 }
 else{
	document.all[id].bgColor = "transparent";  
 }
}*/

function link(url) {
	document.location.href = url;
}


//Muda a cor do campo formulario ao receber ou perder o foco
function MudaCorCampo(campo,evento){
    if(evento=='over'){
    document.formulario[campo].className='foco';
  }else{
    document.formulario[campo].className='blur';
  }
}


////** /////// DATA ///-********

//Verifica a versão do browser
var ie  = (document.all) ? 1 : 0;
var ns4 = (document.layers) ? 1 : 0;
var ns6 = (document.getElementById&&!document.all) ? 1 : 0;

//Esta função é para o evento onKeyPress do Netscape
function netscapeKeyPress(e) {
  if(ns4){
     if (e.which != 13){
         window.captureEvents(Event.KEYPRESS);
		 window.onKeyPress = FormatarData;
     }
  }
}

if (ns4) {
    window.captureEvents(Event.KEYPRESS);
    window.onKeyPress = netscapeKeyPress;
    
}

//**
function FormataData(campo){ 
	var tam, descricao ,i, letra
	var obj = campo.value;
	tam = parseInt(obj.length,10);
	var ST_VCDigitos = "0123456789";
  
	if((ST_VCDigitos.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13)) {
		BO_INumeroInteiro=false;
		window.event.returnValue=false;
	}

	for(i=0;i<tam;i++)
	{
		descricao = obj.charAt(i)
		
		if ((descricao >= '0' && descricao <= '9')||(descricao == '/'))
		{
		//inclusao das barras.
			if (((i==1)||(i==4))&&((tam==2)||(tam==5)))
			{
				campo.value = obj.substring(0,i+1) + '/';
				i = i + 1;
			}
		}
	 }
}


//Adiciona a barra "/" automaticamente nos campos de data.
function FormatarData(DT_VDData)
{
	var tam, descricao ,i, letra
	var obj = DT_VDData.value;
	tam = parseInt(obj.length,10);
	var ST_VCDigitos = "0123456789";
  
	if((ST_VCDigitos.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13)) {
		BO_INumeroInteiro=false;
		window.event.returnValue=false;
	}

	for(i=0;i<tam;i++)
	{
		descricao = obj.charAt(i)
		
		if ((descricao >= '0' && descricao <= '9')||(descricao == '/'))
		{
		//inclusao das barras.
			if (((i==1)||(i==4))&&((tam==2)||(tam==5)))
			{
				DT_VDData.value = obj.substring(0,i+1) + '/';
				i = i + 1;
			}
		}
	 }
}


/////
function FormatarDataBR(){
document.forms[0].datefield.value=today
}

////
function ValidarFormulario(campo){
var valordata = campo.value;
var strdia   = valordata.substring(0,2);
var strmes   = valordata.substring(3,5);
var strano   = valordata.substring(6,10);
var dia = parseInt(strdia,10);
var mes = parseInt(strmes,10);
var ano = parseInt(strano,10);
var anobissexto;
var bo_valido = true;
var anoatual = new Date();

anoatual = anoatual.getYear();

		if(valordata.length!=10){bo_valido=false;}
		if(isNaN(dia)||isNaN(mes)||isNaN(ano)){bo_valido=false;}
		if((strdia.length!=2)||(strmes.length!=2)||(strano.length!=4)){bo_valido=false;}
		if((ano>anoatual)||(ano<=1900)){bo_valido=false;}
		if((dia>31)||(dia==0)||(mes>12)||(mes==0)){bo_valido=false;}
		 
		if(ano%4 == 0)
				anobissexto = 1;
			else
				anobissexto = 0;
		if(((mes == 2) && (dia > (28 + parseInt(anobissexto,10)))) || (mes == 4 || mes == 6 || mes == 9 || mes == 11) && (dia > 30)){
			bo_valido=false;
		}
 
		if(!bo_valido){
		  alert("Data inválida!");
		  campo.focus();
		  return false;
		}else{
		  return true;
		 }
}

function abreJanela(url,parametros,nome,bo_imprimir){
 if(nome==''){
   janela = window.open(url,nome,parametros);
   janela.focus();
   //if(bo_imprimir){ janela.document.print(); }
 }else{ 
   janela2 = window.open(url,nome,parametros);
   janela2.focus();
   //if(bo_imprimir){ janela2.document.print(); }
 }
 
}

function mostraCartorios(texto){
 conteudo="<html>";
 conteudo+="<head>";
 conteudo+="<title>ANOREGDF - www.anoregdf.com.br</title>";
 conteudo+="<style>";
 conteudo+="body { font-family: Verdana; font-size: 10px; color:#FFFFFF; font-weight: bold }";
 conteudo+="</style>";
 conteudo+="<head>";
 conteudo+="<body bgcolor=#0040AF>";
 conteudo+=texto;
 conteudo+="</body>";
 conteudo+="</html>";
 
 janela = window.open('about:blank','jancartorio','top=140,left=20,width=630,height=130,scrollbars=1,resizable=1');
 janela.document.close();
 janela.document.write(conteudo);
 janela.focus();
}



function getImageDimension (imgURL, loadHandler) {
  var img = new Image();
  img.onload = loadHandler;
  if (document.layers 
      && location.protocol.toLowerCase() != 'file:' 
      && navigator.javaEnabled())
    netscape.security.PrivilegeManager.enablePrivilege(
      'UniversalFileRead'
    );
  img.src = imgURL;
}
function getFileSize(fileName) {
  if (document.layers) {
    if (navigator.javaEnabled()) {
      var file = new java.io.File(fileName);
      if (location.protocol.toLowerCase() != 'file:')
        netscape.security.PrivilegeManager.enablePrivilege(
        'UniversalFileRead'
        );
      return file.length();
    }
    else return -1;
  }
  else if (document.all) {
    window.oldOnError = window.onerror;
    window.onerror = function (err) {
      if (err.indexOf('utomation') != -1) {
        alert('file access not possible');
        return true;
      }
      else 
        return false;
    };
    var fso = new ActiveXObject('Scripting.FileSystemObject');
    var file = fso.GetFile(fileName);
    window.onerror = window.oldOnError;
    return file.Size;
  }
}

function showImageDimensions () {
  alert(this.width + 'x' + this.height);
}

function checkImageDimensions (fileName) {
  var imgURL = 'file:///' + fileName;
  getImageDimension(imgURL, showImageDimensions);
}



function verificaTamanho(vlCampo){
	if(vlCampo!=''){
		tamOriginal = getFileSize(vlCampo);
		tam = (tamOriginal/1024);
		if(tam>500){
			alert('O tamanho do arquivo ('+parseInt(tam)+' kb) é maior que o permitido (500 kb).\n');
			//objCampo.focus();
			return false;
		}else{
			return true;
		}
	}
}

function redimencionaLayer(obj1){
	objDiv1 = document.getElementById(obj1);
	objDiv2 = document.getElementById("div_conteudo");
	if(objDiv1){
		if(screen){
			if(screen.width=='1024'){
				objDiv1.style.width = 760;
			}
		}
	}
}

		function validarFormularioDForm(objForm){
			//if(document.forms[0]){ objForm = document.forms[0] }else{ objForm = parent.document.forms[0] }
			var bo_ole = false;
			var strCampoOleNome = "";
			if(objForm.botaoAcao.value!='e'){
				if(!verificaPreenchimento(objForm)){ return false; }
			}
				
				
			for(i=0;i<=objForm.elements.length;i++){
				//objElem = objForm.elements[i];
				objElem = objForm.elements[i];
				if(objElem){
					fldNome = objElem.name;
					fldValor = objElem.value;
					fldTipo = objElem.type;
					csTipo = fldNome.substring(4,7).toLowerCase();
					if(fldNome.substring(0,3)=='sql'&&fldTipo!='hidden'){
						switch (csTipo){
							case 'str':
								//alert('str');
								break;
							case 'dat':
								//alert(fldNome);
								//alert(ValidarData(objElem));
								//if(fldValor!=""){ if(!ValidarData(objElem)){ } }
								break;
							case 'ole':
								if(fldValor!='') bo_ole = true;
									
								encTypeForm(objForm, '1');
								montaFormQueryString(objForm);
								//alert(strQueryString);
								strCampoOleNome = fldNome.substring(8,fldNome.length);
								//alert('blob');
								//alert(ValidarData(objElem));
								//if(fldValor!=""){ if(!ValidarData(objElem)){ } }
								break;
							default:
						}
					}
				}
			}
				

				
		}
		
/////////////////////////

//Procura valores em arrays unidimencionais
function findInArray(thearray,searchvalue){
   for ( var i=0; i<thearray.length; i++ )
      if ( thearray[i] == searchvalue )
         return(true);

   return(false);
}

//////////////////////////
//////////////
function ContaCaracteres(objForm, nmCaracteres, nmTextArea, inMax){
	//alert(objForm.name);
	objTextArea = objForm[nmTextArea];
	objCaracteres = objForm[nmCaracteres];
	
	intCaracteres = inMax - objTextArea.value.length;
	if (intCaracteres > 0){
		objCaracteres.value = intCaracteres;
		return true;
	}
	else{
		intMensagem = inMax - objCaracteres.value.length + 1;
		objTextArea.value = objTextArea.value.substr(0,intMensagem)
		objCaracteres.value = 0;
		return false;
	}
}

////////////////////////

function mudaCheckbox(objChk,objTxt){
	if(isNaN(objChk.value)){
		objTxt.value = objChk.checked; 
	}else{
		if(objChk.checked){
			objTxt.value = '1';
		}else{
			objTxt.value = '0';
		}
	}
	
}

////////////////////////
function validarHora(obj) {
  if(obj.value.length==5||obj.value.length==8){
    boH = /^([01]?[0-9]|[2][0-3])(:[0-5][0-9])?$/.test(obj.value)
    if(!boH){alert('Hora inválida!'); obj.focus(); return false;}
    obj.focus();
    return boH;
  }else{
    if(obj.value.length==0){ return true }
    alert('Hora inválida!');
    obj.focus();
    return false;
  }
  return false;
}

// abre janela com largura fixa e altura de acordo com a resolução 
function janela(url,nome){
  
  var altu    = window.screen.availHeight;
  var posicao = 'top=0,left=0,screenX=0, screenY=0';
  var barra   = 'scrollbars=yes, status=no, menubar=yes, toolbar=no, location=no, resizable=yes';
  var janela  = 'width=660, heigth='+altu+'';
  
  var url   = url;
  var nome  = nome;
  var param = posicao+", "+barra+", "+janela;
  
  window.open(url,nome,param,true);
}

// abre janela com largura fixa e altura de acordo com a resolução 
function janelaEtiqueta(url,nome){
  
  var larg    = window.screen.availHeight;
  var posicao = 'top=0,left=0,screenX=0, screenY=0';
  var barra   = 'scrollbars=yes, status=no, menubar=yes, toolbar=no, location=no, resizable=yes';
  var janela  = 'width=860, heigth='+larg+''; // largura modificada
  
  var url   = url;
  var nome  = nome;
  var param = posicao+", "+barra+", "+janela;
  
  window.open(url,nome,param,true);
}

// abre janela com largura fixa e altura de acordo com a resolução 
function janelaPaisagem(url,nome)
{
  var larg    = window.screen.availHeight;
  var altura  = window.screen.availWidth;
  
  if(altura <= 1024)
  {
    altura = altura;
  }
  else
  {
    altura = 1000;
  }
  
  var posicao = 'top=0,left=0,screenX=0, screenY=0';
  var barra   = 'scrollbars=yes, status=no, menubar=yes, toolbar=no, location=no, resizable=yes';
  var janela  = 'width='+altura+', heigth='+larg+'';
  var url     = url;
  var nome    = nome;
  var param   = posicao+", "+barra+", "+janela;
  
  window.open(url,nome,param,true);
}


//Troca caracter ' por `
function trocaCaracterSQL(campo){
//  campo = document.forms.campo.value;
//  alert(campo);
}



//Verifica a versão do browser
var ie  = (document.all) ? 1 : 0;
var ns4 = (document.layers) ? 1 : 0;
var ns6 = (document.getElementById&&!document.all) ? 1 : 0;

//Esta função é para o evento onKeyPress do Netscape
function netscapeKeyPress(e) {
  if(ns4){
     if (e.which != 13){
         window.captureEvents(Event.KEYPRESS);
		 window.onKeyPress = FormatarData;
     }
  }
}

if (ns4) {
    window.captureEvents(Event.KEYPRESS);
    window.onKeyPress = netscapeKeyPress;
}

//Adiciona a barra "/" automaticamente nos campos de data.
function FormatarData(DT_VDData)
{
  var tam, descricao ,i, letra
  var obj = DT_VDData.value;
  tam = parseInt(obj.length,10);
  var ST_VCDigitos = "0123456789";

  if((ST_VCDigitos.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13))
  {
    BO_INumeroInteiro=false;
    window.event.returnValue=false;
  }

  for(i=0;i<tam;i++)
  {
    descricao = obj.charAt(i)
	
    if ((descricao >= '0' && descricao <= '9')||(descricao == '/'))
    {
      
      //inclusao das barras.
      if (((i==1)||(i==4))&&((tam==2)||(tam==5)))
      {
        DT_VDData.value = obj.substring(0,i+1) + '/';
        i = i + 1;
      }
    }
  }
}

//Adiciona a ":" automaticamente nos campos de hora.
function FormatarHora(HR_VDHora)
{
  var tam, descricao,i , letra
  var obj = HR_VDHora.value;
      tam = parseInt(obj.length,8);
  var ST_VCDigitos = "0123456789";
  
  if((ST_VCDigitos.indexOf(String.fromCharCode(window.event.keyCode)) == -1) && (window.event.keyCode != 13)) {
    BO_INumeroInteiro = false;
    window.event.returnValue = false;
    }
  
  for(i=0;i<tam;i++){
    descricao = obj.charAt(i)
    if ((descricao >= '0' && descricao <= '9')||(descricao == ':')){
      
      //inclusao ":"
      if (((i==1)||(i==4))&&((tam==2)||(tam==5))){
        HR_VDHora.value = obj.substring(0,i+1) + ':';
        i = i + 1;
      }
    }
  } 
}

/////
function FormatarDataBR(){
document.forms[0].datefield.value=today
}

// Valida formulário
function VerficarDataHora(DT_VDData/*,HR_VDHora*/){
  
  var alterar = false;
  
  if (VerificaData(DT_VDData)){
    DT_VDData.value = '';
    DT_VDData.focus();
    document.formulario.btValida.value = 0; // falso
    return false;
  }
  /*else if (VerificaHora(HR_VDHora)){
    HR_VDHora.value = '';
    HR_VDHora.focus();
    return false;
  }*/
  else{
    alterar = true;
    document.formulario.btValida.value = 1; //verdadeiro    
    return alterar;
    return true;
  }
}

// Verifica se a data (dd/mm/aaaa) está correta e ano bissexto
// Verifica se o ano não é maior que o ano atual
function VerificaData(DT_VDData) { 

  var dia = (DT_VDData.value.substring(0,2)); 
  var mes = (DT_VDData.value.substring(3,5)); 
  var ano = (DT_VDData.value.substring(6,10));
  var dataatual = new Date();
  
  anoatual = dataatual.getYear();
  
  situacao = "";
  
  // verifica o dia valido para cada mes 
  if ((dia < 01) || ((dia < 01 || dia > 30) && (mes == 04 || mes == 06 || mes == 09 || mes == 11)) || dia > 31) { 
    situacao = "falsa";
  } 

  // verifica se o mes e valido 
  if ((mes < 01) || (mes > 12)) { 
    situacao = "falsa";
  } 
  
  // verifica se o ano é valido
  if ((ano > anoatual) || (ano < 1900)) {
    situacao = "falsa";
  }
  
  // verifica se e ano bissexto 
  if (mes == 2 && ( dia < 01 || dia > 29 ||  ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
    situacao = "falsa";
  } 
    
  if (DT_VDData.value == "") { 
    situacao = "falsa";
  } 
    
  if (situacao == "falsa") { 
    alert("Data Inválida!");
    return (true);
  }
    return (false);
}

// Verifica se a hora (hh:mm:ss) está correta
function VerificaHora(HR_VDHora){

  var vHra, vMin, vSeg
  
  vHra = (HR_VDHora.value.substring(0,2)); 
  vMin = (HR_VDHora.value.substring(3,5)); 
  vSeg = (HR_VDHora.value.substring(6,8));
        
  //alert('hrs '+ vHra + ', min '+vMin+' sec '+ vSeg);
             
  situacao = ""; 
  // verifica data e hora 
  if ((vHra<00) || (vHra>23) || (vMin<00) ||(vMin>59) || (vSeg<00) || (vSeg>59)){ 
    situacao = "falsa";
  } 
 
  if (HR_VDHora.value == "") {
    situacao = "falsa";
  }
  
  //Sitação Adicionada
  if ((vHra=="") || (vMin=="") || (vSeg=="")) {
    situacao = "falsa";
    }

  if (situacao == "falsa") { 
    alert("Hora inválida!");
    HR_VDHora.value = "";
    HR_VDHora.focus();
    
    return (true);
  }
  else {
    return (false);
  }
}

/********************************************************************** 
Função de formatação de campos tipo texto durante a digitação

Objetivos :
	- Mudar tudo para maiúsculo
	- Não aceitar acentos nem Ç
	
  * Modificação: parametro para limitar TAMANHO do campo
	* Hugo Rogério - 23/12/04	

Parâmetros :
	objeto		-> Nome do campo de formulário (Usar this)
	*tamanho  -> Tamanho limite do campo (Usar valor inteiro)

Exemplo : 
	OnKeyPress    FormataTexto(this);
/**********************************************************************/
function FormataTexto(objeto,tamanho)
{
  var valor = objeto.value;	
	var LetrasArray = new Array();
	
  LetrasArray[1] = new Array();
	LetrasArray[2] = new Array();
	
	//Primeira Coluna : Letras Acentuadas e Símbolos
	LetrasArray[1][1]='á';
	LetrasArray[1][2]='ã';
	LetrasArray[1][3]='à';
	LetrasArray[1][4]='â';
	LetrasArray[1][5]='ä';
	LetrasArray[1][6]='é';
	LetrasArray[1][7]='è';
	LetrasArray[1][8]='ê';
	LetrasArray[1][9]='ë';
	LetrasArray[1][10]='í';
	LetrasArray[1][11]='ì';
	LetrasArray[1][12]='î';
	LetrasArray[1][13]='ï';
	LetrasArray[1][14]='ó';
	LetrasArray[1][15]='õ';
	LetrasArray[1][16]='ò';
	LetrasArray[1][17]='ô';
	LetrasArray[1][18]='ö';
	LetrasArray[1][19]='ú';
	LetrasArray[1][20]='ù';
	LetrasArray[1][21]='û';
	LetrasArray[1][22]='ü';
	LetrasArray[1][23]='ç';
	LetrasArray[1][24]='Á';
	LetrasArray[1][25]='Ã';
	LetrasArray[1][26]='À';
	LetrasArray[1][27]='Â';
	LetrasArray[1][28]='Ä';
	LetrasArray[1][29]='É';
	LetrasArray[1][30]='È';
	LetrasArray[1][31]='Ê';
	LetrasArray[1][32]='Ë';
	LetrasArray[1][33]='Í';
	LetrasArray[1][34]='Ì';
	LetrasArray[1][35]='Î';
	LetrasArray[1][36]='Ï';
	LetrasArray[1][37]='Ó';
	LetrasArray[1][38]='Õ';
	LetrasArray[1][39]='Ò';
	LetrasArray[1][40]='Ô';
	LetrasArray[1][41]='Ö';
	LetrasArray[1][42]='Ú';
	LetrasArray[1][43]='Ù';
	LetrasArray[1][44]='Û';
	LetrasArray[1][45]='Ü';
	LetrasArray[1][46]='Ç';
	LetrasArray[1][47]='Ñ';
	LetrasArray[1][48]='ñ';
	LetrasArray[1][49]='~';
	LetrasArray[1][50]='^';
	LetrasArray[1][51]='´';
	LetrasArray[1][52]='`';
	
	//Segunda Coluna : Letras Equivalentes sem acentos
	LetrasArray[2][1]='a';
	LetrasArray[2][2]='a';
	LetrasArray[2][3]='a';
	LetrasArray[2][4]='a';
	LetrasArray[2][5]='ä';
	LetrasArray[2][6]='e';
	LetrasArray[2][7]='e';
	LetrasArray[2][8]='e';
	LetrasArray[2][9]='e';
	LetrasArray[2][10]='i';
	LetrasArray[2][11]='i';
	LetrasArray[2][12]='i';
	LetrasArray[2][13]='i';
	LetrasArray[2][14]='o';
	LetrasArray[2][15]='o';
	LetrasArray[2][16]='o';
	LetrasArray[2][17]='o';
	LetrasArray[2][18]='o';
	LetrasArray[2][19]='u';
	LetrasArray[2][20]='u';
	LetrasArray[2][21]='u';
	LetrasArray[2][22]='u';
	LetrasArray[2][23]='c';
	LetrasArray[2][24]='A';
	LetrasArray[2][25]='A';
	LetrasArray[2][26]='A';
	LetrasArray[2][27]='A';
	LetrasArray[2][28]='Ä';
	LetrasArray[2][29]='E';
	LetrasArray[2][30]='E';
	LetrasArray[2][31]='E';
	LetrasArray[2][32]='E';
	LetrasArray[2][33]='I';
	LetrasArray[2][34]='I';
	LetrasArray[2][35]='I';
	LetrasArray[2][36]='I';
	LetrasArray[2][37]='O';
	LetrasArray[2][38]='O';
	LetrasArray[2][39]='O';
	LetrasArray[2][40]='O';
	LetrasArray[2][41]='O';
	LetrasArray[2][42]='U';
	LetrasArray[2][43]='U';
	LetrasArray[2][44]='U';
	LetrasArray[2][45]='U';
	LetrasArray[2][46]='C';
	LetrasArray[2][47]='N';
	LetrasArray[2][48]='n';
	LetrasArray[2][49]='';
	LetrasArray[2][50]='';
	LetrasArray[2][51]='';
	LetrasArray[2][52]='';

	temp = "" + valor + (String.fromCharCode(window.event.keyCode));
	
	for (i=1; i<=52 ; i++ )
	{
		while (temp.indexOf((LetrasArray[1][i]))>-1)
			{
				pos  = temp.indexOf((LetrasArray[1][i]));
				temp = "" + (temp.substring(0, pos) + (LetrasArray[2][i]) + temp.substring((pos + (LetrasArray[1][i].length)), temp.length));
			}
	}
	
	if(((window.event.keyCode) != 13))
		{
      objeto.value = (temp.toUpperCase());
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			objeto.value = objeto.value.substr(0,tamanho)
		}
}

/**********************************************************************
Função de formatação de valores numéricos na digitação

Objetivos :
	- Inclusão automática de . e ,

Parametros :
	objeto		-> Nome do campo de formulário (Usar this)
	teclapres	-> Tecla pressionada (Usar event)
	tammax		-> Tamanho máximo de caracteres
	decimais	-> Nº de casas decimais

Exemplo:
	OnKeyDown     FormataValor(this,event,17,0);


/**********************************************************************/ 
function FormataValor(objeto,teclapres,tammax,decimais) 
{

	var tecla			= teclapres.keyCode;
	var tamanhoObjeto	= objeto.value.length;

	if ((tecla == 8) && (tamanhoObjeto == tammax))
	{
		tamanhoObjeto = tamanhoObjeto - 1 ;
	}



if (( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) && ((tamanhoObjeto+1) <= tammax))
	{

		vr	= objeto.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 > 1))
		{
			tam = tam - 1 ;
			vr = objeto.value;
			vr = vr.replace( "/", "" );
			vr = vr.replace( "/", "" );
			vr = vr.replace( ",", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
		}
	
		//Cálculo para casas decimais setadas por parametro
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
		{
			if (decimais > 0)
			{
				if ( (tam <= decimais) )
				{ 
					objeto.value = ("0," + vr) ;
				}
				if( (tam == (decimais + 1)) && (tecla == 8))
				{
					objeto.value = vr.substr( 0, (tam - decimais)) + ',' + vr.substr( tam - (decimais), tam ) ;	
				}
				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) == "0"))
				{
					objeto.value = vr.substr( 1, (tam - (decimais+1))) + ',' + vr.substr( tam - (decimais), tam ) ;
				}
				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) != "0"))
				{
				    objeto.value = vr.substr( 0, tam - decimais ) + ',' + vr.substr( tam - decimais, tam ) ; 
				}
				if ( (tam >= (decimais + 4)) && (tam <= (decimais + 6)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 3) ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
			 	if ( (tam >= (decimais + 7)) && (tam <= (decimais + 9)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 6) ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
				if ( (tam >= (decimais + 10)) && (tam <= (decimais + 12)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 9) ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
				if ( (tam >= (decimais + 13)) && (tam <= (decimais + 15)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 12) ) + '.' + vr.substr( tam - (decimais + 12), 3 ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
			}
			else if(decimais == 0)
			{
				if ( tam <= 3 )
				{ 
			 		objeto.value = vr ;
				}
				if ( (tam >= 4) && (tam <= 6) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr(0, tam - 3) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 7) && (tam <= 9) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 10) && (tam <= 12) )
				{
			 		if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 13) && (tam <= 15) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ) ;
				}			
			}
		}
	}
	else if((window.event.keyCode != 8) && (window.event.keyCode != 9) && (window.event.keyCode != 13) && (window.event.keyCode != 35) && (window.event.keyCode != 36) && (window.event.keyCode != 46))
		{
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
}
