//FUNCOES DE CALENDARIO E CALCULADORA

	function force_close(div){
		//ADICIONADO POR FERNANDO
		div = 'document.getElementById("'+div+'")';

		div2 = eval (div); div2.innerHTML = ''
	}
	function block(data, obj, div){
		force_close (div)
		obj2 = eval(obj)
		obj2.value = data
	}
	var wynik=0, op=0, nowe=0, nowe2=0, done=1, oset=0, kropka, temp;
	function reset(value){
		document.form1.ekran.value = value;  wynik = 0, op    = 0, nowe  = 0, nowe2 = 0; done  = 1; oset  = 0;
	}
	function verifica(){
		var isNS4 = (navigator.appName=="Netscape")?1:0;
	  	if(isNS4)
			key = e.which;
		else
			key = event.keyCode;
		if ((Key == 37) || (Key == 67) || (Key == 99) || (Key > 41 && Key < 58) || (Key == 13)){
			if (String.fromCharCode(Key)==','){
				Key=46;
			}
			if (Key==99){
				Key=67;                        
			}
			if (String.fromCharCode(Key)=='+' ||String.fromCharCode(Key)=='C'||String.fromCharCode(Key)=='c'||String.fromCharCode(Key)=='/'||String.fromCharCode(Key)=='*'||String.fromCharCode(Key)=='-'||String.fromCharCode(Key)=='.'||Key==13 ){
				if (Key==13){
					button(11,'=');
				}
				else{
					button(11,String.fromCharCode(Key));
				}
				return false;
			}
			else{
				button(String.fromCharCode(Key),'');
				return false;
			}
		}
		else{
			return false; 
		}
	}
	function wspolna(new_temp){
		kropka = 1;
		if(nowe || done){
			nowe = 0;
			done = 0;
			temp = new_temp;
		}
		{
		if (temp.indexOf(".")!=-1){
			kropka=0;
		}
	}
}
function button(ktory,ktory2){
	temp = document.form1.ekran.value;
	if(ktory2=='.')
	{
	wspolna('0');
	if(kropka==1){
		temp += ktory2;
		document.form1.ekran.value = temp;
		oset = 0;
	}
	}
	if(ktory>=0 && ktory<=9){
		wspolna('');
		if(temp==0 && kropka==1)
			temp='';
		temp += ktory;
		document.form1.ekran.value = temp;
		oset = 1;
	}
	if(ktory2=='-' || ktory2=='+' || ktory2=='/' || ktory2=='*'){
		if(nowe) op = ktory2;
		else{
			if(!nowe2){
				op = ktory2;
				wynik = temp;
				nowe2=1;
			}
			else {
				wynik = eval(wynik + op + temp);
				op = ktory2;
				document.form1.ekran.value = wynik;
			}
			oset=0;
			nowe = 1;
		}
	}
	if(ktory2=='1/x' ){
		wynik = eval(1 / temp) ; reset(wynik);
	}
	if(ktory2=='sqrt'){
		wynik = Math.sqrt(temp);
		reset(wynik);
	}
	if(ktory2=='exp' ){
		wynik = Math.exp(temp);
		reset(wynik);
	}
	if(ktory2=='+/-')
		document.form1.ekran.value = eval(-temp);
	if(ktory2=='=' && oset && op!='0')
		reset(eval(wynik + op + temp));
	if (ktory2=='C')
		reset(0);
	if(document.form1.ekran.value[0] == '.')
		document.form1.ekran.value = '0' + document.form1.ekran.value;
	document.form1.ekran.focus();
}
	function force_closecal(div,obj){
		obj2 = eval(obj);
		if (obj2){
			obj2.value=document.form1.ekran.value;
		}
		div2 = eval (div); div2.innerHTML = '';
	}
	function calculadora(obj,div,tam,val){

		//ADICIONADO POR FERNANDO
		div = 'document.getElementById("'+div+'")';

		if(val==''){
			val=0;
		}
		txt  = "<table bgcolor='#efefff' style='border:solid #330099; border-width:2' cellspacing='0' cellpadding='3' border='0' >";
		txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellpadding='0' width='100%' bgcolor='#FFFFFF' class='Cabecalho_Calendario'><tr>";
		txt += "<td width=20% align=center>CALCULADORA</TD>";
		txt += "<td width=20% align=right><a href=javascript:force_closecal('"+div+"','"+obj+"') class='Cabecalho_Calendario' title='Fechar Calculadora'> <b>X</b></a></td></tr></table></td></tr>";
		txt +="<tr><td valign='top' ><p align='left'><table width='100%' border='0' cellspacing='0' cellpadding='0'>  <tr >"
		txt +="<td  width='100%' valign='top'>         <form name='form1' id='form1'>          <TABLE bgcolor='330099'>            <TR><TD>"
		txt +="<TABLE BORDER=0 cellspacing=3 cellpadding=1 bgcolor='efefff'>                  <TR align=center bgcolor='CCCCFF'>                    <TD colspan=5>                      <input name='ekran' value='"+val+"'  onkeypress=\"return verifica();\" size='20' style='text-align: right; float: left' class=campo>                    </TD></TR>"
		txt +="<TR align=center bgcolor='CCCCFF'>                    <TD colspan=4><b>                    <font face='Georgia, Times New Roman, Times, serif' size='2' color='0000FF'>FINANC</font></b></TD>                    <TD >                      <input type='button' name='C' value='  C  ' onclick=\"button(11,'C');\" class=botao>                    </TD>                  </TR>"
		txt +="<TR align=center bgcolor='CCCCFF'>                    <TD>                      <input type='button' name='7' value='  7  '   onclick=\"button(7 ,'');\" class=botao>                    </TD><TD>                      <input type='button' name='8' value='  8  '   onclick=\"button(8 ,'');\" class=botao>                    </TD>"
		txt +="<TD> <input type='button' name='9' value='  9  '   onclick=\"button(9 ,'');\" class=botao>                    </TD><TD> <input type='button' name='/' value='  /  '   onclick=\"button(11,'/');\" class=botao>                    </TD>"
		txt +="<TD>  <input type='button' name='sqrt' value='sqrt' onclick=\"button(11,'sqrt');\" class=botao>                    </TD> </TR>                  <TR align=center bgcolor='CCCCFF'>                    <TD>                      <input type='button' name='4' value='  4  ' onclick=\"button(4,'');\" class=botao>                    </TD>"
		txt +="<TD><input type='button' name='5' value='  5  ' onclick=\"button(5,'');\" class=botao>                    </TD>"
		txt +="<TD>                          <input type='button' name='6' value='  6  ' onclick=\"button(6,'');\" class=botao>                    </TD><TD>                      <input type='button' name='*' value=' *  '  onclick=\"button(11,'*');\" class=botao><TD>                      <input type='button' name='exp' value='exp' onclick=\"button(11,'exp');\" class=botao>                    </TD>"
		txt +="</TR>                  <TR align=center bgcolor='CCCCFF'>                    <TD>                      <input type='button' name='1' value='  1  '  onclick=\"button(1,'');\" class=botao>                    </TD>"
		txt +="<TD>                      <input type='button' name='2' value='  2  '  onclick=\"button(2,'');\" class=botao>                    </TD><TD>                      <input type='button' name='3' value='  3  '  onclick=\"button(3,'');\" class=botao>                    </TD><TD>                      <input type='button' name='-' value='  -  '  onclick=\"button(11,'-');\" class=botao>                    </TD><TD>                      <input type='button' name='1/x' value='1/x ' onclick=\"button(11,'1/x');\" class=botao>                    </TD>                  </TR>"
		txt +="<TR align=center bgcolor='CCCCFF'>                    <TD>                      <input type='button' name='0' value='  0  '   onclick=\"button(0,'');\" class=botao>                    </TD><TD>                      <input type='button' name='+/-' value=' +/- ' onclick=\"button(11,'+/-');\" class=botao>                    </TD><TD>                      <input type='button' name='.' value='  ,   '   onclick=\"button(11,'.');\" class=botao>                    </TD><TD>                      <input type='button' name='+' value=' +  '   onclick=\"button(11,'+');\" class=botao>                    </TD><TD>                      <input type='button' name='=' value='  =  '   onclick=\"button(11,'=');\" class=botao>                    </TD></TR></TABLE></TD></TR></TABLE></form></td></tr></table> </td></tr>";
		txt += "</table>";
		div2 = eval (div);
		div2.innerHTML = txt;
		document.form1.ekran.focus();
	}


function popdate(obj,div,tam,ddd){
	if (ddd){
		day = "";
		mmonth = "";
		ano = "";
		c = 1;
		char1 = "";
		for (s=0;s<parseInt(ddd.length);s++){
			char1 = ddd.substr(s,1);
			if (char1 == "/"){
				c++;
				s++;
				char1 = ddd.substr(s,1);
			}
			if (c==1) day    += char1;
			if (c==2) mmonth += char1;
			if (c==3) ano    += char1;
		}
		ddd = mmonth + "/" + day + "/" + ano;
	}
	if(!ddd) {today = new Date();} else {today = new Date(ddd);}
	date_Form = eval (obj);
	if (date_Form.value == "") { date_Form = new Date();} else {date_Form = new Date(date_Form.value);}
	ano = today.getFullYear();
	mmonth = today.getMonth ();
	day = today.toString ().substr (8,2);
	umonth = new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro");
	days_Feb = (!(ano % 4) ? 29 : 28);
	days = new Array (31, days_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	if ((mmonth < 0) || (mmonth > 11))  alert(mmonth);
	if ((mmonth - 1) == -1) {month_prior = 11; year_prior = ano - 1;} else {month_prior = mmonth - 1; year_prior = ano;}
	if ((mmonth + 1) == 12) {month_next  = 0;  year_next  = ano + 1;} else {month_next  = mmonth + 1; year_next  = ano;}
	txt  = "<table bgcolor='#efefff' style='border:solid #330099; border-width:2' cellspacing='0' cellpadding='3' border='0' width='"+tam+"' height='"+tam*1.1 +"'>";
	txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>";
	txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano-1).toString())+"') class='Cabecalho_Calendario' title='Ano Anterior'><<</a></td>";
	txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_prior+1).toString() + "/" + year_prior.toString())+"') class='Cabecalho_Calendario' title='Mês Anterior'><</a></td>";
	txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"') class='Cabecalho_Calendario' title='Próximo Mês'>></a></td>";
	txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"') class='Cabecalho_Calendario' title='Próximo Ano'>>></a></td>";
	txt += "<td width=20% align=right><a href=javascript:force_close('"+div+"') class='link_verde' title='Fechar CalendÃ¡rio'><b>FECHAR</b></a></td></tr></table></td></tr>";
	txt += "<tr><td colspan='7' align='right' bgcolor='#ccccff' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes'>" + ano.toString() + "</a>";
	txt += " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes'>" + umonth[mmonth] + "</a> <div id='popd' style='position:absolute'></div></td></tr>";
	txt += "<tr bgcolor='#FFFFFF'><td width='14%' class='dia' align=center><b>Dom</b></td><td width='14%' class='dia' align=center><b>Seg</b></td><td width='14%' class='dia' align=center><b>Ter</b></td><td width='14%' class='dia' align=center><b>Qua</b></td><td width='14%' class='dia' align=center><b>Qui</b></td><td width='14%' class='dia' align=center><b>Sex<b></td><td width='14%' class='dia' align=center><b>Sab</b></td></tr>";
	today1 = new Date((mmonth+1).toString() +"/01/"+ano.toString());
	diainicio = today1.getDay () + 1;
	week = d = 1;
	start = false;
	for (n=1;n<= 42;n++){
		if (week == 1)  txt += "<tr bgcolor='#efefff' align=center>";
		if (week==diainicio) {start = true;}
		if (d > days[mmonth]) {start=false;}
		if (start){
			dat = new Date((mmonth+1).toString() + "/" + d + "/" + ano.toString());
			day_dat   = dat.toString().substr(0,10);
			day_today  = date_Form.toString().substr(0,10);
			year_dat  = dat.getFullYear ();
			year_today = date_Form.getFullYear ();
			if (d <=9){
				Usea=d;
				d ="0"+d.toString();
			}
			else{
				Usea=d;
			}
			mes=mmonth;
			mes=mes+1;
			if (mes <=9)
				mes="0"+mes;
			colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
			txt += "<td"+colorcell+" align=center><a href=javascript:block('"+  d + "/" + mes + "/" + ano.toString() +"','"+ obj +"','" + div +"') class='data'>"+ d.toString() + "</a></td>";
			d=Usea;
			d ++
		}
		else{
			txt += "<td class='data' align=center> </td>";
		}
		week ++
		if (week == 8){
			week = 1; txt += "</tr>";
		}
	}
	txt += "</table>";

	//ADICIONADO POR FERNANDO
	div = 'document.getElementById("'+div+'")';

	div2 = eval (div);
	div2.innerHTML = txt;
}

// funcao para exibir a janela com os meses
function pop_month(obj, div, tam, ano)
{
 txt  = "<table bgcolor='#CCCCFF' border='0' width=80>"
 for (n = 0; n < 12; n++) { txt += "<tr><td align=center><a class=data href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+("01/" + (n+1).toString() + "/" + ano.toString())+"')>" + umonth[n] +"</a></td></tr>" }
 txt += "</table>"
 
 //ADICIONADO POR FERNANDO
 var isNS4 = (navigator.appName=="Netscape")?1:0;
 if(isNS4==1)
 {
	popd = 'document.getElementById("popd")';
	popd = eval (popd);
 }
 popd.innerHTML = txt;

}

// funcao para exibir a janela com os anos
function pop_year(obj, div, tam, umonth)
{
 txt  = "<table bgcolor='#CCCCFF' border='0' width=160>"
 l = 1
 today2 = new Date();
 n=today.getFullYear();
 a=today.getFullYear()+21;
 for (n; n<a; n++)
 {  if (l == 1) txt += "<tr>"
    txt += "<td align=center><a class='data' href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+(umonth.toString () +"/01/" + n) +"')>" + n + "</a></td>"
    l++
    if (l == 4)
       {txt += "</tr>"; l = 1 }
 }
 txt += "</tr></table>"

 //ADICIONADO POR FERNANDO
 var isNS4 = (navigator.appName=="Netscape")?1:0;
 if(isNS4==1)
 {
	popd = 'document.getElementById("popd")';
	popd = eval (popd);
 }
 popd.innerHTML = txt;

}


//FIM - FUNCOES DE CALENDARIO E CALCULADORA


function abreSistema(formLogin){
	chLogin=document.getElementById("user").value;
	chSenha=document.getElementById("pass").value;
	if (document.getElementById("loja")){
		chLoja=document.getElementById("loja").value;
	}
	else{
		chLoja = 1;
	}
	if(window.name!="sistema"){
		document.getElementById("user").value='';
		document.getElementById("pass").value='';
		if (document.getElementById("loja")){
			document.getElementById("loja").value='';
		}
		document.getElementById("user").focus();
		var isNS4 = (navigator.appName=="Netscape")?1:0;
		//if(isNS4){
		//	window.open(formLogin+'?user='+chLogin+'&pass='+chSenha+'&loja='+chLoja,'_parent','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes');
		//}
		//else{
			if(window.open(formLogin+'?user='+chLogin+'&pass='+chSenha+'&loja='+chLoja,'sistema','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes, fullscreen=yes')){
			//nao funciona no mozilla o código abaixo
		//		setTimeout("window.opener=null;window.close()",10);
			}
		//}
	}
	else{
		window.location='/'+formLogin+'?user='+chLogin+'&pass='+chSenha;
	}
}

function teste(){
	alert(1);
}
function focoCampo(idcampo){
	setTimeout('document.getElementById("'+idcampo+'").focus();',0);
}

function escolha(link){
window.open(link,'Janela', 'top=0,left=0,scrollbars=yes,resizable=yes')
}
function escolha2(link){
window.open(link,'Janela2', 'top=0,left=0,scrollbars=yes,resizable=yes')
}

function mascara_data(obj){
ajustar_numero(obj);
FormataData(obj,10,event);
	
	/*
if (obj.value.length == 2){obj.value =obj.value +
'/';}
if (obj.value.length == 5){obj.value = obj.value +
'/';}
*/
}

function numeros(obj){
if (obj.value == ','){obj.value =obj.value +
'.';}

}

function ChangeBackColor(xObject,tipo,cor) {
	if (tipo=='E')
	{
		if (cor!='')
			{
			xObject.bgColor = cor;
			}
		else
			{
   			xObject.bgColor = cor;
			}
	}
	else
	{
		if (cor!='')
		{
		xObject.bgColor = cor;	
		}
		else
		{
			xObject.bgColor = cor;
		}
		 
	}
}



function aviso (campo, msg)
{ //  alert(msg);
//    campo.focus();
//    campo.select();
    return false;
}

//-------------------------------
function ajustar_numero(input)
	{
	if ((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
	}
//-------------------------------
function VerficaTamanho(campo,tamanho,proximocampo)
{
 if (campo.value.length == tamanho)
 	proximocampo.focus();
}


function FormataValor(campo,tammax,teclapres) {

var Key;
Key = event.keyCode;

if ((event.keyCode<48)||(event.keyCode>57))
	{           event.returnValue = false ;          }
else          {                    

   var tecla = teclapres.keyCode;

	var vr = campo.value;
	var vrn = "";
    tam = vr.length;
    if (tam>tammax) event.returnValue = false;
     else
	 {
	for(var i=0; i<tam; i++)
	  if(vr.charAt(i)!=','&&vr.charAt(i)!='.') vrn += vr.charAt(i);
	vr=vrn;   tam = vr.length;

	tam++;

	if (tam>2) {vr =vr.substr(0,tam-2)+'.'+ vr.substr(tam-2,tam);tam++;}
    if (tam>6) {vr =vr.substr(0,tam-6) + vr.substr(tam-6,tam);tam++;}
    if (tam>10){vr =vr.substr(0,tam-10)+ vr.substr(tam-10,tam);tam++;}
    
	campo.value=vr; 	
	}
}
}

function FormataData(msg,tammax,teclapres) {
campo=msg; 
  
  var tam = campo.value.length;

  if(tam == 2) 
     {var dia = parseInt(campo.value);
	  if(dia==0) dia = parseInt(campo.value.substring(1,2));
	  if(dia>0 && dia <32) 
	      campo.value = campo.value+ "/";
      else
	//      campo.value = dia+"";
	      event.returnValue = false;
	 }
    if(tam == 5)
	  {var mes = parseInt(campo.value.substring(3,5));
 	  if(mes==0) mes = parseInt(campo.value.substring(4,5));
	  if(mes>0 && mes <13) 
	      campo.value = campo.value+ "/";
      else
	      event.returnValue = false;
      }
   }



//-------------------------------
function RetiraCaracteresInvalidos(strCampo,tam) {
	nTamanho = strCampo.length;
	szCampo = "";
	j=0;
	for (i = nTamanho-1;i>=0;i--) 
	{
		if (isDigit(strCampo.charAt(i)))	{
			szCampo = strCampo.charAt(i) + szCampo;
			j++;
			if (j > tam) break;
		}
	}
	if (szCampo.length < tam) {
		for (i = szCampo.length;i<tam;i++) 
		{
			szCampo = "0" + szCampo;
		}
	}
    return szCampo;
}
//-------------------------------
function ContaDigitos(strCampo) {
	nTamanho = strCampo.length;
	szCampo = "";
	j=0;
	for (i = nTamanho-1;i>=0;i--) 
	{
		if (isDigit(strCampo.charAt(i)))	{
			szCampo = strCampo.charAt(i) + szCampo;
			j++;
		}
	}
    return j;
}
//-------------------------------
function validaCPF(rcpf1,c,bAceitaBranco) {

	if ((ContaDigitos(rcpf1.value) > 11 )) {
	   return aviso(rcpf1, c + " inválido.");
	}
	var CPFaux = RetiraCaracteresInvalidos(rcpf1.value,11);
	NR_CPF = CPFaux.substr(0,9);
	var rcpf2 = CPFaux.substr(9,2);
	/*
	if ((isEmpty(NR_CPF)) && (isEmpty(foco)) && bAceitaBranco == false) {
     return aviso(rcpf1, c + " inválido.");
	}
	else if (bAceitaBranco == true)
		return true; 
*/
  if( CPFaux == "00000000000" || CPFaux == "00000000191" || CPFaux == "99999999999")
     return aviso(rcpf1,c + " inválido.");

  d1 = 0;
  for (i=0;i<9;i++)
    d1 += NR_CPF.charAt(i)*(10-i);
  d1 = 11 - (d1 % 11);
  if (d1>9) d1 = 0;

  if (rcpf2.charAt(0) != d1)
    return aviso(rcpf1,c+" inválido.");

  d1 *= 2;
  for (i=0;i<9;i++)
    d1 += NR_CPF.charAt(i)*(11-i);
  d1 = 11 - (d1 % 11);
  if (d1>9) d1 = 0;

  if (rcpf2.charAt(1) != d1)
    return aviso(rcpf1,c+" inválido.");

  return true;

}

//-------------------------------

function PoeZeros(valor,tam) {

	ntam = valor.value.length;
  	if (ntam != 0)  {
	   zeros = '0000000000000';
	   if (tam != ntam) 
		valor.value = zeros.substr(1,13-ntam)+valor.value;
	}
	
}

//-------------------------------

function validaTIT(rcpf1) {
  if (rcpf1.value.length == 0)  
    return true;

  if( !( isInteger(rcpf1.value)) )
     return aviso(rcpf1,"Número do título eleitoral deve ser numérico.");

  if ( !(rcpf1.value.length == 13)  ) 
     PoeZeros(rcpf1,13);

  rcpf2 = rcpf1.value.substr(11,2);
  j = rcpf1.value.substr(9,2);

  if ( (j<1) || (j>28) )
	return aviso(rcpf1,"Número do título eleitoral inválido.")

  d1 = 0;
  for (i=0;i<9;i++)  
    d1 += rcpf1.value.charAt(i)*(10-i);
  d1 = (d1 % 11);
  if (d1<=1){
     if (j<=2)
        d1 = 1 - d1;
      else
        d1 = 0;}
   else
     d1 = 11 - d1;

  if (rcpf2.charAt(0) != d1)
    return aviso(rcpf1,"Número do título eleitoral inválido.");

  d1 *= 2;
  for (i=9;i<11;i++)
    d1 += rcpf1.value.charAt(i)*(13-i);
  d1 = (d1 % 11);
  if (d1<=1){
     if (j<=2)
        d1 = 1 - d1;
      else
        d1 = 0;}
   else
     d1 = 11 - d1;

  if (rcpf2.charAt(1) != d1)
    return aviso(rcpf1,"Número do título eleitoral inválido.");

  return true;

}

//-------------------------------

function EhNumero(field) {
        if (field.value.length == 0) return true;
        if (!isFloat(field) )
 //           return aviso(field,"Digite um valor numérico com no máximo 13 dígitos.\nNÃ£o utilize ponto.\nOs centavos devem ser separados por vírgula.\n       Ex.:   1387,98");
   return aviso(field,"Digite os campos de valores com centavos, inclusive centavos 00, sem ponto nem vírgula."); 
        return true;
    }

//-------------------------------

function EhNumeroPuro(field) {
        var valor = field.value;
        if ( !isInteger(valor) )
            return aviso(field,"Digite um valor numérico sem valores decimais.\nEx.:   13");
        
        return true;
    }

//-------------------------------

function isDigit (c){   
	
	    return ((c >= "0") && (c <= "9"))
    }  

//-------------------------------

function isInteger (s) {

    var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return false;
     
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    return true;
}

//-------------------------------

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 isFloat (f)

{   var i;
    var decimalPointDelimiter = ",";
    var seenDecimalPoint = false;
    var posDecPoint = 0;
    var s = f.value;
    s = s.replace(".","");
    s = s.replace(".","");
    s = s.replace(".","");        

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return false;
         else return true;

    if (s == decimalPointDelimiter) return false;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if ( (c == decimalPointDelimiter) && !seenDecimalPoint){ 
              posDecPoint = i;
              seenDecimalPoint = true }
         else {
              if (!isDigit(c)) return false;}
    }

    if (f.value.length > 13) 
			return false;
    return true;
}


//-------------------------------

function diasInFevereiro (ano){

    return (  ((ano % 4 == 0) && ( (!(ano % 100 == 0)) || (ano % 400 == 0) ) ) ? 29 : 28 );
}

//-------------------------------
// dd/mm/aaaa
function validaData (campo) {
	if(campo.value.length!=10) return aviso(campo,"Data inválida.");
    if(campo.value.substring(2,3)!="/" || campo.value.substring(5,6)!="/") return aviso(campo,"Data inválida.");
    
	var dia = campo.value.substring(0,2);
	var mes = campo.value.substring(3,5);
	var ano = campo.value.substring(6,10);
//    if (isEmpty(ano.value) && isEmpty(mes) && isEmpty(dia)) return aviso(campo,"Informe a data");

//   if (!(isAno(ano.value) && isMes(mes.value) && isDia(dia.value))) return aviso(campo,"Data inválida.");

    var intAno = parseInt(ano,10);
    var intMes = parseInt(mes,10);
    var intDia = parseInt(dia,10);
    dias = new Array(13);
    dias[1] = 31;
    dias[2] = 29;   // must programmatically check this
    dias[3] = 31;
    dias[4] = 30;
    dias[5] = 31;
    dias[6] = 30;
    dias[7] = 31;
    dias[8] = 31;
    dias[9] = 30;
    dias[10] = 31;
    dias[11] = 30;
    dias[12] = 31;

    if (intDia > dias[intMes]) return aviso(campo,"Data inválida."); 

    if ((intMes == 2) && (intDia > diasInFevereiro(intAno))) return aviso(campo,"Data inválida.");

	//if (ano.length == 2)
		ano = "19" + ano;
		
     if (ano<"1000") return aviso(campo,"Data inválida."); 

    return true;
}
//-------------------------------

function separadorDecimal(valor) {

      return (parseFloat(valor) / 100);
    }
    
//-------------------------------

function trunca(valor) {
       valor *= 100;
       valor = parseFloat(valor);
       return separadorDecimal(valor);
    }
	
function valida_data( data ) {
    var Sano;
    var Smes;
    var Sdia;
    SData = data.replace( " ", "" );
    Sdia = SData.substring( 0, 2 );
    Sdia = parseInt(Sdia,10);
    Smes = SData.substring(3,5);
    Smes = parseInt(Smes,10);
    Sano = SData.substring(6,10);
    Sano = parseInt(Sano,10);

    if( !( SData.length == 10 ) || isNaN( Sdia ) || isNaN( Smes ) || isNaN( Sano ) ||
         Sdia < 1 || Sdia > 31 || Smes < 1 || Smes > 12 ||
         ( ( ( Smes == 4 ) || ( Smes == 6 ) || ( Smes == 9 ) || ( Smes == 11 ) ) && ( Sdia > 30 ) )  ||
         ( ( Smes == 2 ) && ( Sdia > 29 ) && bissexto( Sano ) ) ||
         ( Smes == 2 ) && ( Sdia > 28 ) && !bissexto( Sano )) return false;

    else return true;
}
/* 
*  Para poder esconder coisas e aparecer um DIV 
* <a id="lnkEST" class="texto_sobre" style="" href="JavaScript:ShowHide('EST');">[conheça mais sobre...]</a>
* <div id="EST" style="display: none; margin-left: 30px;">
* <div>
*/

function ShowHide(obj){

	if (document.getElementById(obj).style.display == "inline")
		{ 
		document.getElementById(obj).style.display = "none";
		document.getElementById("lnk" + obj).innerHTML = "[conheça mais sobre...]";
		}
	else 	
		{
		document.getElementById(obj).style.display = "inline";
		document.getElementById("lnk" + obj).innerHTML = "[- sobre]";
		}	
}


function desmascara( str, tipo ) {
    if( tipo == "data" ) {
        for( var i = 0; i < str.length; i++ )
            if( !isNum( str.substring( i, i + 1 ) ) && !( str.substring( i, i + 1 ) == "/" && ( i == 2 || i == 5 ) ) ){
                str = str.replace( str.substring( 0, i + 1 ), str.substring( 0, i ) );
                i--;
            }
    }
    else if( tipo == "dinheiro" ) {

        if( str.indexOf( "," ) != -1 ) {
            arrSplit = str.split(",");
            str = arrSplit[ 0 ] + "," + arrSplit[ 1 ];
        }

        for( var i = 0; i < str.length; i++ )
            if( !isNum( str.substring( i, i + 1 ) ) && str.substring( i, i + 1 ) != "," ){
                str = str.replace( str.substring( 0, i + 1 ), str.substring( 0, i ) );
                i--;
            }
    }
    else {
        for( var i = 0; i < str.length; i++ )
            if( !isNum( str.substring( i, i + 1 ) ) ){
                str = str.replace( str.substring( 0, i + 1 ), str.substring( 0, i ) );
                i--;
            }
    }


    return str;
}
function mascara( str, tipo ) {
    var quantidade;
    var a_repor;
    if( tipo == "cnpj" ) {
        quantidade = 14 - str.length;
        for( var i = 0; i < quantidade; i++ )
                str = "0" + str;
        //99.999.999/9999-99
        str = str.replace( str.substring( 0, 2 ), str.substring( 0, 2 ) + "." );
        str = str.replace( str.substring( 0, 6 ), str.substring( 0, 6 ) + "." );
        str = str.replace( str.substring( 0, 10 ), str.substring( 0, 10 ) + "/" );
        str = str.replace( str.substring( 0, 15 ), str.substring( 0, 15 ) + "-" );
    }
    else if( tipo == "cpf" ) {
        quantidade = 11 - str.length;
        for( var i = 0; i < quantidade; i++ )
                str = "0" + str;
        //999.999.999-99
        str = str.replace( str.substring( 0, 3 ), str.substring( 0, 3 ) + "." );
        str = str.replace( str.substring( 0, 7 ), str.substring( 0, 7 ) + "." );
        str = str.replace( str.substring( 0, 11 ), str.substring( 0, 11 ) + "-" );
    }
    else if( tipo == "cep" ) {
        quantidade = 8 - str.length;
        for( var i = 0; i < quantidade; i++ )
                str = "0" + str;
        //999.999.999-99
		if(str[5] != '-'){
       		str = str.replace( str.substring( 0, 5 ), str.substring( 0, 5 ) + "-" );
		}
    }
    else if( tipo == "tituloEleitor" ) {
        quantidade = 12 - str.length;
        for( var i = 0; i < quantidade; i++ )
                str = "0" + str;
        //9999999999/99
        str = str.replace( str.substring( 0, 3 ), str.substring( 0, 3 ) + "." );
        str = str.replace( str.substring( 0, 7 ), str.substring( 0, 7 ) + "." );
        str = str.replace( str.substring( 0, 12 ), str.substring( 0, 12 ) + "/" );
    }
    else if( tipo == "data" ) {
        str = str.replace( str.substring( 0, 2 ), str.substring( 0, 2 ) + "/" );
        str = str.replace( str.substring( 0, 5 ), str.substring( 0, 5 ) + "/" );
    }
    else if( tipo == "dinheiro" ) {
        if( str.indexOf( "," ) == -1 && str != "" )
            str = str + ",00";

        i = str.length - str.indexOf( "," ) + 3;
        while( i < str.length ) {
            a_repor = str.substring( 0, str.length - i );
            str = str.replace( a_repor, a_repor + "." );
            i += 4;
        }
    }
    return str;
}

function isCNPJ( cnpj ) {
    if( cnpj.length == 0 )
        return false;
    cnpj = mascara( cnpj, "cnpj" );
    cnpj = desmascara( cnpj );
    cnpj = trim( cnpj );

    var x = cnpj.length - 2;
    if( testaCNPJ( cnpj, x ) )
    {
        x = cnpj.length - 1;
        return testaCNPJ( cnpj, x );
    }
    else
        return 0;
}

function testaCNPJ( cnpj, x ) {
    var Vercnpj = 0;
    var ind = 2;
    for( y = x; y > 0; y-- ){
            Vercnpj += parseInt( cnpj.substring( y - 1, y ) ) * ind;
            if( ind > 8 )
                    ind = 2;
            else
                    ind++;
    }

    Vercnpj %= 11;
    if( ( Vercnpj == 0 ) || ( Vercnpj == 1 ) )
        Vercnpj=0;
    else
        Vercnpj = 11 - Vercnpj;

    return Vercnpj == parseInt( cnpj.substring( x, x + 1 ) );

}

function isCPF( cpf ) {
  cpf = trim( cpf );
  cpf = desmascara( cpf );
  cpf = mascara( cpf, "cpf" );
  cpf = desmascara( cpf );

  var tamanho = cpf.length;
  var soma = 0;
  var resto;
  var i;

  if( tamanho != 11 || numRepetidos( cpf ) )
    return false;

  for ( i = 0; i < 9; i++ )
    soma += parseInt( cpf.substring( i, i + 1 ) ) * ( 10 - i );

  resto = 11 - ( soma % 11 );

  if ( resto == 10 || resto == 11 )
    resto = 0;

  if ( resto != parseInt( cpf.substring( 9, 10 ) ) )
    return 0;

  soma = 0;

  for ( i = 0; i < 10; i ++ )
    soma += parseInt( cpf.substring( i, i + 1 ) ) * (11 - i);
  resto = 11 - ( soma % 11 );

  if ( resto == 10 || resto == 11 )
    resto = 0;

  if ( resto != parseInt( cpf.substring( 10, 11 ) ) )
    return 0;

  return 1;
}


function FormataCNPJ(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

function isNum( caractere ) {
    var exp1 = /[0-9]/;
    return( exp1.test( caractere ) );
}

function trim( str ) {
    return String( str ).replace( /^\s+/, "" ).replace( /[\s]+$/, "" );
}
function so_numero(evtKeyPress)
{
  var nTecla = 0;
  if (document.all) 
  {
    nTecla = evtKeyPress.keyCode;
  } else {
    nTecla = evtKeyPress.which;
  }
  if((nTecla> 47 && nTecla <58) || nTecla == 8 || nTecla == 127 || nTecla == 0 || nTecla == 9  || nTecla == 13)
  {
    return true;
  } else {
    return false;
  }
}

function valida_email(emailobj){

      if (emailobj.value != ""){

        if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailobj.value))){

          alert("Favor informar um email válido.");

          emailobj.focus();

          return (false);

        }else{

          return (true);

        }

      }

}

function formata(obj,tipo){
    if(tipo=="telefone"){
      valor='';
      anterior=obj.getAttribute("anterior");
      if(anterior==null) anterior='';

      if(anterior.length < obj.value.length){
        for(i=0;i<obj.value.length && i < 14;i++){
          ultimo_char=obj.value.substring(i,i+1);

          if(ultimo_char == "0" || ultimo_char == "1" || ultimo_char == "2" || ultimo_char == "3" ||
             ultimo_char == "4" || ultimo_char == "5" || ultimo_char == "6" || ultimo_char == "7" ||
             ultimo_char == "8" || ultimo_char == "9" || ultimo_char == "(" ){
            valor=valor+ultimo_char;
            tamanho=valor.length;
            if(tamanho==1 && ultimo_char != '('){
              valor='('+valor;
            }
            else if (tamanho==3){
              valor=valor+') ';
            }
            else if (tamanho==9){
              valor=valor+'-';
            }
            else if (tamanho==14){
              valor=valor.substring(0,9)+valor.substring(10,10)+'-'+valor.substring(10);
            }
          }
        }
        obj.value=valor;
      }
      obj.setAttribute("anterior",obj.value);
    }
  }
  
  
	function ShowHide(obj){
		if (document.getElementById(obj).style.display == "inline")
		{
			document.getElementById(obj).style.display = "none";
			document.getElementById("lnk" + obj).innerHTML = "[mais ...]";
		}
		else
		{
			document.getElementById(obj).style.display = "inline";
			document.getElementById("lnk" + obj).innerHTML = "[mais ...]";
		}
	}
	
	function escreve_div( nome, str )
	{
	    eval( "objTemp = document.getElementById('" + nome + "');" );
	    if (typeof objTemp != "undefined" )
	    {
	        objTemp.innerHTML=str;
	    }
	}
	function enviar_dados(acao){
		pode_enviar=true;
		for ( var i = 0; i < document.frm.elements.length; i++ )
		{
			x=document.frm.elements[ i ];
			//x.className="";
			obr= x.getAttribute("obrigatorio");
			//x.className=x.getAttribute("class");

			if (obr!=1) obr=0;
			else if(x.value == "")
			{
				x.className="Estilo5";
				escreve_div("mensagem","<font class = \"\" color=\"0000FF\">Mensagem:</font> <font color=\"FF0000\"> Os campos em <font color=\"#0000FF\">Azul</font> são obrigatórios</font>");
				//document.location='<?$PHP_SELF?>#top';
				pode_enviar=false;
			}
		}
		
		if(pode_enviar)
		{
			document.frm.acao.value=acao;
			document.frm.submit();
		}
	}

	function link(id){
			document.frm.crcoid.value = id;
			document.frm.acao.value = "alterar";
			document.frm.submit();
	}
	function $(id) {
        return document.getElementById(id);
    }
		
	function validar(){
        pode_enviar=true;
        frm_obj = document.getElementById("frm");
    
        for ( var i = 0; i < frm_obj.elements.length; i++ ){
            obj = frm_obj.elements[ i ];
            obr = obj.getAttribute("obrigatorio");
            if(obr == 1){
                if(obj.value == ""){
                    obj.className = "form_field_error"
                    pode_enviar=false;
                }else{
                    obj.className = "form_field"
                }
            }else{
                if(obj.className == "form_field_error"){
                    obj.className = "form_field"
                }
            }
        }
        if(pode_enviar == true){
            document.getElementById('msg').innerHTML = "";
        }else{
            document.getElementById('msg').innerHTML = "Campos Obrigatórios não preenchidos";
        }
        return pode_enviar;
    }
    
    function enviar(acao){
      if(validar()){
        document.frm.acao.value=acao;
  			document.frm.submit();
      }
    }
	
	
	
	function moeda(campo,casas){
	var valida = campo.value.substring(campo.value.length-1);	
	if(valida != 0 && valida != 1 && valida != 2 && valida != 3 && valida != 4 && valida != 5 && valida != 6 && valida != 7 && valida != 8 && valida != 9)
		campo.value = campo.value.substr(0,campo.value.length-1);
	if(parseFloat(campo.value) < 1)
		campo.value = parseFloat(campo.value.replace('0.',''));
	var zeros = '';
	if(campo.value.length <= casas){
		for(i=0;i<casas-campo.value.length;i++){
			zeros += '0';
		}
		campo.value = '0.' + zeros + campo.value;
	}
	else{
		campo.value = campo.value.substr(0,campo.value.length -casas).replace('.','') + '.' + campo.value.substr(campo.value.length -casas);
	}
}

function formatarDt(src, mask, e)
{
    if (e.keyCode != 8){ //backspace
        var i = src.value.length;
        var saida = mask.substring(0,1);
        var texto = mask.substring(i)
        if (texto.substring(0,1) != saida) {
            src.value += texto.substring (0,1);
        }
    }

}


function valida_data( data ) {
/*********************************************************************************/
// Nome:      valida_data
// Descrição: verifica se uma data é uma data válida e possível
// Retorno:   boolean
// Uso:       return valida_data(this.value) || if(!valida_data(this.value)){...}
/*********************************************************************************/
    var Sano;
    var Smes;
    var Sdia;
    SData = data.replace( " ", "" );
    Sdia = SData.substring( 0, 2 );
    Sdia = parseInt(Sdia,10);
    Smes = SData.substring(3,5);
    Smes = parseInt(Smes,10);
    Sano = SData.substring(6,10);
    Sano = parseInt(Sano,10);
    sep1 = SData.substring( 2, 3 );
    sep2 = SData.substring( 5, 6 );

    if( !( SData.length == 10 ) || isNaN( Sdia ) || isNaN( Smes ) || isNaN( Sano ) ||
         (sep1 != '/') || (sep2 != '/') ||
         Sdia < 1 || Sdia > 31 || Smes < 1 || Smes > 12 ||
         ( ( ( Smes == 4 ) || ( Smes == 6 ) || ( Smes == 9 ) || ( Smes == 11 ) ) && ( Sdia > 30 ) )  ||
         ( ( Smes == 2 ) && ( Sdia > 29 ) && bissexto( Sano ) ) ||
         ( Smes == 2 ) && ( Sdia > 28 ) && !bissexto( Sano )) return false;

    else return true;
}
