// Rotinas de validação de formulário
// Elcio Ferreira
// Versão 2.2 - 18/05/2001
// Mais informações: http://javascript.elciof.cjb.net

//#####################################
//mensagens de erro customizáveis
//#####################################

mensagens=new Array()
mensagens[1]="Email inválido."
mensagens[2]="CPF inválido."
mensagens[3]="CGC inválido."
mensagens[4]="CGC/CPF inválido."
mensagens[5]="Data inválida."
mensagens[6]="Campo obrigatório não preenchido."


//#####################################
//constantes
//#####################################

if (document.all){sender="event.srcElement"}else{sender="e.target"}
nenhuma=0;  
reais=1;  
dolares=2;  
nada=3;
truncar=0;  
aproximar=1;  

//#####################################
//varre o formulário validando os campos
//#####################################

function valida(){
	obj=this.parent
	ixx=obj.campos
	for(y=0;y<obj.total;y++){

		//Valida email
		if (ixx[y].tipo=="email" && !branco(ixx[y].campo.value)){
			if(!verificaEmail(ixx[y].campo.value)){
				alert(mensagens[1])
				ixx[y].campo.focus()
				return false
			}
		}

		//Valida cpf
		if (ixx[y].tipo=="cpf" && !branco(ixx[y].campo.value)){
			if(!verificaCPF(ixx[y].campo.value)){
				alert(mensagens[2])
				ixx[y].campo.focus()
				return false
			}
		}

		//valida cgc
		if (ixx[y].tipo=="cgc" && !branco(ixx[y].campo.value)){
			if(!verificaCGC(ixx[y].campo.value)){
				alert(mensagens[3])
				ixx[y].campo.focus()
				return false
			}
		}

		//valida cgc ou cpf
		if (ixx[y].tipo=="cgcoucpf" && !branco(ixx[y].campo.value)){
			if(!verificaCPF(ixx[y].campo.value) && !verificaCGC(ixx[y].campo.value)){
				alert(mensagens[4])
				ixx[y].campo.focus()
				return false
			}
		}

		//valida data
		if ((ixx[y].tipo=="data" || ixx[y].tipo=="engdata") && !branco(ixx[y].campo.value)){
			if(!ValData(ixx[y].campo.value)){
				alert(mensagens[5])
				ixx[y].campo.focus()
				return false
			}
		}

		//valida campos obrigatórios
		if (!ixx[y].branco){
			if(ixx[y].campo.value==""){
				alert(mensagens[6] + '(' + ixx[y].campo.name + ')' )
				ixx[y].campo.focus()
				return false
			}
		}
	}
	for(y=0;y<obj.total;y++){
		if (ixx[y].dinheiro){ixx[y].campo.value=eval("x"+ixx[y].campo.name)};
		if (ixx[y].tipo=="cgc" || ixx[y].tipo=="cpf" || ixx[y].tipo=="cgcoucpf" || ixx[y].tipo=="cep"){
			ixx[y].campo.value=trimtodigits(ixx[y].campo.value)
		}
		if (ixx[y].tipo=="engdata" && !branco(ixx[y].value)){
			strvar=trimtodigits(ixx[y].campo.value)
			strvar=strvar.substr(2,2)+"/"+strvar.substr(0,2)+"/"+strvar.substr(4,4)
			ixx[y].campo.value=strvar
		}
	}
	return true
};


//#####################################
//Funcoes de validação
//#####################################
function ValData (data) {
    if ( (data == null) || (data.length < 10) ) {
      return false;
    }
    var jsDataValida = true;
    var jsDia = data.substring(0,2)-0;
    var jsMes = data.substring(3,5)-1;
    var jsAno = data.substring(6,10)-0;
    var oData = new Date(jsAno, jsMes, jsDia);    
    if (jsDia != oData.getDate()) { jsDataValida = false }
    if (jsMes != oData.getMonth()) { jsDataValida = false }
    if (jsAno != oData.getFullYear()) { jsDataValida = false }
    return jsDataValida;
}

function branco(valor)	{
	 if (valor== ""){
		return true
	 }else{
		return false
	 } 
}


function verificaEmail(email) {  
	var s = new String(email);  
	// { } ( ) < > [ ] | \ /  
	if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )  
		return false;  
	// & * $ % ? ! ^ ~ ` ' "  
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )  
		return false;  
		// , ; : = #  
	if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) )  
		return false;  
	// procura se existe apenas um @  
	if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )  
		return false;  
	// verifica se tem pelo menos um ponto após o @  
	if (s.lastIndexOf(".") < s.indexOf("@"))  
	return false;  
	return true;  
} 


/************************************************  
* function verificaCGC  
* Verifica se um CGC é válido  
* Input: cgc a ser verificado  
************************************************/  
 
function verificaCGC(scgc) {  
	cgc = trimtodigits(scgc);  
	if ((cgc.indexOf("-") != -1) || (cgc.indexOf(".") != -1) || (cgc.indexOf("/") != -1)){  
		return( false )  
	}  
	var df, resto, dac = ""  
	df = 5*cgc.charAt(0)+4*cgc.charAt(1)+3*cgc.charAt(2)+2*cgc.charAt(3)+9*cgc.charAt(4)+8*cgc.charAt(5)+7*cgc.charAt(6)+6*cgc.charAt(7)+5*cgc.charAt(8)+4*cgc.charAt(9)+3*cgc.charAt(10)+2*cgc.charAt(11)  
	resto = df % 11  
	dac += ( (resto <= 1) ? 0 : (11-resto) )  
	df = 6*cgc.charAt(0)+5*cgc.charAt(1)+4*cgc.charAt(2)+3*cgc.charAt(3)+2*cgc.charAt(4)+9*cgc.charAt(5)+8*cgc.charAt(6)+7*cgc.charAt(7)+6*cgc.charAt(8)+5*cgc.charAt(9)+4*cgc.charAt(10)+3*cgc.charAt(11)+2*parseInt(dac)  
	resto = df % 11  
	dac += ( (resto <= 1) ? 0 : (11-resto) )  
	return (dac == cgc.substring(cgc.length-2,cgc.length))  
}  
 
// Gera uma string com os caracteres básicos na sequência de códigos ASC  
function makeCharsetString(){  
	var astr  
	astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@'  
	astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  
	astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz'  
	astr+= '{|}~'  
	return astr  
}  
 
 
//Remove todos os caracteres excetos 0-9  
function trimtodigits(tstring){  
	s="";  
	ts=new String(tstring);  
	for (x=0;x<ts.length;x++){  
		ch=ts.charAt(x);  
			if (asc(ch)>=48 && asc(ch)<=57){  
			s=s+ch;  
		}  
	}  
	return s;  
}  
 
// Retorna o código ASC do caracter passada por parâmetro  
function asc(achar){  
	var n=0;  
	var ascstr = makeCharsetString()  
	for(i=0;i<ascstr.length;i++){  
		if(achar==ascstr.substring(i,i+1)){  
			n=i;  
			break;  
		}  
	}  
	return n+32  
}  



/************************************************  
* function verificaCPF  
* Verifica se um CPF é válido  
* Input: cpf a ser verificado  
************************************************/  
 
function verificaCPF(xcpf){
	cpf=trimtodigits(xcpf)  
	var dac = "", inicio = 2, fim = 10, soma, digito, i, j  
	for (j=1;j<=2;j++) {  
		soma = 0  
		for (i=inicio;i<=fim;i++) {  
			soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)  
		}  
		if (j == 2) { soma += 2*digito }  
		digito = (10*soma) % 11  
		if (digito == 10) { digito = 0 }  
		dac += digito  
		inicio = 3  
		fim = 11  
	}  
	return (dac == cpf.substring(cpf.length-2,cpf.length))  
}  


//#####################################
//eventos e funções de formatação de dinheiro
//#####################################

function formatamoeda(valor,moeda,metodo) {  
	retorno="";  
	if (moeda==reais){retorno="R$ "}  
	//if (moeda==reais){retorno=""}  
	if (moeda==dolares){retorno="US$ "}  
	if (moeda==nada){retorno=""}  
	if (metodo==aproximar){valor=valor+.005}  
	if(valor<0){  
		retorno=retorno+"-";  
		valor=-valor};  
	if(valor<1){  
		casas=1  
	}else{  
		for( casas = 0 ; Math.pow(1000,casas) < valor; casas++){};};  
	strvalor=""+Math.floor(valor);  
	dif= strvalor.length;  
	dif=dif + 3- (casas*3);  
	retorno=retorno+strvalor.substring(0,dif);  
	for(x=0;x<=casas;x++){  
		if(x<casas-1){retorno=retorno+"."};  
		retorno=retorno+strvalor.substring((x*3)+dif,(x*3)+3+dif);};  
	retorno=retorno+",";  
	decimal=Math.floor(valor*100-Math.floor(valor)*100);  
	if (decimal<10){retorno=retorno+"0"};  
	retorno=retorno+decimal;  
	return retorno;  
}; 
function mfoco(e){

	obj=eval(sender)
	if(eval("x"+obj.name)!=0){
		obj.value=eval("x"+obj.name)
	}else{
		obj.value=""
	}
}
function mperde(e){
	obj=eval(sender)
	valor=obj.value
	while(valor.indexOf("0")==0){
		valor=valor.substring(1,100)
	}
	if(valor!=0){
		eval("x"+obj.name+"="+valor)}
	else{
		eval("x"+obj.name+"=0")}
	obj.value=formatamoeda(eval("x"+obj.name),reais,truncar)
}

//#####################################
//eventos e funcoes de validacao de CEP, CGC e CPF
//#####################################

function cepfoco(e){
	obj=eval(sender)
	obj.value=trimtodigits(obj.value)
}
function cgcfoco(e){
	obj=eval(sender)
	obj.value=trimtodigits(obj.value)
}
function cpffoco(e){
	obj=eval(sender)
	obj.value=trimtodigits(obj.value)
}
function cgcoucpffoco(e){
	obj=eval(sender)
	obj.value=trimtodigits(obj.value)
}
function cepperde(e){
	obj=eval(sender)
	valor=obj.value
	if(valor.length==8){
		valor=valor.substr(0,5)+"-"+valor.substr(5,3)
		obj.value=valor
	}
}
function cgcperde(e){
	obj=eval(sender)
	valor=obj.value
	if(valor.length==14){
		valor=valor.substr(0,2)+"."+valor.substr(2,3)+"."+valor.substr(5,3)+"/"+valor.substr(8,4)+"-"+valor.substr(12,2)
		obj.value=valor
	}
}
function cpfperde(e){
	obj=eval(sender)
	valor=obj.value
	if(valor.length==11){
		valor=valor.substr(0,3)+"."+valor.substr(3,3)+"."+valor.substr(6,3)+"-"+valor.substr(9,2)
		obj.value=valor
	}
}
function cgcoucpfperde(e){
	obj=eval(sender)
	ovalor=obj.value
	if(ovalor.length==11){return cpfperde(e)}else{return cgcperde(e)}
}

//#####################################
//insere/remove o sinal de negatico de um campo
//#####################################

function inverte(a){
	valor=a.value
	if (valor.indexOf("-")==-1){
		a.value="-"+valor
	}else{
		a.value=valor.substr(1,100)
	}
}

//#####################################
//tratadores de teclas
//#####################################

function inteiro(e){
	alvo=eval(sender)
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	
	if (x>47 && x<58 || x==8){return true}else{return false}
}
function inteironegativo(e){
	alvo=eval(sender)
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	alert(parseInt(x));
	if (x>47 && x<58 || x==8){return true}else{
	if (x==45){setTimeout("inverte(alvo)",50)}
	return false}
}
function email(e){
	regra="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.@-_1234567890"
	alvo=eval(sender)
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	key=String.fromCharCode(x)
	if(regra.indexOf(key)==-1){return false}else{
	valor=alvo.value
	if(key=="@" && valor.indexOf("@")!=-1){return false}
	return true}
}
function tudo(e){
	return true
}
function numero(e){
	obj=eval(sender)
	valor=obj.value;
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	
	
	if(x==44){
		if(document.all && valor.indexOf(".")==-1){
			event.keyCode=46;
			return true
		}else{
		window.status="Use ponto como separador de centavos."}
	}
//	if (x>47 && x<58 || x==8 || (x==46 && valor.indexOf(".")==-1)){return true}
	if (x>47 && x<58 || x==8 || (x==46 && valor.indexOf(".")==-1) || (x==45 && (valor.indexOf("-")==-1)      )      ){return true}  // Modificado por Cau, para aceitar valores negativos

	else{
		return false
	}
}
function negativo(e){
	obj=eval(sender)
	valor=obj.value;
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	if(x==45){setTimeout("inverte(obj)",50)}
	if(x==44){
		if(document.all && valor.indexOf(".")==-1){
			event.keyCode=46;
			return true
		}else{
		window.status="Use ponto como separador de centavos."}
	}
	if (x>47 && x<58 || x==8 || (x==46 && valor.indexOf(".")==-1)){return true}
	else{
		return false
	}
}
function cep(e){
	return inteiro(e)
}
function cgc(e){
	return inteiro(e)
}
function cpf(e){
	return inteiro(e)
}
function cgcoucpf(e){
	return inteiro(e)
}
function data(e){
	alvo=eval(sender)
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	if (x==8){return true}
	if(document.all){
		if (x>47 && x<58){
			x=x-48
			valor=alvo.value
			if (valor.length==0){
				if (x>3){alvo.value="0"}
			}
			if (valor.length==2){
				if (x>1){alvo.value+="/0"}else{alvo.value+="/"}
			}
			if (valor.length==5){
				if (x>3){alvo.value+="/19"}else{
					if (x>0){alvo.value+="/"}else{alvo.value+="/20"}
				}
			}
			return true
		}
	}else{
		if (x>46 && x<58){ alert(x); return true}
	}
	return false
}
function engdata(e){
	alvo=eval(sender)
	if (document.all){
		x=event.keyCode;
	}else{
		x=e.which
	}
	if (x==8){return true}
	if(document.all){
		if (x>47 && x<58){
			x=x-48
			valor=alvo.value
			if (valor.length==0){
				if (x>3){alvo.value="0"}
			}
			if (valor.length==2){
				if (x>1){alvo.value+="/0"}else{alvo.value+="/"}
			}
			if (valor.length==5){
				if (x>3){alvo.value+="/19"}else{
					if (x>0){alvo.value+="/"}else{alvo.value+="/20"}
				}
			}
			return true
		}
	}else{
		if (x>46 && x<58){return true}
	}
	return false
}

//#####################################
//objeto xform
//#####################################

function xform(obj){
	this.form=obj
	this.campos=new Array
	this.total=0
	this.add=add
	obj.onsubmit=valida
	obj.parent=this
}

//metodo para adicionar inputs

function add(campo,tipo,dinheiro,branco){

	this.campos[this.total++]=new xinput(campo,tipo,dinheiro,branco)
}

//#####################################
//objeto xinput
//#####################################
function xinput(campo,tipo,dinheiro,branco){
	this.campo=campo
	this.tipo=tipo
	this.dinheiro=dinheiro
	this.branco=branco
	campo.onkeypress=eval(tipo)
	if (dinheiro){
		eval("x"+campo.name+"="+campo.value)
		campo.value=formatamoeda(eval("x"+campo.name),reais,truncar)
		campo.onfocus=mfoco
		campo.onblur=mperde
	}
	if (tipo=="cgc"){
		campo.onfocus=cgcfoco
		campo.onblur=cgcperde
	}
	if (tipo=="cpf"){
		campo.onfocus=cpffoco
		campo.onblur=cpfperde
	}
	if (tipo=="cgcoucpf"){
		campo.onfocus=cgcoucpffoco
		campo.onblur=cgcoucpfperde
	}
	if (tipo=="cep"){
		campo.onfocus=cepfoco
		campo.onblur=cepperde
	}
}



//*** Verifica se existem espaços no campo ***
function Espaco(fld,NomeCampo) 
{
   t= fld.value
   if (t.indexOf(" ") != -1) 
	{
      alert("O campo " + NomeCampo + " não pode conter espaços.");
      fld.focus();
	  fld.select();
	  return false;	
	}
	  return true;	
}
//*********



//*** By Cau ***
function validaLogin(frm)
{

	if (!Espaco(frm.login,"Login"))
	{	return false; }


	if(frm.login.value=="")
	{
		alert("Informe o login!");
		frm.login.focus();
		return false;
	}


	if(frm.login.value.length<3)
	{
		alert("O login deve ter, ao menos, 3 caracteres!");
		frm.login.select();
		frm.login.focus();
		return false;
	}



	if(frm.senha.value=="")
	{
		alert("Informe a sua senha!");
		frm.senha.focus();
		return false;
	}


//	if (!Espaco(frm.senha,"Senha"))
//	{	return false; }


	if(frm.senha.value.length<4)
	{
	//	alert("A senha deve ter, ao menos, 4 caracteres!");
	//	frm.senha.value="";
	//	frm.senha.select();
	//	frm.senha.focus();
	//	return false;
	}

	

	return true;
}




function maiuscula(s)
{
	s.value=(s.value).toUpperCase();

}


function minuscula(s)
{
	s.value=(s.value).toLowerCase();

}


function vlToAmericano(v)
{
	v=v.replace('.',''); 
	v=v.replace(',','.');
	return  v;
}	


// Arredonda um n° para "places" casas decimais
function roundNumber(v,places) {
	v = Math.round(v*Math.pow(10,places))/Math.pow(10,places);
	return v
}
//

function maxTela()
{

<!--

/*
Auto Maximize Window Script- By Nick Lowe (nicklowe@ukonline.co.uk)
For full source code, 100's more free DHTML scripts, and Terms Of Use
Visit http://www.dynamicdrive.com
*/

top.window.moveTo(0,0);
if (document.all) {
top.window.resizeTo(screen.availWidth,screen.availHeight);
}
else if (document.layers||document.getElementById) {
if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){
top.window.outerHeight = screen.availHeight;
top.window.outerWidth = screen.availWidth;
}
}
//-->

}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function RetiraAcentos(Campo) {
   var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyz'";
   var Traducao ="AAAAAAAAAEEEEIIOOOOOOUUUUCCABCDEFGHIJKLMNOPQRSTUVXWYZ ";
   var Posic, Carac;
   var TempLog = "";
   for (var i=0; i < Campo.length; i++)
   {
   Carac = Campo.charAt (i);
   Posic  = Acentos.indexOf (Carac);
   if (Posic > -1)
	  TempLog += Traducao.charAt (Posic);
   else
      TempLog += Campo.charAt (i);
   }
      return (TempLog);
}
//
// No form tem que incluir a seguinte linha
// <INPUT onblur="document.formulario.nomecampo.value = RetiraAcentos(document.formulario.nomecampo.value)" title="Informe o nome, sem acentos.&#13;&#10;Mas se vc colocar acentos, o input não aceitará..." maxLength=60 size=40 name=nomecampo>
//

/*
 * NumberFormat 1.5.2
 * v1.5.2 - 27-August-2004
 * v1.5.1 - 13-February-2004
 * v1.5.0 - 20-December-2002
 * v1.0.3 - 23-March-2002
 * v1.0.2 - 13-March-2002
 * v1.0.1 - 20-July-2001
 * v1.0.0 - 13-April-2000
 * http://www.mredkj.com
 * http://www.mredkj.com/javascript/nfdocs.html
 */
  
/*
 * NumberFormat -The constructor
 * num - The number to be formatted.
 *  Also refer to setNumber
 * inputDecimal - (Optional) The decimal character for the input
 *  Also refer to setInputDecimal
 */
function NumberFormat(num, inputDecimal)
{

	// constants
	this.COMMA = ',';
	this.PERIOD = '.';
	this.DASH = '-'; // v1.5.0 - new - used internally
	this.LEFT_PAREN = '('; // v1.5.0 - new - used internally
	this.RIGHT_PAREN = ')'; // v1.5.0 - new - used internally
	this.LEFT_OUTSIDE = 0; // v1.5.0 - new - currency
	this.LEFT_INSIDE = 1;  // v1.5.0 - new - currency
	this.RIGHT_INSIDE = 2;  // v1.5.0 - new - currency
	this.RIGHT_OUTSIDE = 3;  // v1.5.0 - new - currency
	this.LEFT_DASH = 0; // v1.5.0 - new - negative
	this.RIGHT_DASH = 1; // v1.5.0 - new - negative
	this.PARENTHESIS = 2; // v1.5.0 - new - negative
	this.NO_ROUNDING = -1 // v1.5.1 - new

	// member variables
	this.num;
	this.numOriginal;
	this.hasSeparators = false;  // v1.5.0 - new
	this.separatorValue;  // v1.5.0 - new
	this.inputDecimalValue; // v1.5.0 - new
	this.decimalValue;  // v1.5.0 - new
	this.negativeFormat; // v1.5.0 - new
	this.negativeRed; // v1.5.0 - new
	this.hasCurrency;  // v1.5.0 - modified
	this.currencyPosition;  // v1.5.0 - new
	this.currencyValue;  // v1.5.0 - modified
	this.places;
	this.roundToPlaces; // v1.5.1 - new

	// external methods
	this.setNumber = setNumberNF;
	this.toUnformatted = toUnformattedNF;
	this.setInputDecimal = setInputDecimalNF; // v1.5.0 - new
	this.setSeparators = setSeparatorsNF; // v1.5.0 - new - for separators and decimals
	this.setCommas = setCommasNF;
	this.setNegativeFormat = setNegativeFormatNF; // v1.5.0 - new
	this.setNegativeRed = setNegativeRedNF; // v1.5.0 - new
	this.setCurrency = setCurrencyNF;
	this.setCurrencyPrefix = setCurrencyPrefixNF;
	this.setCurrencyValue = setCurrencyValueNF; // v1.5.0 - new - setCurrencyPrefix uses this
	this.setCurrencyPosition = setCurrencyPositionNF; // v1.5.0 - new - setCurrencyPrefix uses this
	this.setPlaces = setPlacesNF;
	this.toFormatted = toFormattedNF;
	this.toPercentage = toPercentageNF;
	this.getOriginal = getOriginalNF;
	this.moveDecimalRight = moveDecimalRightNF;
	this.moveDecimalLeft = moveDecimalLeftNF;

	// internal methods
	this.getRounded = getRoundedNF;
	this.preserveZeros = preserveZerosNF;
	this.justNumber = justNumberNF;
	this.expandExponential = expandExponentialNF;
	this.getZeros = getZerosNF;
	this.moveDecimalAsString = moveDecimalAsStringNF;
	this.moveDecimal = moveDecimalNF;
	this.addSeparators = addSeparatorsNF;

	// setup defaults
	if (inputDecimal == null) {
		this.setNumber(num, this.PERIOD);
	} else {
		this.setNumber(num, inputDecimal); // v.1.5.1 - new
	}
	this.setCommas(true);
	this.setNegativeFormat(this.LEFT_DASH); // v1.5.0 - new
	this.setNegativeRed(false); // v1.5.0 - new
	this.setCurrency(false); // v1.5.1 - false by default
	this.setCurrencyPrefix('$');
	this.setPlaces(2);
}

/*
 * setInputDecimal
 * val - The decimal value for the input.
 *
 * v1.5.0 - new
 */
function setInputDecimalNF(val)
{
	this.inputDecimalValue = val;
}

/*
 * setNumber - Sets the number
 * num - The number to be formatted
 * inputDecimal - (Optional) The decimal character for the input
 *  Also refer to setInputDecimal
 * 
 * If there is a non-period decimal format for the input,
 * setInputDecimal should be called before calling setNumber.
 *
 * v1.5.0 - modified
 */
function setNumberNF(num, inputDecimal)
{
	if (inputDecimal != null) {
		this.setInputDecimal(inputDecimal); // v.1.5.1 - new
	}
	
	this.numOriginal = num;
	this.num = this.justNumber(num);
}

/*
 * toUnformatted - Returns the number as just a number.
 * If the original value was '100,000', then this method will return the number 100000
 * v1.0.2 - Modified comments, because this method no longer returns the original value.
 */
function toUnformattedNF()
{
	return (this.num);
}

/*
 * getOriginal - Returns the number as it was passed in, which may include non-number characters.
 * This function is new in v1.0.2
 */
function getOriginalNF()
{
	return (this.numOriginal);
}

/*
 * setNegativeFormat - How to format a negative number.
 * 
 * format - The format. Use one of the following constants.
 * LEFT_DASH   example: -1000
 * RIGHT_DASH  example: 1000-
 * PARENTHESIS example: (1000)
 *
 * v1.5.0 - new
 */
function setNegativeFormatNF(format)
{
	this.negativeFormat = format;

}

/*
 * setNegativeRed - Format the number red if it's negative.
 * 
 * isRed - true, to format the number red if negative, black if positive;
 *  false, for it to always be black font.
 *
 * v1.5.0 - new
 */
function setNegativeRedNF(isRed)
{
	this.negativeRed = isRed;
}

/*
 * setSeparators - One purpose of this method is to set a
 *  switch that indicates if there should be separators between groups of numbers.
 *  Also, can use it to set the values for the separator and decimal.
 *  For example, in the value 1,000.00
 *   The comma (,) is the separator and the period (.) is the decimal.
 *
 * Both separator or decimal are not required.
 * The separator and decimal cannot be the same value. If they are, decimal with be changed.
 * Can use the following constants (via the instantiated object) for separator or decimal:
 *  COMMA
 *  PERIOD
 * 
 * isC - true, if there should be separators; false, if there should be no separators
 * separator - the value of the separator.
 * decimal - the value of the decimal.
 *
 * v1.5.0 - new
 */
function setSeparatorsNF(isC, separator, decimal)
{
	this.hasSeparators = isC;
	
	// Make sure a separator was passed in
	if (separator == null) separator = this.COMMA;
	
	// Make sure a decimal was passed in
	if (decimal == null) decimal = this.PERIOD;
	
	// Additionally, make sure the values aren't the same.
	//  When the separator and decimal both are periods, make the decimal a comma.
	//  When the separator and decimal both are any other value, make the decimal a period.
	if (separator == decimal) {
		this.decimalValue = (decimal == this.PERIOD) ? this.COMMA : this.PERIOD;
	} else {
		this.decimalValue = decimal;
	}
	
	// Since the decimal value changes if decimal and separator are the same,
	// the separator value can keep its setting.
	this.separatorValue = separator;
}

/*
 * setCommas - Sets a switch that indicates if there should be commas.
 * The separator value is set to a comma and the decimal value is set to a period.
 * isC - true, if the number should be formatted with separators (commas); false, if no separators
 *
 * v1.5.0 - modified
 */
function setCommasNF(isC)
{
	this.setSeparators(isC, this.COMMA, this.PERIOD);
}

/*
 * setCurrency - Sets a switch that indicates if should be displayed as currency
 * isC - true, if should be currency; false, if not currency
 */
function setCurrencyNF(isC)
{
	this.hasCurrency = isC;
}

/*
 * setCurrencyPrefix - Sets the symbol for currency.
 * val - The symbol
 */
function setCurrencyValueNF(val)
{
	this.currencyValue = val;
}

/*
 * setCurrencyPrefix - Sets the symbol for currency.
 * The symbol will show up on the left of the numbers and outside a negative sign.
 * cp - The symbol
 *
 * v1.5.0 - modified - This now calls setCurrencyValue and setCurrencyPosition(this.LEFT_OUTSIDE)
 */
function setCurrencyPrefixNF(cp)
{
	this.setCurrencyValue(cp);
	this.setCurrencyPosition(this.LEFT_OUTSIDE);
}

/*
 * setCurrencyPosition - Sets the position for currency,
 *  which includes position relative to the numbers and negative sign.
 * cp - The position. Use one of the following constants.
 *  This method does not automatically put the negative sign at the left or right.
 *  They are left by default, and would need to be set right with setNegativeFormat.
 *	LEFT_OUTSIDE  example: $-1.00
 *	LEFT_INSIDE   example: -$1.00
 *	RIGHT_INSIDE  example: 1.00$-
 *	RIGHT_OUTSIDE example: 1.00-$
 *
 * v1.5.0 - new
 */
function setCurrencyPositionNF(cp)
{
	this.currencyPosition = cp
}

/*
 * setPlaces - Sets the precision of decimal places
 * p - The number of places.
 *  -1 or the constant NO_ROUNDING turns off rounding to a set number of places.
 *  Any other number of places less than or equal to zero is considered zero.
 *
 * v1.5.1 - modified
 */
function setPlacesNF(p)
{
	this.roundToPlaces = !(p == this.NO_ROUNDING); // v1.5.1
	this.places = (p < 0) ? 0 : p; // v1.5.1 - Don't leave negatives.
}

/*
 * v1.5.2 - new
 *
 * addSeparators
 * The value to be formatted shouldn't have any formatting already.
 *
 * nStr - A number or number as a string
 * inD - Input decimal (string value). Example: '.'
 * outD - Output decimal (string value). Example: '.'
 * sep - Output separator (string value). Example: ','
 */
function addSeparatorsNF(nStr, inD, outD, sep)
{
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}

/*
 * toFormatted - Returns the number formatted according to the settings (a string)
 *
 * v1.5.0 - modified
 * v1.5.1 - modified
 */
function toFormattedNF()
{	
	var pos;
	var nNum = this.num; // v1.0.1 - number as a number
	var nStr;            // v1.0.1 - number as a string
	var splitString = new Array(2);   // v1.5.0
	
	// round decimal places - modified v1.5.1
	// Note: Take away negative temporarily with Math.abs
	if (this.roundToPlaces) {
		nNum = this.getRounded(nNum);
		nStr = this.preserveZeros(Math.abs(nNum)); // this step makes nNum into a string. v1.0.1 Math.abs
	} else {
		nStr = this.expandExponential(Math.abs(nNum)); // expandExponential is called in preserveZeros, so call it here too
	}
	
	// v1.5.2
	// Note that the argument being passed in for inD is this.PERIOD
	//  That's because the toFormatted method is working with an unformatted number
	nStr = this.addSeparators(nStr, this.PERIOD, this.decimalValue, this.separatorValue);
	
	// negative and currency
	// $[c0] -[n0] $[c1] -[n1] #.#[nStr] -[n2] $[c2] -[n3] $[c3]
	var c0 = '';
	var n0 = '';
	var c1 = '';
	var n1 = '';
	var n2 = '';
	var c2 = '';
	var n3 = '';
	var c3 = '';
	var negSignL = (this.negativeFormat == this.PARENTHESIS) ? this.LEFT_PAREN : this.DASH;
	var negSignR = (this.negativeFormat == this.PARENTHESIS) ? this.RIGHT_PAREN : this.DASH;
		
	if (this.currencyPosition == this.LEFT_OUTSIDE) {
		// add currency sign in front, outside of any negative. example: $-1.00	
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c0 = this.currencyValue;
	} else if (this.currencyPosition == this.LEFT_INSIDE) {
		// add currency sign in front, inside of any negative. example: -$1.00
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c1 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_INSIDE) {
		// add currency sign at the end, inside of any negative. example: 1.00$-
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c2 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_OUTSIDE) {
		// add currency sign at the end, outside of any negative. example: 1.00-$
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c3 = this.currencyValue;
	}

	nStr = c0 + n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
	
	// negative red
	if (this.negativeRed && nNum < 0) {
		nStr = '<font color="red">' + nStr + '</font>';
	}

	return (nStr);
}

/*
 * toPercentage - Format the current number as a percentage.
 * This is separate from most of the regular formatting settings.
 * The exception is the number of decimal places.
 * If a number is 0.123 it will be formatted as 12.3%
 *
 * !! This is an initial version, so it doesn't use many settings.
 * !! should use some of the formatting settings that toFormatted uses.
 * !! probably won't want to use settings like currency.
 *
 * v1.5.0 - new
 */
function toPercentageNF()
{
	nNum = this.num * 100;
	
	// round decimal places
	nNum = this.getRounded(nNum);
	
	return nNum + '%';
}

/*
 * Return concatenated zeros as a string. Used to pad a number.
 * It might be extra if already have many decimal places
 * but is needed if the number doesn't have enough decimals. 
 */
function getZerosNF(places)
{
		var extraZ = '';
		var i;
		for (i=0; i<places; i++) {
			extraZ += '0';
		}
		return extraZ;
}

/*
 * Takes a number that JavaScript expresses in notational format
 * and makes it the full number (as a string).
 * e.g. Makes -1e-21 into -0.000000000000000000001
 *
 * If the value passed in is not a number (as determined by isNaN),
 * this function just returns the original value.
 *
 * Exponential number formats can include 1e21 1e+21 1e-21
 *  where 1e21 and 1e+21 are the same thing.
 *
 * If an exponential number is evaluated by JavaScript,
 * it will change 12.34e-9 to 1.234e-8,
 * which is a benefit to this method, because
 * it prevents extra zeros that occur for certain numbers
 * when using moveDecimalAsString
 *
 * Returns a string.
 *
 * v1.5.1 - new
 */
function expandExponentialNF(origVal)
{
	if (isNaN(origVal)) return origVal;

	var newVal = parseFloat(origVal) + ''; // parseFloat to let JavaScript evaluate number
	var eLoc = newVal.toLowerCase().indexOf('e');

	if (eLoc != -1) {
		var plusLoc = newVal.toLowerCase().indexOf('+');
		var negLoc = newVal.toLowerCase().indexOf('-', eLoc); // search for - after the e
		var justNumber = newVal.substring(0, eLoc);
		
		if (negLoc != -1) {
			// shift decimal to the left
			var places = newVal.substring(negLoc + 1, newVal.length);
			justNumber = this.moveDecimalAsString(justNumber, true, parseInt(places));
		} else {
			// shift decimal to the right
			// Check if there's a plus sign, and if not refer to where the e is.
			// This is to account for either formatting 1e21 or 1e+21
			if (plusLoc == -1) plusLoc = eLoc;
			var places = newVal.substring(plusLoc + 1, newVal.length);
			justNumber = this.moveDecimalAsString(justNumber, false, parseInt(places));
		}
		
		newVal = justNumber;
	}

	return newVal;
} 

/*
 * Move decimal right.
 * Returns a number.
 *
 * v1.5.1 - new
 */
function moveDecimalRightNF(val, places)
{
	var newVal = '';
	
	if (places == null) {
		newVal = this.moveDecimal(val, false);
	} else {
		newVal = this.moveDecimal(val, false, places);
	}
	
	return newVal;
}

/*
 * Move decimal left.
 * Returns a number.
 *
 * v1.5.1 - new
 */
function moveDecimalLeftNF(val, places)
{
	var newVal = '';
	
	if (places == null) {
		newVal = this.moveDecimal(val, true);
	} else {
		newVal = this.moveDecimal(val, true, places);
	}
	
	return newVal;
}

/*
 * moveDecimalAsString
 * This is used by moveDecimal, and does not run parseFloat on the return value.
 * 
 * Normally a decimal place is moved by multiplying by powers of 10
 * Multiplication and division in JavaScript can result in floating point limitations.
 * So use this method to move a decimal place left or right.
 *
 * Parameters:
 * val - The value to be shifted. Can be a number or a string,
 *  but don't include special characters. It should evaluate to a number.
 * left - If true, then move decimal left. If false, move right.
 * places - (optional) If not included, then use the objects this.places
 *  The purpose is so this method can be used independent of the state of the object.
 *
 * The regular expressions:
 * re1
 * Pad with zeros in case there aren't enough numbers to cover the spaces shift.
 * A left shift pads to the left, and a right shift pads to the right.
 * Can't just concatenate. There might be a negative sign or the value could be an exponential.
 *
 * re2
 * Switch the decimal.
 * Need the first [0-9]+ to force the search to start rightmost.
 * The \.? and [0-9]{} criteria are the pieces that will be switched
 *
 * Other notes:
 * This method works on exponential numbers, e.g. 1.7e-12
 * because the regular expressions only modify the number and decimal parts.
 *
 * Mozilla can't handle [0-9]{0} in the regular expression.
 *  Fix: Since nothing changes when the decimal is shifted zero places, return the original value.
 *
 * IE is incorrect if exponential ends in .
 *  e.g. -8500000000000000000000. should be -8.5e+21
 *  IE counts it as -8.5e+22
 *	Fix: Replace trailing period, if there is one, using replace(/\.$/, '').
 *
 * Netscape 4.74 cannot handle a leading - in the string being searched for the re2 expressions.
 *  e.g. /([0-9]*)(\.?)([0-9]{2})/ should match everything in -100.00 except the -
 *  but it matches nothing using Netscape 4.74.
 *  It might be a combination of the * ? special characters.
 *  Fix: (-?) was added to each of the re2 expressions to look for - one or zero times.
 *
 * Returns a string.
 *
 * v1.5.1 - new
 * v1.5.2 - modified
 */
function moveDecimalAsStringNF(val, left, places)
{
	var spaces = (arguments.length < 3) ? this.places : places;
	if (spaces <= 0) return val; // to avoid Mozilla limitation
			
	var newVal = val + '';
	var extraZ = this.getZeros(spaces);
	var re1 = new RegExp('([0-9.]+)');
	if (left) {
		newVal = newVal.replace(re1, extraZ + '$1');
		var re2 = new RegExp('(-?)([0-9]*)([0-9]{' + spaces + '})(\\.?)');		
		newVal = newVal.replace(re2, '$1$2.$3');
	} else {
		var reArray = re1.exec(newVal); // v1.5.2
		if (reArray != null) {
			newVal = newVal.substring(0,reArray.index) + reArray[1] + extraZ + newVal.substring(reArray.index + reArray[0].length); // v1.5.2
		}
		var re2 = new RegExp('(-?)([0-9]*)(\\.?)([0-9]{' + spaces + '})');
		newVal = newVal.replace(re2, '$1$2$4.');
	}
	newVal = newVal.replace(/\.$/, ''); // to avoid IE flaw
	
	return newVal;
}

/*
 * moveDecimal
 * Refer to notes in moveDecimalAsString
 * parseFloat is called here to clear away the padded zeros.
 *
 * Returns a number.
 *
 * v1.5.1 - new
 */
function moveDecimalNF(val, left, places)
{
	var newVal = '';
	
	if (places == null) {
		newVal = this.moveDecimalAsString(val, left);
	} else {
		newVal = this.moveDecimalAsString(val, left, places);
	}
	
	return parseFloat(newVal);
}

/*
 * getRounded - Used internally to round a value
 * val - The number to be rounded
 * 
 *  To round to a certain decimal precision,
 *  all that should need to be done is
 *  multiply by a power of 10, round, then divide by the same power of 10.
 *  However, occasional numbers don't get exact results in most browsers.
 *  e.g. 0.295 multiplied by 10 yields 2.9499999999999997 instead of 2.95
 *  Instead of adjusting the incorrect multiplication,
 *  this function uses string manipulation to shift the decimal.
 *
 * Returns a number.
 *
 * v1.5.1 - modified
 */
function getRoundedNF(val)
{
	val = this.moveDecimalRight(val);
	val = Math.round(val);
	val = this.moveDecimalLeft(val);
	
	return val;
}

/*
 * preserveZeros - Used internally to make the number a string
 * 	that preserves zeros at the end of the number
 * val - The number
 */
function preserveZerosNF(val)
{
	var i;

	// make a string - to preserve the zeros at the end
	val = this.expandExponential(val);
	
	if (this.places <= 0) return val; // leave now. no zeros are necessary - v1.0.1 less than or equal
	
	var decimalPos = val.indexOf('.');
	if (decimalPos == -1) {
		val += '.';
		for (i=0; i<this.places; i++) {
			val += '0';
		}
	} else {
		var actualDecimals = (val.length - 1) - decimalPos;
		var difference = this.places - actualDecimals;
		for (i=0; i<difference; i++) {
			val += '0';
		}
	}
	
	return val;
}

/*
 * justNumber - Used internally to parse the value into a floating point number.
 * Replace all characters that are not 0-9, a decimal point, or a negative sign.
 *
 *  A number can be entered using special notation.
 *  For example, the following is a valid number: 0.0314E+2
 *
 * v1.0.2 - new
 * v1.5.0 - modified
 * v1.5.1 - modified
 * v1.5.2 - modified
 */
function justNumberNF(val)
{
	newVal = val + '';
	
	var isPercentage = false;
	
	// check for percentage
	// v1.5.0
	if (newVal.indexOf('%') != -1) {
		newVal = newVal.replace(/\%/g, '');
		isPercentage = true; // mark a flag
	}
		
	// Replace everything but digits - + ( ) e E
	var re = new RegExp('[^\\' + this.inputDecimalValue + '\\d\\-\\+\\(\\)eE]', 'g');	// v1.5.2	
	newVal = newVal.replace(re, '');
	// Replace the first decimal with a period and the rest with blank
	// The regular expression will only break if a special character
	//  is used as the inputDecimalValue
	//  e.g. \ but not .
	var tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');
	var treArray = tempRe.exec(newVal); // v1.5.2
	if (treArray != null) {
	  var tempRight = newVal.substring(treArray.index + treArray[0].length); // v1.5.2
		newVal = newVal.substring(0,treArray.index) + this.PERIOD + tempRight.replace(tempRe, ''); // v1.5.2
	}
	
	// If negative, get it in -n format
	if (newVal.charAt(newVal.length - 1) == this.DASH ) {
		newVal = newVal.substring(0, newVal.length - 1);
		newVal = '-' + newVal;
	}
	else if (newVal.charAt(0) == this.LEFT_PAREN
	 && newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) {
		newVal = newVal.substring(1, newVal.length - 1);
		newVal = '-' + newVal;
	}
	
	newVal = parseFloat(newVal);
	
	if (!isFinite(newVal)) {
		newVal = 0;
  }
	
	// now that it's a number, adjust for percentage, if applicable.
  // example. if the number was formatted 24%, then move decimal left to get 0.24
  // v1.5.0 - updated v1.5.1
  if (isPercentage) {
  	newVal = this.moveDecimalLeft(newVal, 2);
  }
		
	return newVal;
}

function formataNumero(v)
{
	var vlRet, nf = new NumberFormat(v);
	nf.setSeparators(true, nf.PERIOD, nf.COMMA);
	vlRet = nf.toFormatted();
	return vlRet;
}


// Exclui todos os espaçoes do inicio e do final da string
function Trim(str)
{
while (str.charAt(0) == " ")
str = str.substr(1,str.length -1);

while (str.charAt(str.length-1) == " ")
str = str.substr(0,str.length-1);

return str;
} 


// Escrever texto em um layer
function writit(text,id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
		x.innerHTML = '';
		x.innerHTML = text;
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML = text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		text2 = '<P CLASS="testclass">' + text + '</P>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}

function exibeLayer(id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
	}
	else if (document.all)
	{
		x = document.all[id];
	}
		x.style.visibility='visible';			
}

function escondeLayer(id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
	}
	else if (document.all)
	{
		x = document.all[id];
	}
		x.style.visibility='hidden';			
}

<!-- textCounter() parameters are:  text field, the count field, max length -->


<!-- Original:  Ronnie T. Moore -->
<!-- Web Site:  The JavaScript Source -->

<!-- Dynamic 'fix' by: Nannette Thacker -->
<!-- Web Site: http://www.shiningstar.net -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else 
countfield.value = maxlimit - field.value.length;
}
// End -->


// Calcula idade em anos
// Usa todas as funções abaixo
<!-- chamada da função: calcular_idade(Data) -->
<!-- Data no formato dd/mm/yyyy -->
<!-- Original:  Dev Pragad (devpragad@yahoo.com) -->
<!-- Web Site:  http://www.geocities.com/devpragad -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Adaptado por Cau, em 18/10/2007 -->
function leapyear(a) {
	if(((a%4==0)&&(a%100!=0))||(a%400==0)) return true
	else 
	return false
}

function go(StoredAge) {
			mm=parseInt(mm,10)
			dd=parseInt(dd,10)
			yy=parseInt(yy,10)
		
			if ((mm<1) || (mm>12) || (dd<1) || (dd>31) || (yy<1) ||(mm==" ") || (dd==" ") || (yy==" "))  main="Invalid" 
			else 
			if (((mm==4) || (mm==6) || (mm==9) || (mm==11)) && (dd>30)) main="Invalid"
			else if (mm==2) {
				if (dd>29)main="Invalid" 
				else if((dd>28) && (!lyear(yy)))   main="Invalid"
			}
			else main=main
		
			if(main=="valid") {
				var m
				if (mm==1) n=31+1
				if (mm==2)
				   { n=59+1}
				if (mm==3)  n=90+1//;  if (lyear(yy)) n=n+1; }
				if (mm==4)  n=120+1//  if (lyear(yy)) n=n+1; }
				if (mm==5)  n=151+1// ; if (lyear(yy)) n=n+1; }
				if (mm==6)  n=181+1//;  if (lyear(yy)) n=n+1; }
				if (mm==7)  n=212+1// ; if (lyear(yy)) n=n+1; }
				if (mm==8)  n=243+1//  ;if (lyear(yy)) n=n+1; }
				if (mm==9)  n=273+1//;  if (lyear(yy)) n=n+1; }
				if (mm==10)  n=304+1//;  if (lyear(yy)) n=n+1; }
				if (mm==11)  n=334+1//;  if (lyear(yy)) n=n+1; }
				if (mm==12)  n=365+1//;  if (lyear(yy)) n=n+1; }
		
				if((mm==1)||(mm==3)||(mm==5)||(mm==7)||(mm==8)||(mm==10)||(mm==12))
				n+=31+dd
				else if((mm==4)||(mm==6)||(mm==9)||(mm==11))
				n+=31+dd+1
				else if(mm==2) {
					if(lyear(yy)) n+=29+dd-3
					else if(!lyear(yy)) n+=28+dd-1
				}
			
				fours = yy/4
				hunds = yy/100
				fhunds = yy/400
				var day
				
				day=(yy + n + fours - hunds + fhunds) % 7;
				day=parseInt(day,10)
			

				switch(day)
				{/*
					case 1 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Sunday"
					break
					case 2 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Monday"
					break
					case 3 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Tuesday"
					break
					case 4 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Wednesday"
					break
					case 5 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Thursday"
					break
					case 6 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Friday"
					break
					case 7 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Saturday"
					break
					case 0 : document.form1.age.value = "You are " + StoredAge + " years old  and  you were born on a  Saturday"
					break
					*/
				}
				
				return StoredAge;
				
			}	
}


function lyear(a) {
return leapyear(a); 
/*if(((a%4==0) && (a%100!=0)) || (a%400==0)) return true;
else return false;*/
}

function calcular_idade(data) {
	var ap,data;
	var array_data = data.split('/');
	
	yy = parseInt(array_data[2],10); 
	mm = parseInt(array_data[1],10); 
	dd = parseInt(array_data[0],10); 

	main="valid"

	if ((mm<1) || (mm>12) || (dd<1) || (dd>31) || (yy<1) ||(mm=="") || (dd=="") || (yy==""))  main="Invalid" 
	else 
	if (((mm==4) || (mm==6) || (mm==9) || (mm==11)) && (dd>30)) main="Invalid"
	else if (mm==2) {
		if (dd>29)main="Invalid" 
		else if((dd>28) && (!lyear(yy)))   main="Invalid"
	}
	else if((yy>9999)||(yy<0)) main="Invalid"
	else main=main

	if(main=="valid") {
	
		days = new Date()
		gdate = days.getDate()
		gmonth = days.getMonth()
		gyear = days.getFullYear()

		if (gyear < yy) {main = "Invalid"; alert('Você digitou uma data futura ou a data de seu micreo está errada!'); return;}
		if (gyear==yy && gmonth+1 < mm) {main = "Invalid";alert('Você digitou uma data futura ou a data de seu micreo está errada!'); return;}
		if (gyear==yy && gmonth+1 == mm && gdate < dd) {main = "Invalid";alert('Você digitou uma data futura ou a data de seu micreo está errada!'); return;}

		//alert(gyear);
		age=gyear-yy;


		if((mm==(gmonth+1))&&(dd<=parseInt(gdate,10))) {
			age=age 
		} 
		else {
			if(mm<=(gmonth)) {
				age=age
			} else {
				age=age-1 
			} 
		}
		
		if(age==0)	age=age
		{
			storeAge=age;
			//document.form1.age.value="  You are " + age+ " years old   &  "
		}
		
		if(mm<=(gmonth+1))
			age=age-1
		if((mm==(gmonth+1))&&(dd>parseInt(gdate,10))) 
			age=age+1
	
		var m=0;
		var n=0;
		
		if (mm==12) { n=31-dd; }
		if (mm==11) { n=61-dd;}   
		if (mm==10) { n=92-dd; }  
		if (mm==9) { n=122-dd;  } 
		if (mm==8) { n=153-dd;}   
		if (mm==7) { n=184-dd;}   
		if (mm==6) { n=214-dd; }  
		if (mm==5) { n=245-dd;  } 
		if (mm==4) { n=275-dd;  } 
		if (mm==3) { n=306-dd;  }
		if (mm==2) { n=334-dd; if(leapyear(yy)) n=n+1 }
		if (mm==1) { n=365-dd;  if (leapyear(yy)) n=n+1 }
		
		
	
		if (gmonth==1) m=31
		if (gmonth==2)
		{ 
			m=59
			if (leapyear(gyear)) m=m+1;  
		}
		if (gmonth==3) { m=90;  if (leapyear(gyear)) m=m+1; }
		if (gmonth==4) { m=120;  if (leapyear(gyear)) m=m+1; }
		if (gmonth==5) { m=151 ; if (leapyear(gyear)) m=m+1; }
		if (gmonth==6) { m=181;  if (leapyear(gyear)) m=m+1; }
		if (gmonth==7) { m=212 ; if (leapyear(gyear)) m=m+1; }
		if (gmonth==8) { m=243  ;if (leapyear(gyear)) m=m+1; }
		if (gmonth==9) { m=273;  if (leapyear(gyear)) m=m+1; }
		if (gmonth==10) { m=304;  if (leapyear(gyear)) m=m+1; }
		if (gmonth==11) { m=334;  if (leapyear(gyear)) m=m+1; }
		if (gmonth==12) { m=365;  if (leapyear(gyear)) m=m+1; }
		
		totdays=(parseInt(age,10)*365)
		totdays+=age/4;
		totdays=parseInt(totdays,10)+gdate+m+n;
	
		// month
		gmonth = gmonth +1;	
		months=storeAge*12
//			months+=12-parseInt(mm);
//			months+=gmonth;
		//alert(gmonth)
		if (parseInt(mm,10) > gmonth)
		{
		//alert('a')
			months+=12-parseInt(mm,10);
			months+=gmonth;
		}
		else if (parseInt(mm,10) != gmonth)
		{
			months += gmonth - parseInt(mm,10);
			//alert(gmonth - parseInt(mm));
			if (dd > gdate && months >0)
				{months = months - 1;}
				
		}
		
		/*if (dd <= gdate){
		//alert('dd = ' + dd + '  days = ' +  gdate) 
			months = months+1;
		}*/
		
		//alert('age*12 = ' + age*12 + ' |  parseInt(mm) =  ' + mm + '  | gmonth=  ' + gmonth + '    | Total Months = ' + months);
		gmonth = gmonth -1;
		var p=0;
		//weeks
		if (gmonth==1) p=31+gdate
		if (gmonth==2)
		   { p=59+gdate
			 if (leapyear(gyear)) m=m+1;  }
		if (gmonth==3) { p=90+gdate;  if (leapyear(gyear)) p=p+1; }
		if (gmonth==4) { p=120+gdate;  if (leapyear(gyear)) p=p+1; }
		if (gmonth==5) { p=151+gdate ; if (leapyear(gyear)) p=p+1; }
		if (gmonth==6) { p=181+gdate;  if (leapyear(gyear)) p=p+1; }
		if (gmonth==7) { p=212+gdate ; if (leapyear(gyear)) p=p+1; }
		if (gmonth==8) { p=243+gdate  ;if (leapyear(gyear)) p=p+1; }
		if (gmonth==9) { p=273+gdate;  if (leapyear(gyear)) p=p+1; }
		if (gmonth==10) { p=304+gdate;  if (leapyear(gyear)) p=p+1; }
		if (gmonth==11) { p=334+gdate;  if (leapyear(gyear)) p=p+1; }
		if (gmonth==12) { p=365+gdate;  if (leapyear(gyear)) p=p+1; }
		/*
		weeks=(age*365)+n+p
		weeks=weeks/7
		etcdays=parseFloat(weeks)-parseInt(weeks)
		etcdays=Math.round(etcdays*7)
		weeks=parseInt(weeks)
		etcdays+=parseInt(age/4)
		if(etcdays>7)
		weeks+=parseInt(etcdays/7)
		*/
		
		
		return go(storeAge);
	
	
	
	} else {

	}
}


//  End -->
