/****************************************
 * Title: Mascara
 * Description: Mascara global
 * Copyright:    Copyright (c) 2003
 * @version 1.0
 ***************************************/
/*
 As seguintes convenções devem ser utilizadas:

	- Para bloquear a entrada somente para digitos deve-se formatar a mascara utilizando '9'
			Ex: 99/99/9999  formatando datas
	- Para bloquear a entrada somente para letras e digitos deve-se formatar a mascara utilizando '#'
			Ex: ###.###
	- A quantidade de caracteres permitida será limitada pela propriedade maxlength e pela mascara especificada
	- Pode-se especificar mais de uma mascara. Neste caso, utiliza-se o operador || para separar as mascaras
	- A função irá ordenar as mascaras de acordo com o tamanho delas. A primeira mascara a ser utilizada será a menor
	  passando para as outras quando a entrada for maior que o tamanho da mascara atual.
	- Deve-se utilizar colchetes para especificar caracteres de repetição
			Ex: [###.]###,##    formatando valores
/*
	Segue alguns exemplos das mascaras mais comuns:
      - (###)               --> DDD.  
      - ##                  --> Número inteiro, ignora do 3 em diante      
	  - ###-####||####-#### --> Telefone de 7 ou 8 digitos<br>
      - ##/##/####          --> Data com dia, mes e ano
      - ##/##               --> Data com dia, mes
      - ##:##:##            --> Horário com: hora, minuto, segundo
      - ##:##               --> Horário com: hora, minuto
      - ####/##/##          --> Data (invertida) ano, mes, dia
      - ##.###-###          --> Cep
      - ###.###.###-##      --> Cpf
      - ##.###.###/####-##  --> Cgc
      - ###.###.###-##||##.###.###/####-## -->Cpf (pondendo ser cgc também)           
      - [###.]###           --> Número inteiro (que pode variar)
      - [###.]###,##        --> Dinheiro (que pode variar)<br>
*/


//Ponto de partida para as outras functions
function mascara(obj,mascara){		
	var texto = obj.value;
	var max = obj.maxLength;
	
	if(limparEntrada(obj).length > max-1){
		event.keyCode = 0;
		return;
	}
		
	//Default
	if( buscaDigito(mascara,'#') != -1){//Utiliza Lazanha		
		mascaraLazanha(obj,mascara);
	}
	else if( buscaDigito(mascara,'9') != -1){//Utiliza Digito	
		mascaraDigito(obj,substituiPorLazanha(mascara));
	}
	return;
}	

//Função que coloca as mascaras
function mascarar(obj,mascara){
	
		var valor_duplicar = "";
		var valor_completar = "";
		var colchete_abre = abriuColchete(mascara);
		var colchete_fecha = fechouColchete(mascara)
		var retorno = "";
		var tam_lazanha = contaLazanha(mascara);		
		var texto = obj.value+retornaValor(event);
		event.keyCode = 0;
		if(colchete_abre ==-1 && texto.length > tam_lazanha){			
			texto = obj.value;			
		}

		mascara = limpaMascara(mascara);
				
		//aumenta a mascara quando existem colchetes
		if(colchete_abre < colchete_fecha  && colchete_abre!=-1 && colchete_fecha!=-1){
			var tamanhoDoTexto = 1+obj.value.length;			
			valor_duplicar = mascara.substring(colchete_abre+1,colchete_fecha);
			valor_completar = mascara.substring(colchete_fecha+1);

			//valor_completar = valor_duplicar + valor_completar;
			while(contaLazanha(valor_completar) < tamanhoDoTexto){
				valor_completar = valor_duplicar + valor_completar;				
			}			
			mascara = valor_completar;

			var j = texto.length-1;											
			for (i = mascara.length-1; i>-1 && j>-1; i--) {		
				if (mascara.substring(i,i+1)=="#") {								
					retorno = texto.substring(j,j+1) + retorno;
					j--;							
				}
				else{
					retorno = mascara.substring(i,i+1) + retorno;
				}				
			}
		}//Caso não tem colchetes e não tem ||
		else if(mascara.split('||').length == 1){
			var j = 0;											
			for(i = 0 ; i<mascara.length && j<texto.length; i++) {		
				if (mascara.substring(i,i+1)=="#") {								
					retorno = retorno + texto.substring(j,j+1);
					j++;							
				}
				else{
					retorno = retorno + mascara.substring(i,i+1) ;
				}				
			}
			var f = mascara.length;
			while(mascara.substring(f-1,f)!="#"){
				retorno = retorno + mascara.substring(f-1,f);
				f--;
			}

		}//Não tem Colchetes e Tem ||
		else if(mascara.split('||').length != 1){

			///////////Trecho de código que quebra a mascara para pegar a mascara adequada////
			var array = mascara.split('||');			
			array = tamanho(array);		
			var i = 0;
			mascara = array[i];			
			while(contaLazanha(mascara) < texto.length  && i+1 < array.length){
				i=i+1;
				mascara = array[i];		
			}
			/////////////////////////////////////////////////////////////////////////////////

			var tam_lazanha = contaLazanha(mascara);
			if(texto.length > tam_lazanha){			
				texto = obj.value;			
			}	
		
			//mascarando			
			var j = 0;											
			for(i = 0 ; i<mascara.length && j<texto.length; i++) {		
				if (mascara.substring(i,i+1)=="#") {								
					retorno = retorno + texto.substring(j,j+1);
					j++;							
				}
				else{
					retorno = retorno + mascara.substring(i,i+1) ;
				}				
			}
			var f = mascara.length;
			while(mascara.substring(f-1,f)!="#"){
				retorno = retorno + mascara.substring(f-1,f);
				f--;
			}			
		}
				
		obj.value = retorno;
		return obj;
}

//Funcao que retira os espacos em branco antes e depois da mascara
function limpaMascara(mascara){
	var masc = "";

    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if (sub != " "){
            masc=masc+sub;
        }
    }
	return masc;
}

//Função que ordena um array, de acordo com o tamanho dos seus elementos. Ordenação Ascendente.
function tamanho(array){
	var temp1;
	var temp2;
	for(i=0; i<array.length-1; i++){
		temp1 = array[i];
		for(j=i+1; j<array.length; j++){
			temp2 = array[j];
			if(temp2.length < temp1.length){				
				array[i] = temp2;
				array[j] = temp1;
				temp1= temp2;
				temp2= array[j]; 
			}
		}
	}	
	return array;
}

//funcao que conta quantas lazanhas tem na palavra
function contaLazanha(mascara){
	var cont_lazanha = 0;
	for (i = 0; i < mascara.length; i++){
		if (mascara.substring(i,i+1) == "#"){
			cont_lazanha++;
        }
	}
	return cont_lazanha;
}

//função que deixa apenas os digitos e as letras
function limparEntrada(obj){
	var texto = "";
    for (i = 0; i < obj.value.length; i++) {
		var temp = obj.value.substring(i,i+1);
		if( validar(temp)  ){
			texto= texto+obj.value.substring(i,i+1);
        }	
    }
	return texto;
}

//retorna true quando o parametro é um digito ou uma letra
function validar(temp){
	if( !isNaN(temp) || temp=='a' || temp=='A' || temp=='b' || temp=='B' || temp=='c' || temp=='C' || temp=='d' || temp=='D' || temp=='e' || temp=='E'
			 || temp=='f' || temp=='F' || temp=='g' || temp=='G' || temp=='h' || temp=='H' || temp=='i' || temp=='I' || temp=='j' || temp=='J'
			 || temp=='k' || temp=='K' || temp=='l' || temp=='L' || temp=='m' || temp=='M' || temp=='n' || temp=='N' || temp=='o' || temp=='O'
			 || temp=='p' || temp=='P' || temp=='q' || temp=='Q' || temp=='r' || temp=='R' || temp=='s'|| temp=='S' || temp=='t' || temp=='T'
			 || temp=='u' || temp=='U' || temp=='v' || temp=='V' || temp=='x' || temp=='X' || temp=='y' || temp=='Y' || temp=='z' || temp=='Z' ){
		return true;
	}
	else{
		return false;
	}
}

//função que retorna -1 caso naum encotre o digito desejado, se encontrar retorna o indice onde ele foi encontrado
function buscaDigito(valor,digito){
		indice= valor.indexOf(digito);
		return indice;
}

//Função que bloqueia a entrada apenas para digito
function mascaraDigito(obj,mascara){
	if (event.keyCode <= 47 || event.keyCode >57){
		event.keyCode = 0;
		return false;
	}
	else{
		obj.value = limparEntrada(obj);
		mascarar(obj,mascara);
	}
}

//Função que bloqueia a entrada apenas para digito e letras
function mascaraLazanha(obj,mascara){
	if ( !(event.keyCode > 47 && event.keyCode <58) && !(event.keyCode > 64  && event.keyCode < 91) && !(event.keyCode > 96  && event.keyCode < 123)  ){
		event.keyCode = 0;
		return false;
	}
	else{
		obj.value = limparEntrada(obj);
		mascarar(obj,mascara);
	}
	return;
}

//Funcao que retorna o indice onde foi encontrado um ]
function fechouColchete(mascara){
	var posicao = -1;

	//verificar se existe colchete abrindo e fechando
    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if (sub == ']' ){
            posicao = i;
        }
    }
	return posicao;
}

//Funcao que retorna o indice onde foi encontrado um [
function abriuColchete(mascara){
	var posicao  = -1;

	//verificar se existe colchete abrindo e fechando
    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if( sub == '[' ){
			posicao = i;
        }
    }
	return posicao;
}

function substituiPorLazanha(mascara){
	var masc = "";

	//verificar se existe colchete abrindo e fechando
    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if( sub == '9' ){
			masc = masc+'#';
        }
		else{
			masc = masc+sub;
		}
    }
	return masc;
}


//Retorna  o valor de um evento
function retornaValor(ev){
	var temp = ev.keyCode;
	var retorno = "";

	if(temp > 64 && temp<91){
		switch(temp){
		case 65:
			retorno = 'A';
			break;
		case 66:
			retorno = 'B';
			break;
		case 67:
			retorno = 'C';
			break;
		case 68:
			retorno = 'D';
			break;
		case 69:
			retorno = 'E';
			break;
		case 70:
			retorno = 'F';
			break;
		case 71:
			retorno = 'G';
			break;
		case 72:
			retorno = 'H';
			break;
		case 73:
			retorno = 'I';
			break;
		case 74:
			retorno = 'J';
			break;
		case 75:
			retorno = 'K';
			break;
		case 76:
			retorno = 'L';
			break;
		case 77:
			retorno = 'M';
			break;
		case 78:
			retorno = 'N';
			break;
		case 79:
			retorno = 'O';
			break;
		case 80:
			retorno = 'P';
			break;
		case 81:
			retorno = 'Q';
			break;
		case 82:
			retorno = 'R';
			break;
		case 83:
			retorno = 'S';
			break;
		case 84:
			retorno = 'T';
			break;
		case 85:
			retorno = 'U';
			break;
		case 86:
			retorno = 'V';
			break;
		case 87:
			retorno = 'W';
			break;
		case 88:
			retorno = 'X';
			break;
		case 89:
			retorno = 'Y';
			break;
		case 90:
			retorno = 'Z';
			break;
		default:
			retorno = '#';
			break;
		}
	}
	else if(temp>96 && temp<123){
		
		switch (temp){
		case 97:
			retorno = 'a';
			break;
		case 98:
			retorno = 'b';
			break;
		case 99:
			retorno = 'c';
			break;
		case 100:
			retorno = 'd';
			break;
		case 101:
			retorno = 'e';
			break;
		case 102:
			retorno = 'f';
			break;
		case 103:
			retorno = 'g';
			break;
		case 104:
			retorno = 'h';
			break;
		case 105:
			retorno = 'i';
			break;
		case 106:
			retorno = 'j';
			break;
		case 107:
			retorno = 'k';
			break;
		case 108:
			retorno = 'l';
			break;
		case 109:
			retorno = 'm';
			break;
		case 110:
			retorno = 'n';
			break;
		case 111:
			retorno = 'o';
			break;
		case 112:
			retorno = 'p';
			break;
		case 113:
			retorno = 'q';
			break;
		case 114:
			retorno = 'r';
			break;
		case 115:
			retorno = 's';
			break;
		case 116:
			retorno = 't';
			break;
		case 117:
			retorno = 'u';
			break;
		case 118:
			retorno = 'v';
			break;
		case 119:
			retorno = 'w';
			break;
		case 120:
			retorno = 'x';
			break;
		case 121:
			retorno = 'y';
			break;
		case 122:
			retorno = 'z';
			break;
		default:
			retorno = '#';
			break;
		}
	}
	else if(temp>47 && temp<58){
		switch (temp){		
		case 48:
			retorno = '0';
			break;
		case 49:
			retorno = '1';
			break;
		case 50:
			retorno = '2';
			break;
		case 51:
			retorno = '3';
			break;
		case 52:
			retorno = '4';
			break;
		case 53:
			retorno = '5';
			break;
		case 54:
			retorno = '6';
			break;
		case 55:
			retorno = '7';
			break;
		case 56:
			retorno = '8';
			break;
		case 57:
			retorno = '9';
			break;
		default:
			retorno = '#';
			break;
		}
	}

	return retorno;
}


function isValido(data1 , data2) {
  return true;
}

var CODE_MINUS            = 45;
var CODE_PLUS             = 43;
var CODE_DOT              = 46;
var CODE_SPACE            = 32;
var CODE_TILDE              = 126;

// key codes for onKeyPres events (ASCII codes)
var CODE_0 = 48;
var CODE_1 = 49;
var CODE_2 = 50;
var CODE_3 = 51;
var CODE_4 = 52;
var CODE_5 = 53;
var CODE_6 = 54;
var CODE_7 = 55;
var CODE_8 = 56;
var CODE_9 = 57;

var CODE_A = 65;
var CODE_B = 66;
var CODE_C = 67;
var CODE_D = 68;
var CODE_E = 69;
var CODE_F = 70;
var CODE_G = 71;
var CODE_H = 72;
var CODE_I = 73;
var CODE_J = 74;
var CODE_K = 75;
var CODE_L = 76;
var CODE_M = 77;
var CODE_N = 78;
var CODE_O = 79;
var CODE_P = 80;
var CODE_Q = 81;
var CODE_R = 82;
var CODE_S = 83;
var CODE_T = 84;
var CODE_U = 85;
var CODE_V = 86;
var CODE_W = 87;
var CODE_X = 88;
var CODE_Y = 89;
var CODE_Z = 90;

var CODE_a = 97;
var CODE_b = 98;
var CODE_c = 99;
var CODE_d = 100;
var CODE_e = 101;
var CODE_f = 102;
var CODE_g = 103;
var CODE_h = 104;
var CODE_i = 105;
var CODE_j = 106;
var CODE_k = 107;
var CODE_l = 108;
var CODE_m = 109;
var CODE_n = 110;
var CODE_o = 111;
var CODE_p = 112;
var CODE_q = 113;
var CODE_r = 114;
var CODE_s = 115;
var CODE_t = 116;
var CODE_u = 117;
var CODE_v = 118;
var CODE_w = 119;
var CODE_x = 120;
var CODE_y = 121;
var CODE_z = 122;

function FormataHora(campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;
		if ( tam > 2 && tam < 5 )
			campo.value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
}

function FormataCEP(objeto, keypress)
{
//onKeyPress="FormataCEP(this, window.event.keyCode);"
campo = eval (objeto);
	caracteres = '01234567890';
	separacoes = 1;
	separacao1 = '-';
	conjuntos = 2;
	conjunto1 = 5;
	conjunto2 = 3;
	if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < 
	(conjunto1 + conjunto2 + 1))
		{
		if (campo.value.length == conjunto1) 
		   campo.value = campo.value + separacao1;
		}
	else 
		event.returnValue = false;

}

function SoNumeros(campo) {
    if (event.keyCode != 13) {
       if ((event.keyCode < 48 || event.keyCode > 57) ) {
          event.keyCode=0;
       }
    }
}

function FormataData(campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

		if ( tam > 2 && tam < 5 )
			campo.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );

                if ( tam >= 9 ){
                  if ( ! isDate(vr.substr( 4, 4 ), vr.substr( 2, 2 ), vr.substr( 0, 2 )) )
                  {
                    alert("  Data Inválida !  ");
                    campo.value = '';
                    return (false);
                  }
                }
}


function validarTamanho( campo, tamanho ) {
    vr = campo.value;
    if ( vr.length == tamanho ) {
     alert("Excedeu o tamanho máximo ( " + tamanho + " caracteres ) permitido para o campo.");
     event.keyCode=0;
     campo.focus();
     return( false );
    }
    return( true );
}









function FormataCPF(campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	tam = vr.length + 1;

		if ( tam > 3 && tam < 7 )
			campo.value = vr.substr( 0, tam - 3  ) + '.' + vr.substr( tam - 3, tam );
		if ( tam >= 7 && tam < 10 )
			campo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6, 3 );
		if ( tam >= 10 && tam <= 14 )
			campo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6, 3 ) + '-' + vr.substr( 9, 2 );
                if ( tam >= 12){
                  if (! isCPF (vr.substr( 0, 3 ) +  vr.substr( 3, 3 ) + vr.substr( 6, 3 ) +  vr.substr( 9, 2 )))
                  {
                    alert("    CPF Incorreto!   ");
                    campo.value ='';
                  }
                }

}

//Função de validação de CPF
function isCPF(st) {
  if (st == "")
    return (false);
  l = st.length;

//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
  if ((l == 9) || (l == 8))
  {
     for (i = l ; i < 10; i++)
     {
        st = '0' + st
     }
  }
  l = st.length;
  st2 = "";
  for (i = 0; i < l; i++) {
    caracter = st.substring(i,i+1);
    if ((caracter >= '0') && (caracter <= '9'));
       st2 = st2 + caracter;
  }
  if ((st2.length > 11) || (st2.length < 10))
     return (false);
  if (st2.length==10)
    st2 = '0' + st2;
    digito1 = st2.substring(9,10);
    digito2 = st2.substring(10,11);
    digito1 = parseInt(digito1,10);
    digito2 = parseInt(digito2,10);
    sum = 0; mul = 10;
    for (i = 0; i < 9 ; i++) {
        digit = st2.substring(i,i+1);
        tproduct = parseInt(digit ,10) * mul;
        sum += tproduct;
        mul--;
    }
    dig1 = ( sum % 11 );
    if ( dig1==0 || dig1==1 )
       dig1=0;
    else
      dig1 = 11 - dig1;
    if (dig1!=digito1)
      return (false);
    sum = 0;
    mul = 11;
    for (i = 0; i < 10 ; i++) {
        digit = st2.substring(i,i+1);
        tproduct = parseInt(digit ,10)*mul;
        sum += tproduct;
        mul--;
    }
    dig2 = (sum % 11);
    if ( dig2==0 || dig2==1 )
      dig2=0;
    else
      dig2 = 11 - dig2;
    if (dig2 != digito2)
      return (false);
    return (true);
    }



function TemDado(campo) {
	vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length;
	if(tam < 11) {
		alert("O campo está vazio incompleto, favor digitar o dado solicitado.");
		document.form[campo].focus();
	} else {
		document.form.submit();
	}
}

function VerData(DataI, DataF) {

	var SECOND = 1000;
	var MINUTE = SECOND * 60;
	var HOUR = MINUTE * 60;
	var DAY = HOUR * 24;
	var WEEK = DAY * 7;

	yearI = DataI.substr(6,4)
	monthI = DataI.substr(3,2);
	dayI = DataI.substr(0,2);
	yearF = DataF.substr(6,4)
	monthF = DataF.substr(3,2);
	dayF = DataF.substr(0,2);

	var nTime = Date.UTC(yearI, monthI - 1, dayI);
	var dTime = Date.UTC(yearF, monthF - 1, dayF);
	var bTime = Math.abs(nTime - dTime);

	if (nTime <= dTime) {
	  return false ;//	alert(Math.round(bTime / DAY));
	} else {
          return true;
	}

}




function CaixaAlta(campo) {
	texto = campo.value;
	texto = texto.toUpperCase();
	campo.value = texto;
}


////////////////////////////////////////////////////////////////////////////////
// Auxiliary functions
////////////////////////////////////////////////////////////////////////////////

// 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;

// 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 = "."

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";

// non-number characters which are allowed in dates
var dateDelimiters = "-/";

// maxnumber of days in months
var daysInMonth = new Array(12);
daysInMonth[0]  = 31;
daysInMonth[1]  = 29;
daysInMonth[2]  = 31;
daysInMonth[3]  = 30;
daysInMonth[4]  = 31;
daysInMonth[5]  = 30;
daysInMonth[6]  = 31;
daysInMonth[7]  = 31;
daysInMonth[8]  = 30;
daysInMonth[9]  = 31;
daysInMonth[10] = 30;
daysInMonth[11] = 31;

// isDay(STRING day [, BOOLEAN emptyOK])
//
// isDay returns true if "day" is a number between 1 and 31.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isDay(day) {
  var result;
  if (isEmpty(day)) {
    result = (isDay.arguments.length == 2 ?
              isDay.arguments[1] : defaultEmptyOK);
  }
  else {
    result = isIntegerInRange(day, 1, 31);
  }
  return result;
}

// isMonth(STRING month [, BOOLEAN emptyOK])
//
// isMonth returns true if "month" is a number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isMonth(month) {
  if (isEmpty(month)) {
    result = (isMonth.arguments.length == 2 ?
              isMonth.arguments[1] : defaultEmptyOK);
  }
  else {
    result = isIntegerInRange(month, 1, 12);
  }
  return result;
}

// isYear(STRING year [, BOOLEAN emptyOK])
//
// isYear returns true if "year"is a valid calendar year.
//  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 7999 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 isUnsignedInteger.
//

function isYear(year) {
  var result;
  if (isEmpty(year)) {
    result = (isYear.arguments.length == 2 ?
              isYear.arguments[1] : defaultEmptyOK);
  }
  else {
    result = (isIntegerInRange(year, 1, 9999) &&
              ((year.length == 2) || (year.length == 4)));
  }
  return result;
}

// isDate(STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day
// form a valid date. The year argument may be null.
//
function isDate(year, month, day) {
  var result = false;
  // catch invalid years (not 2- or 4-digit) and invalid months and days.
  if ((isEmpty(year) || isYear(year, false)) &&
      isMonth(month, false) && isDay(day, false)) {
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = 0;
    if (!isEmpty(year)) {
      intYear = parseInt(year, 10);
    }
    var intMonth = parseInt(month, 10);
    var intDay   = parseInt(day, 10);
    var maxDay   = daysInMonth[intMonth - 1];
    if (intMonth == 2 && intYear > 0 && ((intYear % 4) != 0 || ((intYear % 100) == 0 && (intYear % 400) != 0))) {
       maxDay--;
    }
    result = (intDay <= maxDay);
  }
  return result;
}

// isFloat(STRING str [, BOOLEAN emptyOK])
//
// Returns true if string str encodes a valid floating-point number.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isFloat(str) {
  var result;
  if (isEmpty(str)) {
    result = (isFloat.arguments.length == 2 ?
              isFloat.arguments[1] : defaultEmptyOK);
  }
  else {
    if (str.length > 1) {
      if (str.charCodeAt(0) == CODE_DOT) {
        str = "0" + str;
      }
      if (str.charCodeAt(str.length - 1) == CODE_DOT) {
        str += "0";
      }
    }
    var segs = str.split('.');
    result = ((segs.length == 1 || segs.length == 2) &&
              isInteger(segs[0]) &&
              (segs.length == 1 || isUnsignedInteger(segs[1])));
  }
  return result;
}

// isInteger(STRING str [, BOOLEAN emptyOK])
//
// Returns true if string str encodes a valid integer number.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isInteger(str) {
  var result;
  if (isEmpty(str)) {
    result = (isInteger.arguments.length == 2 ?
              isInteger.arguments[1] : defaultEmptyOK);
  }
  else {
    var code = str.charCodeAt(0);
    result = isUnsignedInteger(code == CODE_MINUS || code == CODE_PLUS ?
                               str.substring(1, str.length) : str);
  }
  return result;
}

// isUnsignedInteger(STRING str [, BOOLEAN emptyOK])
//
// Returns true if all characters in string str 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 str 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 str is empty.
// If emptyOK is true, the function will return true if str is empty.
//
// EXAMPLE FUNCTION CALL:            RESULT:
// isUnsignedInteger("5")            true
// isUnsignedInteger("")             defaultEmptyOK
// isUnsignedInteger("-5")           false
// isUnsignedInteger("", true)       true
// isUnsignedInteger("", false)      false
// isUnsignedInteger("5", false)     true
//
function isUnsignedInteger(str) {
  var result = true;
  if (isEmpty(str)) {
    result = (isUnsignedInteger.arguments.length == 2 ?
              isUnsignedInteger.arguments[1] : defaultEmptyOK);
  }
  else {
    var code;
    // 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 (var i = 0; i < str.length; i++) {
      // Check if the current character is number.
      code = str.charCodeAt(i);
      if (!isDigit(code)) {
        result = false;
        break;
      }
    }
  }
  return result;
}

// isIntegerInRange(STRING str, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
//
// isIntegerInRange returns true if string str 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(str, a, b) {
  var result = false;
  if (isEmpty(str)) {
    result = (isIntegerInRange.arguments.length == 2 ?
              isIntegerInRange.arguments[1] : defaultEmptyOK);
  }
  else if (isInteger(str, false)) {
    // Catched non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    // 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(str, 10);
    result = (num >= a && num <= b);
  }
  return result;
}

// isDigit(int code [, BOOLEAN emptyOK])
//
// Returns true if ASCII code represents a number.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isDigit(code) {
  var result = true;
  if (isEmpty(code)) {
    result = (isDigit.arguments.length == 2 ?
              isDigit.arguments[1] : defaultEmptyOK);
  }
  else {
//  var chr = String.fromCharCode(code);
//  result = (chr >= '0' && chr <= '9');
    result = (code >= CODE_0 && code <= CODE_9);
  }
  return result;
}

// isCharacter(int code [, BOOLEAN emptyOK])
//
// Returns true if ASCII code represents a character.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isCharacter(code) {
  var result = true;
  if (isEmpty(code)) {
    result = (isCharacter.arguments.length == 2 ?
              isCharacter.arguments[1] : defaultEmptyOK);
  }
  else {
//  var chr = String.fromCharCode(code);
//  result = (chr >= ' ' && chr <= '~');
    result = (code >= CODE_SPACE && code <= CODE_TILDE);
  }
  return result;
}

// isLetter(int code [, BOOLEAN emptyOK])
//
// Returns true if ASCII code represents a letter.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isLetter(code) {
  var result = true;
  if (isEmpty(code)) {
    result = (isLetter.arguments.length == 2 ?
              isLetter.arguments[1] : defaultEmptyOK);
  }
  else {
//  var chr = String.fromCharCode(code);
//  result = ((chr >= 'A' && chr <= 'Z') ||
//            (chr <= 'a' && chr <= 'z'));
    result = ((code >= CODE_A && code <= CODE_Z) ||
              (code >= CODE_a && code <= CODE_z));
  }
  return result;
}

// isLowerCaseLetter(int code [, BOOLEAN emptyOK])
//
// Returns true if ASCII code represents a lower case letter.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isLowerCaseLetter(code) {
  var result = true;
  if (isEmpty(code)) {
    result = (isLowerCaseLetter.arguments.length == 2 ?
              isLowerCaseLetter.arguments[1] : defaultEmptyOK);
  }
  else {
//  var chr = String.fromCharCode(code);
//  result = (chr <= 'a' && chr <= 'z');
    result = (code >= CODE_a && code <= CODE_z);
  }
  return result;
}

// isUpperCaseLetter(int code [, BOOLEAN emptyOK])
//
// Returns true if ASCII code represents an upper case letter.
//
// For explanation of optional argument emptyOK,
// see comments of function isUnsignedInteger.
//
function isUpperCaseLetter(code) {
  var result = true;
  if (isEmpty(code)) {
    result = (isUpperCaseLetter.arguments.length == 2 ?
              isUpperCaseLetter.arguments[1] : defaultEmptyOK);
  }
  else {
//  var chr = String.fromCharCode(code);
//  result = (chr >= 'A' && chr <= 'Z');
    result = (code >= CODE_A && code <= CODE_Z);
  }
  return result;
}

function isEmpty(val) {
  return (!val || (val.length && val.length == 0));
}

function replaceChar(str, oldChar, newChar) {
  var result;
  if (str.length > 0 &&
      oldChar.length == 1 &&
      newChar.length == 1 &&
      str.indexOf(oldChar) >= 0) {
    result = "";
    var code = oldChar.charCodeAt(0);
    for (var i = 0; i < str.length; i++) {
      if (code == str.charCodeAt(i)) {
        result += newChar;
      }
      else {
        result += str.charAt(i);
      }
    }
  }
  else {
    result = str;
  }
  return result;
}

//<INPUT ID="zoomfactor" TYPE="text" VALUE="50" SIZE="3" MAXLENGTH="4" onkeyup="updateZoom()">%

