
//*************************************************************
//	Formata campos de acordo com a mascara passada
//*************************************************************
/*
Para usar é bem simples
carrege esse arquivo em seu html e no onload do body execute
Mascaras.carregar();
<body onload="Mascaras.carregar();">

pontro o codigo vai percorrer todoseu html procurando as marcacoes abaixo em seus inputs e aplicando a mascara

insira os seguintes atributos nos seus input

tipo = pode ser numerico ou decimal
mascara = é a mascara a ser usada coloque # nas posições dos caracteres ex : "##:##"
casasdecimais = para o caso do tiposer decimal aqui eh dito quantas casas decimais vaum ser usadas
negativo = isso define um sinal de negativo no inicio do valor

pronto é so isso
exemplos:
<input type="text" tipo="numerico"> aqui so da para digitar numeros
<input type="text" tipo="numerico" negativo=true> aqui so da para digitar numeros e no caso de precionar "-" umsinal de negativo vai aparecer
<input type="text" tipo="decimal" negativo=true casasdecimais=3>
<input type="text" tipo="numerico" mascara="##/##/####"> data
<input type="text" tipo="numerico" mascara="###.###.###-##"> cpf
*/
Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,

// retirei o array de acentos porque ele estava causando problemas no script
// RENE CASTRO
//Acentos: /[À-ÿ]/i,
// ******************************
Num: /[0-9]/,
carregar: function(parte){
						 var Tags = ['input','textarea'];
						 if (typeof parte == "undefined") parte = document;
						 for(var z=0;z<Tags.length;z++){
							Inputs=parte.getElementsByTagName(Tags[z]);
							for(var i=0;i<Inputs.length;i++)
								if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
							this.aplicar(Inputs[i]);
						 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50)
   tamanho = 10;
  if (!casasdecimais)
   casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
 }
 if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
  campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; return true;
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');
 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
aplicarMascara: function(campo, valor){
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-")
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0";
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
}
};

//*************************************************************
//	Funções usadas para pegar dados de outras telas
//*************************************************************
function f_parametro(txt_parametro)
	{
    arr_parametro = txt_parametro.split("$$")
    for (var i=1; i <= arr_parametro.length-2; i++)
        {
        if((i % 2) != 0)
            {
            eval('opener.document.form1.' + arr_parametro[i] + '.value = document.form1.' + arr_parametro[parseInt(i,10)+1] + '.value');
            }
        }
    window.close();
	} 
function f_atalho(opcao,caminho)
    {
	openWindow(caminho,'Atalho','scrollbars=yes,left=20,top=50,width=950,height=500');
    }


//*************************************************************
//	abre uma popup com o calendario
//*************************************************************
function calendarPicker(strField,strCaminho)
{
 	window.open(strCaminho + '../sysDiversos/Calendario.aspx?field=' + strField,'Calendario','toolbar=no,scrollbars=no,menubar=no,width=238,height=165,resizable=no,');
}
function isArray(valor){
    try{
    	return !(String(valor.length) == "undefined");
    }catch(ex){
        return false;
    }
    
}

function isArray(valor){
    try{
    	return !(String(valor.length) == "undefined");
    }catch(ex){
        return false;
    }
    
}



function f_trataCampoNumeroExit(obj){
	if ( f_converteNumero(obj.value, 0) == 0 ){
		obj.value = "0,00";
	}
}

//*************************************************************
//	CONVERTE O VALOR PASSADO EM NÚMERO OU RETORNA O PADRAO
//*************************************************************
function f_converteNumero(valor, padrao){
	var temp = "";

//	padrao = f_converteNumero(padrao,0);
	
	temp = String(valor).replace(".","").replace(",",".");
	if (isNaN(temp)){
		return Number(padrao);
	}
	else{
		return Number(temp);
	}
		
}

function f_formataValor(valor, decimais){
	
	valor = valor.split('.');
	
	if (valor.length == 1) valor[1] = "";
	
	for(var i=valor[1].length;i<decimais;i++)
		valor[1] += "0";
		
	valor[1] = valor[1].substr(0,2);
	
	return (valor[0] + "," + valor[1]);
 
}

//*************************************************************
function fnPermitirDocumento()
//*************************************************************
{
	if(!(isNonnegativeInteger(String.fromCharCode(event.keyCode))||String.fromCharCode(event.keyCode)=="-"||String.fromCharCode(event.keyCode)=="."||String.fromCharCode(event.keyCode)=="/"))
		event.returnValue = false;
}

function openWindow(theURL,winName,features){
	var browser="";
	if(navigator.appName=="Netscape" && parseInt(navigator.appVersion)==2) { browser="n2"; }
	if(navigator.appName=="Netscape" && parseInt(navigator.appVersion)==3) { browser="n3"; }
	if(navigator.appName=="Netscape" && parseInt(navigator.appVersion)==4) { browser="n4"; }
	if(navigator.appVersion.indexOf("MSIE 3.0") != -1) { browser="ie3"; }
	if(navigator.appVersion.indexOf("MSIE 4.0") != -1) { browser="ie4"; }
	
	var w=0;
	var h=0;
	if ( browser=="n4" )
	  {
	  var screen_height=parent.screen.height;
	  var screen_width=parent.screen.width;
	  var main_height=parent.window.innerHeight;
	  h=(screen_height-main_height);
	  w=(screen_width/2)-275;
	  }
	
	features += ",screenX=" + w + ",screenY=" + h;
	
  var newWind=window.open(theURL,winName,features);


  if (newWind.opener == null)
     {newWind.opener = window;}
  else{
     if ( browser=="n3"  ||  browser=="n4"  ||  browser=="ie4" )
     
        newWind.focus();
     }   
  }

//*************************************************************
function f_tabula(limpa,valor1,valor2)
//*************************************************************
	{
	// Salta de um text para o outro quando o limite de digitos for atingido.
	// Exemplo.: onKeyUp="f_passa(0,this.name,'mes');"
	if(eval("document.form."+valor1+".value.length")>=eval("document.form."+valor1+".maxLength")) 
		{
		if(limpa == 0)
			{
			eval("document.form."+valor2+".value = ''");
			}
		eval("document.form."+valor2+".focus()");
		}
	}
//*************************************************************
function f_foco(limpa,valor)
//*************************************************************
	{
	// Salta de um campo
	// Exemplo.: onKeyUp="f_foco(0,'mes');"
	if(limpa == 0)
		{
		eval("document.form."+valor+".value = '';");
		}
	eval("document.form."+valor+".focus();");
	}
//*************************************************************
function BloquearAspas()
//*************************************************************
{
	//ATENCAO: este codigo eh compativel apenas com o Internet Explorer
	var strNavegador=navigator.appName;
	if(strNavegador.indexOf('Microsoft') > -1)
	{
		if((event.keyCode==34) || (event.keyCode==39)) //se for ' ou "
		{
		alert('Este campo não aceita aspas !')
			event.returnValue = false;
		}
	}
	else
	{
		if((event.keyCode==34) || (event.keyCode==39)) //se for ' ou "
		{
			Event.returnValue = false;
		}
	}
}
//*************************************************************
function fnPermitirNumeros()
//*************************************************************
{
	/*
		45 - tecla "-" do teclado
	*/

	if (event.keyCode==45){
		event.returnValue = true;
	} else if(!isNonnegativeInteger(String.fromCharCode(event.keyCode))){
		event.returnValue = false;
	}
}
//*************************************************************
function fnPermitirMoney()
//*************************************************************
{
	/*
		45 - tecla "-" do teclado
	*/
	
	if ( (event.keyCode==44) || (event.keyCode==45) ){
		event.returnValue = true;
	} else if ((event.keyCode<48)||(event.keyCode>57)){
		event.returnValue = false;
	}
}
//*************************************************************
function fnRepetidos(strValor, intQuantidade)
//*************************************************************
{
	var blnRetorno=false;
	var i;
	var intIguais=1;
	var strCharAnt=strValor.charAt(0);
	for (i = 1; i < strValor.length ;i++)
	{
		if(intIguais==intQuantidade)
		{
			blnRetorno=true;
			break;			
		}
		else
		{
			if(strValor.charAt(i)==strCharAnt)
			{
				intIguais++;
			}
			else
			{
				intIguais=1;
				strCharAnt=strValor.charAt(i);
			}
		}		
	}
	return blnRetorno;
}
//*************************************************************
function fnPermitirCEP()
//*************************************************************
{
	if (event.keyCode==45)
		event.returnValue = true;
	else
	{
		if((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
	}
}
//*************************************************************
function fnPermitirData()
//*************************************************************
{
alert(event.keyCode);
	if (event.keyCode==45)
		event.returnValue = true;
	else
	{
		if((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
	}
}
//*************************************************************
function fnPermitirFone()
//*************************************************************
{
	if ((event.keyCode==40) || (event.keyCode==41) || (event.keyCode==45) || (event.keyCode==32))
		event.returnValue = true;
	else
	{
		if((event.keyCode<48)||(event.keyCode>57))
		event.returnValue = false;
	}
}

//*************************************************************
function fnumero(S)
//*************************************************************
// onkeyup='document.form.campo.value = fnumero(form.campo.value)'
// Deixa so' os digitos no numero
//
	{
var Digitos	= "0123456789";
var temp	= "";
var digito	= "";
    for (var i=0; i<S.length; i++)
		{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0){temp=temp+digito}
		}
    return temp
	}
//*************************************************************
function f_radio(tipo,radio,texto,foco)
//*************************************************************
	{
	if(tipo == 0)
		{
		alert("Informe o campo "+texto+" !");
		}
	else
		{
		alert(texto);
		}
	for (var i = 0; i < radio.length; i++)
		{
		if (radio[i].checked) { break }
	    }
	if(foco == 1)	{radio[1].focus();}
	}
//*************************************************************
function f_cgc(chave)
//*************************************************************
// deve ser passado f_cgc(document.form.campo.value);
	{
    if (chave.length > 14)
	    {
	    chave = chave.substring(0,2) + chave.substring(3,6) + chave.substring(7,10) + chave.substring(11,15) + chave.substring(16,18)
	    }
    
    var digito1 ;
    var digito2 ;
	var X=0;
    if (chave.length == 14)
	    {
		digito1 = " ";
		digito2 = " ";
		digito1 = f_cgc_modulo(chave.substring ( 12 , 0 ), 9, 0);
		digito2 = f_cgc_modulo(chave.substring ( 13 , 0 ), 9, 0);
		if ( digito1 == chave.substring ( 13 , 12 ) ) 
			if ( digito2 == chave.substring ( 14 , 13 ) )
				{
				return (1);
				}
		}
		return (X) ;
		}
//*************************************************************
function f_cgc_modulo(argumento,fator,resto) 
//*************************************************************
	{
	var vl_total	=0;
	var vl_fator	=0;
	var vl_numero	=0;
	var vl_tamanho	=0;
	var vl_resto	=0;
	var vl_digito	=0;
   
	vl_fator = 2;
	vl_total = 0;
	for ( vl_tamanho = argumento.length; vl_tamanho > 0; vl_tamanho-- )
		{
		vl_numero = argumento.substring ( vl_tamanho , vl_tamanho - 1 );
		vl_numero *= vl_fator;
		vl_total += vl_numero;
		if ( vl_fator == fator )
			vl_fator = 2;
		else
			++vl_fator;
		}
	vl_resto = vl_total % 11;
	if ( vl_resto == 0 )
		vl_digito = resto;
	else
		{
		if ( vl_resto == 1 )
			vl_digito = 0;
		else
			vl_digito = 11 - vl_resto;
		}
	return vl_digito;  
	}
//*************************************************************
function testaemail(campo)
//*************************************************************
	{
	if (!isEmail(campo))
		{
		alert("O e-mail informado não é válido !"); 
		}
	}
//*************************************************************
function imprimir()
//*************************************************************
	{
	var da = (document.all) ? 1 : 0;
	var pr = (window.print) ? 1 : 0;
	var mac = (navigator.userAgent.indexOf("Mac") != -1); 
	if (pr) // NS4, IE5
		window.print()
	else if (da && !mac) // IE4 (Windows)
		vbPrintPage()
	else // other browsers
		return false;
	if (da && !pr && !mac) with (document)
		{
		writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
		writeln('<' + 'SCRIPT LANGUAGE="VBScript">');
		writeln('Sub window_onunload');
		writeln('  On Error Resume Next');
		writeln('  Set WB = nothing');
		writeln('End Sub');
		writeln('Sub vbPrintPage');
		writeln('  OLECMDID_PRINT = 6');
		writeln('  OLECMDEXECOPT_DONTPROMPTUSER = 2');
		writeln('  OLECMDEXECOPT_PROMPTUSER = 1');
		writeln('  On Error Resume Next');
		writeln('  WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
		writeln('End Sub');
		writeln('<' + '/SCRIPT>');
		}
	}
//*************************************************************
// passar uma string no formato aaaa/mm/dd
function transforma(chave,ordem)
//*************************************************************
	{
	var ydata,xdia,xmes,xano;
	ydata= new Date(chave);
	if(ydata.getDate()< 10)
		{
		xdia="0"+ydata.getDate();
		}
	else
		{
		xdia=ydata.getDate();
		}
	if(ydata.getMonth()+1< 10)
		{
		xmes="0"+(ydata.getMonth()+1);
		}
	else
		{
		xmes=(ydata.getMonth()+1);
		}
	xano=ydata.getYear();
	if(ordem == 1)  // mostra dd/mm/aaaa
		{
		ydata = xdia+"/"+xmes+"/"+xano;
		}
	else			// mostra aaaa/mm/dd
		{
		ydata = xano+"/"+xmes+"/"+xdia;
		}
	return ydata;

	}
//*************************************************************
function f_valida(xdia,xmes,xano)
//*************************************************************
//  Recebe uma string no formato dd/mm/aaaa  QUE NÃO DEVE ser transformada em data (deve vir como string)
//  Exemplo:
//	if(f_valida(document.form.data_dia.value,document.form.data_mes.value,document.form.data_ano.value) == 0)
//		{
//		alert("Ocorreu um erro !");
//		}
//
//	xdia=chave.substring(0,02);
//	xmes=chave.substring(3,05);
//	xano=chave.substring(6,10);
// Retorno 0 (Erro), 1 (Ok), 2 (Tem um campo vazio)
	{
	if(xdia == "" || xmes == "" || xano == "") return 2; // erro
	if(xmes < 1 || xmes > 12) return 0; // erro
	if(xano < 1 || xano > 9999) return 0; // erro
	if(xmes == "04" || xmes == "06" || xmes == "09" || xmes == "11")
		{
		if(xdia > 30) return 0; // erro
		}
	else
		{
		if(xmes == "02") 
			{
			if(xano%4 == 0)
				{
				if(xdia > 29) return 0;
				}
			else
				{
				if(xdia > 28) return 0;
				}
			}			
		}
	return 1;  // sem erro
	}
//*************************************************************
function tremer(n)
//*************************************************************
	{
	if (self.moveBy)
		{
		for (i = 10; i > 0; i--)
			{
			for (j = n; j > 0; j--)
				{
				self.moveBy( 0, i);
				self.moveBy( i, 0);
				self.moveBy( 0,-i);
				self.moveBy(-i, 0);
				}   
			}
		}
	}
//*************************************************************
function fnMaxChar(objTextarea, numTamanho)
//*************************************************************
//limitar o preenchimento do textarea como um textbox
	{
	var strConteudo;
	strConteudo = objTextarea.value;
	if (strConteudo.length >= numTamanho)
		{
		var Cod = '|' + event.keyCode + '|';
		if(teclas.indexOf(Cod)==-1)
			{
			event.returnValue = false;
			}
		}
	}
//*************************************************************
function fnxxMaxChar(objTextarea, numTamanho)
//*************************************************************
//limitar o preenchimento do textarea como um textbox
	{
	var strConteudo;
	strConteudo = objTextarea.value;
	if (strConteudo.length >= numTamanho)
		{
			event.returnValue = false;
		}
	}
//*************************************************************
// isWhitespace (s)                    Check whether string s is empty or whitespace.
// isLetter (c)                        Check whether character c is an English letter 
// isDigit (c)                         Check whether character c is a digit 
// isLetterOrDigit (c)                 Check whether character c is a letter or digit.
// isInteger (s [,eok])                True if all characters in string s are numbers.
// isSignedInteger (s [,eok])          True if all characters in string s are numbers; leading + or - allowed.
// isPositiveInteger (s [,eok])        True if string s is an integer > 0.
// isNonnegativeInteger (s [,eok])     True if string s is an integer >= 0.
// isNegativeInteger (s [,eok])        True if s is an integer < 0.
// isNonpositiveInteger (s [,eok])     True if s is an integer <= 0.
// isFloat (s [,eok])                  True if string s is an unsigned floating point (real) number. (Integers also OK.)
// isSignedFloat (s [,eok])            True if string s is a floating point number; leading + or - allowed. (Integers also OK.)
// isAlphabetic (s [,eok])             True if string s is English letters 
// isAlphanumeric (s [,eok])           True if string s is English letters and numbers only.
// isEmail (s [,eok])                  True if string s is a valid email address.
// isYear (s [,eok])                   True if string s is a valid Year number.
// isIntegerInRange (s, a, b [,eok])   True if string s is an integer between a and b, inclusive.
// isMonth (s [,eok])                  True if string s is a valid month between 1 and 12.
// isDay (s [,eok])                    True if string s is a valid day between 1 and 31.
// daysInFebruary (year)               Returns number of days in February of that year.
// isDate (year, month, day)           True if string arguments form a valid date.
// CPFValido(s)						   Retorna true se o CPF for válido. 

// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
// stripCharsNotInBag (s, bag)         Removes all characters NOT in string bag from string s.
// stripWhitespace (s)                 Removes all whitespace characters from s.
// stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.
// reformat (TARGETSTRING, STRING,     Function for inserting formatting characters or
//   INTEGER, STRING, INTEGER ... )       delimiters into TARGETSTRING.                                       

// FUNCTIONS TO PROMPT USER:
//
// prompt (s)                          Display prompt string s in status bar.
// promptEntry (s)                     Display data entry prompt string s in status bar.
// warnEmpty (theField, s)             Notify user that required field theField is empty.
// warnInvalid (theField, s)           Notify user that contents of field theField are invalid.


// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok])    Check that theField.value is not empty or all whitespace.
// checkEmail (theField [,eok])        Check that theField.value is a valid Email.
// checkYear (theField [,eok])         Check that theField.value is a valid Year.
// checkMonth (theField [,eok])        Check that theField.value is a valid Month.
// checkDay (theField [,eok])          Check that theField.value is a valid Day.
// checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
//                                     Check that field values form a valid date.
// getRadioButtonValue (radio)         Get checked value from radio button.
// VARIABLE DECLARATIONS
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// whitespace characters
var whitespace = " \t\n\r";
// decimal point character differs by language and culture
var decimalPointDelimiter = ","
// CONSTANT STRING DECLARATIONS
// (grouped for ease of translation and localization)
// m is an abbreviation for "missing"
var mPrefix = "Voce nao entrou com o valor no campo "
var mSuffix = ". Este é um campo obrigatorio. Favor entrar com o valor do campo agora."
// s is an abbreviation for "string"
var sUSLastName = "Last Name"
var sUSFirstName = "First Name"
var sWorldLastName = "Family Name"
var sWorldFirstName = "Given Name"
var sTitle = "Cargo"
var sCompanyName = "Empresa"
var sUSAddress = "Rua"
var sWorldAddress = "Endereco"
var sCity = "Cidade"
var sCountry = "Pais"
var sWorldPostalCode = "Codigo Postal"
var sFax = "Fax"
var sDateOfBirth = "Data de Nascimento"
var sEmail = "E-mail"
var sOtherInfo = "Outras Informacoes"

// i is an abbreviation for "invalid"

var iEmail = "Este campo deve conter um E-mail válido."
var iDay = "Este campo deve conter um dia entre 1 e 31."
var iMonth = "Este campo deve conter um mês 1 e 12."
var iYear = "Este campo deve conter um ano com 2 ou 4 digitos."
var iDatePrefix = "O Dia, Mês e Ano para "
var iDateSuffix = " não compõem uma data vália."

// p is an abbreviation for "prompt"

var pEntryPrompt = "Por favor, forneça "
var pEmail = "um e-mail válido."
var pDay = "um dia entre 1 e 31."
var pMonth = "um mês entre 1 e 12"
var pYear = "um ano com 2 ou 4 dígitos."


// Global variable defaultEmptyOK defines default return value 
// for many functions when they are passed the empty string. 
// By default, they will return defaultEmptyOK.
//
// defaultEmptyOK is false, which means that by default, 
// these functions will do "strict" validation.  Function
// isInteger, for example, will only return true if it is
// passed a string containing an integer; if it is passed
// the empty string, it will return false.
//
// You can change this default behavior globally (for all 
// functions which use defaultEmptyOK) by changing the value
// of defaultEmptyOK.
//
// Most of these functions have an optional argument emptyOK
// which allows you to override the default behavior for 
// the duration of a function call.
//
// This functionality is useful because it is possible to
// say "if the user puts anything in this field, it must
// be an integer (or a phone number, or a string, etc.), 
// but it's OK to leave the field empty too."
// This is the case for fields which are optional but which
// must have a certain kind of content if filled in.

var defaultEmptyOK = false

// Attempting to make this library run on Navigator 2.0,
// so I'm supplying this array creation routine as per
// JavaScript 1.0 documentation.  If you're using 
// Navigator 3.0 or later, you don't need to do this;
// you can use the Array constructor instead.
//*************************************************************
function makeArray(n)
//*************************************************************
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
	{
	for (var i = 1; i <= n; i++)
		{
		this[i] = 0
		} 
	return this
	}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;


// Check whether string s is empty.
//*************************************************************
function isEmpty(s)
//*************************************************************
{   if ((s == null) || (s.length == 0))
	{
		return true;
	}
	else
	{
	    for (var i = 0 ; i < s.length ; i++) 
	    {
	        if (s.charAt(i) != ' ') 
		    {
			    return false;
			}
		}
    }
    return true;
}


// Returns true if string s is empty or 
// whitespace characters only.
//*************************************************************
function isWhitespace (s)
//*************************************************************
{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



// Removes all characters which appear in string bag from string s.
//*************************************************************
function stripCharsInBag (s, bag)
//*************************************************************
{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag 
// from string s.
//*************************************************************
function stripCharsNotInBag (s, bag)
//*************************************************************
{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}



// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.
//*************************************************************
function stripWhitespace (s)
//*************************************************************
{   return stripCharsInBag (s, whitespace)
}




// WORKAROUND FUNCTION FOR NAVIGATOR 2.0.2 COMPATIBILITY.
//
// The below function *should* be unnecessary.  In general,
// avoid using it.  Use the standard method indexOf instead.
//
// However, because of an apparent bug in indexOf on 
// Navigator 2.0.2, the below loop does not work as the
// body of stripInitialWhitespace:
//
// while ((i < s.length) && (whitespace.indexOf(s.charAt(i)) != -1))
//   i++;
//
// ... so we provide this workaround function charInString
// instead.
//
// charInString (CHARACTER c, STRING s)
//
// Returns true if single character c (actually a string)
// is contained within string s.

//*************************************************************
function charInString (c, s)
//*************************************************************
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}



// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

//*************************************************************
function stripInitialWhitespace (s)
//*************************************************************
{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}


// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

//*************************************************************
function isLetter (c)
//*************************************************************
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}



// Returns true if character c is a digit 
// (0 .. 9).

//*************************************************************
function isDigit (c)
//*************************************************************
{   return ((c >= "0") && (c <= "9"))
}



// Returns true if character c is a letter or digit.

//*************************************************************
function isLetterOrDigit (c)
//*************************************************************
{   return (isLetter(c) || isDigit(c))
}



// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

//*************************************************************
function isInteger (s)
//*************************************************************
{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}


// isSignedInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters are numbers; 
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true 
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

//*************************************************************
function isSignedInteger (s)
//*************************************************************

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}




// isPositiveInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer > 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isPositiveInteger (s)
//*************************************************************
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) > 0) ) );
}






// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isNonnegativeInteger (s)
//*************************************************************
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) >= 0) ) );
}






// isNegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer < 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isNegativeInteger (s)
//*************************************************************
{   var secondArg = defaultEmptyOK;

    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a negative, not positive, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) < 0) ) );
}






// isNonpositiveInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer <= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isNonpositiveInteger (s)
//*************************************************************
{   var secondArg = defaultEmptyOK;

    if (isNonpositiveInteger.arguments.length > 1)
        secondArg = isNonpositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number <= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) <= 0) ) );
}





// isFloat (STRING s [, BOOLEAN emptyOK])
// 
// True if string s is an unsigned floating point (real) number. 
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isInteger, then call isFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isFloat (s)
//*************************************************************
{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}







// isSignedFloat (STRING s [, BOOLEAN emptyOK])
// 
// True if string s is a signed or unsigned floating point 
// (real) number. First character is allowed to be + or -.
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isSignedInteger, then call isSignedFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isSignedFloat (s)
//*************************************************************

{   if (isEmpty(s)) 
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}




// isAlphabetic (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

//*************************************************************
function isAlphabetic (s)
//*************************************************************

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}




// isAlphanumeric (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

//*************************************************************
function isAlphanumeric (s)
//*************************************************************

{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphanumeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    // All characters are numbers or letters.
    return true;
}




// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number 
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call function stripCharsNotInBag to remove the unwanted 
// characters, THEN call function reformat to delimit as desired.
//
// EXAMPLE:
//
// reformat (stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

//*************************************************************
function reformat (s)
//*************************************************************

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}


// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isEmail (s)
//*************************************************************
	{   
	if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
		{
		i++
		}

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}





// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isYear (s)
//*************************************************************
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


//*************************************************************
function isIntegerInRange (s, a, b)
//*************************************************************
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s,10);
    return ((num >= a) && (num <= b));
}



// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isMonth (s)
//*************************************************************
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}



// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function isDay (s)
//*************************************************************
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}



// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.

//*************************************************************
function daysInFebruary (year)
//*************************************************************
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}



// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

//*************************************************************
function isDate (year, month, day)
//*************************************************************
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year, 10);
    var intMonth = parseInt(month, 10);
    var intDay = parseInt(day, 10);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}




/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */


// Display prompt string s in status bar.

//*************************************************************
function prompt (s)
//*************************************************************
{   window.status = s
}



// Display data entry prompt string s in status bar.

//*************************************************************
function promptEntry (s)
//*************************************************************
{   window.status = pEntryPrompt + s
}




// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

//*************************************************************
function warnEmpty (theField, s)
//*************************************************************
{   
    alert(mPrefix + s + mSuffix)
    theField.focus()
    return false
}



// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

//*************************************************************
function warnInvalid (theField, s)
//*************************************************************
{   theField.focus()
    theField.select()
    alert(s)
    return false
}




/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

// checkString (TEXTFIELD theField, STRING s, [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is not all whitespace.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function checkString (theField, s, emptyOK)
//*************************************************************
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return warnEmpty (theField, s);
    else return true;
}


// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function checkEmail (theField, emptyOK)
//*************************************************************
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
       return warnInvalid (theField, iEmail);
    else return true;
}





// Check that string theField.value is a valid Year.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function checkYear (theField, emptyOK)
//*************************************************************
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return warnInvalid (theField, iYear);
    else return true;
}


// Check that string theField.value is a valid Month.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function checkMonth (theField, emptyOK)
//*************************************************************
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return warnInvalid (theField, iMonth);
    else return true;
}


// Check that string theField.value is a valid Day.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

//*************************************************************
function checkDay (theField, emptyOK)
//*************************************************************
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false)) 
       return warnInvalid (theField, iDay);
    else return true;
}



// checkDate (yearField, monthField, dayField, STRING labelString [, OKtoOmitDay==false])
//
// Check that yearField.value, monthField.value, and dayField.value 
// form a valid date.
//
// If they don't, labelString (the name of the date, like "Birth Date")
// is displayed to tell the user which date field is invalid.
//
// If it is OK for the day field to be empty, set optional argument
// OKtoOmitDay to true.  It defaults to false.

//*************************************************************
function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
//*************************************************************
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value)) 
       return warnInvalid (dayField, iDay);
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}


//*************************************************************
// Get checked value from radio button.
function getRadioButtonValue (radio)
//*************************************************************
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    if(i==radio.length)
		return null;
	else
		return radio[i].value;
}

//*************************************************************
function fnPermitirSomenteNumeros()
//*************************************************************
{
	if (!isNonnegativeInteger(String.fromCharCode(event.keyCode)))
		event.returnValue = false;
}

//*************************************************************
function fnPermitirNumeros()
//*************************************************************
{
	if(!(isNonnegativeInteger(String.fromCharCode(event.keyCode))||String.fromCharCode(event.keyCode)==","||String.fromCharCode(event.keyCode)=="."))
		event.returnValue = false;
}

//*************************************************************
//limita o numero de caracteres do textarea. usar no evento onkeydown
function tamMax(ObjText,MaxSize)
//*************************************************************
{	
	if (ObjText.value.length > MaxSize)
	{
		ObjText.value = ObjText.value.substring(0,MaxSize);
	}	
}
//*************************************************************
function DecimalPoint(strValor)
//*************************************************************
{
	var i;
	var strSaida='';
	for(i=0;i<strValor.length;i++)
	{
		if(strValor.charAt(i)==',')
		{
			strSaida = strSaida + '' + '.';
		}
		else
		{
			strSaida = strSaida + '' + strValor.charAt(i);
		}
	}
	strSaida = parseFloat(strSaida);
	return strSaida;
}
//*************************************************************
function CPFValido(s)
//*************************************************************
// Deve passar CPFValido(document.form.campo.value)
	{
		
	s = s.replace(".","");
	s = s.replace(".","");
	s = s.replace("-","");
	
	if (s.length < 11)
		return false;
    else
		{
		var varFirstChr	= s.charAt(0);
		var vaCharCPF	= false;
		for ( var i=0; i<=10; i++ ) 
			{ 
			var c = s.charAt(i);
            if( ! (c>="0")&&(c<="9") ) 
				return false;
            if( c!=varFirstChr ) 
				vaCharCPF = true; 
			} 
        if( ! vaCharCPF ) 
			return false;
		soma=0;
		for ( i=0; i<9; i++ ) 
			{ 
			soma += (10-i) * ( eval(s.charAt(i)) );	
			} 
		digito_verificador = 11-(soma % 11);
		if ( (soma % 11) < 2 )
			digito_verificador = 0;
		if ( eval(s.charAt(9)) != digito_verificador ) 
			return false;
		soma=0;
		for ( i=0; i<9; i++ ) 
			{
			soma += (11-i) * ( eval(s.charAt(i)) ); 
			}
		soma += 2 * ( eval(s.charAt(9)) );
		digito_verificador = 11-(soma % 11);
		if ( (soma % 11) < 2 )
			digito_verificador = 0;
		if ( eval(s.charAt(10)) != digito_verificador ) 
			return false; 
		return true;
		}
	}
//*************************************************************
//validação e comparação de datas tipo dd/mm/yyyy OBS: cada data é digitada em somente um campo
//*************************************************************
function fnValida_Data_2(data_inicio,data_fim)
{

	var combinacao;
	
	if (data_inicio!="")
	{
		if (data_inicio.length==10)
		{   //extrai o dia, mes e ano da data início
			dia_ini=data_inicio.substring(0,2);
			mes_ini=data_inicio.substring(3,5);
			ano_ini=data_inicio.substring(6);
			
			combinacao=dia_mes_ano(dia_ini,mes_ini,ano_ini);
			if (! combinacao)
			{				
				return false;	
			}										
		}	
		else
			{
				return false;
			}
	}
	
	
	if (data_fim!="")
	{
		if (data_fim.length==10)
		{	//extrai o dia, mes e ano da data fim
			dia_fim=data_fim.substring(0,2);
			mes_fim=data_fim.substring(3,5);
			ano_fim=data_fim.substring(6);
		
			combinacao=dia_mes_ano(dia_fim,mes_fim,ano_fim);
			if (! combinacao) 
			{				
				return false;		
			}									
		}	
		else
			{
			
			return false;
			}
	}
	
	if ( (data_inicio!="") && (data_fim!="") )
	{
		
		if (ano_fim < ano_ini)			
			return false;
		else			
			if (ano_fim == ano_ini)
			{				
				if (mes_fim < mes_ini)
					return false;
				else
					if ( (mes_fim == mes_ini) && (dia_fim < dia_ini) )
						return false;
			}					
	}
	
	return true;	
}	
//*************************************************************
//função para verificar se a combinação de dia,mês e ano estão corretas
//*************************************************************
function dia_mes_ano(dia,mes,ano)
	{
	if((dia.length!=2) || (mes.length!=2) || (ano.length!=4))
		return false; 
	if (mes<=00 || mes > 12)
		return false;
	else		
		//janeiro,março, maio, julho, agosto,outubro, dezembro
		if ( (mes==01 || mes==03 || mes==05 || mes==07 || mes==08 || mes==10 || mes==12) && (dia<=00 || dia>31) )			  
				return false;		
		else//demais meses (excluindo-se fevereiro)
			if ( (mes==04 || mes==06 || mes==09 || mes==11) && (dia<=00 || dia>30) )					 
					return false;				
			else 
				if ( (mes==02) && (dia<=00 || dia>29) )//fevereiro							
					return false;
				else
					if ( (dia==29) && ((ano%4)!=0) ) //ano bissexto	
						return false;
					else							
						if (( (ano.substring(2)==00) && ((ano%400)!=0) ) || (ano.substring(4)<2000))
							return false;
						else							 										
							return true;		
																										return true;									
	}
//*************************************************************
// Verifica se uma data é maior, igual ou menor que outra (Depende da direção)
// Exemplo :f_compara_data("==",document.form.inicio_dia.value,document.form.inicio_mes.value,document.form.inicio_ano.value,document.form.fim_dia.value,document.form.fim_mes.value,document.form.fim_ano.value)
//*************************************************************
function f_compara_data(direcao,inicio_dia,inicio_mes,inicio_ano,fim_dia,fim_mes,fim_ano)
	{
	xinicio	= parseInt(inicio_ano+inicio_mes+inicio_dia,10)
	xfim	= parseInt(fim_ano+fim_mes+fim_dia,10)

	if(eval(xinicio+direcao+xfim))
		{
		return true;
		}
	else
		{
		return false;
		}
	}	
//*************************************************************
// Verifica se uma hora é maior, igual ou menor que outra (Depende da direção)
// Exemplo :  f_compara_hora("==",document.form.inicio_hora.value+"/"+document.form.inicio_minuto.value,document.form.fim_hora.value+"/"+document.form.fim_minuto.value);  Passar 00:00 ou 0:00
//*************************************************************
function f_compara_hora(direcao,inicio_hora,inicio_minuto,fim_hora,fim_minuto)
	{
	xinicio	= (parseInt(inicio_hora,10)*60) + parseInt(inicio_minuto,10);
	xfim	= (parseInt(fim_hora,10)*60) + parseInt(fim_minuto,10);

	if(eval(xinicio+direcao+xfim))
		{
		return true;
		}
	else
		{
		return false;
		}
	}	
//*************************************************************
// Funções para mostrar o relógio no browser.
function MakeArrayday(size) 
//*************************************************************
	{
	this.length = size;
	for(var i = 1; i <= size; i++)
		{
		this[i] = "";
		}
	return this;
	}
function MakeArraymonth(size) 
	{
	this.length = size;
	for(var i = 1; i <= size; i++)
		{
		this[i] = "";
		}
	return this;
	}
function funClock() 
	{
	if (!document.layers && !document.all)
	return;
	var runTime = new Date();
	var hours = runTime.getHours();
	var minutes = runTime.getMinutes();
	var seconds = runTime.getSeconds();
	var dn = "AM";
	if (hours >= 12) 
		{
		dn = "PM";
		hours = hours - 12;
		}
	if (hours == 0) 
		{
		hours = 12;
		}
	if (minutes <= 9) 
		{
		minutes = "0" + minutes;
		}
	if (seconds <= 9) 
		{
		seconds = "0" + seconds;
		}
	movingtime = "<b>"+ hours + ":" + minutes + ":" + seconds + " " + dn + "</b>";
	if (document.layers) 
		{
		document.layers.clock.document.write(movingtime);
		document.layers.clock.document.close();
		}
	else if (document.all) 
		{
		clock.innerHTML = movingtime;
		}
	setTimeout("funClock()", 1000)
	}
//  Colocar isto no final desta função
//	    window.onload = funClock;

//  Ou isto no onload do body.
//		onload="funClock();"

//  Colocar isto onde for aparecer a hora.
//		<span id="clock"></span>
//*************************************************************
// Funções para Select Progressivo.
//*************************************************************
	function pesqIncDown(ocombo) {
		cletra=String.fromCharCode(event.keyCode);
		if ((event.keyCode!=40) && (event.keyCode>18) && (cacentos.search(cletra)==-1))
			pesqIncPress(ocombo,cletra);
	}
	function pesqIncPress1() {
		event.returnValue=false;
	}
cacentos="áéíóúÁÉÍÓÚãõÃÕâêîôûÂÊÎÔÛàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçÇñ~'`\""
ctrans="aeiouAEIOUaoAOaeiouAEIOUaeiouAEIOUaeiouAEIOUcCn    "
nletras=cacentos.length
tpesqIncTimerPesq=null;
tpesqIncTimerRes=null;
opesqInc=null;
cpesqInc="";
npesqIncPesqTime=100;
npesqIncResetTime=1000;


function accentLess(ctexto) {
	ntamtexto=ctexto.length
	ctextoRes="";
	for (ncont=0;ncont<ntamtexto;ncont++) {
		cchar=ctexto.charAt(ncont)
//		if (cchar!="(" && cchar!=")")
		nposAcents=cacentos.indexOf(cchar,0)
		if (nposAcents==-1) {
			ctextoRes=ctextoRes+cchar
		} else {
			ctextoRes=ctextoRes+ctrans.charAt(nposAcents)
		}
	}
	return ctextoRes;
}

function pesqIncPress (ocombo,letra) {
	opesqInc=ocombo;
	if (letra=='%') {
		if (cpesqInc!="") {
			cpesqInc=cpesqInc.substr(0,cpesqInc.length-1)
		}
	} else {
		cpesqInc=cpesqInc+letra;
	}
	if (tpesqIncTimerPesq!=null) 
		clearTimeout(tpesqIncTimerPesq);
	if (cpesqInc!="")
		tpesqIncTimerPesq=setTimeout("pesqIncDoit();",npesqIncPesqTime);
	if (tpesqIncTimerRes!=null)
		clearTimeout(tpesqIncTimerRes)
	tpesqIncTimerRes=setTimeout("pesqIncReset();",npesqIncResetTime)
}

function pesqIncReset() {
	cpesqInc="";
}

function pesqIncDoit() {
	ntam=opesqInc.length
	cproc=cpesqInc.toLowerCase()
	ntproc=cproc.length
	nbot=0
	ntop=ntam-1
	npos=Math.floor(ntop/2)
	while (true) {
		cactual=accentLess(opesqInc.options[npos].text.substring(0,ntproc).toLowerCase())
		if (cactual==cproc) {
			while ((npos>0) && (accentLess(opesqInc.options[npos-1].text.substring(0,ntproc).toLowerCase())==cproc)) {npos--;}
			opesqInc.selectedIndex=npos;
			tpesqIncTimerPesq=null;
			return
		} else {
			if (cproc>cactual) {
				nbot=npos+1
				npos=Math.floor((nbot+ntop)/2)
			} else {
				ntop=npos-1
				npos=Math.floor((ntop+nbot)/2);
			}
			if (ntop<nbot) {
				tpesqIncTimerPesq=null;
				return;
			}
		}
	}
}
//*************************************************************

