//==========================================================================================
//PURPOSE: Remove leading blanks from our string.
//IN: str - the string we want to LTrim
//==========================================================================================
function LTrim(str)

{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}

//==========================================================================================
//PURPOSE: Remove trailing blanks from our string.
//IN: str - the string we want to RTrim
//==========================================================================================
function RTrim(str)
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}

//==========================================================================================
// Concatena o traço para preencher conta corrente e agencia bancária	
//==========================================================================================
function FormataDado(campo,tammax,pos,teclapres){
	var tecla = teclapres.keyCode;
	vr = document.Proposta[campo].value;
	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 == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
	 		document.Proposta[campo].value = vr ;}
		if ( tam > pos && tam <= tammax ){
			document.Proposta[campo].value = vr.substr( 0, tam - pos ) + '-' + vr.substr( tam - pos, tam );}
	}
	//alert("campo: " + document.Proposta[campo+1].name);
	if ( !teclapres.shiftKey && tecla == 9 && document.Proposta[campo+1].name == "senhaConta" && document.applets['tclJava'] ){
		//alert("aki 1");
			document.applets['tclJava'].setFocus();
	}
}


//==========================================================================================
// Concatena a virgula em valores numericos.	
//==========================================================================================
function FormataVirgula(campo,tammax,pos,teclapres)
{
	var tecla = teclapres.keyCode;
	// alert(tecla);

	if ( tecla >= 48 && tecla <= 57 )
	{
	        var cmd = 'document.Simulador.' + campo + '.value';
		var vr = eval(cmd);

		//if ( tecla == 8 || tecla == 88 || tecla >= 96 && tecla <= 105 )
        	//  return false;

       		var old_vr = vr;
		vr = vr.replace( "-", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ",", "" );
		vr = vr.replace( "/", "" );

		tam = vr.length+1;
		tammax = tammax - 1; // retira o caracter ocupado pela virgula

		//if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; } // espaço
		//if (tecla == 8 ){ tam = tam - 1 ; } // espaço
		if ( tam <= pos )
 			{ document.Simulador[campo].value = vr ;}
		if ((tam > pos) && (tam <= tammax))
			{ document.Simulador[campo].value = vr.substr( 0, tam - pos ) + ',' + vr.substr( tam - pos, pos ); }
		if ( !teclapres.shiftKey && tecla == 9 && document.applets['tclJava'] ){
			document.applets['tclJava'].setFocus(); }

        	return true;
	}
        else
        	return false;
}


//==========================================================================================
//Retorna os limites mínimos e máximos para contribuições e benefícios do Plano de 
//acordo com o produto e o segmento
//==========================================================================================
function fLimites(nLimite,sProduto,sSegmento)
{
  var valor = 0;

  switch (nLimite)
  {  // PGBL e VGBL
	// Valor do Salário Mínimo
	case 1:
		valor = 380;
		break;	

	// Valor mínimo para contribuição única (PGBL ou VGBL)
	case 2:
		if (sSegmento == "Exclusivo")
			{ valor = 10000;}
		else if (sSegmento == "ExclusivoPlus")
			{ valor = 100000;}
		else  
			{ valor = 3000;}
		break;	

	// Valor máximo para Pensão por Prazo Certo 
	case 5:
		valor = 10000;
		break;
		
	// Valor máximo para Invalidez 
	case 6:	
		valor = 15000;
		break; 

	// Valor máximo para Pecúlio
	case 7:
		valor = 300000;
		break;

	// Valor máximo para Pensão aos Filhos
	case 8:
		valor = 10000;
		break;

	// Valor máximo para Pensão ao Cônjuge
	case 9:
		valor = 10000;
		break;

	// Valor mínimo para Invalidez		
	case 10:
		valor = fLimites(1, sProduto, sSegmento);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pecúlio
	case 11:
		valor = fLimites(1, sProduto, sSegmento);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pensão aos Filhos
	case 12:
		valor = fLimites(1, sProduto, sSegmento);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pensão ao Conjuge
	case 13:
		valor = fLimites(1, sProduto, sSegmento);   // Igualado ao Salário Mínimo
		break;	

	// Valor mínimo para Aporte Extra Inicial planos individuais
	case 16:
		if (sSegmento == "Exclusivo")
			{ valor = 400; }
		else
			{ valor = 80; }
		break;	

	// Valor mínimo para Pensão por Prazo Certo 
	case 18:
		valor = fLimites(1, sProduto, sSegmento);   // Igualado ao Salário Mínimo
		break;

	// Valor maximo para contribuição somente (solicitar ao cliente contato com o BB)
	case 19:
		valor = 9999999999; //Limitado pela Cinthia e-mail de 260804 antes estava 1000000
		break;

	// Valor mínimo para Aporte Extra Inicial planos júnior
	case 20:
		valor = 50; 
		break;

	// Valor maximo para APORTE MENSAL em planos júnior limitado devido a PENSAO POR PRAZO CERTO
	case 21:
		valor = 10000;
		break;

	// Valor maximo para contribuição extra inicial somente para solicitar ao cliente contato com o BB
	case 22:
		valor = 500000; //Limitado pela Cinthia e-mail de 260804 antes nao havia restricao
		break;

	// Valor maximo de contribuição mensal para que o plano Junior possa ser contratado por canal 
	// diferente de corretor 
	case 23:
		valor = 1000; 
		break;

  }

  if  (valor == 0)
  {
	if (sProduto == "VGBL") 
	{ // VGBL
		switch (nLimite)
		{   
		// Valor mínimo de Contribuição Total (Somente para Junior) 		
		case 3:
			valor = 25;
			break;
	
		// Valor mínimo de Contribuição de Aposentadoria 
		case 4:
			valor = 25;
	 		break;
	
		// Valor minimo para Aporte periodico
		case 14:
			if (sSegmento == "Exclusivo")
				{ valor = 300; }
			//else if (sSegmento == "ExclusivoPlus")
			//	{ valor = 5000; }				
			else
				{ valor = 60; }
			break;

		// Valor máximo para Aporte periodico
		case 15:
			valor = 10000;
			break;
	
		// Valor minimo para Aporte periodico junior
		case 17:
			valor = 25;
			break;
		}
	  }

	  if (sProduto == "PGBL")
	  { // PGBL
		switch (nLimite)
		{   	
		// Valor mínimo de Contribuição Total (Somente para Junior) 	
		case 3:
			valor = 50;
			break;
		
		// Valor mínimo de Contribuição de Aposentadoria
		case 4:
			valor = 100;
	 		break;
	
		// Valor minimo para Aporte Periodico
		case 14:
			if (sSegmento == "Exclusivo")
				{ valor = 400; }
			else if (sSegmento == "ExclusivoPlus")
				{ valor = 5000; }				
			else
				{ valor = 100; }
			break;	

		// Valor máximo para Aporte Periodico
		case 15:
			valor = 10000;
			break;
	
		// Valor minimo para Aporte Periodico Junior
		case 17:
			valor = 50;
			break;
		}
	  }
  }
  return valor;
}


//==========================================================================================
//Retorna os limites mínimos e máximos para idades dos participantes
//==========================================================================================
function fLimitesIdades(nLimite)
{
	var valor = 0;

	switch (nLimite)
	{   
	// Idade mínima para proponente do PGBL e VGBL (Junior e Individual)
	case 1:
		valor = 14;
		break;	
	
	// Idade máxima para proponente do PGBL e VGBL Individual Varejo
	case 2:
		valor = 69;
		break;
	
	// Idade mínima para invalidez do PGBL
	case 3:
		valor = 14;
		break;	
	
	// Idade máxima para invalidez do PGBL
	case 4:
		valor = 65;
		break;

	// Idade mínima para pensao dos filhos do PGBL
	case 5:
		valor = 16;
		break;	
	
	// Idade máxima para pensao dos filhos do PGBL
	case 6:
		valor = 69;
		break;

	// Idade mínima para pensao do conjuge do PGBL
	case 7:
		valor = 16;
		break;	
	
	// Idade máxima para pensao do conjuge do PGBL
	case 8:
		valor = 69;
		break;

	// Idade mínima para junior do PGBL
	case 9:
		valor = 0;
		break;	
	
	// Idade máxima para junior do PGBL
	case 10:
		valor = 20;
		break;

	// Idade mínima para proponente do VGBL
	case 11:
		valor = 14;
		break;	
	
	// Idade máxima para proponente do VGBL
	case 12:
		valor = 69;
		break;

	// Idade mínima para pensao dos filhos do VGBL
	case 13:
		valor = 16;
		break;	
	
	// Idade máxima para pensao dos filhos do VGBL
	case 14:
		valor = 69;
		break;

	// Idade mínima para pensao do conjuge do VGBL
	case 15:
		valor = 16;
		break;	
	
	// Idade máxima para pensao do conjuge do VGBL
	case 16:
		valor = 69;
		break;

	// Idade mínima para junior do VGBL
	case 17:
		valor = 0;
		break;	
	
	// Idade máxima para junior do VGBL
	case 18:
		valor = 20;
		break;

	// Idade máxima para proponente do PGBL e VGBL Júnior
	case 19:
		valor = 69;
		break;

	// Idade máxima para proponente do PGBL e VGBL Exclusivo
	case 20:
		valor = 99;
		break;

	// Idade de SAIDA mínima para individual varejo do VGBL ou PGBL 
	case 21:
		valor = 50;
		break;	

	// Idade de SAIDA máxima para individual varejo do VGBL ou PGBL 
	case 22:
		valor = 70;
		break;

	// Idade de SAIDA mínima para individual exclusivo do VGBL ou PGBL 
	case 23:
		valor = 50;
		break;	

	// Idade de SAIDA máxima para individual exclusivo do VGBL ou PGBL 
	case 24:
		valor = 100;
		break;

	// Idade mínima para proponente Individual do PGBL e VGBL se tiver beneficio de risco
	case 25:
		valor = 16;
		break;	


	// Idade máxima para que o proponente possa contratar risco
	case 26:
		valor = 69;
		break;	
		
	// Idade minima para junior prazo certo
	case 27:
		valor = 18;
		break;			

    // Idade de SAIDA mínima para individual varejo do VGBL ou PGBL 
	case 28:
		valor = 50;
		break;	

	// Idade de SAIDA máxima para individual varejo do VGBL ou PGBL 
	case 29:
		valor = 100;
		break;

	}
	return valor;
}


//==========================================================================================
//Consiste o tamanho dos campos
//==========================================================================================
var flag = true;

function verificaTam (comp, tam, prox)
{
	str = new String (comp);
	str = "document.Simulador." + str + ".value";
	str2 = new String(eval (str));
	if ((str2.length == tam) && flag) 
	{
		flag = false;
		str = "document.Simulador." + prox + ".focus()";
		eval (str);
	}
	return 1;    	    
}


//==========================================================================================
//Calcula da idade e atualiza o campo indicado
//==========================================================================================
function calculaIdade(diaNasc, mesNasc, anoNasc, campo) 
{
	//if ((parseInt(diaNasc) > 0) && (parseInt(mesNasc) > 0) && (parseInt(anoNasc) >= 1900))
	if ((diaNasc > 0) && (mesNasc > 0) && (anoNasc >= 1900))
	{
		dNasc = new Date(anoNasc, mesNasc - 1, diaNasc);
	
		hoje = document.Simulador.DataSistema.value;
		hoje = new Date();

		idademilisegundos = hoje - dNasc;
		idade = idademilisegundos/(1000.0*60.0*60.0*24.0*365.25)

		str = new String;
		str = "document.Simulador." + campo + ".value = parseInt(idade)";
		eval (str);
        MudaTextoIdade();
	}
}

//==========================================================================================
//Calcula da idade do Responsavel e atualiza o campo indicado 
//==========================================================================================
function calculaIdadeRe(diaNasc, mesNasc, anoNasc, campo) 
{
	//if ((parseInt(diaNasc) > 0) && (parseInt(mesNasc) > 0) && (parseInt(anoNasc) >= 1900))
	if ((diaNasc > 0) && (mesNasc > 0) && (anoNasc >= 1900))
	{
		dNasc = new Date(anoNasc, mesNasc - 1, diaNasc);
	
		hoje = document.Simulador.DataSistema.value;
		hoje = new Date();

		idademilisegundos = hoje - dNasc;
		idade = idademilisegundos/(1000.0*60.0*60.0*24.0*365.25)

		str = new String;
		str = "document.Simulador." + campo + ".value = parseInt(idade)";
		eval (str);
        
	}
}

//==========================================================================================
//Seta o foco para o campo que desejar no formulário (inicia-se com 0,0)
//==========================================================================================
function putFocus(formInst, elementInst) 
{ 
	if (document.forms.length > 0) 
	{ 
		//alert(document.forms[formInst].elements[elementInst].name);
		//alert(document.forms.length);
		document.forms[formInst].elements[elementInst].focus(); 
	} 
} 


//==========================================================================================
//Retorna a string do nome da periodicidade escolhida
//==========================================================================================
function stringPer()
{	
	if (document.Simulador.Per.value == 1)
		{ return "mensal";}
	if (document.Simulador.Per.value == 3)
		{ return "trimestral";}
	if (document.Simulador.Per.value == 6)
		{ return "semestral";}
	if (document.Simulador.Per.value == 12)
		{ return "anual";}
	if (document.Simulador.Per.value == 0)
		{ return "unica";}

}


//==========================================================================================
//Verifica se o valor é válido
//==========================================================================================
function fValidaValores(nValor,sNomeValor,bMsg) 
{
	valorC = new String(nValor);
	num1 = valorC.indexOf(",");
	num2 = valorC.lastIndexOf(",");
	if (num1 != num2) 
		{ 
	 	if (bMsg==1)
			{
			alert ("Valor inválido em "+ sNomeValor +".");
			}
		return 0;
	 	}
 	if (valorC.search(/[^0-9\.,]/) != -1) 
		{
	 	if (bMsg==1) 
			{
			alert ("Caracteres inválidos em "+ sNomeValor +".");
			}
		return 0;
 		}
 	//if (valorC.search(/\./) != -1)
	//	{
	// 	if (bMsg==1) 
	//		{
	//		alert ("Favor digitar o valor sem pontos, para separador decimal utilize uma vírgula.");
	//		}
	//	return 0;
	//	}
      	valorC = parseFloat(valorC);   
      	if (isNaN(valorC) || valorC.length == 0 ) 
		{
	 	if (bMsg==1) 
			{
			alert ("O valor de " + sNomeValor + " não é válido.");
			}
		return 0;
		}
	return 1;
};


//==========================================================================================
//Funções para tratamento do menu do sistema
//==========================================================================================
//function MM_findObj(n, d) { //v3.0
//  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
//    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
//  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
//  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
//}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
//========================================================================================



//=========================================================================================
//Seta a janela como modal
//==========================================================================================
function Modal(strWindow,strParam,largura,altura)
{
	return window.showModalDialog(strWindow, strParam, "dialogWidth:" + largura + "px; dialogHeight:" + altura + "px;center:yes; status:no;")
}



//==========================================================================================
//Permite que sejam digitados somente números.
//Esse função deve ser chamada no evento OnKeyPress do objeto TEXT do HTML
//Ex: <Input Type="Text" name="txtNumero" OnKeyPress="Numero()">
//==========================================================================================
function Numero() 
{ 
	if (navigator.appName != "Netscape")
		{
		if ((event.keyCode < 48 || event.keyCode > 57))
			{
			if ((event.keyCode != 44))
				{
				if ((event.keyCode != 8)) 
					{
					event.keyCode = 0;
					}
				}
			}
		}
	}


//==========================================================================================
//Verifica se a data informada é valida.
//Retorna FALSE caso data não válida.
//Retorna TRUE caso data válida.
//Obs: A data informada deverá ser passada no formato "D/M/AAAA" ou "DD/M/AAAA" ou "D/MM/AAAA"
//ou "DD/MM/AAAA".
//==========================================================================================
function ValidaDataCompleta(Data)
{
	var strData = new String();
	strData = Data;
	if(strData.length < 10)
	{
		return false;
	}
	vntData = strData.split("/");
		
	if(vntData[2].length < 4 || parseInt(vntData[2]) < 1900)
	{
		return false;
	}
	if(parseInt(vntData[1]) > 12)
	{
		return false;
	}
	if(parseInt(vntData[1]) == 1 ||	parseInt(vntData[1]) == 3 || parseInt(vntData[1]) == 5 || parseInt(vntData[1]) == 7 || parseInt(vntData[1]) == 8 || parseInt(vntData[1]) == 10 || parseInt(vntData[1]) == 12)
	{
		if(parseInt(vntData[0]) > 31)
		{
			return false;
		}
	}
	if(parseInt(vntData[1]) == 4 || parseInt(vntData[1]) == 6 || parseInt(vntData[1]) == 9 || parseInt(vntData[1]) == 11)
	{
		if(parseInt(vntData[0]) > 30)
		{
			return false;
		}
	}
			
	if(parseInt(vntData[1]) == 2)
	{
		if(parseInt(vntData[2]) % 4 == 0)
		{
			if(parseInt(vntData[0]) > 29)
			{
				return false;
			}
		}
		else
		{
			if(parseInt(vntData[0]) > 28)
			{
				return false;
			}
		}
	}
	return true;
}
	

//==========================================================================================
//Tem	quase a mesma funcionalidade da função TRIM do ASP, porém só tem a funcionalidade de 
//verificar se texto informado é composto de somente espaços ou é vazio ...
//Retorna TRUE caso o texto informado seja diferente de	VAZIO (TEXTO != "")
//Retorna FALSE caso o texto informado seja VAZIO (TEXTO = "")
//==========================================================================================
function Trim(Texto)
{
	var strTexto = Texto;
	if(strTexto.length == 0)
	{
		return false;
	}
	else
	{
		for(var i = 0; i < strTexto.length; i++)
		{
			if(strTexto.charAt(i) != " ")
			{
				return true;
			}
		}
	}
	return false;
}


//==========================================================================================
//De acordo com os parâmetros informados, verifica se o objeto informado (tem que ser um 
//CHECKBOX ou um RADIO) está "CHECADO" e caso esteja, o layer informado passará a ser VISÍVEL,
//caso contrário o layer informado passará a ser INVISÍVEL.
//==========================================================================================
function lyrGenerica(Objeto,Layer)
{
	if(Objeto.checked == true)
	{
		Layer.style.visibility = "visible";
	}
	else
	{
		Layer.style.visibility = "hidden";		
	}
}


//==========================================================================================
//Função utilizada para formatação de moeda
//Ex: <INPUT type="text" name="txtValor" onkeyup="txt_onkeyup(this)" onkeypress="txt_OnKeyPress(this)" onblur="txt_OnBlur(this)" style="text-align: right">
//==========================================================================================
function txt_OnKeyPress(objeto)
{
	if(event.keyCode == 44)
	{
		VerificaVirgula(objeto);
	}	
	else
	{
		if(event.keyCode < 48 || event.keyCode > 57) 
		{
			event.keyCode = 0;
		}
	}
}


//==========================================================================================
//Função utilizada para formatação de moeda
//Ex: <INPUT type="text" name="txtValor" onkeyup="txt_onkeyup(this)" onkeypress="txt_OnKeyPress(this)" onblur="txt_OnBlur(this)" style="text-align: right">
//==========================================================================================
function txt_OnBlur(objeto)
{
	var sTexto = objeto.value;
	
	if(sTexto != "")
	{
		virgula = false;
		for(var i = 0; i < sTexto.length; i++)
		{
			if(sTexto.substring(i, i+1) == ",")
			{
				virgula = true;
			}
		} 
		if(virgula == false)
		{
			objeto.value = sTexto + ",00";
		}
		else
		{
			if (sTexto.substring((sTexto.length - 1), sTexto.length) == ",")
			{
				objeto.value = sTexto + "00";		
			}
		}
	}
}


//==========================================================================================
//Função auxiliar utilizada para formatação de moeda
//Ex: <INPUT type="text" name="txtValor" onkeyup="txt_onkeyup(this)" onkeypress="txt_OnKeyPress(this)" onblur="txt_OnBlur(this)" style="text-align: right">
//==========================================================================================
function VerificaVirgula(objeto)
{
	var sTexto = objeto.value;
	
	for(var i = 0; i < sTexto.length; i++)
	{
		if (sTexto.substring(i, i+1) == ",")
		{
			event.keyCode = 0;
		}
	} 
}


//==========================================================================================
//Função utilizada para formatação de moeda
//Ex: <INPUT type="text" name="txtValor" onkeyup="txt_onkeyup(this)" onkeypress="txt_OnKeyPress(this)" onblur="txt_OnBlur(this)" style="text-align: right">
//==========================================================================================
function txt_onkeyup(objeto)
{
	var sTexto = objeto.value;
	var sValor = "";
	var vVirgula = "";
		
	for(var i = 0; i < sTexto.length; i++)
		{
		if (sTexto.substring(i, i+1) == ",")
			{
			vVirgula = sTexto.substring(i, sTexto.length);
			break;
			}
		if (sTexto.substring(i, i+1) != ".")
			{
			sValor = sValor + sTexto.substring(i, i+1);
			}
		} 
	
	sTexto = "";
	vPonto = false;
	if (sValor.length > 3)
	{
		if((sValor.length % 3) == 0)
		{
			for(var i = 0; i < sValor.length; i = i + 3)
			{
				if (vPonto == false)
				{
					sTexto = sTexto + sValor.substring(i, i +3);
					vPonto = true;
				}
				else
				{
					sTexto = sTexto + "." + sValor.substring(i, i +3);
				}
			}
		}
		else
		{
			for(var i = sValor.length; i > 0; i = i - 3)
			{
				if (vPonto == false)
				{
					sTexto = sValor.substring(i, i - 3) + sTexto;
					vPonto = true;
				}
				else
				{
					sTexto =  sValor.substring(i, i - 3) + "." + sTexto;
				}
			}
		}
		objeto.value = sTexto + vVirgula;	
	}
	else
	{
		objeto.value = sValor + vVirgula;
	}
}


//==========================================================================================
//Efeito de botão nas imagens
//==========================================================================================
function ItemClicked(item)
{
	if(this.sliding)
		return;
	item.style.border="2 inset #ffffff";
}


//==========================================================================================
//Efeito de botão nas imagens
//==========================================================================================
function OverItems(item)
{
	if(this.sliding)
		return;
	item.style.border="2 outset #ffffff";
}


//==========================================================================================
//Efeito de botão nas imagens
//==========================================================================================
function OutItems(item)
{
	if(this.sliding)	
		{
		return;
		}
	item.style.border="0 none black";
}


//==========================================================================================
//Efeito de botão nas imagens
//==========================================================================================
function ItemSelected(item)
{
	if(this.sliding)
		return;		
	item.style.border="1 outset #ffffff";
}


//==========================================================================================
//Coloca todo o texto digitado em "maiúsculo".
//Ex:
//<input type="text" name="txtNome" onkeypress="UCase()">
//==========================================================================================
function UCase()
{
	var x = new String();
	
	x = String.fromCharCode(event.keyCode)
	x = x.toUpperCase();
	event.keyCode = x.charCodeAt(0);
}


//==========================================================================================
//Coloca todo o texto digitado em "minúsculo"
//Ex:
//<input type="text" name="txtNome" onkeypress="LCase()">
//==========================================================================================
function LCase()
{
	var x = new String();
	
	x = String.fromCharCode(event.keyCode)
	x = x.toLowerCase();
	event.keyCode = x.charCodeAt(0);
}


//==========================================================================================
//Valida a data informada
//==========================================================================================
function validadata(dateString, flagObrigatorio, Campo) {
        erro=0
        
        if (flagObrigatorio) {
            if (dateString.length==0) {
                alert('O campo "' + Campo + '" é obrigatório.');
                return false;
                }
        }        
        else {
           if (dateString.length==0) {
               return true;
               }
        }

        if (dateString.length == 8) {
           // if (!mask(dateString,"##/##/##")) {erro=2}
		   alert('No campo "' + Campo + '" informar ano com quatro dígitos.');
           return (false);
           }
        else {
           if (!mask(dateString,"##/##/####")) {erro=3}
           }
           
        if (erro!=0) 
           {
             alert('O campo "' + Campo + '" não está no formato data.');
             return (false);
           }
                
        Ano=dateString.substring(6,10);
        Mes=dateString.substring(3,5);
        Dia=dateString.substring(0,2);
        
        var dateVar = new Date(dateString.substring(6,10), dateString.substring(3,5)-1, dateString.substring(0,2));
	
        if (Dia!=dateVar.getDate()) {erro=4};
        if (Mes!=dateVar.getMonth()+1) {erro=5};

        if (dateVar.getYear()!= Ano)
           {
	 if (Ano > 100) // 4 digitos
 	{
	 	if ((dateVar.getYear()<10))
		                {if (Ano-2000!=dateVar.getYear()) {erro=6}}
		else
		                {if (Ano-1900!=dateVar.getYear()) {erro=7}}
               }
           }  
         
        if (erro!=0) {
                alert('O campo "' + Campo + '" não está no formato data.');
                return false;
                };
        return true;
}



//==========================================================================================
// ???
//==========================================================================================
function mask (InString, Mask) {

        LenStr = InString.length;
        LenMsk = Mask.length;
        if ((LenStr==0) || (LenMsk==0))
                return(false);
        if (LenStr!=LenMsk)
                return(false);
        TempString=""
        for (Count=0; Count<=InString.length; Count++) {
                StrChar = InString.substring(Count, Count+1);
                MskChar = Mask.substring(Count, Count+1);
                if (MskChar=='#') {
                        if(!isNumberChar(StrChar))
                                return(false);
                }
                else if (MskChar=='?') {
                        if(!isAlphabeticChar(StrChar))
                                return(false);
                }
                else if (MskChar=='!') {
                        if(!isNumOrChar(StrChar))
                                return(false);
                }
                else if (MskChar=='*') {
                }
                else {
                        if (MskChar!=StrChar)
                                return(false);
                }
        }
        return (true);
}


//==========================================================================================
// ???
//==========================================================================================
function isAlphabeticChar (InString) {

        if (InString.length!=1)
                return (false);
        InString=InString.toLowerCase();
        RefString="abcdefghijklmnopqrstuvwxyz";
        if (RefString.indexOf (InString.toLowerCase(), 0)==-1)
                return (false);
        return (true);
}


//==========================================================================================
// ???
//==========================================================================================
function isNumberChar (InString) {

        if (InString.length!=1)
                return (false);
        RefString="1234567890,";        
        if (RefString.indexOf (InString, 0)==-1)
                return (false);
        return (true);
}


//==========================================================================================
// ???
//==========================================================================================
function isNumOrChar (InString) {

        if (InString.length!=1) 
				return (false);
        InString=InString.toLowerCase();
        RefString="1234567890abcdefghijklmnopqrstuvwxyz";
        if (RefString.indexOf (InString, 0)==-1)
                return (false);
        return (true);
}


//==========================================================================================
// ???
//==========================================================================================
function Vazio0(v)
{
	if (v.length == 0) return true;
	
	for (i=0; i<v.length; i++) if ((v.charAt(i) != ' ') && (v.charAt(i) != '0')) return false;
	return true;
}


//==========================================================================================
// ???
//==========================================================================================
function validanumero(InString, flObrigatorio, Tamanho, Campo) 
{
	if (Vazio0(InString)) {
	   if (flObrigatorio) {	
		   alert('O campo "' + Campo + '" é obrigatório.');
		   return false;
		   }
	   else
	       {return true}
	   }
	StrMask = "";
	if (Tamanho==0) {
		for (Count=1; Count<=InString.length; Count++)
			{ StrMask = StrMask + "#"; }
		}
	else
		{
		for (Count=1; Count<=Tamanho; Count++)
			{ StrMask = StrMask + "#"; }
		}
	if (!mask(InString, StrMask)) 
		{
		if (Tamanho==0) 
			alert('O campo "' + Campo + '" deve ser numérico e inteiro.');
		else
			alert('O campo "' + Campo + '" deve ser numérico, inteiro e ter até ' + Tamanho + ' caracteres.');
		return false;
		}
	return true;
}


//==========================================================================================
// ???
//==========================================================================================
function ContaItem(Item,Tamanho)
{
var x;

  Tamanho = Tamanho + 1;
  
 	x=Item.value;
 	if (x.length>Tamanho-1) 
	{
	Item.value = Item.value.substring(0,Item.value.length-1);
	}
}


//==========================================================================================
//Formata qualquer valor em moeda brasileira
//==========================================================================================
function jsFormatNumber(num) 
{
	num = num.toString().replace(",",".");		
	num = num.toString().replace(/\$|/g,"");
	if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/100).toString();
	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+"."+num.substring(num.length-(4*i+3));	
	return (num + "," + cents);	
}


//==========================================================================================
// ???
//==========================================================================================
function TrataValor(valor)
{
	var Count;
	var StrChar;
	var retorno;
	var achou;
	achou = 0
	retorno = "";
for(Count=0; Count<=valor.length; Count++)
{
	StrChar = valor.substring(Count, Count+1);
	if (StrChar==".") 
		{
		retorno = retorno + ",";
		achou = 1;
		}
	if (StrChar==",") 
		{
		retorno = retorno + ",";
		achou = 1;
		}
	if((StrChar!=".") && (StrChar!=",")) 
		{
		retorno = retorno + StrChar;	
		}
}
if (achou == 0) 
	{
	retorno = retorno + ",00";
	}
	
return retorno;
}          


//==========================================================================================
// ???
//==========================================================================================
function formatCurrency(num)
{
num = num.toString().replace(/\$|\,/g,"");
if(isNaN(num)) num = "0";
	{
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/100).toString();
	}
if(cents < 10) cents = "0" + cents;
	{
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		{
		num = num.substring(0,num.length-(4*i+3))+"."+num.substring(num.length-(4*i+3));
		}
	}	
return ("R$" + num + "," + cents);
}


//==========================================================================================
// ???
//==========================================================================================
function Tecla(e)
{
if(document.all) // Internet Explorer
	var tecla = event.keyCode;
else if(document.layers) // Nestcape
	var tecla = e.which;

if(tecla > 47 && tecla < 58) // numeros de 0 a 9
	return true;
else
	{
	if (tecla != 8) // backspace
		return false;
	else
		return true;
	}
}


//==========================================================================================
//Retorna a  versão do JavaScript em uso
//==========================================================================================
function GetScriptEngineInfo()
{
	var s;
	s = ""; // Build string with necessary info.
	s += ScriptEngine() + " Version ";
	s += ScriptEngineMajorVersion() + ".";
	s += ScriptEngineMinorVersion() + ".";
	s += ScriptEngineBuildVersion();
	return(s);
}


//==========================================================================================
//Divide percentagem entre dois campos
//==========================================================================================
function percentagem(form,lista,txtcomp,valor)
{
	var str = form
	var lista = lista
	var txtcomp = txtcomp

	str = "document." + form + "." + txtcomp + ".value = valor - document." + form + "." + lista + ".value";
	//alert(str);
	eval (str);
}



//===================================================

// funcçoes mantidas apenas para compatibilidade com a versão atula.
//após implantacao podem ser excluidas



//==========================================================================================
//Verifica se a data informada é valida.
//Retorna FALSE caso data não válida.
//Retorna TRUE caso data válida.
//Obs: A data informada deverá ser passada no formato "D/M/AAAA" ou "DD/M/AAAA" ou "D/MM/AAAA"
//ou "DD/MM/AAAA".
//==========================================================================================
function ValidaData(Data)
{
	var strData = new String();
	strData = Data;
	if(strData.length < 10)
	{
		return false;
	}
	vntData = strData.split("/");
		
	if(vntData[2].length < 4 || parseInt(vntData[2]) < 1900)
	{
		return false;
	}
	if(parseInt(vntData[1]) > 12)
	{
		return false;
	}
	if(parseInt(vntData[1]) == 1 ||	parseInt(vntData[1]) == 3 || parseInt(vntData[1]) == 5 || parseInt(vntData[1]) == 7 || parseInt(vntData[1]) == 8 || parseInt(vntData[1]) == 10 || parseInt(vntData[1]) == 12)
	{
		if(parseInt(vntData[0]) > 31)
		{
			return false;
		}
	}
	if(parseInt(vntData[1]) == 4 || parseInt(vntData[1]) == 6 || parseInt(vntData[1]) == 9 || parseInt(vntData[1]) == 11)
	{
		if(parseInt(vntData[0]) > 30)
		{
			return false;
		}
	}
			
	if(parseInt(vntData[1]) == 2)
	{
		if(parseInt(vntData[2]) % 4 == 0)
		{
			if(parseInt(vntData[0]) > 29)
			{
				return false;
			}
		}
		else
		{
			if(parseInt(vntData[0]) > 28)
			{
				return false;
			}
		}
	}
	return true;
}


//==========================================================================================
//Retorna os limites mínimos e máximos para contribuições e benefícios do Plano Renda Total
//==========================================================================================
function fLimitesVGBL(nLimite)
{
var valor = 0;
switch (nLimite)
	{   
	// Valor do Salário Mínimo
	case 1:
		valor = 240;
		break;	
	
	// 	Valor mínimo para contribuição única
	case 2:
		valor = 3000;
		break;
	
	// Valor mínimo de Contribuição Total (Somente para Junior) 		
	case 3:
		valor = 25;
		break;
	
	// Valor mínimo de Contribuição de Aposentadoria 
	case 4:
		valor = 25;
 		break;
	
	// Valor máximo para Pensão por Prazo Certo 
	case 5:
		valor = 10000;
		break;
		
	// Valor máximo para Invalidez 
	case 6:	
		valor = 15000;
		break;
		
	// Valor máximo para Pecúlio 
	case 7:
		valor = 300000;
		break;
		
	// Valor máximo para Pensão aos Filhos 
	case 8:
		valor = 10000;
		break;

	// Valor máximo para Pensão ao Cônjuge
	case 9:
		valor = 10000;
		break;
		
	// Valor mínimo para Invalidez		
	case 10:
		valor = fLimitesVGBL(1);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pecúlio
	case 11:
		valor = fLimitesVGBL(1);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pensão aos Filhos
	case 12:
		valor = fLimitesVGBL(1);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pensão ao Conjuge
	case 13:
		valor = fLimitesVGBL(1);   // Igualado ao Salário Mínimo
		break;

	// Valor minimo para Aporte mensal
	case 14:
		valor = 60;
		break;

	// Valor máximo para Aporte mensal 
	case 15:
		valor = 10000;
		break;

	// Valor mínimo para Aporte inicial
	case 16:
		valor = 3000;
		break;	

	// Valor minimo para Aporte junior
	case 17:
		valor = 25;
		break;
	}
return valor;
}


//==========================================================================================
//Retorna os limites mínimos e máximos para contribuições e benefícios do Plano Renda Total
//==========================================================================================
function fLimitesPGBL(nLimite)
{
var valor = 0;
switch (nLimite)
	{   
	// Valor do Salário Mínimo
	case 1:
		valor = 240;
		break;	
	
	// 	Valor mínimo para contribuição única
	case 2:
		valor = 3000;
		break;
	
	// Valor mínimo de Contribuição Total (Somente para Junior) 	
	case 3:
		valor = 50;
		break;
	
	// Valor mínimo de Contribuição de Aposentadoria
	case 4:
		valor = 100;
 		break;
	
	// Valor máximo para Pensão por Prazo Certo
	case 5:
		valor = 10000;
		break;
		
	// Valor máximo para Invalidez
	case 6:	
		valor = 15000;
		break;
		
	// Valor máximo para Pecúlio
	case 7:
		valor = 300000;
		break;
		
	// Valor máximo para Pensão aos Filhos
	case 8:
		valor = 10000;
		break;

	// Valor máximo para Pensão ao Cônjuge
	case 9:
		valor = 10000;
		break;
		
	// Valor mínimo para Invalidez		
	case 10:
		valor = fLimitesPGBL(1);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pecúlio
	case 11:
		valor = fLimitesPGBL(1);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pensão aos Filhos
	case 12:
		valor = fLimitesPGBL(1);   // Igualado ao Salário Mínimo
		break;
	
	// Valor mínimo para Pensão ao Conjuge
	case 13:
		valor = fLimitesPGBL(1);   // Igualado ao Salário Mínimo
		break;	

	// Valor mínimo para Aporte inicial
	case 14:
		valor = 3000; //fLimitesPGBL(1);  ->  Igualado ao Salário Mínimo
		break;	

	// Valor máximo para Aporte inicial 
	case 15:
		valor = 100000;
		break;

	// Valor mínimo para Pensao com Prazo Certo
	case 16:
		valor = 0; //fLimitesPGBL(1);  ->  Igualado ao Salário Mínimo
		break;	

	// Valor máximo para Pensao com Prazo Certo
	case 17:
		valor = 10000;
		break;

	// Valor minimo para Aporte mensal
	case 18:
		valor = 100;
		break;

	// Valor máximo para Aporte mensal
	case 19:
		valor = 10000;
		break;

	// Valor minimo para Aporte mensal junior
	case 20:
		valor = 50;
		break;
	}
return valor;
}
