// Procedimentos para evitar cache
document.write("<meta http-equiv='Pragma' content='no-cache'>\n");
document.write("<meta http-equiv='Expires' content='Thu, 01 Jan 1970 00:00:00 GMT'>\n");
document.write("<meta http-equiv='Cache-Control' content='no-store'>\n");
document.write("<meta name='ROBOTS' content='NOINDEX, NOFOLLOW'>\n");


//  Fim dos Procedimentos contra cache


if (window.event)
{
	document.captureEvents(event.MOUSEUP);
	document.captureEvents(event.KeyPress);
}

if (document.layers)
{
	document.captureEvents(Event.MOUSEDOWN);
	document.captureEvents(Event.KEYDOWN);
}


String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g, "").replace(/\s+/g," ");
 }


// Funções de Compatibilidade

function setpGetElemefntById(id)
{
	if (document.getElementById(id))
	return document.getElementById(id);
	else if (document.all[id])
	return document.all[id];
	else if (document.layers && document.layers[id])
	return (document.layers[id]);
	else
	return false;
}


/*
   use a função DesligaEnter() do PHP
   ou declare <script>autorizaEnter=false;</script>
   no início da página que não quer
   enter automático.

   A variável scriptEnter server para substituir a ação SUBMIT
   por uma função em javascript.

   A função ENTER fica desativada em campos longos gerados pelo PHP,
   se utilizar manual, declare: 
         OnFocus='javascript:autorizaEnter=false;'
         OnBlur='javascript:autorizaEnter=true;'
*/

   var autorizaEnter = true; 
   var scriptEnter="";
   var MudarCampo = true;
   //var autorizaTab = true;

   //Se autorizaTab false desliga o evento onkeypress para tabulação automática e true liga
   function AutorizaTab(bAutorizaTab){
      if (bAutorizaTab) {
         document.onkeypress = HabilitarTABAutom;
      }
      return bAutorizaTab;
   }

   //function desligaTab(autorizaTab){      
      //if (autorizaTab) {
      //   document.onkeypress = HabilitarTABAutom;
      //}
   //   return autorizaTab;      
   //}

function Enter(event, nForm)
{
   if (autorizaEnter==false)
      return ;

   var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
      if (scriptEnter=="")
   		Submeter(nForm);
      else
         eval(scriptEnter);
	}
	return false;
}

/*
   Corrigir Imagens transparentes PNG - Win IE 5.5 & 6.
   Gerar na página html a linha abaixo da forma que se apresenta, inclusive com comentários:
   <!--[if lt IE 7]><script>if (window.attachEvent) {window.attachEvent('onload', correctPNG);}</script><![endif]-->
*/


function correctPNG() 
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])

   if ((version >= 5.5) && (document.body.filters))
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }   
}


function ValidaIP(id,bAviso)
{
   if (document.getElementById(id).value.length <=0 )
      return true;

   var ipRegExp = /^(([1]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}([1]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))$/;
   var ipValido = document.getElementById(id).value.match(ipRegExp);
   if (ipValido==null)
   {
      document.getElementById(id).value='';
      PoeFoco(id,0);
      if (bAviso)
         alert("Endereço IP inválido ou fora da faixa permitida. Verifique! ");
      return false;
   }
   else
      return true;
}


function ValidaCEI(cpoCEI,aviso)
{
	if (cpoCEI.value.length==0)
	return true;

	var localcei = cpoCEI.value;
	var calculo = 0;
	var subst = localcei.substring(0,10);
	var digito = 0;
	var digit = 0;

	if(localcei.length == 0)
	return true;

	calculo = (parseInt(localcei.substring(0,1), 10) * 7) +
	(parseInt(localcei.substring(1, 2),10) * 4) +
	(parseInt(localcei.substring(2, 3),10) * 1) +
	(parseInt(localcei.substring(3, 4),10) * 8) +
	(parseInt(localcei.substring(4, 5),10) * 5) +
	(parseInt(localcei.substring(5, 6),10) * 2) +
	(parseInt(localcei.substring(6, 7),10) * 1) +
	(parseInt(localcei.substring(7, 8),10) * 6) +
	(parseInt(localcei.substring(8, 9),10) * 3) +
	(parseInt(localcei.substring(9, 10),10) * 7) +
	(parseInt(localcei.substring(10, 11),10) * 4);

	calculo = calculo.toString();
	var size = calculo.length;
	digito = parseInt(calculo.substring((size-2),(size-1)),10) + parseInt(calculo.substring((size-1), size));
	digito = digito.toString();
	size = digito.length;
	digit = parseInt(digito.substring((size-1),size), 10);

	if(digit != 0)
	digit = 10 - digit;

	digito = localcei.substring(11,12)

	if(digito == digit)
	return true;
	else
	{
		if (aviso==1)
		alert("O número do CEI informado não é válido. Por favor verifique.");
      _chave = cpoCei.name;
      //_chave = _chave + ".focus()";
      if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";
		setTimeout(_chave,50);
		return false;
	}
}



function ValidaEmail(cpoEmail,aviso)
{
	//var chars="?!´`,;<>~§º%¨@#$&[]()/\\\{}!^:'\"";
   var chars="çáéíóúÁÉÍÓÚÇ*+¨äëïöü°|;¬£¢³²¹ª?!´`,;<>~§º%¨@#$&[]()/\\\{}!^:'\"";
	var pat=/^(.+)@(.+)$/;
	var emaildiv = cpoEmail.value.match(pat);
	var formOk = true;
	var strMaiusculo="";

	if (cpoEmail.value.length==0)
	return true;

	if (cpoEmail.value.toUpperCase()==cpoEmail.value)
	{
		strMaiusculo ="Seu e-mail foi digitado em letras maiúsculas. ";
		strMaiusculo+="Você tem certeza de que isso está correto?\n";
		strMaiusculo+="Normalmente os endereços de e-mail são em letras minúsculas.\n";
		strMaiusculo+="Por favor, se estiver errado corrija, para evitar transtornos no ";
		strMaiusculo+="recebimento das mensagens direcionadas à você.";
		alert(strMaiusculo);
	}

	if (emaildiv==null)
	formOk = false;
	else
	{
		var login =emaildiv[1];
		var server=emaildiv[2];

      for(var i=0;i<chars.length;i++)
		   if(login.indexOf(chars.substr(i,1))!=-1)
		      formOk = false;

      for(var i=0;i<chars.length;i++)
		   if(server.indexOf(chars.substr(i,1))!=-1)
		      formOk = false;
	}

	if (cpoEmail.value.indexOf("@.")!=-1)
	{
		formOk = false;
	}

   if (cpoEmail.value.indexOf("..")!=-1)
	{
		formOk = false;
	}

	if (!formOk)
	{
		if (aviso==1)
		alert("e-mail inválido: Caracteres não permitidos, ou formação inválida.");
		cpoEmail.value='';
      _chave = cpoEmail.name;
      //_chave = _chave + ".focus()";
      if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";
		setTimeout(_chave,50);

	}
	return formOk;
}

function Maiusculo(strCpo)
{
	strCpo.value=strCpo.value.toUpperCase();
	return true;
}

function Minusculo(strCpo)
{
	strCpo.value=strCpo.value.toLowerCase();
	return true;
}

function ReplicaStr(strValor,nVezes)
{
	var strRetorno='';
	for (var i=1; i<=nVezes ; i++)
	strRetorno+=strValor;
	return(strRetorno);
}

/*function ValidaCPF(cpoCPF,aviso)
{
	var FormOk   = false;
	var NumAux   = 0;
	var NumAux2  = 0;
	var Digito1  = 0;
	var Digito2  = 0;
	var NumCPF   = Trim(cpoCPF.value);
	var Bytes    = 0;
	var PrimeiroByte = NumCPF.substring(0,1);
	var controle;

   _chave = cpoCPF.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus();";


	if(NumCPF.length>0 )
	{
		if (NumCPF==ReplicaStr(PrimeiroByte,NumCPF.length))
		{
			//if (aviso==1)
			alert ('CPF Inválido, número não permitido');
			cpoCPF.value = '';
         setTimeout(_chave,50);
			return false;
		}
	}
	if (NumCPF.length>0 ) {
		if (NumCPF.length<11) {
			if (aviso==1) {
				alert('Tamanho Inválido: O CPF deve possuir 11 dígitos.');
			}
		}
		else {
			NumAux2 = 2
			for ( var contador=9 ; contador > 0 ; contador-=1 )
			{
				Bytes = parseInt(NumCPF.substring(contador-1,contador),10);
				NumAux+=Bytes*NumAux2;
				NumAux2+=1;
			}
			Digito1 = 11 - (NumAux % 11 )
			if (Digito1 > 9) {
				Digito1 = 0;
			}
			NumAux2 = 3
			NumAux  = 0
			for ( var contador=9 ; contador > 0 ; contador-=1 )
			{
				Bytes = parseInt(NumCPF.substring(contador-1,contador),10);
				NumAux +=Bytes*NumAux2;
				NumAux2+=1;
			}
			Digito2 = 11 - ((Digito1 * 2 + NumAux) % 11)
			if (Digito2 > 9) {
				Digito2 = 0;
			}
			if ( (Digito1*10+Digito2) == (parseInt(NumCPF.substring(9,11),10)) ) {
				FormOk = true;
			}
			else {
				if (aviso==1) {
					alert('Número Inválido: O CPF informado está incorreto, verifique.');
				}
			}
		}
	}
	else {
		FormOk=true;
	}
	if (FormOk==false) {
      setTimeout(_chave,50);

	}
	return (FormOk);
}
*/
function ValidaCPF(cpoCPF,aviso)
{
//alert(cpoCPF.value);
   var FormOk   = false;
	var NumAux   = 0;
	var NumAux2  = 0;
	var Digito1  = 0;
	var Digito2  = 0;
   if (cpoCPF.value == "undefined")
   {
      var NumCPF = '';   
   }
   else
   {
      var NumCPF = Trim(cpoCPF.value);
   }
//   var NumCPF   = Trim(cpoCPF.value);
//alert(NumCPF);
   var Bytes    = 0;
	var PrimeiroByte = NumCPF.substring(0,1);
	var controle;

   _chave = cpoCPF.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";


	if(NumCPF.length>0 )
	{
		if (NumCPF==ReplicaStr(PrimeiroByte,NumCPF.length))
		{
			//if (aviso==1)
			alert ('CPF Inválido, número não permitido');
			cpoCPF.value = '';
         setTimeout(_chave,50);
			return false;
		}
	}
	if (NumCPF.length>0 ) {
		if (NumCPF.length<11) {
			if (aviso==1) {
				alert('Tamanho Inválido: O CPF deve possuir 11 dígitos.');
			}
		}
		else {
			NumAux2 = 2
			for ( var contador=9 ; contador > 0 ; contador-=1 )
			{
				Bytes = parseInt(NumCPF.substring(contador-1,contador),10);
				NumAux+=Bytes*NumAux2;
				NumAux2+=1;
			}
			Digito1 = 11 - (NumAux % 11 )
			if (Digito1 > 9) {
				Digito1 = 0;
			}
			NumAux2 = 3
			NumAux  = 0
			for ( var contador=9 ; contador > 0 ; contador-=1 )
			{
				Bytes = parseInt(NumCPF.substring(contador-1,contador),10);
				NumAux +=Bytes*NumAux2;
				NumAux2+=1;
			}
			Digito2 = 11 - ((Digito1 * 2 + NumAux) % 11)
			if (Digito2 > 9) {
				Digito2 = 0;
			}
			if ( (Digito1*10+Digito2) == (parseInt(NumCPF.substring(9,11),10)) ) {
				FormOk = true;
			}
			else {
				if (aviso==1) {
					alert('Número Inválido: O CPF informado está incorreto, verifique.');
				}
			}
		}
	}
	else {
		FormOk=true;
	}
	if (FormOk==false) {
      setTimeout(_chave,50);
	}
	return (FormOk);
}

function ValidaCNPJ(cpoCNPJ,aviso)
{
	var cnpj = cpoCNPJ.value;
	var FormOk = true;
	var aux_cnpj = "";
	var cnpj1=0,cnpj2=0;

   _chave = cpoCNPJ.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (cpoCNPJ.value.length>0)
	{
		for(j=0;j<cnpj.length;j++)
		if(cnpj.substr(j,1)>="0" && cnpj.substr(j,1)<="9")
		aux_cnpj += cnpj.substr(j,1);
		if(aux_cnpj.length!=14)
		FormOk = false;
		else
		{
			cnpj1 = aux_cnpj.substr(0,12);
			cnpj2 = aux_cnpj.substr(aux_cnpj.length-2,2);
			fator = "543298765432";
			controle = "";
			for(j=0;j<2;j++)
			{
				soma = 0;
				for(i=0;i<12;i++)
				soma += cnpj1.substr(i,1) * fator.substr(i,1);
				if(j==1) soma += digito * 2;
				digito = (soma * 10) % 11;
				if(digito==10) digito = 0;
				controle += digito;
				fator = "654329876543";
			}
			if(controle!=cnpj2 || cnpj=='00000000000000' )
			FormOk = false;
		}
	}
	else
	FormOK = true;

	if (aviso==true && FormOk==false)
	   alert('CNPJ Inválido. Verifique o valor digitado e corrija.');

	if (FormOk==false)
      setTimeout(_chave,50);
	return (FormOk);
}

function ValidaCpfCnpj(objCampo,aviso)
{
	if(objCampo.value.length>11)
	return(ValidaCNPJ(objCampo,true));
	else
	return(ValidaCPF(objCampo,true));
}

function ValidaTitulo(objCampo,aviso)
{
	var nTitulo=objCampo.value;
	var strTitulo=objCampo.value;
	var nDig1  = 0;
	var nDig2  = 0;
	var nSoma  = 0;
	var nResto = 0;
	var bRetorno=true;

   _chave = objCampo.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";


	if (nTitulo.length>=9)
	{
		strTitulo = strZero(strTitulo,13);
		nSoma=strTitulo.substr(0,1)*2+strTitulo.substr(1,1)*9+strTitulo.substr(2,1)*8
		+strTitulo.substr(3,1)*7+strTitulo.substr(4,1)*6+strTitulo.substr(5,1)*5
		+strTitulo.substr(6,1)*4+strTitulo.substr(7,1)*3+strTitulo.substr(8,1)*2;

		nResto= (nSoma % 11);

		if (nResto==0 || nResto==1)
		{
			if(strTitulo.substr(9,2)=="01" || strTitulo.substr(9,2)=="02")
			if (nResto==0)
			nDig1=1;
		}
		else
		nDig1=11-nResto;

		nSoma=strTitulo.substr(9,1)*4 + strTitulo.substr(10,1)*3 + nDig1*2;
		nResto= (nSoma % 11);

		if (nResto==0 || nResto==1)
		{
			if(strTitulo.substr(9,2)=="01" || strTitulo.substr(9,2)=="02")
			if (nResto==0)
			nDig2=1;
		}
		else
		nDig2=11-nResto;

		if (strTitulo.substr(11,1) != nDig1 || strTitulo.substr(12,1) != nDig2 )
		bRetorno=false;


		alert(nDig1+" "+nDig2 + " " + strTitulo )
	}
	else if (nTitulo.length>0 && nTitulo.length<11)
	{
		bRetorno=false;
	}

	if (aviso==true && bRetorno==false)
	alert("Título de Eleitor Inválido. Verifique o valor digitado e corrija.");

	if (bRetorno==false)
      setTimeout(_chave,50);

	return (bRetorno);
}

   function strZero(nNumero,nBytes)
   {
      var strRetorno;
      var strNumero = new String(nNumero);
      if (strNumero.length==nBytes)
         return strNumero;
      else
      {
         strRetorno=strNumero;
         for (var i=1;i<=nBytes-strNumero.length;i++)
            strRetorno ="0"+strRetorno;
         return strRetorno;
      }
   }


function HoraLimite(hrInicio,hrFinal)
{

	var hrIni = hrInicio.value.substr(0,2);
	var hrFim = hrFinal.value.substr(0,2);
	//alert(hrFim);

	if(hrFim<hrIni)
	{
		alert("Hora Inválido. Horário final é menor do que horário inicial.");
		hrFinal.value="";
		setTimeout("hrFinal.focus()",50);
		return false;
	}
	else
	{
		return true;
	}

}


function DataTamanho(dtInicio,dtFinal)
{
   var dtIni = dtInicio.value.substr(6,4)+dtInicio.value.substr(3,2)+dtInicio.value.substr(0,2);  
	var dtFim = dtFinal.value.substr(6,4)+dtFinal.value.substr(3,2) +dtFinal.value.substr(0,2);
   
	if(dtFim<dtIni) {
		alert("Período Inválido. Data final é menor do que data inicial.");
		dtFinal.value="";
		setTimeout("dtFinal.focus()",50);
		return false;
	}
	else {
		return true;
	}
}

function HoraTamanho(hrInicio,hrFinal)
{

	var hrIni = hrInicio.value.substr(0,2);
	var hrFim  = hrFinal.value.substr(0,2);

	if(hrFim<=hrIni)
	{
		alert("Período Inválido. Hora final é menor do que hora inicial.");
		hrInicio.value="";
		setTimeout("hrFinal.focus()",50);
		return false;
	}
	else
	{
		return true;
	}

}


function DataLimite(cpoData,dtInicio,dtFinal)
{
	if (cpoData.value=="")
	{
		return true;
	}

	ValidaData(cpoData,false);

/*	var dtIni = new Date(Ano(dtInicio),Mes(dtInicio),Dia(dtInicio));
	var dtFim = new Date(Ano(dtFinal),Mes(dtFinal),Dia(dtFinal));
	var dtDig = new Date(Ano(cpoData.value),Mes(cpoData.value),Dia(cpoData.value)); */

	var dtIni = dtInicio.substr(6)+dtInicio.substr(3,2)+dtInicio.substr(0,2);
	var dtFim = dtFinal.substr(6)+dtFinal.substr(3,2)+dtFinal.substr(0,2);
	var dtDig = cpoData.value.substr(6)+cpoData.value.substr(3,2)+cpoData.value.substr(0,2);

   _chave = cpoData.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (dtDig >=dtIni && dtDig<=dtFim )
	{
		return true;
	}
	else
	{
		alert("A data máxima para esta consulta é: "+dtFinal);
		cpoData.value=dtFinal;
		setTimeout(_chave,50);
		return false;
	}
}

function Dia(dtDia)
{
	return (dtDia.substr(0,2));
}

function Mes(dtDia)
{
	return (dtDia.substr(3,2));
}

function Ano(dtDia)
{
	return (dtDia.substr(6,4));
}

function NaoBarra(strData)
{
	var retorno=true;
	for(var i=0;i<strData.length;i++)
	if(strData.indexOf("/")!=-1)
	retorno = false;
	return retorno;
}

   function MascaraData(cpoData,objEvento)
   {
      var  strData=cpoData.value;
      var  nBytes =strData.length;
      var  nTecla = 0 ;

      if (window.Event)           // Mozilla
      nTecla=objEvento.which;
      else
      nTecla=event.keyCode;

      if((nBytes==2 || nBytes==5) && (nTecla >=48 && nTecla <=57) )
      cpoData.value=strData+"/";

      return true;
   }

function MascaraHora(cpoData, objEvento)
{
	var  strData=cpoData.value;
	var  nBytes =strData.length;

	if (window.Event)          // Mozilla
	nTecla=objEvento.which;
	else
	nTecla=event.keyCode;

	if((nBytes==2) && (nTecla >=48 && nTecla <=57))
	cpoData.value=strData+":";

	return true;
}

   /*function ValidaHora(cpoHora,aviso)
   {
      var nHora = cpoHora.value.substr(0,2);
      var nMin  = cpoHora.value.substr(3,2);
      var bRetorno = true;
      var strMensagem="";

      _chave = cpoHora.name;
      //_chave = _chave + ".focus()";
      if(document.getElementById(_chave))
         _chave = "document.getElementById('"+_chave+"').focus()";

      if (nHora>23 && nMin>59)
      {
         bRetorno=false;
         strMensagem='Horário Inválido! Deve estar entre 00:00 e 23:59';
      }
      else if (nHora <0 || nHora >23)
      {
         bRetorno=false;
         strMensagem='Hora Inválida! Deve estar entre 00 e 23';
      }
      else if (nMin < 0 || nMin > 59)
      {
         bRetorno=false;
         strMensagem='Minuto Inválido! Deve estar entre 0 e 59';
      }

      if (aviso==true && bRetorno==false)
      {
         alert (strMensagem);
         setTimeout(_chave,50);
      }

      return bRetorno;
   }*/

   function ValidaHora(cpoHora,aviso)
   {
      var nHora = cpoHora.value.substr(0,2);
      var nMin  = cpoHora.value.substr(3,2);
      
      nHora = strZero(nHora,2);
      nMin  = strZero(nMin,2);

      cpoHora.value=nHora+":"+nMin;
      
      var bRetorno = true;
      var strMensagem="";

      _chave = cpoHora.name;
      //_chave = _chave + ".focus()";

      if(document.getElementById(_chave))
         _chave = "document.getElementById('"+_chave+"').focus()";


      if (nHora>24 && nMin>0)
      {
         bRetorno=false;
         strMensagem='Horário Inválido! Deve estar entre 00:00 e 24:00';
      }
      else if (nHora <0 || nHora >24)
      {
         bRetorno=false;
         strMensagem='Hora Inválida! Deve estar entre 00 e 24';
      }
      else if (nMin < 0 || nMin > 59)
      {
         bRetorno=false;
         strMensagem='Minuto Inválido! Deve estar entre 0 e 59';
      }

      if (aviso==true && bRetorno==false)
      {
         alert (strMensagem);
         setTimeout(_chave,50);
      }

      return bRetorno;
   }

function ValidaData(cpoData,aviso)
{
	var strData = cpoData.value;

	if (strData.length==6)
	strData = strData.substr(0,2)+"/"+strData.substr(2,2)+"/"+strData.substr(4,2);
	else if (strData.length==8 && NaoBarra(strData))
	strData = strData.substr(0,2)+"/"+strData.substr(2,2)+"/"+strData.substr(4,4);

	var datePat=/^(\d{1,2})(\/|-|.)(\d{1,2})\2(\d{2,4})$/;
	var datadiv = strData.match(datePat);

	datadiv = strData.match(datePat);

   _chave = cpoData.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (strData.length==0)
	return true;

	if (datadiv==null)
	{
		alert('Data Inválida: Caracteres não permitidos ou tamanho inválido');
		cpoData.value="";
		setTimeout(_chave,50);
		return false;
	}

	var dia     = datadiv[1];
	var mes     = datadiv[3];
	var ano     = datadiv[4];
	var FormOk  = true;

	if (ano.length < 3)
	{
		if (parseInt(ano) > 30)
		{
			ano = parseInt(ano)+1900;
		}
		else
		{
			ano = parseInt(ano)+2000;
		}
	}
	else
	{
		if(ano.length==4 || ano.length==3)

		if(ano < 1900 )
		{
			if (aviso==1)
			{
				alert('Data Inválida: dia, mês ou ano fora do escopo.');
    		    cpoData.value='';
				setTimeout(_chave,50);

			}
			FormOk=false;
		}
	}


	var strNovaData = strZero(dia,2)+"/"+strZero(mes,2)+"/"+ano;

	if(dia<1 || dia>31 || mes<1 || mes>12 ) {
		if (aviso==1) {
			alert('Data Inválida: dia, mês ou ano fora do escopo.');
		    cpoData.value='';
			setTimeout(_chave,50);
		}
		FormOk=false;
	}
	if ((mes==4 || mes==6 || mes==9 || mes==11) && dia>30) {
		if (aviso==1) {
			alert('Data Inválida: Este mês não pode ter mais do que 30 dias.');
		    cpoData.value='';
			setTimeout(_chave,50);
		}
		FormOk=false;
	}
	if(mes==2) {
		if(dia>29) {
			if (aviso==1) {
				alert('O mês é fevereiro e o dia não pode ser maior que 29.');
			    cpoData.value='';
				setTimeout(_chave,50);
			}
			FormOk=false;
		}
		if(dia==29 && ! (Bissexto(ano)) ) {
			if (aviso==1) {
				alert('Data inválida: Esse ano não é bissexto.');
			    cpoData.value='';
				setTimeout(_chave,50);
			}
			FormOk=false;
		}
	}
	if (FormOk==false) {
		setTimeout(_chave,50);
	}
	if (FormOk)
	cpoData.value=strNovaData;
	return (FormOk);
}


function Bissexto(ano)
{
	if (ano % 100 == 0) {
		if (ano % 400 == 0) {
			return true;
		}
	}
	else {
		if ((ano % 4) == 0) {
			return true;
		}
		return false;
	}
}


function Ajuda()
{
	var strNomeForm = document.forms[0].name;
	var strNomeFoco = document.forms[0].FocoAnterior.value;
	AbreJanela('Ajuda.php?strTela='+strNomeForm+'&strFoco='+strNomeFoco);
	return;
}

function RegistraFoco(strNomeCampo)
{
	document.forms[0].FocoAnterior.value=strNomeCampo;
	//alert(document.forms[0].FocoAnterior.value);
	return true;
}


function TituloCombo(strCombo,strCampo)
{
	var nPos     = strCombo.selectedIndex;
	var strTexto = strCombo.options[nPos].text;

	strCampo.value=strTexto;

	//alert("Valor do Campo Oculto: "+document.forms[0].strCombo.value);
	//alert (strTexto);
}

function EnviaSubmit(nForm)
{
	//LayerAlerta('Aguarde, processando...');
	document.forms[nForm].submit();
}

function SubmitRedireciona(nForm,strRediciona)
{
	//LayerAlerta('Aguarde, processando...');
	if (document.formName != "") {
		document.forms[nForm].submit();
		location.href = strRediciona;
	}
}

function Excluir(strCampo)
{
	strCampo.value="E";
	document.forms[0].submit();
}

function Alterar(strCampo)
{
	strCampo.value="A";
	document.forms[0].submit();
}
function Incluir(strCampo)
{
	strCampo.value="I";
	document.forms[0].submit();
}

function Submeter(nForm)
{
	if (CamposObrigatorios())
	   EnviaSubmit(nForm);
	else
	   return false;
}

function SubmeterTrabalhador(nForm,tab,id,old)
{
	document.forms[0].tab.value    = tab ;
	document.forms[0].id.value     = id ;
	document.forms[0].idOLD.value  = old ;

	if (CamposObrigatorios())
	EnviaSubmit(nForm);
	/*  else
	{
	// alert('erro!!!!!');
	return false;
	}*/
}

function SubSetAcao(chAcao,nForm)
{
	document.forms[nForm].acao.value=chAcao;
	EnviaSubmit(nForm);
}

function subForm()
{
	document.forms[0].submit();
}

function FocoInicial(nForm)
{
	var nItensForm=document.forms[nForm].length;
	var strCampo;
	var bFoco=false;
	for (var j=0;j<nItensForm;j++)
	{
		strCampo=document.forms[nForm].elements[j];
		if (strCampo.type!="hidden" && strCampo.type !="radio" && strCampo.type != "checkbox" ){
			bFoco=true;
			break;
		}
	}

   if (bFoco)
   {
	   _chave = strCampo.name;
      //alert(document.getElementById(_chave));
      if(document.getElementById(_chave)) {
	      _chave = "document.getElementById('"+_chave+"').focus()";
         setTimeout(_chave,50);
      }      
   }
   return;
}

function PoeFoco(strCampo,nForm)
{
   if (isNaN(nForm))
      nForm=0;

   if (typeof(strCampo)=="undefined")
      return true;

   if (document.getElementById(strCampo))
	   if (document.getElementById(strCampo).type == "hidden")
		  return true;

   if (document.getElementById(strCampo))
      var strFoco = "document.getElementById('"+strCampo+"').focus()";
   else if (parent.frames[0].document.getElementById(strCampo))
      var strFoco = "parent.frames[0].document.getElementById('"+strCampo+"').focus()";
   else
   {
      var strNomeForm=document.forms[nForm].name ;
      var strFoco = "document."+strNomeForm+"."+ strCampo + ".focus()";   
   }

   setTimeout(strFoco,30);
   return true;
}

function CamposObrigatorios()
{
   var nItensForm=document.forms[0].length;
   var nItensObri=cpoObrigatorio.length;
   var bRetorno=true;
   var strNomeCampo;
   var strValorCampo;
   var strLista="";
   var imgErrado = new Image();
   var imgInvisivel = new Image();
   var strFocoCampo;
   var bFoco=false;
   imgErrado.src='/fig/pt_errado.gif';
   imgInvisivel.src='/fig/pt_nulo.gif';
   var strNomeImg = "";

   for (var i=0;i<=nItensObri;i++)
   for (var j=0;j<nItensForm;j++)
   {
      strNomeCampo=document.forms[0].elements[j].name;

      if (strNomeCampo==cpoObrigatorio[i])
      {
         strValorCampo=Trim(document.forms[0].elements[j].value);
         strNomeImg="img"+cpoObrigatorio[i];
         if (document.forms[0].elements[j].type=="select-one") //!=select
         {
            if (document.forms[0].elements[j].value==-1)
            {
               strLista += '\r'+strNomeCampo;
               eval("document.forms[0]."+strNomeImg+".src=imgErrado.src")
               bRetorno=false;
               if (bFoco==false  && document.forms[0].elements[j].type!="hidden")
               {
                  strFocoCampo=document.forms[0].elements[j];
                  bFoco=true;
               }
               break;
            }
         }
         //inicio - adicionado suporte à campo radio, Ricardo Spinoza - 12/05/2009
         if (document.forms[0].elements[j].type=="radio")
         {
            var nroItem = 0;
            var bRadioChecked = false;
            do {
               if (document.getElementById(document.forms[0].elements[j].name + nroItem).checked == true) {
                  bRadioChecked = true;
                  break;
               }
               nroItem++;
            }
            while (document.getElementById(document.forms[0].elements[j].name + nroItem) != null);
            
            if (!bRadioChecked){                  
               strLista += '\r'+strNomeCampo;
               eval("document.forms[0]."+strNomeImg+".src=imgErrado.src");
               bRetorno=false;
               if (bFoco==false  && document.forms[0].elements[j].type!="hidden") {
                  strFocoCampo=document.forms[0].elements[j];
                  bFoco=true;
               }
               break;
            }
         }
         //fim - adicionado suporte à campo radio, Ricardo Spinoza - 12/05/2009
         if ((strValorCampo.length<=0)||(strValorCampo.value=""))
         {
            strLista += '\r'+strNomeCampo;
            eval("document.forms[0]."+strNomeImg+".src=imgErrado.src");
            if (bFoco==false && document.forms[0].elements[j].type!="hidden")
            {
               strFocoCampo=document.forms[0].elements[j];
               bFoco=true;
            }
            bRetorno=false;
            break;
         }
         else
            eval("document.forms[0]."+strNomeImg+".src=imgInvisivel.src");
         break;
      }
   }
   if (!bRetorno)
   {
      //strFocoCampo.focus();
      alert("Existem campos obrigatórios a serem preenchidos. Verifique...\n");
      if (bFoco)
         PoeFoco(strFocoCampo.name,0);
   }
   return bRetorno;
}

function JanelaNormal(url)
{
   janela=window.open(url,"","directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no,top=0");
   return;
}


function AbreComp(url,bEsconder) {
	if (isNaN(bEsconder))
	var bEsconder=false;

	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	if(versao <4 && browser == "Microsoft Internet Explorer") {
		alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
		return false;
	}
	if (bEsconder==false)
	if(browser == 'Netscape') {
		return window.open(url,"","directories=no,height=390,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=800,top=10,left=65");
	}
	else {
		if(versao > 4) {
			return window.open(url,"","directories=no,height=390,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=800,top=10,left=65");
		}
		else {
			return window.open(url,"","directories=no,height=390,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=800,top=10,left=65");
		}
	}
	else
	return window.open("","","directories=no,border=0,color=#ffffff,height=5,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=5,top=0,left=4000");
	;
}

function AbreJanela(url,bEsconder) {

	return AbrePopUp(url,bEsconder,200,400,true);

	//  11/11/2005 - Eraldo  - Esta função, foi inutilizada. Favor utilizar a função AbrePopUp

	/*
	if (isNaN(bEsconder))
	var bEsconder=false;

	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	if(versao <4 && browser == "Microsoft Internet Explorer") {
	alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
	return false;
	}
	if (bEsconder==false)
	if(browser == 'Netscape') {
	return window.open(url,"","directories=no,height=200,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=400,top=10,left=365");
	}
	else {
	if(versao > 4) {
	return window.open(url,"","directories=no,height=200,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=400,top=10,left=365");
	}
	else {
	return window.open(url,"","directories=no,height=200,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=400,top=10,left=365");
	}
	}
	else
	return window.open("","","directories=no,border=0,color=#ffffff,height=0,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=1,top=0,left=4000");
	;

	*/
}

function AbrePopUp(url,bEsconder,nHeigh,nWidth,bRetorno) {
	var novajanela;
	if (isNaN(bEsconder))
	var bEsconder=false;

	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	if(versao <4 && browser == "Microsoft Internet Explorer") {
		alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
		return false;
	}
	if (bEsconder==false) {
		if(browser == 'Netscape') {
			novajanela = window.open(url,"","directories=no,height="+ nHeigh +",location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no,width="+ nWidth +",top=10,left=365");
		}
		else {
			if(versao > 4) {
				novajanela = window.open(url,"","directories=no,height="+nHeigh+",location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no,width="+nWidth+",top=10,left=365");
			}
			else {
				novajanela =  window.open(url,"","directories=no,height="+nHeigh+",location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no,width="+nWidth+",top=10,left=365");
			}
		}
	}
	else
	   novajanela= window.open("","","directories=no,border=0,color=#ffffff,height=0,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=0,top=0,left=0");
	if (bRetorno)
	{
		return novajanela;
	}

	;
}


//Crei um nova função abre pop-up (AbrePopUp2)alterando apenas o height e o weight
//permanecendo a original como estava

function AbrePopUp2(url,bEsconder,nHeigh,nWidth,bRetorno) {
	var novajanela;
	if (isNaN(bEsconder))
	   var bEsconder=false;

	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	if(versao <4 && browser == "Microsoft Internet Explorer") {
		alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
		return false;
	}
	if (bEsconder==false) {
		if(browser == 'Netscape') {
			novajanela = window.open(url,"","directories=no,height=480,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=640,top=10,left=100");
		}
		else {
			if(versao > 4) {
				novajanela = window.open(url,"","directories=no,height=600,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=800,top=10,left=100");
			}
			else {
				novajanela =  window.open(url,"","directories=no,height=600,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=800,top=10,left=100");
			}
		}
	}
	else
      novajanela= window.open("","","directories=no,border=0,color=#ffffff,height=0,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=0,top=0,left=4000");

	if (bRetorno)
	{
		return novajanela;
	}
}

function LogoJanela(url,bEsconder) {
	if (isNaN(bEsconder))
	var bEsconder=false;

	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	if(versao <4 && browser == "Microsoft Internet Explorer") {
		alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
		return false;
	}
	if (bEsconder==false)
	if(browser == 'Netscape') {
		return window.open(url,"","directories=no,height=460,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=435,top=10,left=365");
	}
	else {
		if(versao > 4) {
			return window.open(url,"","directories=no,height=460,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=435,top=10,left=365");
		}
		else {
			return window.open(url,"","directories=no,height=460,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=435,top=10,left=365");
		}
	}
	else
	return window.open("","","directories=no,border=0,color=#ffffff,height=5,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=5,top=0,left=4000");
	;
}

function AbreJanelaGrande(url,bEsconder) {
	if (isNaN(bEsconder))
	var bEsconder=false;

	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	if (versao <4 && browser == "Microsoft Internet Explorer") {
		alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
		return false;
	}
	if (bEsconder==false)
	if (browser == 'Netscape') {
		return window.open(url,"","directories=no,height=400,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=560,top=10,left=365");
	}
	else {
		if (versao > 4) {
			return window.open(url,"","directories=no,height=400,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=560,top=10,left=365");
		}
		else {
			return window.open(url,"","directories=no,height=400,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=560,top=10,left=365");
		}
	}
	else
	return window.open("","","directories=no,border=0,color=#ffffff,height=5,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=5,top=0,left=4000");
	;
}

function Redir(strUrl,nTempo)
{
	setTimeout("window.location.href=\'"+strUrl+"\'",nTempo);
	return;
}

function Redireciona(strUrl,nTempo)
{
	strInicio = new Date();
	nInicio  = strInicio.getTime();
	nAtual   = 0;
	while ((nInicio+nTempo*1000)>nAtual )
	{
		strHora = new Date();
		nAtual  = strHora.getTime();
	}
	window.location.href=strUrl;
	return;
}

function ValidaSenha(strSenha,strLogin)
{

	if (strSenha.value.length<=0)
	   return true;

	var strReservado = new Array (10);
	var bRetorno=true;
	var strMsg="";

	strReservado[1]="SENHA";
	strReservado[2]="PARANA";
	strReservado[3]="SERT";
	strReservado[4]="SEMPRE";
	strReservado[5]="SINE";
	strReservado[6]="SETP";
	strReservado[7]="ACESSO";
	strReservado[8]="CCTG";
	strReservado[9]="GUAIRA";
	strReservado[10]="TEATRO";

	for (var i=1;i<=10 ;i++ )
	{
		if (strSenha.value.toUpperCase()==strReservado[i])
		{
			strMsg +="Não é permitido usar esta senha, ela é muito comum.\n";
			bRetorno=false;
			break;
		}
	}

	if(strLogin.value.toUpperCase()==strSenha.value.toUpperCase())
	{
		strMsg +="Sua Senha Não pode ser igual ao login.\n";
		bRetorno=false;
	}

	if( numero (strSenha.value.substr(0,1)))
	{
		strMsg +="Sua Senha não pode começar com números, deve ter no mínimo uma letra no início.\n";
		bRetorno=false;
	}

	if ( strSenha.value.length < 6)
	{
		strMsg +="Sua Senha não pode ter menos do que 6 (seis) dígitos\n";
		bRetorno=false;
	}

	if (strSenha.value.indexOf(" ")!=-1)
	{
		strMsg +="Sua Senha não pode conter espaços em branco\n";
		bRetorno=false;
	}

	if (bRetorno==false)
	{
		alert(strMsg);
		strSenha.value="";
		PoeFoco(strSenha.name,0);
		return false;
	}

}

function charProibido(objCampo)
{
	if (objCampo.value.length<=0)
	return true;

	var strCaracter=".>,<;:/?~^]}[\{´`=+-)(*&¨%$#@!'\\|ªº§°¹²³£¢\"¬ãäáàâéêèëíìïîóòöõôúùüûñÃÄÁÀÂÉÊÈËÍÌÏÎÓÒÖÕÔÚÙÜÛÑ ";
	var bRetorno=true;

   _chave = objCampo.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	   _chave = "document.getElementById('"+_chave+"').focus()";

	for(var i=0;i<strCaracter.length;i++)
	if(objCampo.value.indexOf(strCaracter.substr(i,1))!=-1)
	{
		bRetorno = false;
		break;
	}

	if (bRetorno==false)
	{
		alert("Digitação Inválida: Contém Caracteres Não Permitidos.");
		objCampo.value="";
      setTimeout(_chave,50);
		return bRetorno;
	}
	return bRetorno;
}

function numero(nNumero)
{
	var strNumeros="0123456789";
	for (var i=0;i<10 ;i++ )
	{
		if (nNumero==strNumeros.substr(i,1) )
		{
			return true;
		}
	}
}


function TrocouUF(chAcao)
{
	if (document.forms[0].UFINICIAL.value != document.forms[0].strUF.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouAno(chAcao)
{
	if (document.forms[0].ANOINICIAL.value != document.forms[0].strAno.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function ReloadCPF(chAcao)
{
	if (document.forms[0].CPFINICIAL.value != document.forms[0].nCPF.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function Trunca(objCampo,nBytes)
{
	//alert(objCampo.value.length);
	objCampo.value=objCampo.value.substring(0,nBytes);
	return true;
}

function ValidaInteiro(objNumero,aviso)
{
   _chave = objNumero.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	   _chave = "document.getElementById('"+_chave+"').focus()";

	if (objNumero.value.length > 0)
	{
		//nValor = parseInt(objNumero.value);
		nValor = objNumero.value;
		if (isNaN(nValor))
		{
			if (aviso==true)
			alert("Número Inválido: Você deve informar um número Inteiro.");
			objNumero.value="";
         setTimeout(_chave,50);
			return false;
		}
		else
		{
			objNumero.value=nValor;
			return true;
		}
	}
}

function ValidaMes(objNumero, aviso)
{
	var bRetorno=false;

   _chave = objNumero.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	   _chave = "document.getElementById('"+_chave+"').focus()";


	if (objNumero.value.length<=0)
	return true;

	if (ValidaInteiro(objNumero,true))
	{
		nValor=objNumero.value;
		if (nValor>=1 && nValor <=12)
		{
			bRetorno=true;
		}
	}
	if (aviso==true && bRetorno==false)
	{
		alert("Número Inválido: Você deve informar um número Inteiro entre 1 e 12.");
		objNumero.value="";
      setTimeout(_chave,50);
	}
	return bRetorno;
}

function ValidaAno(objNumero, aviso)
{
	var bRetorno=false;
   _chave = objNumero.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (objNumero.value.length<=0)
	return true;

	if (ValidaInteiro(objNumero,true))
	{
		nValor=objNumero.value;
		if (nValor>=1900 && nValor <=2020)
		{
			bRetorno=true;
		}
	}
	if (aviso==true && bRetorno==false)
	{
		alert("Número Inválido: Você deve informar um número Inteiro entre 1900 e 2020.");
		objNumero.value="";
		setTimeout(_chave,50);
	}
	return bRetorno;
}


function FechaJanela()
{
	//WB.ExecWB(45,2); controle activeX que não se comporta muito bem
	window.close();
}

function SimNao(objCampo)
{
	var chValor=objCampo.value.toUpperCase();
   _chave = objCampo.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (chValor=="S" || chValor=="N")
	{
		objCampo.value=chValor;
		return true;
	}
	else
	{
		objCampo.value="";
      setTimeout(_chave,50);
		alert("Somente é permitido informar S(IM) ou N(ão)");
		return false;
	}
}

function Sexo(objCampo)
{
	var chValor=objCampo.value.toUpperCase();
   _chave = objCampo.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (chValor=="M" || chValor=="F")
	{
		objCampo.value=chValor;
		return true;
	}
	else
	{
		objCampo.value="";
		setTimeout(_chave,50);
		alert("Somente é permitido informar M(asculino) ou F(eminino)");
		return false;
	}
}

function Imprimir()
{
	var NS = (navigator.appName == "Netscape");
	var VERSION = parseInt(navigator.appVersion);
	if (NS || VERSION <=5)
	{
		self.print() ;
	}
	else
	{
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);
		WebBrowser1.outerHTML = "";
	}
}

function Calculadora()
{
	var browser = navigator.appName;
	var versao = parseInt(navigator.appVersion);
	var url="calculadora.html";
	if(versao <4 && browser == "Microsoft Internet Explorer") {
		alert('Esta versão do seu browser não suporta os comandos JavaScript presentes nesta página, o que poderá causar alguma mensagem de erro.Obrigado!');
		return false;
	}
	if(browser == 'Netscape') {
		window.open(url,null,"directories=no,height=190,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no,width=365,top=10,left=355");
	}
	else {
		if(versao > 4) {
			window.open(url,null,"directories=no,height=190,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no,width=325,top=10,left=355");
		}
		else {
			window.open(url,null,"directories=no,height=190,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no,width=325,top=10,left=355");
		}
	}
	return true;
}

function atualizapagina(pagina,nform)
{
	document.forms[nform].action=pagina;
	document.forms[nform].submit();
	return true;
}


   function confirmaSenha(cpoSenhaA,cpoSenhaB)
   {
      if (cpoSenhaA.value!=cpoSenhaB.value)
      {
         alert('Redigitação de Senha não confere, são diferentes. Verifique !');
         cpoSenhaA.value="";
         cpoSenhaB.value="";
         PoeFoco(cpoSenhaA.name,0);
         return false;
      }
      else
      {
         return true;
      }
   }


function confereTamSenha(cpoSenha)
{
   _chave = cpoSenha.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

   if (cpoSenha.value < 6)
	{
		alert('Sua senha deve possuir no mínimo 6 digitos!');
		cpoSenha.value="";
      setTimeout(_chave,50);
		return false;
	}
	else
	{
		return true;
	}
}


function confirmaEmail(emailA,emailB)
{
   _chave = emailA.name;
   if(document.getElementById(_chave))
      _chave = "document.getElementById('"+_chave+"').focus()";

	if (emailA.value!=emailB.value)
	{
//		alert('A confirmação do E-mail não confere. Verifique !');  Comentado em 06-12-2010 Silvano
		alert('A confirmação do E-mail não confere (Esta diferente do E-mail). Verifique !');
//		emailA.value="";  Comentado em 06-12-2010 Silvano
//		emailB.value="";  Comentado em 06-12-2010 Silvano
		setTimeout(_chave,50);
      document.getElementById('emailB').focus();
      return false;
	}
	else
	{
		return true;
	}
}

function LayerAlerta(strTexto)
{

	var strAviso = strTexto;

	// Na linha -200 = Altura da Letra (100px x 2)

	var nLinCen= new Number((screen.height-200)/2);
	var nColIni= new Number((screen.width-(strAviso.length*25))/2);

	document.writeln("<div style=\"background:blue;position:absolute; top:"+parseInt(nLinCen)+";left:"+parseInt(nColIni)+"\">");
	document.writeln("<font size=16px color=white face=arial>"+strTexto+"</font>");
	document.writeln("</div>");
	return true;
}


function LayerAtual()
{
	var nsstyle='display:""'

	if (document.layers)
	var scrolldoc=document.scroll1.document.scroll2
	else if (document.all)
	var scrolldoc=""
	else
	event="Versão do Browser não compatível com o uso de Layers";

	return;
}



function Dimensiona(nReferencia,nTipo)
{
	//alert();
	if (nTipo==1)
	return (nReferencia*screen.width/800);
	else
	{
		nAjuste=(screen.height-600)/2;
		return (nReferencia*screen.height/600 + nAjuste);
	}
}

function up()
{
	if (!document.layers)
	return;
	if (scrolldoc.top<0)
	scrolldoc.top+=10;
	temp2=setTimeout("up()",50);
}

function down()
{
	if (!document.layers)
	return;
	if (scrolldoc.top-150>=scrolldoc.document.height*-1)
	scrolldoc.top-=10;
	temp=setTimeout("down()",50);
}

function ComboItemFoco(strNomeSelect,nOpcao,nForm)
{
	if (isNaN(nForm))  { nForm  =0; }
	if (isNaN(nOpcao)) { nOpcao =1; }

	var retorno="";

	if (nOpcao==1)
	retorno=eval("document.forms["+nForm+"]."+strNomeSelect+".options[document.forms["+nForm+"].Escolaridade.selectedIndex].value");
	else
	retorno=eval("document.forms["+nForm+"]."+strNomeSelect+".options[document.forms["+nForm+"].Escolaridade.selectedIndex].text");
	return(retorno);
}

function div(nWD,nHG,CsClass)
{
	nHG=Dimensiona(nHG,2);
	document.write("      <div id=\"scroll3\"  class=\""+CsClass+"\"  style=\"position:relative;width:"+nWD+";visibility:visible;height:"+nHG+";background-color:#FFFFFF;overflow:auto\">\n");
}

function div2(nWD,nHG,CsClass)
{
	nHG=Dimensiona(nHG,2);
	nHG = 92;

	document.write("      <div id=\"lServico\" border = 0 class=\""+CsClass+"\"  style=\"position:relative;width:"+nWD+";visibility:visible;height:"+nHG+";background-color:#FFFFFF;overflow:auto\">\n");
}

function ValidaCasaDec(s, prec)
{
	if (s.length - s.lastIndexOf(",") != (prec + 1))
	return false;
	return true;
}

// Alterações realizadas em 28-01-2008 por Alessandro Rocha.
// Imprime as informações dos formularios tanto no IE como no Firefox.
// O parâmetro "divMostrar" é utilizado no Indicadores para exibir o cabeçalho do resultado
// porém pode ser utilizado em qualquer sistema de precise de tal funcionalidade.
// Esta função trabalha em conjunto com a função "EqualizaForm".
function DivImprime(strNomeDiv, divMostrar, strClasse)
{
		if(strNomeDiv == 'undefined') { alert("informe a div a ser impressa");return false; }
	if(strClasse != "" && strClasse == "noticia")
	document.getElementById('noticias').style.display='block';
	
	var browser = navigator.appName;

   if(document.getElementById('logo'))
      document.getElementById('logo').style.display='block';

	//janela=AbreJanela(null,true);
	janela=window.open("","","directories=no,height=390,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,width=800,top=10,left=65");
	e = document.getElementById(strNomeDiv).innerHTML;


	if(browser != "Microsoft Internet Explorer")
	{
		janela.document.writeln("<body><form>");
      
        if (typeof strClasse != "undefined")
            janela.document.writeln("<link rel=stylesheet type='text/css' href='"+strClasse+"'>");


        if (document.all)
		{
			if(divMostrar != "")
			janela.document.writeln( eval("document.all."+divMostrar+".innerHTML"));
		}
		else
		{
			if(divMostrar != "")
			{		
				e1=document.getElementById(divMostrar);				
				janela.document.writeln(e1.innerHTML);
			}
		}

		
		e = document.getElementById(strNomeDiv).innerHTML;
		janela.document.writeln(e);

		if( janela.document.getElementById("imprimir"))
	      janela.document.getElementById("imprimir").style.display='none';

		EqualizaForm(janela);
	   	janela.document.writeln("</form></body>");
	}
	else
	{
	
		janela.document.writeln("<body onload=window.print();window.close();>");

      if (typeof strClasse != "undefined")
         janela.document.writeln("<link rel=stylesheet type='text/css' href='"+strClasse+"'>");

		if (document.all)
		{
			if(divMostrar != "")
			janela.document.writeln( eval("document.all."+divMostrar+".innerHTML"));
		}
		else
		{
			if(divMostrar != "")
			{
				e1=document.getElementById(divMostrar);
				janela.document.writeln(e1.innerHTML);
			}
		}
		janela.document.writeln(e);
		janela.document.writeln("<script>if(document.getElementById('imprimir')){document.getElementById('imprimir').style.display='none';}</script>");
    	janela.document.writeln("</form></body>");
      janela.location.reload(true);
	}

   if(document.getElementById('logo'))
      document.getElementById('logo').style.display='none';
   return true;
}


function EqualizaForm(janela)
{
	for (var i=0;i<document.forms.length;i++)
	{
		var nItensForm=document.forms[i].length;
		for (var j=0;j<nItensForm;j++ )
		{
			var tipo = document.forms[i].elements[j].type;
         var id   = document.forms[i].elements[j].id;
         if (janela.document.getElementById(id))
         {
            if (tipo=='select-one')
               janela.document.forms[i].elements[j].selectedIndex=document.forms[i].elements[j].selectedIndex;
            else if (tipo=='radio' || tipo=='checkbox')
               janela.document.forms[i].elements[j].checked=document.forms[i].elements[j].checked
            else if (tipo=='text' || tipo=='textarea')
               janela.document.forms[i].elements[j].value=document.forms[i].elements[j].value;
         }
		}
	}
	janela.print();
 	setTimeout("janela.window.close()",150);
	return true;
}
//---------------------------------------------------------------

function ValidaDecimal(objNumero,aviso)
{
   _chave = objNumero.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

	if (objNumero.value.length > 0)
	{
		nValor = parseFloat(objNumero.value);
		if (isNaN(nValor))
		{
			if (aviso==true)
			alert("Número Inválido: Você deve informar um número.");
			objNumero.value=0;
			setTimeout(_chave,50);
			return false;
		}
		else
		{
			objNumero.value=nValor;
			return true;
		}
	}
}

//CRIADA POR MARCOS E CLAUDIO
// Funções Para Abrir janela
function janela(pagina)
{
	Nova_url=pagina; //Nome da Página WEB a ser aberta na nova janela.
	Nova_win='width=680,height=480,toolbar=no,location=no,directories=no,status=yes,menubar=no,resize=yes,scrollbars=yes';
	NovaWindow = window.open(Nova_url,'',Nova_win);
}

//Funções para Abrir janela com tamanho definido
function janeladef(pagina,largura,altura)
{
	Nova_url=pagina; //Nome da Página WEB a ser aberta na nova janela.
	Nova_win='width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,resize=yes,scrollbars=yes';
	NovaWindow = window.open(Nova_url,'',Nova_win);
}

//Função pra abrir janela com um nome definido, assim evita abrir varias vezes a mesma janela
function janeladef2(pagina,largura,altura,name)
{
	Nova_url=pagina; //Nome da Página WEB a ser aberta na nova janela.
	Nova_win='width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,resize=yes,scrollbars=yes';
	NovaWindow = window.open(Nova_url,name,Nova_win);
}


/******  Função para formatar um valor monetário em formato americano (xxxxxxx.xx) *********/

function FormataMoeda(valor)
{
	//alert(valor)
	var strtemp = valor
	var tamanho = valor.length;

	//alert("O valor foi formatado para a carga no banco de dados. Verifique se está correto.")
	for(i=0; i < tamanho; i++)
	{
		if(strtemp.substring(i,i+1) == "." || strtemp.substring(i,i+1) == ",")
		{
			var moeda = SoNumeros(temp);
			alert(moeda + '  ' + tamanho)
			var valorfinal = moeda.substring(0,tamanho-2)+ '.'+moeda.substring(tamanho-2,moeda.length)
			alert(valorfinal)
			if(valorfinal.length >1)
			valor.value = valorfinal;
			alert("O valor foi formatado para a carga no banco de dados. Verifique se está correto.")
		}
	}
}

function TrocouEixo(chAcao)
{
	if (document.forms[0].EIXOINICIAL.value != document.forms[0].strEixo.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouGestao(chAcao)
{
	if (document.forms[0].GESTAOINICIAL.value != document.forms[0].strGestao.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouRegra(chAcao)
{
	if (document.forms[0].REGRAINICIAL.value != document.forms[0].strRegra.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouArea(chAcao)
{
	if (document.forms[0].AreaINICIAL.value != document.forms[0].strArea.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}



function TrocouBeneficio(chAcao)
{
	if (document.forms[0].BENINICIAL.value != document.forms[0].strBeneficio.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}


function TrocouCodAcao(chAcao)
{
	if (document.forms[0].ACAOINICIAL.value != document.forms[0].strAcoes.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouComp(chAcao)
{
	if (document.forms[0].COMPINICIAL.value != document.forms[0].strComp.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}
function TrocouTpCurs(chAcao)
{
	if (document.forms[0].CURINICIAL.value != document.forms[0].strTipoCurso.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouCkeckBox(chAcao,ckInfo)
{
	document.forms[0].acao.value=chAcao;

	if (document.forms[0].ckInfo.value == 1)
	{
		document.forms[0].ckInfo.value = 0 ;
		alert ("0");
	}
	else
	{
		document.forms[0].ckInfo.value =  1 ;
		alert ("1");
	}


	document.forms[0].submit();
}

function TrocouServicos(chAcao)
{
	if (document.forms[0].SERVINICIAL.value != document.forms[0].strServicos.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouCarac(chAcao)
{
	if (document.forms[0].CARACINICIAL.value != document.forms[0].strOutrosCarac.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouEvento(chAcao)
{
	if (document.forms[0].EVENTOINICIAL.value != document.forms[0].strEvento.value)
	{
		document.forms[0].acao.value='N';
		document.forms[0].submit();
	}
}

function TrocouStatus(chAcao)
{
	//  alert(document.forms[0].acao.value);
	document.forms[0].acao.value=chAcao;
	document.forms[0].submit();
}

function TrocouGrupo(chAcao)
{
	if (document.forms[0].GRUPOINICIAL.value != document.forms[0].strGrupo.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}

function TrocouFuncionario(chAcao)
{
	if (document.forms[0].FUNCINICIAL.value != document.forms[0].strFuncionario.value)
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}


function formataReal(ValoraFormatar) {
	var i ;
	var decimalPointDelimiter = ",";
	var posDecPoint = parseInt("");
	var hasDecPoint = false;
	var s = new String(ValoraFormatar);
	var sAux = new String("");

	for (i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if ( c == '.' ) c = decimalPointDelimiter;
		sAux += c;
		if (c == decimalPointDelimiter){
			hasDecPoint = true;
			posDecPoint = i;
			break;}
	}
	for (var j = i+1; j < s.length; j++) sAux += s.charAt(j);

	if (!hasDecPoint) //(isNaN(posDecPoint))
	{	ValoraFormatar = s + ",00";}
	else
	{
		s = sAux + '00';
		ValoraFormatar= s.charAt(0);
		for (i = 1; i <= (posDecPoint+2); i++){
			ValoraFormatar += s.charAt(i);}
			if (posDecPoint == 0) ValoraFormatar = '0'+ValoraFormatar;
	}
	s = ValoraFormatar;
	ValoraFormatar = "";
	i=0;

	for (var j=s.length-4; j>=0; j--)
	{
		i++;
		ValoraFormatar = s.charAt(j) + ValoraFormatar;
		if (i == 3 && j != 0)
		{
			ValoraFormatar = "." + ValoraFormatar;
			i = 0;
		}
	}
	ValoraFormatar +=  s.substring(s.length-3,s.length);

	return ValoraFormatar;
}

function separadorDecimal(valor)
{
	return (parseFloat(valor) / 100);
}


function FormataValor(campo,tammax,teclapres) {

	var tecla = teclapres.keyCode;
	var vr = campo.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==0 || tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
		if ( tam <= 2 ){
			campo.value = vr ; }
			tam = tam - 1;
			if ( (tam > 2) && (tam <= 5) ){
				campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
				if ( (tam >= 6) && (tam <= 8) ){
					campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, 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 - 2, 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 - 2, 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 ) ;}
	}
}

function PreRequisito(ObjCheck,ObjCampo)
{
   _chave = ObjCheck.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

   if (ObjCheck.checked == true)
	{
		if (ObjCampo.value.length <= 0)
		{
			setTimeout(_chave,50);
			return false ;
		}
	}
	else
	{
		ObjCampo.value = "" ;
	}
	return true ;
}

function PreRequisitoRadio(ObjRadio,ObjCampo,nValor)
{
   _chave = ObjCampo.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";

   if (ObjRadio.value == nValor)
	{
		if (ObjCampo.value.length <= 0)
		{
			setTimeout(_chave,50);
			return false ;
		}
	}
	else
	{
		ObjCampo.value = "" ;
	}
	return true ;
}

//FUNÇÃO CRIADA POR ANTONIO DIA 24/03/2004
//Abrir uma nova Janela uma unica vez
function janeladef2(pagina,largura,altura,name)
{
	Nova_url=pagina; //Nome da Página WEB a ser aberta na nova janela.
	Nova_win='width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,resize=yes,scrollbars=yes';
	NovaWindow = window.open(Nova_url,name,Nova_win);
}

function pega_cep(valor)
{
	n_url = 'cep.php?cep='+valor;
	document.getElementById('Divcep').innerHTML='<iframe src="'+ n_url + '" name="contato" width="100" height="100" marginwidth=0 marginheight=0 frameborder=1 scrolling=yes align="default"> </iframe>';
	return;
}

function TrocaAcao(chAcao,chInicial,strInicial)
{
	if ((eval('document.forms[0].'+chInicial+'.value')) != (eval('document.forms[0].'+strInicial+'.value')))
	{
		document.forms[0].acao.value=chAcao;
		document.forms[0].submit();
	}
}   

function DataMaior(dtInicio,dtAtual)
{
	var dtIni   = dtInicio.value.substr(6,4)+dtInicio.value.substr(3,2)+dtInicio.value.substr(0,2);
	var dtFim   = dtAtual.value.substr(6,4)+dtAtual.value.substr(3,2) +dtAtual.value.substr(0,2);

   _chave = dtInicio.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";


	var dtResult = dtIni - dtFim ;

	//alert(dtResult);

	if(dtResult < 0)
	{
		alert("Data deve ser igual ou posterior a hoje.");
		dtInicio.value="";
		setTimeout(_chave,50);
		return false;
	}
	else
	{
		return true;
	}
}

function LimiteInscricao(dtInicio)
{

	document.forms[0].dtLimite.value = document.forms[0].dtInicio.value - 1 ;

	return true;

}

function validaform(form)
{
	if(form.unidade.value==-1)
	{
		alert('Escolha um local de atendimento');
		form.unidade.focus();
		return(false);
	}

}

function VerificaLogin(chLogin)
{
	strUrl = 'ctrlSolicitacao.php?acao=V&chLogin='+chLogin.value ;
	window.location.href=strUrl;
	form.chLogin.focus();
	return;
}

function mostraDiv(objCampo,objDiv)
{
	if (objCampo.checked)
	   objDiv.style.visibility="visible";
	else
	   objDiv.style.visibility="hidden";
	return true;

}

function pesquisacbo(campo,nomecbo)
{
	if(tamanho(nomecbo)<=3 || tamanho(nomecbo)>50)
	{
		alert("Para que sua pesquisa seja mais precisa, digite um mínimo de 4 caracteres e no máximo 50 caracteres no campo Descrição de CBO e clique no botão Pesquisar.");
	}
	else
	{
		pagina = '/lib/selecionaCBO.php?cbo='+escape(nomecbo);
		window.open(pagina,'Pesquisa','toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes,width=450,height=550');
	}
}

function imprimirelatorio()
{
	pagina = '/setp/extranet/syscib/relatorio/dicas.php';
	window.open(pagina,'Dicas de Impressão','toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes,width=450,height=550');
}

function tamanho(variavel)
{
	return(variavel.length);
}

function retornaresultadocbo(codigo,nome)
{
	window.opener.voltadados(codigo,nome);
	window.close();

	return;
}

function voltadados(codigo,nome)
{
	eval("document.forms[0].cdOcup.value='"+codigo+"'");
	eval("document.forms[0].strOcup.value='"+nome+"'");

}

function ConfirmaExclusao(link)
{
	varConfirma = confirm("Deseja realmente efetuar a exclusão ?");
	if(varConfirma)
	window.location = link ;
	else
	return;
}

function ConfirmaValida(link)
{
	varConfirma = confirm("Deseja realmente Confirmar ?");
	if(varConfirma)
	window.location = link ;
	else
	return;
}

function amf2005_BecameCurrency(cur,len)
{
	n='__0123456789';
	d=cur.value;
	l=d.length;
	r='';
	if (l > 0)
	{
		z=d.substr(0,l-1);
		s='';
		a=2;
		for (i=0; i < l; i++)
		{
			c=d.charAt(i);
			if (n.indexOf(c) > a)
			{
				a=1;
				s+=c;
			};
		};
		l=s.length;
		t=len-1;
		if (l > t)
		{
			l=t;
			s=s.substr(0,t);
		};
		if (l > 2)
		{
			r=s.substr(0,l-2)+','+s.substr(l-2,2);
		}
		else
		{
			if (l == 2)
			{
				r='0,'+s;
			}
			else
			{
				if (l == 1)
				{
					r='0,0'+s;
				};
			};
		};
		if (r == '')
		{
			r='0,00';
		}
		else
		{
			l=r.length;
			if (l > 6)
			{
				j=l%3;
				w=r.substr(0,j);
				wa=r.substr(j,l-j-6);
				wb=r.substr(l-6,6);
				if (j > 0)
				{
					w+='.';
				};
				k=(l-j)/3-2;
				for (i=0; i < k; i++)
				{
					w+=wa.substr(i*3,3)+'.';
				};
				r=w+wb;
			};
		};
	};
	if (r.length <= len)
	{
		cur.value=r;
	}
	else
	{
		cur.value=z;
	};
	return 'ok';
};

function ContaCaracter(str,tamanho)
{
	var strCampo = str.length;
	var tamDes = tamanho.value;

	if(strCampo > tamDes)
	alert('O máximo de caracteres permitido é '+ tamDes+'.Verifique!');

	return;
}

function foco(nNumero)
{
	alert('oi');
	document.foms[0].nNumero.focus();
	return;
}

function AtivaCandidato(idForm)
{
	var retorno = true ;
	var msgErro = "" ;

	var possuiCNH  = document.getElementById('oCNH').checked;
	var possuiCert = document.forms[idForm].nCertidao.value;
	var possuiCTPS = document.forms[idForm].nCTPS.value;

	if(possuiCNH)
	{
		if(document.forms[idForm].nCNH.value == "")
		{
			var retorno = false ;
			msgErro = "- Número da Carteira Nacional de Habilitação\n";
		}

		if(document.forms[idForm].strCategoria.value == "")
		{
			var retorno = false ;
			msgErro = msgErro+"- Categoria da Carteira Nacional de Habilitação\n";
		}
	}

	if(possuiCert != "")
	{
		if(document.forms[idForm].nLivro.value == "")
		{
			var retorno = false ;
			msgErro = msgErro+"- Número do Livro - Certidão de Nascimento\n";
		}

		if(document.forms[idForm].nFolha.value == "")
		{
			var retorno = false ;
			msgErro = msgErro+"- Número da Folha - Certidão de Nascimento\n";
		}
	}

	if(possuiCTPS != "")
	{
		if(document.forms[idForm].nSerie.value == "")
		{
			var retorno = false ;
			msgErro = msgErro+"- Número de Série da CTPS\n";
		}

		if(document.forms[idForm].UFCtps.value == "")
		{
			var retorno = false ;
			msgErro = msgErro+"- Estado Emissor da CTPS\n";
		}
	}


	if(retorno)
	   Submeter(idForm);
	else
	   alert("Você deve preencher os seguintes itens:\n"+msgErro);
}
function ValidaPis(nrodocto)
{
	var valorPIS = nrodocto.value;
	var NumPIS = Trim(valorPIS);

   _chave = nrodocto.name;
   //_chave = _chave + ".focus()";
   if(document.getElementById(_chave))
	      _chave = "document.getElementById('"+_chave+"').focus()";


	if( NumPIS.length > 0 && NumPIS.length < 11 ) // Se o nro for incompleto
	{
		alert("PIS Inválido");
		nrodocto.value='';
		setTimeout(_chave,50);
		return(false);
	}
	else
	{
		if( NumPIS.length == 0 )
		{
			return(true);
		}
	}

	var calculo = 0;
	var resto = 0;
	var digito = 0;

	calculo = (parseInt(NumPIS.substring(0, 1), 10) * 3) +
	(parseInt(NumPIS.substring(1, 2), 10) * 2) +
	(parseInt(NumPIS.substring(2, 3), 10) * 9) +
	(parseInt(NumPIS.substring(3, 4), 10) * 8) +
	(parseInt(NumPIS.substring(4, 5), 10) * 7) +
	(parseInt(NumPIS.substring(5, 6), 10) * 6) +
	(parseInt(NumPIS.substring(6, 7), 10) * 5) +
	(parseInt(NumPIS.substring(7, 8), 10) * 4) +
	(parseInt(NumPIS.substring(8, 9), 10) * 3) +
	(parseInt(NumPIS.substring(9, 10), 10) * 2);

	resto = parseInt(calculo % 11, 10);
	if(resto == 0 || resto == 1) {
		resto = 0;
	}
	else {
		resto = 11 - resto;
	}

	digito = NumPIS.substring(10,11);

	if(digito == resto) {
		return(true);
	}
	else {
		alert("PIS Inválido");
		nrodocto.value='';
		setTimeout(_chave,50);
		return(false);
	}
}
function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
		return "";
	}
	else{
		return TRIM_VALUE;
	}
}
function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
		return"";
	}
	var iTemp = v_length -1;

	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;

	}
	return strTemp;

}

function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 1){
		return"";
	}

	var iTemp = 0;

	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;

	}
	return strTemp;

}

function linkConfirma(strURL,strMensagem)
{
	if (confirm(strMensagem))
	location.href=strURL;
}

function LigaReadOnly(id)
{
   if (document.getElementById(id))
      document.getElementById(id).disabled=true;
   return;
}

function DesligaReadOnly(id)
{
   if (document.getElementById(id))
      document.getElementById(id).disabled=false;
   return;
}

/* Inicio inclusão de Função em 09-11-2011 */
function desligaFormReadOnly(nForm)
{
   var nItensForm=document.forms[nForm].length;
   for (var j=0;j<nItensForm;j++)
   {
      if (document.forms[nForm].elements[j].type!="hidden")
         document.forms[nForm].elements[j].disabled=false;
   }
   return;
}

function LigaFormReadOnly(nForm)
{
   var nItensForm=document.forms[nForm].length;
   for (var j=0;j<nItensForm;j++)
   {
      if (document.forms[nForm].elements[j].type!="hidden")
      {
         document.forms[nForm].elements[j].disabled=true;
//         document.forms[nForm].elements[j].style.color='red';
         document.forms[nForm].elements[j].style.backgroundColor='#C0C0C0';
      }
   }
   return;
}
/* Termino inclusão de Função em 09-11-2011 */

function pause(ms) 
{
   var date = new Date();
   var curDate = null;

   do { curDate = new Date(); }
   while(curDate-date < ms);
} 

//16/05/2008 - Função criada devido a necessidade do submit não avançar o form
function TrocaAcaoGenerico(valor)
{
	if (valor == 'S')
	{
		document.getElementById('tdeficiencia').disabled=false;
		document.getElementById('nOpcao').value = 'S'
	}
	else
	{
		document.getElementById('tdeficiencia').disabled=true;
		document.getElementById('nOpcao').value = 'N'
	}

}

function excSol(cont)
{
	var cont;
	var nRegistro	= document.getElementById('nRegistro').value;
	var nSolicitante= document.getElementById('nSolicitante'+cont).value;
	var url='../registro/solicitante.php?nRegistro='+nRegistro+'&nSolicitante='+nSolicitante+'&apagar='+1;
	if (confirm("Deseja realmente excluir?"))
		exibe('divsol',url);
}
			
function excIdo(cont)
{
	var cont;
	var nRegistro	= document.getElementById('nRegistro').value;
	var nIdoso		= document.getElementById('nIdoso'+cont).value;
	var url='../registro/idoso.php?nRegistro='+nRegistro+'&nIdoso='+nIdoso+'&apagar='+1;
	if (confirm("Deseja realmente excluir?"))
		exibe('dividoso',url);
}

function excEnt(cont)
{
	var cont;
	var nRegistro	= document.getElementById('nRegistro').value;
	var nEntidade	= document.getElementById('nEntidade'+cont).value;			
	var url='../registro/entidade.php?nRegistro='+nRegistro+'&nEntidade='+nEntidade+'&apagar='+1;
	if (confirm("Deseja realmente excluir?"))
		exibe('divent',url);
}

function excDoc(cont)
{
	var cont;
	var nRegistro	= document.getElementById('nRegistro').value;
	var nDoc	= document.getElementById('nDoc'+cont).value;			
	var url='../registro/documento.php?nRegistro='+nRegistro+'&nDoc='+nDoc+'&apagar='+1;
	if (confirm("Deseja realmente excluir?"))
		exibe('divdoc',url);
}
	
/** FUNÇÃO PARA AUMENTO DE TEXTO DINAMICO
*
*	AUTHOR: SÉRGIO R. TAMOGAMI
*
*										*/
/*function TamanhoFonte(num, id)
{
	document.getElementById(id).className = "fonte"+num;
}*/

/**
 * @describe: A função tabAutom(quem) faz a tabulação automática para utiliza-la basta incluir na tag input o atributo onkeyup="tabAutom(this)"
 * @author: Ricardo Spinoza
 * @email: ricardopereira@setp.pr.gov.br, ricardospinoza@yahoo.com.br
 * @date: 02 junho 2006
 * @use: <input type="text" name="diaVencimento" id="diaVencimento" value="" size="2" maxlength="2" title="Dia da data do vencimento"  onkeyup="tabAutom(this,true);" />
 * @information: necessário que a tag tenha definido o maxlenght
 * @version: 1.0
 * @update: incluido parametro "autorizaTab" booleano que liga(true ou omissão do parametro) ou desliga(false) o auto tab, 
 * tabAutom(this) - liga a auto tabulação, tbem equivalente á tabAutom(this,true) default
 * tabAutom(this,false) - desliga auto tabulação
*/
	//Desabilita autocomplete dos campos input para evitar bug do ff
	window.onload = function(){
	var inputs = document.getElementsByTagName("INPUT");
		for(var i=0; i<inputs.length; i++) {
				inputs[i].setAttribute('autocomplete', 'off');
		}
	}


	function HabilitarTABAutom(evt)
	{
		var codTecla;
	 	var e = evt ? evt : window.event; 

		if(e.keyCode)  // IE
		{
			codTecla = e.keyCode;
		}
		else // Netscape/Firefox/Opera
		{
			codTecla = e.which;
		}

		if ( (codTecla < 48) || (codTecla >  255) )
			MudarCampo = false;
		else
			MudarCampo = true;
	}
   
	//AutoTab de campos
	function tabAutom(quem, bAutorizaTab)
	{      
      if (typeof bAutorizaTab == 'undefined') {
         bAutorizaTab = true;
      }      
      
      if (AutorizaTab(bAutorizaTab)) {
         if ( ( quem.value.length == quem.maxLength ) && ( MudarCampo ) ){
            var i=0,j=0, indice=-1;
            for (i=0; i<document.forms.length; i++) {
               for (j=0; j<document.forms[i].elements.length; j++) {
                  if (document.forms[i].elements[j].name == quem.name) {
                     indice=i;
                     break;
                  }
               }
               if (indice != -1)
                     break;
            }

            // Localiza o input no documento e verifica se existe outro input para receber o foco
            for (i=0; i<document.forms[indice].elements.length; i++) 
            {
               if (document.forms[indice].elements[i].name == quem.name) 
               {
                  while ( ((i+1) < document.forms[indice].elements.length) && 
                           (document.forms[indice].elements[(i+1)].type == "hidden") )
                  {
                           i++;
                  }
                  if ( (i+1) < document.forms[indice].elements.length )
                  {
                     document.forms[indice].elements[(i+1)].focus();
                     MudarCampo = false;
                  }
                  break;
               } 
            }
         }
      }
	}

	VerifiqueTAB=true;
   /*
    *	Fim - tabAutom(quem) tabulação automática
    **/

   //Objetivo: Permitir focus do campo no FF e IE, pois existe um bug do Focus do Firefox.
   //Report do Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=53579
   //Desenvolvedor: Ricardo Spinoza 21.02.07
   //Uso: _focus(this)
   var reFocusField;
   function reFocus(){
      reFocusField.focus();
   }
   function _focus(field){
      reFocusField=field;   
      setTimeout("reFocus()", 100);
   }
   //Fim solução Bug do Focus no Firefox

   //Uso onblur="this.value=this.value.trim();"
   String.prototype.trim = function() {
      return this.replace(/^\s+|\s+$/g, "").replace(/\s+/g," ");
   }

   //Uso onblur="this.value=this.value.ucase();"
   String.prototype.ucase = function(){
	   return this.toUpperCase();
   }
   //Uso onblur="this.value=this.value.lcase();"
   String.prototype.lcase = function(){
	   return this.toLowerCase();
   }

   //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   //Remove caracteres invalidos(!= numero e letras) e retorna os dados filtrados ao campo.
   //Exemplos de uso:
   // <input type="text" id="campo" name="campo" size="80" maxlength="70" value="" onblur="isValidChar(this);">
   // <input type="text" id="campo2" name="campo2" size="80" maxlength="70" value="" onblur="isValidChar(this, 'A');">
   //paremetro tipo: 
   //	N: só número
   //	A: Alfa-numerico
   //	AB: Alfa-numerico, porém não aceita espaços em branco.
   //	paramêtro vazio (default): letras, números, e alguns caracteres especiais(exceto %%;)

   //Adaptações, by Ricardo Spinoza
   //03/04/2007
   //melhorias, Ricardo Spinoza
   //16/03/2009
   function isValidChar(field,tipo) {
         
      var validString = field.value.trim();
      var isCharValid = true;
      var i;
         
      var invalidChar = "";
      for (i=0; i<validString.length; i++) {
         if (validateCharacter(validString.charAt(i),tipo) == false) {
            isCharValid = false;
            
            invalidChar += validString.charAt(i);
         }
      }

      for (i=0; i<invalidChar.length; i++){
         validString = validString.replace(invalidChar.charAt(i),'');	
      }

      if (isCharValid == false) {
         //if (invalidChar)
         //   alert("O(s) caracter(es) especial(ais) entre os conchetes\n abaixo não é(são) válido(s) para este campo: \n\n\t\t\t[" + invalidChar + "]");
         //else
         //   alert('Caracter inválido!');
         if (field) {
            field.value = validString.trim();
            if (validString.length ==0) {
               _focus(field);
            }
            else {
               tabAutom(field);
            }
         }
         return false;
      }
      else {//realiza outros tratamentos: trim, espaço duplos...
         field.value = validString.trim();
         tabAutom(field);
      }
      return true;
   }

   //função auxiliar de isValidChar:
   //define as regras de validação de acordo com o tipo escolhido
   function validateCharacter(character,tipo) {
      if (typeof tipo == "undefined")	{
         tipo = "D";//default
      }

      if (tipo.toUpperCase() == "N") //só número
      {
         var reLetras = /^\d+$/;		
         
      }
      else if (tipo.toUpperCase() == "A"){//Alfa-numerico
         var reLetras = /^[0-9a-zA-ZãáàäâéèëêíìïîõóòöôúùüûçÃÁÀÄÂÉÈËÊÍÌÏÎÕÓÒÖÔÚÙÜÛÇ\s]*$/;
      }
      else if (tipo.toUpperCase() == "AB"){//Alfa-numerico, porém não aceita espaços em branco, nem acentuação.
         var reLetras = /^[0-9a-zA-ZçÇ]*$/;
      }
      else if (tipo.toUpperCase() == "A_") //Alfa-numerico, porém não aceita espaços em branco, nem acentuação, mas aceita undescore.
      {
         var reLetras = /^[0-9a-zA-ZçÇ_]*$/;
      }
      else //letras e números - caracteres especiais
      {
         var reLetras = /^[0-9a-zA-ZãáàäâéèëêíìïîõóòöôúùüûçÃÁÀÄÂÉÈËÊÍÌÏÎÕÓÒÖÔÚÙÜÛÇ.,?!@$*ªº#+-:_§()\\\/:\s]*$/;		
      }

      if (!(reLetras.test(character)))
         return false;
      else
         return true;
   }
   //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   //Pega valores da URL corrente
   //Exemplo de uso:
   //Dada a url -> http://10.24.1.239/sert/testes/applet.html?id=1234&nome=ricardo
   //O código abaixo:
   //getURLParameters('nome'); //retorna o valor ricardo
   //getURLParameters('nome', 'http://10.24.1.239/sert/testes/applet.html?id=1234&nome=ricardo'); //retorna o valor ricardo
   //Ateração, adicionado parametro url, por Ricardo 29/04/2009
   function getURLParameters( paramName, url )
   {
     
     paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
     var regexS = "[\\?&]"+paramName+"=([^&#]*)";
     var regex = new RegExp( regexS );
     //se url não for informado, assume a url corrente da página
      if (typeof url == "undefined")
         var results = regex.exec( window.location.href );          
      else
         var results = regex.exec( url );
     if( results == null )
       return "";
     else
       return results[1];
   }
   //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

   function Data_Diff(data1,data2)
   {
      Var_Dia1=Dia(data1);
      Var_Mes1=Mes(data1);
      Var_Mes1=Math.floor(Var_Mes1)-1;
      Var_Ano1=Ano(data1);
      var data1 = new Date(Var_Ano1,Var_Mes1,Var_Dia1);

      Var_Dia2=Dia(data2);
      Var_Mes2=Mes(data2);
      Var_Mes2=Math.floor(Var_Mes2)-1;
      Var_Ano2=Ano(data2);
      var data2 = new Date(Var_Ano2,Var_Mes2,Var_Dia2);

      var diferenca = data2.getTime() - data1.getTime();
      var diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));
      return diferenca
   }

   //Possibilitar adicionar no onload da página a execução de multiplas funções js
   //Parametro func é a função a ser carregada
   //Ricardo Spinoza - 15/05/2009
   //Exemplo de uso:
   //addEventoOnLoad(func1);
   //addEventoOnLoad(func2);
   //créditos: http://www.htmlgoodies.com/beyond/javascript/print.php/3724571
   function addEventoOnLoad(func) {
     var oldonload = window.onload;
     if (typeof window.onload != 'function') {
       window.onload = func;
     } else {
       window.onload = function() {
         if (oldonload) {
           oldonload();
         }
         func();
       }
     }
   }//fim função addEventoOnLoad

   function adicionaItemCombo(strOrigem,strDestino)
   {
      nItens = document.getElementById(strOrigem).length;
      if (nItens <=0)
         return;

      nSelecionado=document.getElementById(strOrigem).selectedIndex;

      if (nSelecionado < 0)
         return;

      strTexto = document.getElementById(strOrigem).options[nSelecionado].text;
      nValor   = document.getElementById(strOrigem).options[nSelecionado].value;

      objOpcao=document.createElement("OPTION");
      objOpcao.value=nValor;
      objOpcao.text =strTexto;

      if(document.all)
         document.getElementById(strDestino).add(objOpcao);
      else
         document.getElementById(strDestino).appendChild(objOpcao);

      document.getElementById(strOrigem).remove(nSelecionado);

      nItens = document.getElementById(strDestino).length;

      if (nSelecionado <= nItens)
         document.getElementById(strOrigem).selectedIndex=nSelecionado;
      else
         if (nItens>0)
            document.getElementById(strOrigem).selectedIndex=nSelecionado-1;

      OrdenarCombo(strDestino);
      return;
   }

   function OrdenarCombo(idCombo) 
   {

      var lb = document.getElementById(idCombo);
      if (lb.length<=0)
         return;

      arrTexts = new Array();
      for(i=0; i<lb.length; i++)  
      {
         arrTexts[i] = lb.options[i].text+'#*#'+lb.options[i].value;
      }

      arrTexts.sort();

      for(i=0; i<lb.length; i++)
      {
         arrTextsAux = arrTexts[i].split("#*#");
         lb.options[i].text  = arrTextsAux[0];
         lb.options[i].value = arrTextsAux[1];
      }
   }

  	//Flexibiliza o uso de campo obrigatorio, deixando a cargo do js do form setar ou não quais os campos são obrigatórios
   //Dada uma lista de campos obrigatório, permite especificar dinamicamente os campos obrigatórios
   //parametros: I - incluir campo para lista de obrigatorios, E - Excluir campo da lista de obrigatorios
   function ModificaCpoObrigatorio(chAcao, campo)
   {
      nLenVetor = cpoObrigatorio.length;
      if (typeof(chAcao)=="undefined" || typeof(nLenVetor)=="undefined")
         return;

      if (chAcao == "I")
        cpoObrigatorio[nLenVetor+1] = campo;
      else if (chAcao == "E")
      {
         arrayAux = new Array;
         j = 0;
         for (i=0; i<nLenVetor; i++)
         {
            if (cpoObrigatorio[i] != campo)
            {
               arrayAux[j] = cpoObrigatorio[i];
               j++;
            }
         }
         var imgCampo = 'img'+campo;
         //alert('imgchSituacaoContrato [' + imgCampo+']');
         document.getElementById('img'+campo).src = '/fig/pt_nulo.gif';
         cpoObrigatorio = arrayAux;
      }
      return;
   }

   //http://www.developerfusion.com/code/2310/building-a-multidimensional-array-in-javascript/
   //gera array multidimensional dinamicamente
   //Ricardo Spinoza
   //uso var dateArray=MultiDimensionalArray(6,3);//6 linhas, 3 colunas
   function MultiDimensionalArray(iRows,iCols)
   {
      var i;
      var j;
      var a = new Array(iRows);
      for (i=0; i < iRows; i++)
      {
          a[i] = new Array(iCols);
          for (j=0; j < iCols; j++)
          {
              a[i][j] = "";
          }
      }
      return(a);
   }

   /**
*
*  Scrollable HTML table
*  http://www.webtoolkit.info/
*  http://www.webtoolkit.info/demo/javascript/scrollable/demo.html
*  http://www.webtoolkit.info/scrollable-html-table.html
**/
 
function ScrollableTable (tableEl, tableHeight, tableWidth) {
 
	this.initIEengine = function () {
 
		this.containerEl.style.overflowY = 'auto';
		if (this.tableEl.parentElement.clientHeight - this.tableEl.offsetHeight < 0) {
			this.tableEl.style.width = this.newWidth - this.scrollWidth +'px';
		} else {
			this.containerEl.style.overflowY = 'hidden';
			this.tableEl.style.width = this.newWidth +'px';
		}
 
		if (this.thead) {
			var trs = this.thead.getElementsByTagName('tr');
			for (x=0; x<trs.length; x++) {
				trs[x].style.position ='relative';
				trs[x].style.setExpression("top",  "this.parentElement.parentElement.parentElement.scrollTop + 'px'");
			}
		}
 
		if (this.tfoot) {
			var trs = this.tfoot.getElementsByTagName('tr');
			for (x=0; x<trs.length; x++) {
				trs[x].style.position ='relative';
				trs[x].style.setExpression("bottom",  "(this.parentElement.parentElement.offsetHeight - this.parentElement.parentElement.parentElement.clientHeight - this.parentElement.parentElement.parentElement.scrollTop) + 'px'");
			}
		}
 
		eval("window.attachEvent('onresize', function () { document.getElementById('" + this.tableEl.id + "').style.visibility = 'hidden'; document.getElementById('" + this.tableEl.id + "').style.visibility = 'visible'; } )");
	};
 
 
	this.initFFengine = function () {
		this.containerEl.style.overflow = 'hidden';
		this.tableEl.style.width = this.newWidth + 'px';
 
		var headHeight = (this.thead) ? this.thead.clientHeight : 0;
		var footHeight = (this.tfoot) ? this.tfoot.clientHeight : 0;
		var bodyHeight = this.tbody.clientHeight;
		var trs = this.tbody.getElementsByTagName('tr');
		if (bodyHeight >= (this.newHeight - (headHeight + footHeight))) {
			this.tbody.style.overflow = '-moz-scrollbars-vertical';
			for (x=0; x<trs.length; x++) {
				var tds = trs[x].getElementsByTagName('td');
				tds[tds.length-1].style.paddingRight += this.scrollWidth + 'px';
			}
		} else {
			this.tbody.style.overflow = '-moz-scrollbars-none';
		}
 
		var cellSpacing = (this.tableEl.offsetHeight - (this.tbody.clientHeight + headHeight + footHeight)) / 4;
		this.tbody.style.height = (this.newHeight - (headHeight + cellSpacing * 2) - (footHeight + cellSpacing * 2)) + 'px';
 
	};
 
	this.tableEl = tableEl;
	this.scrollWidth = 16;
 
	this.originalHeight = this.tableEl.clientHeight;
	this.originalWidth = this.tableEl.clientWidth;
 
	this.newHeight = parseInt(tableHeight);
	this.newWidth = tableWidth ? parseInt(tableWidth) : this.originalWidth;
 
	this.tableEl.style.height = 'auto';
	this.tableEl.removeAttribute('height');
 
	this.containerEl = this.tableEl.parentNode.insertBefore(document.createElement('div'), this.tableEl);
	this.containerEl.appendChild(this.tableEl);
	this.containerEl.style.height = this.newHeight + 'px';
	this.containerEl.style.width = this.newWidth + 'px';
 
 
	var thead = this.tableEl.getElementsByTagName('thead');
	this.thead = (thead[0]) ? thead[0] : null;
 
	var tfoot = this.tableEl.getElementsByTagName('tfoot');
	this.tfoot = (tfoot[0]) ? tfoot[0] : null;
 
	var tbody = this.tableEl.getElementsByTagName('tbody');
	this.tbody = (tbody[0]) ? tbody[0] : null;
 
	if (!this.tbody) return;
 
	if (document.all && document.getElementById && !window.opera) this.initIEengine();
	if (!document.all && document.getElementById && !window.opera) this.initFFengine();
}

function AjustaTable(idTable,nHeight,nWidth)
{
   if (typeof(nWidth)=="undefined")
      var nTamanho=null;

   if (typeof(nHeight)=="undefined")
      var nHeight=90;

   if (document.getElementById(idTable))
      var t = new ScrollableTable(document.getElementById(idTable),nHeight,nWidth);
   return true;
}

/*
   Função e evento do sistema para ajustar automáticamente
   a posição do collmenu na tela e evitar que o menu fique
   na posição incorreta.

   Para usar, deve ser colocado o valor ZERO no atributo
   RESIZECHECK do collmenu.

   Exemplo: oCMenu.resizeCheck=0;

*/

if (! window.onresize)                                               // Caso alguma parte do programa já tenha definido não faz nada.
   window.onresize= new Function ("ReposicionaMenu();");             // Define a função a ser chamada quando a tela for redimensionada.

function PosicionaMenu(nPosicao)
{
   var browser = navigator.appName;
   oCMenu.fromLeft=327;                                       
   if(browser=='Microsoft Internet Explorer')
      oCMenu.menuPlacement='center';
   else
      oCMenu.menuPlacement='left';
   oCMenu.isresized=1;
   oCMenu.construct(1);                                           
}

function ReposicionaMenu(idObjeto)
{
   if (typeof(idObjeto)=="undefined")                                // Se não foi informado um id aplica o default.
      var idObjeto="backgroundCab";                                  

   if (typeof(oCMenu)!='object')
      return;

   if (document.getElementById(idObjeto)  && oCMenu )
   {
      var browser = navigator.appName;
      posicao=document.getElementById(idObjeto).offsetLeft+5;        // calcula posição de início baseada em objeto que se ajusta sozinho com o resize.
           
		if (document.getElementById(idObjeto) == '[object HTMLDivElement]') // Se o elemento for uma div não precisa adicionar 5 pixels, não funciona no ie6
			posicao=document.getElementById(idObjeto).offsetLeft;
      
      tamanho=(document.getElementById(idObjeto).offsetWidth);

      if (tamanho==979)                                              // ajuste para menu de 979px
      {
         if(browser=='Microsoft Internet Explorer') 
            {var posicao = 5;} 
         else 
            { var posicao=posicao-5;}
      }

      oCMenu.fromLeft=posicao;                                       // define a nova posição de início do menu.
      oCMenu.isresized=1;                                            // Controle interno que indica que houve redimensionamento da tela.
      oCMenu.construct(1);                                           // reposiciona a barra principal e reconstrói os menus.
   }
}

function getPosicaoElemento(elemID)
{ 
    var offsetTrail = document.getElementById(elemID);
    var i = 0;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail || i>1) 
    {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") 
    {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

function modalLocalizacao()
{

	var Pleft = getPosicaoElemento("posRodape").left+100;
	var Ptop = getPosicaoElemento("posRodape").top-350;

	var url = '/sets/Agencia/agenciavirtual/PainelVagas/InfoUnidade.php';
	var win = new Window({id: 'win1', url: '/sets/Agencia/agenciavirtual/PainelVagas/InfoUnidade.php',className: 'alphacube', title: 'Localização da Unidade', width:440, height:385, destroyOnClose: true, top:Ptop, left: Pleft, minimizable:true, maximizable:true});win.show();win.setDestroyOnClose();win.toFront();return true;

}
