/*
	Autor: Guilherme Silva
	Web: http://www.suporteon.com.br
	E-Mail: guilhermesilva11@yahoo.com.br
	Data da última alteração: 29/03/2006
*/

/*
if( !window.XMLHttpRequest ) {
window.XMLHttpRequest = function() {
var types = [
"Microsoft.XMLHTTP",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP"
];

for( var i = 0; i < types.length; i++ ) {
try {
return new ActiveXObject( types[ i ] );
} catch( e ) {}
}

return undefined;
}
} 
*/

String.prototype.trim = function() {
	/*
		Cria método trim() para o objeto String.
	*/
	objeto = this;
	objeto = objeto.replace(/^\s*(.*)/, "$1");
	objeto = objeto.replace(/(.*?)\s*$/, "$1");
	return(objeto);
}

String.prototype.left = function(deslocamento) {
	/*
		Cria método right() para o objeto String.
	*/
	objeto = this;
	objeto = objeto.substr(0, deslocamento);
	return(objeto);
}

String.prototype.right = function(deslocamento) {
	/*
		Cria método right() para o objeto String.
	*/
	objeto = this;
	objeto = objeto.substr(objeto.length - deslocamento);
	return(objeto);
}

Date.prototype.add = function (intervalo, tempo) {
  var data = this;
  if (!intervalo || tempo == 0) return data;
  switch (intervalo.toLowerCase()){
    case "ms":
      data.setMilliseconds(data.getMilliseconds() + tempo);
      break;
    case "s":
      data.setSeconds(data.getSeconds() + tempo);
      break;
    case "mi":
      data.setMinutes(data.getMinutes() + tempo);
      break;
    case "h":
      data.setHours(data.getHours() + tempo);
      break;
    case "d":
      data.setDate(data.getDate() + tempo);
      break;
    case "m":
      data.setMonth(data.getMonth() + tempo);
      break;
    case "y":
      data.setFullYear(data.getFullYear() + tempo);
      break;
  }
  return data;
}

function redirect(url) {
	/*
		Redireciona para outra página simulando um clique,
		para fazer uso do parâmetro Request.ServerVariables("HTTP_REFERER").
	*/
	var elemento = document.createElement("A");
	elemento.style.display = "none";
	elemento.href = url;
	document.body.appendChild(elemento);
	elemento.click();
}

function altera_parametro_url(url, parametro, valor)
{
	var achou = false;
	if (url.substr(url.length - 1) == "#")
	{
		url = url.substr(0, url.length - 1);
	}
	var array_parametros = url.replace("?", "&").split("&");
	for (var indice = 0; indice < array_parametros.length; indice++)
	{
		if (array_parametros[indice].substr(0, parametro.length + 1) == parametro + "=")
		{
			if (valor.trim() == "")
			{
				array_parametros.splice(indice, 1);
			}
			else
			{
				array_parametros[indice] = parametro + "=" + valor;
			}
			achou = true;
			break;
		}
	}
	if (!achou)
	{
		if (valor.trim() != "")
		{
			array_parametros.push(parametro + "=" + valor);
		}
	}
	if (array_parametros.length == 1)
	{
		array_parametros = array_parametros.join("&");
	}
	else
	{
		array_parametros[0] += "?";
		array_parametros = array_parametros.join("&");
		array_parametros = array_parametros.replace("?&", "?");
	}
	return(array_parametros);
}

function elementIndex(objeto)
{
	if (objeto.name.length > 0)
	{
		if (document.all(objeto.name).length > 0)
		{
			for (var contador = 0; contador < document.all(objeto.name).length; contador++)
			{
				if (document.all(objeto.name).item(contador) == objeto)
				{
					return(contador);
				}
			}
		}
	}
	if (objeto.id.length > 0)
	{
		if (document.all(objeto.id).length > 0)
		{
			for (var contador = 0; contador < document.all(objeto.id).length; contador++)
			{
				if (document.all(objeto.id).item(contador) == objeto)
				{
					return(contador);
				}
			}
		}
	}
	return(null);
}

function absoluteTop(objeto)
{
	/*
		Retorna a propriedade top de um elemento filho (<TD>, <TR>, etc.) relativo
		ao documento (<BODY>).
	*/
	var offset = objeto.offsetTop;
	while (objeto.tagName!="BODY")
	{
		offset += objeto.offsetTop;
		objeto = objeto.offsetParent;
	}
	return(offset);
}

function absoluteLeft(objeto)
{
	/*
		Retorna a propriedade left de um elemento filho (<TD>, <TR>, etc.) relativo
		ao documento (<BODY>).
	*/
	var offset = objeto.offsetLeft;
	while (objeto.tagName!="BODY")
	{
		offset += objeto.offsetLeft;
		objeto = objeto.offsetParent;
	}
	return(offset);
}

function html_encode(texto)
{
	/*
		Função originada do PHP.
	*/
	texto = texto.replace(/&/g, "&amp;");
	texto = texto.replace(/\"/g, "&quot;");
	texto = texto.replace(/\'/g, "&#039;");
	texto = texto.replace(/</g, "&lt;");
	texto = texto.replace(/>/g, "&gt;");
	return(texto);
}

function html_decode(texto)
{
	/*
		Função originada do PHP.
	*/
	texto = texto.replace(/&amp;/g, "&");
	texto = texto.replace(/&quot;/g, "\"");
	texto = texto.replace(/&#039;/g, "\'");
	texto = texto.replace(/&lt;/g, "<");
	texto = texto.replace(/&gt;/g, ">");
	return(texto);
}

function htmlspecialchars(texto)
{
	/*
		Função originada do PHP.
	*/
	texto = texto.replace(/&/g, "&amp;");
	texto = texto.replace(/\"/g, "&quot;");
	texto = texto.replace(/\'/g, "&#039;");
	texto = texto.replace(/</g, "&lt;");
	texto = texto.replace(/>/g, "&gt;");
	return(texto);
}

function htmlentities(texto)
{
	/*
		Função originada do PHP.
	*/
	texto = texto.replace(/&/g, "&amp;");
	texto = texto.replace(/</g, "&lt;");
	texto = texto.replace(/\"/g, "&quot;");
	return(texto);
}

function tecla(er)
{
	window.event.returnValue = er.test(String.fromCharCode(window.event.keyCode));
	return;
}

function auto_tab_enter(proximo)
{
	/*
		Função para ser usada no evento onkeyup.
		Desvia para o próximo campo em caso de teclar Enter.
	*/
	if (window.event.keyCode == 13)
	{
		proximo.focus();
	}
}

function auto_tab_size(campo, tamanho, proximo)
{
	/*
		Função para ser usada no evento onkeyup.
		Desvia para o próximo campo.
	*/
	if (campo.value.trim().length == tamanho)
	{
		proximo.focus();
	}
	if (window.event.keyCode == 13)
	{
		proximo.focus();
	}
}

function auto_tab_select(campo, proximo)
{
	/*
		Função para ser usada no evento onchange.
		Desvia para o próximo campo.
	*/
	if (campo.options.length > 0)
	{
		if ((campo.options(0).text == "") && (campo.options(0).value = ""))
		{
			if (campo.selectedIndex > 0)
			{
				proximo.focus();
			}
		}
		else
		{
			if (campo.selectedIndex >= 0)
			{
				proximo.focus();
			}
		}
	}
}

function auto_tab_check(campo, proximo)
{
	/*
		Função para ser usada no evento onclick.
		Desvia para o próximo campo.
	*/
	if (campo.checked)
	{
		proximo.focus();
	}
}

function auto_tab_submit(proximo)
{
	/*
		Função para ser usada no evento onkeyup.
		Executa o método click() no campo passado com parâmetro em caso de teclar Enter.
	*/
	if (window.event.keyCode == 13)
	{
		proximo.click();
	}
}

function sel_combo(combo, valor)
{
	/*
		Seleciona o índice do combo na opção passada pelo parâmetro "valor".
	*/
	if (valor.length == 0)
	{
		return;
	}
	for (contador = 0; contador < combo.length; contador++)
	{
		if (combo.options(contador).value == valor)
		{
			combo.selectedIndex = contador;
			break;
		}
	}
}

function sel_option(option, valor)
{
	/*
		Marca o option na opção passada pelo parâmetro "valor".
	*/
	if (valor.length == 0)
	{
		return;
	}
	for (contador = 0; contador < option.length; contador++)
	{
		if (option(contador).value == valor)
		{
			option(contador).checked = true;
			break;
		}
	}
}

function sel_checkbox(checkbox, sequencia)
{
	/*
		Marca os checkboxes nas opções passadas pelo parâmetro "sequencia".
	*/
	if (sequencia.length == 0)
	{
		return;
	}
	if (checkbox.length == null)
	{
		if (checkbox.value == sequencia)
		{
			checkbox.checked = true;
		}
	}
	else
	{
		contador = 0;
		while (sequencia != "")
		{
			if (sequencia.indexOf(",") == -1)
			{
				valor = sequencia;
				sequencia = "";
			}
			else
			{
				valor = sequencia.substr(0, sequencia.indexOf(","));
				sequencia = sequencia.substr(sequencia.indexOf(",") + 2);
			}
			contador++;
			if (contador > 100)
			{
				return;
			}
			for (contador = 0; contador < checkbox.length; contador++)
			{
				if (checkbox(contador).value == valor)
				{
					checkbox(contador).checked = true;
					break;
				}
			}
		}
	}
}

function sel_lista(combo, sequencia)
{
	/*
		Marca as opções de uma lista (combo múltiplo) através do parâmetro "sequencia".
	*/
	sequencia = sequencia.trim();
	if (sequencia.length == 0)
	{
		return;
	}
	if (sequencia.indexOf(",") == -1)
	{
		sel_combo(combo, sequencia);
		return;
	}
	while (sequencia != "")
	{
		if (sequencia.indexOf(",") == -1)
		{
			valor = sequencia;
			sequencia = "";
		}
		else
		{
			valor = sequencia.substr(0, sequencia.indexOf(","));
			sequencia = sequencia.substr(sequencia.indexOf(",") + 2);
			sequencia = sequencia.trim();
		}
		for (contador = 0; contador < combo.options.length; contador++)
		{
			if (combo.options(contador).value == valor)
			{
				combo.options(contador).selected = true;
				break;
			}
		}
	}
}

function sel_textbox(textbox, sequencia)
{
	/*
		Marca os textboxes nas opções passadas pelo parâmetro "sequencia".
		O parâmetro "sequencia" contém valores em dupla. Isto significa
		que os valores pares são os "id", e os valores ímpares, os "value".
	*/
	if (sequencia.length == 0)
	{
		return;
	}
	if (textbox.length == null)
	{
		if (sequencia.indexOf(",") == -1)
		{
			return;
		}
		identificador = sequencia.substr(0, sequencia.indexOf(","));
		sequencia = sequencia.substr(sequencia.indexOf(",") + 2);
		if (sequencia.indexOf(",") == -1)
		{
			valor = sequencia;
		}
		else
		{
			return;
		}
		if (textbox.id == identificador)
		{
			textbox.value = valor;
		}
	}
	else
	{
		contador = 0;
		while (sequencia != "")
		{
			if (sequencia.indexOf(",") == -1)
			{
				return;
			}
			identificador = sequencia.substr(0, sequencia.indexOf(","));
			sequencia = sequencia.substr(sequencia.indexOf(",") + 2);
			if (sequencia.indexOf(",") == -1)
			{
				valor = sequencia;
				sequencia = "";
			}
			else
			{
				valor = sequencia.substr(0, sequencia.indexOf(","));
				sequencia = sequencia.substr(sequencia.indexOf(",") + 2);
			}
			contador++;
			if (contador > 100)
			{
				return;
			}
			for (contador = 0; contador < textbox.length; contador++)
			{
				if (textbox(contador).id == identificador)
				{
					textbox(contador).value = valor;
					break;
				}
			}
		}
	}
}

function filtra_tecla(er)
{
	/*
		Filtra teclas de um objeto durante a digitação.
		
		Obs: os códigos das teclas para os eventos "onkeyup" e "onkeydown"
		são diferentes dos códigos para o evento "onkeypress".
		
		Esta função deve ser usada no evento "onkeydown".
	*/
	var array_tecla, array_caractere, caractere, indice;
	if ((window.event.keyCode < 48) && (window.event.keyCode != 32))
	{
		return;
	}
	array_tecla = new Array("96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "109", "110", "111", "188", "190", "191", "193", "194");
	array_caractere = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "+", "-", ",", "/", ",", ".", ";", "/", ".");
	caractere = null;
	for (var indice = 0; indice < array_tecla.length; indice++)
	{
		if (parseInt(array_tecla[indice]) == window.event.keyCode)
		{
			caractere = array_caractere[indice];
			break;
		}
	}
	if (caractere == null)
	{
		caractere = String.fromCharCode(window.event.keyCode);
	}
	window.event.returnValue = er.test(caractere);
	return;
}

function formata_numero(numero, casas_decimais)
{
	/*
		Formata um número com separador de milhar e casas decimais,
		no formato "###.###.###,##".
		
		formata_numero(38125.49, 2)  Resultado: 38.125,49
		formata_numero(38125.49, null)  Resultado: 38.125,49

		Em certos casos, poderá ocorrer arredondamento:

		formata_numero(38125.49, 1)  Resultado: 38.125,5
		formata_numero(38125.89, 0)  Resultado: 38.126
		
		Se o parâmetro "casas_decimais" for "null", o número de
		casas decimais será preservado:
		
		formata_numero(38211.4, null)  Resultado: 38.211,4
	*/
	var contador, parte_inteira, parte_fracionaria;
	if (numero.length == 0)
	{
		return(numero);
	}
	if (casas_decimais != null)
	{
		numero = Math.round(numero * Math.pow(10, casas_decimais)) / Math.pow(10, casas_decimais);
		numero = numero.toString();
	}
	if (numero.indexOf(".") == -1)
	{
		parte_inteira = numero;
		if ((casas_decimais == null) || (casas_decimais == 0))
		{
			parte_fracionaria = "";
		}
		else
		{
			parte_fracionaria = ",";
			for (contador = 0; contador < casas_decimais; contador++)
			{
				parte_fracionaria += "0";
			}
		}
	}
	else
	{
		parte_inteira = numero.substr(0, numero.indexOf("."));
		parte_fracionaria = numero.substr(numero.indexOf("."));
		parte_fracionaria = parte_fracionaria.replace(/\./g, ",");
		if (casas_decimais != null)
		{
			if (casas_decimais > parte_fracionaria.length - 1)
			{
				for (contador = 0; contador < casas_decimais - (numero.substr(numero.indexOf(".")).length - 1); contador++)
				{
					parte_fracionaria += "0";
				}
			}
		}
	}
	numero = "";
	for (contador = 0; contador < parte_inteira.length; contador++)
	{
		numero += parte_inteira.charAt(contador);
		if (((parte_inteira.length - contador) % 3) == 1)
		{
			numero += ".";
		}
	}
	numero = numero.substr(0, numero.length - 1);
	numero += parte_fracionaria;
	return(numero);
}

function formata_numero_eua(numero)
{
	/*
		Formata um número sem separador de milhar e casas decimais, se houver,
		no formato "#########.##", padrão EUA.
		
		O número de casas decimais será preservado:
		
		formata_numero_eua("38.211,4")  Resultado: 38211.4
		formata_numero_eua("38.211")  Resultado: 38211
	*/
	numero = numero.replace(/\./g, "").replace(/,/, ".");
	return(numero);
}

function formata_moeda(moeda)
{
	/*
		Formata um valor com separador de milhar e duas casas decimais,
		no formato "###.###.###,##".
		
		Em certos casos, poderá ocorrer arredondamento:
		
		formata_moeda(38125.499)  Resultado: 38.125,50
		formata_moeda(38125.899)  Resultado: 38.125,90
	*/
	var contador, parte_inteira, parte_fracionaria;
	if (moeda.length == 0)
	{
		return(moeda);
	}
	moeda = Math.round(moeda * 100) / 100;
	moeda = moeda.toString();
	if (moeda.indexOf(".") == -1)
	{
		parte_inteira = moeda;
		parte_fracionaria = ",00";
	}
	else
	{
		parte_inteira = moeda.substr(0, moeda.indexOf("."));
		parte_fracionaria = moeda.substr(moeda.indexOf("."));
		parte_fracionaria = parte_fracionaria.replace(/\./g, ",");
		if (parte_fracionaria.length == 2)
		{
			parte_fracionaria += "0";
		}
	}
	moeda = "";
	for (contador = 0; contador < parte_inteira.length; contador++)
	{
		moeda += parte_inteira.charAt(contador);
		if (((parte_inteira.length - contador) % 3) == 1)
		{
			moeda += ".";
		}
	}
	moeda = moeda.substr(0, moeda.length - 1);
	moeda += parte_fracionaria;
	return(moeda);
}

function formata_moeda_eua(moeda)
{
	/*
		Formata um valor sem separador de milhar e duas casas decimais,
		no formato "#########.##", padrão EUA.
		
		Em certos casos, poderá ocorrer arredondamento:
		
		formata_moeda_eua("38.125,499")  Resultado: 38125.50
		formata_moeda_eua("38.125,899")  Resultado: 38125.90
	*/
	if (moeda.length == 0)
	{
		return(moeda);
	}
	moeda = moeda.replace(/\./g, "").replace(/,/, ".");
	moeda = Math.round(moeda * 100) / 100;
	moeda = moeda.toString();
	if (moeda.indexOf(".") == -1)
	{
		moeda += ".00";
	}
	else if ((moeda.indexOf(".") + 1) == moeda.length - 1)
	{
		moeda += "0";
	}
	return(moeda);
}

function mascara_data(data)
{
	/*
		Mascara um campo de data com a máscara "##/##/####"
		inserindo as barras na posição correta durante a digitação.
		
		Esta função deve ser usada no evento "onkeypress".
	*/
	if ((window.event.keyCode < 47) || (window.event.keyCode > 57))
	{
		window.event.keyCode = 0;
		return;
	}
	if ((data.value.length == 1) || (data.value.length == 4))
	{
		data.value += String.fromCharCode(window.event.keyCode) + "/";
		window.event.keyCode = 0;
	}
}

function mascara_hora(hora)
{
	/*
		Mascara um campo de hora com a máscara "##:##" ou "##:##:##"
		inserindo o sinal de dois-pontos ":" na posição correta
		durante a digitação.
		
		Esta função deve ser usada no evento "onkeypress".
	*/
	if (hora.value.length == 1)
	{
		hora.value += String.fromCharCode(window.event.keyCode) + ":";
		window.event.keyCode = 0;
	}
	if ((hora.maxLength == 8) && (hora.value.length == 4))
	{
		hora.value += String.fromCharCode(window.event.keyCode) + ":";
		window.event.keyCode = 0;
	}
}

function mascara_cpf(cpf)
{
	/*
		Mascara um campo de CPF com a máscara "###.###.###-##"
		inserindo o ponto e o traço na posição correta durante
		a digitação.
		
		Esta função deve ser usada no evento "onkeypress".
	*/
	if ((cpf.value.length == 3) || (cpf.value.length == 7))
	{
		cpf.value += ".";
	}
	if (cpf.value.length == 11)
	{
		cpf.value += "-";
	}
}

function mascara_cnpj(cnpj)
{
	/*
		Mascara um campo de CNPJ com a máscara "##.###.###/####-##"
		inserindo o ponto, a barra e o traço na posição correta
		durante a digitação.
		
		Esta função deve ser usada no evento "onkeypress".
	*/
	if ((cnpj.value.length == 2) || (cnpj.value.length == 6))
	{
		cnpj.value += ".";
	}
	if (cnpj.value.length == 10)
	{
		cnpj.value += "/";
	}
	if (cnpj.value.length == 15)
	{
		cnpj.value += "-";
	}
}

function valida_url(url)
{
	/*
		Verifica se a sintaxe de uma URL tem o formato: 'http://www.dominio.com'.
	*/
	var er;
	er = /^(http:\/\/)?\w+(\.\w+)+$/;
	return(er.test(url));
}

function valida_email(email)
{
	/*
		Verifica se a sintaxe de um E-Mail tem o formato: 'usuario@dominio.com'.
	*/
	var er;
	er = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,3}$/;
	return(er.test(email));
}

function valida_data(data)
{
	/*
		Verifica se uma data é válida.
		A data deve estar no formato "DD/MM/YYYY".
	*/
	var er, array_data, dia, mes, ano, bissexto;
	er = /^[0-3][0-9]\/[0-1][0-9]\/[0-9]{4}$/;
	if (er.test(data) == false)
	{
		return(false);
	}
	array_data = data.split("/");
	if (array_data == null)
	{
		return(false);
	}
	dia = array_data[0];
	mes = array_data[1];
	ano = array_data[2];
	if ((mes < 1) || (mes > 12))
	{
		return(false);
	}
	if ((dia < 1) || (dia > 31))
	{
		return(false);
	}
	if (((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) && (dia == 31))
	{
		return(false);
	}
	if (mes == 2)
	{
		bissexto = (((ano % 4) == 0) && (((ano % 100) != 0) || ((ano % 400) == 0)));
		if ((dia > 29) || ((dia == 29) && !bissexto))
		{
			return(false);
		}
	}
	return(true);
}

function valida_hora(hora)
{
	/*
		Verifica se uma hora é válida.
		A hora deve estar nos formatos "HH:MM" ou "HH:MM:SS".
	*/
	var er;
	er = /^[0-2][0-9]:[0-5][0-9](:[0-5][0-9])?$/;
	if (er.test(hora) == false)
	{
		return(false);
	}
	if (parseInt(hora.substr(0, 2)) > 23)
	{
		return(false);
	}
	return(true);
}

function valida_numero(numero, digitos_parte_inteira, digitos_parte_fracionaria)
{
	/*
		Verifica se o número passado é válido.
		O nº de dígitos da parte inteira será verificado.
		O nº de dígitos da parte fracionária também será verificado.
		
		Exemplos:
		
		valida_numero("234.345,56", 5, 2)  Retorna Falso
		valida_numero("45,12", 3, 2)  Retorna Verdadeiro
		valida_numero("145,12", 3, 0)  Retorna Falso
		valida_numero("4.111", 4, 0)  Retorna Verdadeiro
		valida_numero("4111", 4, 0)  Retorna Verdadeiro
	*/
	if (digitos_parte_inteira == null)
	{
		digitos_parte_inteira = 9;
	}
	if (digitos_parte_fracionaria == null)
	{
		digitos_parte_fracionaria = 2;
	}
	var er;
	er = /^(([0-9]+(,[0-9]+)?)|([0-9]{1,3}(\.[0-9]{3})*)(,[0-9]+)?)$/;
	if (!er.test(numero))
	{
		return(false);
	}
	er = /^[0-9]+$/;
	if (!er.test(digitos_parte_inteira))
	{
		return(false);
	}
	if (parseInt(digitos_parte_inteira) == 0)
	{
		return(false);
	}
	if (!er.test(digitos_parte_fracionaria))
	{
		return(false);
	}
	if ((parseInt(digitos_parte_fracionaria) == 0) && (numero.indexOf(",") != -1))
	{
		return(false);
	}
	if (numero.indexOf(",") == -1)
	{
		if (numero.replace(/\./g, "").length > parseInt(digitos_parte_inteira))
		{
			return(false);
		}
	}
	else
	{
		if (numero.substr(0, numero.indexOf(",")).replace(/\./g, "").length > parseInt(digitos_parte_inteira))
		{
			return(false);
		}
		if (numero.substr(numero.indexOf(",") + 1).length > parseInt(digitos_parte_fracionaria))
		{
			return(false);
		}
	}
	return(true);
}

function valida_moeda(moeda)
{
	/*
		Verifica se o valor passado tem o formato: "###.###.###,##".
	*/
	var er;
	er = /^(([0-9]+(,[0-9]+)?)|([0-9]{1,3}(\.[0-9]{3})*)(,[0-9]+)?)$/;
	if (!er.test(moeda))
	{
		return(false);
	}
	if (moeda.indexOf(",") == -1)
	{
		if (moeda.replace(/\./g, "").length > 9)
		{
			return(false);
		}
	}
	else
	{
		if (moeda.substr(0, moeda.indexOf(",")).replace(/\./g, "").length > 9)
		{
			return(false);
		}
		if (moeda.substr(moeda.indexOf(",") + 1).length > 2)
		{
			return(false);
		}
	}
	return(true);
}

function valida_cpf(cpf)
{
	/*
		Verifica se um CPF é válido.
	*/
	var soma, indice, digito;
	if ((cpf.length != 11) || (cpf == "00000000000") || (cpf == "11111111111") || (cpf == "22222222222") || (cpf == "33333333333") || (cpf == "44444444444") || (cpf == "55555555555") || (cpf == "66666666666") || (cpf == "77777777777") || (cpf == "88888888888") || (cpf == "99999999999"))
	{
		return(false);
	}
	soma = 0;
	for (var indice = 0; indice < 9; indice++)
	{
		soma += parseInt(cpf.charAt(indice)) * (10 - indice);
	}
	digito = soma - (Math.floor(soma / 11) * 11);
	if ((digito == 0) || (digito == 1))
	{
		digito = 0;
	}
	else
	{
		digito = 11 - digito;
	}
	if (digito != parseInt(cpf.charAt(9)))
	{
		return(false);
	}
	soma = 0;
	for (var indice = 0; indice < 10; indice++)
	{
		soma += parseInt(cpf.charAt(indice)) * (11 - indice);
	}
	digito = soma - (Math.floor(soma / 11) * 11);
	if ((digito == 0) || (digito == 1))
	{
		digito = 0;
	}
	else
	{
		digito = 11 - digito;
	}
	if (digito != parseInt(cpf.charAt(10)))
	{
		return(false);
	}
	return(true);
}

function valida_cnpj(cnpj)
{
	/*
		Verifica se um CNPJ é válido.
	*/
	var sequencia, soma, indice, resto;
	if ((cnpj.length != 14) || (cnpj == "00000000000000") || (cnpj == "11111111111111") || (cnpj == "22222222222222") || (cnpj == "33333333333333") || (cnpj == "44444444444444") || (cnpj == "55555555555555") || (cnpj == "66666666666666") || (cnpj == "77777777777777") || (cnpj == "88888888888888") || (cnpj == "99999999999999"))
	{
		return(false);
	}
	sequencia = "543298765432";
	soma = 0;
	for (var indice = 0; indice < sequencia.length; indice++)
	{
		soma += parseInt(cnpj.charAt(indice)) * (sequencia.charAt(indice));
	}
	resto = (soma % 11);
	if ((resto == 0) || (resto == 1))
	{
		resto = 0;
	}
	else
	{
		resto = (11 - resto);
	}
	if (resto != parseInt(cnpj.charAt(12)))
	{
		return(false);
	}
	sequencia = "654329876543";
	soma = 0;
	for (var indice = 0; indice < sequencia.length; indice++)
	{
		soma += parseInt(cnpj.charAt(indice)) * (sequencia.charAt(indice));
	}
	soma += (resto * 2);
	resto = (soma % 11);
	if ((resto == 0) || (resto == 1))
	{
		resto = 0;
	}
	else
	{
		resto = (11 - resto);
	}
	if (resto != parseInt(cnpj.charAt(13)))
	{
		return(false);
	}
	return(true);
}

function valida_pis(pis)
{
	/*
		Verifica se um PIS é válido.
	*/
	var sequencia, soma, indice, resto;
	if ((pis.length != 11) || (parseInt(pis) == 0))
	{
		return(false);
	}
	sequencia = "3298765432";
	soma = 0;
	for (var indice = 0; indice < 10; indice++)
	{
		soma += parseInt(pis.charAt(indice)) * (sequencia.charAt(indice));
	}
	resto = (soma % 11);
	if (resto != 0)
	{
		resto = (11 - resto);
	}
	if (resto != parseInt(pis.charAt(10)))
	{
		return(false);
	}
	return(true);
}

function hoje()
{
	var data_hoje = new Date();
	return(("0" + data_hoje.getDate()).right(2) + "/" + ("0" + (data_hoje.getMonth() + 1)).right(2) + "/" + data_hoje.getFullYear());
}

function adiciona_data(data, tempo, intervalo)
{
	/*
		Realiza uma adição à data fornecida.
		
		O parâmetro 'data' deve estar no formato:
			DD/MM/YYYY

		O parâmetro 'tempo' pode assumir:
			milissegundos - ms
			segundos - s
			minutos - mi
			horas - h
			dias - d
			meses - m
			anos - y ou a

		O parâmetro 'intervalo' é o parâmetro que será adicionado à data, e pode estar expresso em	milissegundos, segundos, minutos, horas, dias, meses ou anos.
			
	*/
	if (tempo == "a")
	{
		tempo = "y";
	}
	var nova_data = new Date();
	nova_data.setFullYear(data.substr(data.length - 4), data.substr(3, 2), data.substr(0, 2));
	var data = nova_data.add(tempo, intervalo);
	return(("0" + data.getDate()).right(2) + "/" + ("0" + data.getMonth()).right(2) + "/" + data.getFullYear());
}

function compara_data(data1, data2, comparacao)
{
	/*
		Efetua uma comparação entre duas datas.
		Primeiramente, verifica se as datas são válidas.
		As datas devem estar num dos seguintes formatos:
			"DD/MM/YYYY"
			"DD/MM/YYYY HH:MM"
			"DD/MM/YYYY HH:MM:SS"
		O campo comparação pode ser:
			"=" ou "==" Igual
			"<" Menor
			"<=" Menor ou Igual
			">" Maior
			">=" Maior ou Igual
			"!=" Diferente
	*/
	var objeto1, objeto2;
	if ((data1.length < 10) || (data2.length < 10))
	{
		return(false);
	}
	if (!valida_data(data1.substr(0,10)))
	{
		return(false);
	}
	if (data1.length > 10)
	{
		if (data1.substr(10,1) != " ")
		{
			return(false);
		}
		if (!valida_hora(data1.substr(11)))
		{
			return(false);
		}
	}
	if (!valida_data(data2.substr(0,10)))
	{
		return(false);
	}
	if (data2.length > 10)
	{
		if (data2.substr(10,1) != " ")
		{
			return(false);
		}
		if (!valida_hora(data2.substr(11)))
		{
			return(false);
		}
	}
	var objeto1 = new Date(data1.substr(6,4) + "/" + data1.substr(3,2) + "/" + data1.substr(0,2));
	if (data1.length > 10)
	{
		objeto1.setHours(data1.substr(11,2));
		objeto1.setMinutes(data1.substr(14,2));
		if (data1.length > 16)
		{
			objeto1.setSeconds(data1.substr(17,2));
		}
	}
	objeto2 = new Date(data2.substr(6,4) + "/" + data2.substr(3,2) + "/" + data2.substr(0,2));
	if (data2.length > 10)
	{
		objeto2.setHours(data2.substr(11,2));
		objeto2.setMinutes(data2.substr(14,2));
		if (data2.length > 16)
		{
			objeto2.setSeconds(data2.substr(17,2));
		}
	}
	if ((comparacao == "=") || (comparacao == "=="))
	{
		return(objeto1.valueOf() == objeto2.valueOf());
	}
	if (comparacao == "<")
	{
		return(objeto1.valueOf() < objeto2.valueOf());
	}
	if (comparacao == "<=")
	{
		return(objeto1.valueOf() <= objeto2.valueOf());
	}
	if (comparacao == ">")
	{
		return(objeto1.valueOf() > objeto2.valueOf());
	}
	if (comparacao == ">=")
	{
		return(objeto1.valueOf() >= objeto2.valueOf());
	}
	if (comparacao == "!=")
	{
		return(objeto1.valueOf() != objeto2.valueOf());
	}
	return(false);
}

function desliga_form()
{
	/*
		Desabilita todos os controles (assim eu espero) da tela após qualquer tentativa
		de submit da página, impedindo que o usuário interaja com a página nos segundos
		que antecedem o submit do formulário.
	*/
	var objeto, indice1, indice2;
	return;
	window.document.onclick = null;
	objeto = document.all;
	for (var indice1 = 0; indice1 < objeto.length; indice1++)
	{
		objeto(indice1).onclick = null;
		if (objeto(indice1).tagName == "A")
		{
			objeto(indice1).href = "javascript:void(0)";
			objeto(indice1).target = "";
		}
		if (objeto(indice1).tagName == "INPUT")
		{
			objeto(indice1).readOnly = true;
		}
		if (objeto(indice1).tagName == "TEXTAREA")
		{
			objeto(indice1).readOnly = true;
		}
		if (objeto(indice1).tagName == "SELECT")
		{
			indice2 = 0;
			while (objeto(indice1).length > 1)
			{
				if (objeto(indice1).options.item(indice2).selected == false)
				{
					objeto(indice1).options.remove(indice2);
				}
				else
				{
					indice2++;
				}
			}
		}
	}
}

function abre_dialog(objeto, pagina, largura, altura)
{
	/*
		Abre uma janela Modal Child (Dialog) e atribui ao "controle" o valor de retorno.
	*/
	var retorno;
	objeto.focus();
	retorno = window.showModalDialog(pagina, '', "dialogWidth: " + largura.toString() + "px; dialogHeight: " + altura.toString() + "px; status: no;");
	if (retorno)
	{
		if ((objeto.tagName == "INPUT") && (objeto.type == "text"))
		{
			objeto.value = retorno;
		}
		else if (objeto.tagName == "SELECT")
		{
			sel_combo(objeto, retorno);
		}
	}
}

function abre_dialog_old(objeto, pagina, parametros, opcoes)
{
	/*
		Abre uma janela Modal (Child) e atribui ao controle o valor de retorno.
	*/
	var retorno;
	objeto.focus();
	retorno = window.showModalDialog(pagina, parametros, opcoes);
	if (retorno)
	{
		if ((objeto.tagName == "INPUT") && (objeto.type == "text"))
		{
			objeto.value = retorno;
		}
		else if (objeto.tagName == "SELECT")
		{
			sel_combo(objeto, retorno);
		}
	}
}

function abre_dialog_pessoa(objeto)
{
	var id_pessoa;
	if (objeto.selectedIndex >= 0)
	{
		id_pessoa = objeto.options(objeto.selectedIndex).value;
		if (parseInt(id_pessoa) > 0)
		{
			window.showModalDialog('dlg_pessoa.asp?id_pessoa=' + id_pessoa, '', 'dialogWidth: 500px; dialogHeight: 500px; status: no;');
			return;
		}
	}
	alert("O campo '" + objeto.parentElement.parentElement.children(0).innerText + "' não foi selecionado.");
	objeto.focus();
}

function ajax(objeto, url, texto)
{
	if (window.event.keyCode != 0)
	{
		if (((window.event.keyCode < 32) && (window.event.keyCode != 8)) || ((window.event.keyCode >= 37) && (window.event.keyCode <= 40)))
		{
			return;
		}
	}
	if (document.getElementById(objeto.name + "_ajax") != null)
	{
		document.body.removeChild(document.getElementById(objeto.name + "_ajax"));
	}
	var http_request = ajax_http_request();
	if (http_request)
	{
		if (objeto.type == "text")
		{
			url += "?s=" + objeto.value.trim();
		}
		http_request.open("GET", url, true);
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				if (http_request.status == 200)
				{
					var xml = http_request.responseXML.documentElement;
					if (xml.hasChildNodes())
					{
						elemento = document.createElement("DIV");
						elemento.id = objeto.name + "_ajax";
						elemento.className = "ajax";
						elemento.style.top = absoluteTop(objeto) + 15;
						elemento.style.left = absoluteLeft(objeto);
						elemento.style.width = objeto.clientWidth;
						array_ajax = new Array();
						for (var i = 0; i < xml.childNodes.length; i++)
						{
							var achou = false;
							for (var j = 0; j < array_ajax.length; j++)
							{
								if (array_ajax[j] == xml.childNodes(i).getAttribute("value"))
								{
									achou = true;
									break;
								}
							}
							if (!achou)
							{
								array_ajax[i] = xml.childNodes(i).getAttribute("value");
								texto += "<a href=";
								texto += '"';
								texto += "javascript:ajax_clique('"
								texto += objeto.name;
								texto += "', " + i + ")";
								texto += '"';
								texto += ">"
								texto += xml.childNodes(i).getAttribute("value");
								texto += "</a><br>";
							}
						}
						elemento.innerHTML = texto;
						document.body.insertBefore(elemento);
					}
				}
			}
		}
		http_request.send(null);
	}
}

function ajax_clique(objeto, indice)
{
	if (document.all(objeto).type == "text")
	{
		document.all(objeto).value = array_ajax[indice];
	}
	document.body.removeChild(document.getElementById(objeto + "_ajax"));
	document.all(objeto).focus();
}

function ajax_textbox(textbox, url)
{
	if (window.event.keyCode != 0)
	{
		if (((window.event.keyCode < 32) && (window.event.keyCode != 8)) || ((window.event.keyCode >= 37) && (window.event.keyCode <= 40)))
		{
			return;
		}
	}
	if (url == null)
	{
		window.setTimeout("ajax_textbox_close()", 300);
		return;
	}
	ajax_textbox_close();
	var http_request = ajax_http_request();
	if (http_request)
	{
		http_request.open("GET", url, true);
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				if (http_request.status == 200)
				{
					var xml = http_request.responseXML.documentElement;
					if (xml.hasChildNodes())
					{
						var iframe = document.createElement("IFRAME");
						iframe.id = "objeto_ajax_iframe";
						iframe.style.position = "absolute";
						iframe.style.top = absoluteTop(textbox) + textbox.clientHeight - 3;
						iframe.style.left = absoluteLeft(textbox) - 3;
						iframe.style.width = textbox.offsetWidth;
						iframe.style.height = 0;
						iframe.style.display = "none";
						document.body.appendChild(iframe);
						var div = document.createElement("DIV");
						div.id = "objeto_ajax_div";
						div.className = textbox.className;
						div.style.position = "absolute";
						div.style.top = absoluteTop(textbox) + textbox.clientHeight - 3;
						div.style.left = absoluteLeft(textbox) - 3;
						div.style.width = textbox.offsetWidth;
						div.style.height = 0;
						div.style.padding = "5px";
						div.style.display = "none";
						document.body.insertBefore(div);
						var texto = "";
						for (var i = 0; i < xml.childNodes.length; i++)
						{
							var elemento = document.createElement("SPAN");
							elemento.onclick = function()
							{
								textbox.value = this.innerText;
								ajax_textbox_close();
								textbox.focus();
							}
							elemento.innerText = xml.childNodes(i).getAttribute("value");
							elemento.className = "ajax_link";
							div.appendChild(elemento);
							var elemento = document.createElement("BR");
							div.appendChild(elemento);
						}
						div.style.display = "block";
						iframe.style.height = div.offsetHeight;
						iframe.style.display = "block";
					}
				}
			}
		}
		http_request.send(null);
	}
}

function ajax_textbox_close()
{
	if (document.getElementById("objeto_ajax_iframe") != null)
	{
		document.body.removeChild(document.getElementById("objeto_ajax_iframe"));
	}
	if (document.getElementById("objeto_ajax_div") != null)
	{
		document.body.removeChild(document.getElementById("objeto_ajax_div"));
	}
}

function ajax_combobox(combobox, url, valor, funcao)
{
	/*
		Carrega um combobox com resultados da consulta de uma página XML.
	*/
	var primeiro_item = false;
	if (combobox.options.length > 0)
	{
		if ((combobox.options(0).text == "") && (combobox.options(0).value == ""))
		{
			primeiro_item = true;
		}
		else
		{
			primeiro_item = false;
		}
		while (combobox.options.length > 0)
		{
			combobox.options.remove(0);
		}
	}
	var elemento = document.createElement("OPTION");
	elemento.value = "Carregando...";
	elemento.text = "Carregando...";
	combobox.add(elemento);
	var http_request = ajax_http_request();
	if (http_request)
	{
		http_request.open("GET", url, true);
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				remove_item_array_http_request(http_request);
				if (http_request.status == 200)
				{
					combobox.options.remove(0);
					if (primeiro_item)
					{
						var elemento = document.createElement("OPTION");
						elemento.value = "";
						elemento.text = "";
						combobox.add(elemento);
					}
					var xml = http_request.responseXML.documentElement;
					if (xml.hasChildNodes())
					{
						for (var i = 0; i < xml.childNodes.length; i++)
						{
							var elemento = document.createElement("OPTION");
							elemento.value = xml.childNodes(i).getAttribute("value");
							elemento.text = xml.childNodes(i).getAttribute("text");
							combobox.add(elemento, combobox.options.length);
						}
						if (valor != null)
						{
							sel_combo(combobox, valor);
						}
						if (funcao != null)
						{
							funcao();
						}
					}
				}
			}
		}
		http_request.send(null);
	}
}

function ajax_combo_combo(combo1, combo2, url)
{
	if (combo2.options.length > 0)
	{
		if ((combo2.options(0).text == "") && (combo2.options(0).value == ""))
		{
			indice = 1;
		}
		else
		{
			indice = 0;
		}
		while (combo2.options.length > indice)
		{
			combo2.options.remove(indice);
		}
	}
	var http_request = ajax_http_request();
	if (http_request)
	{
		http_request.open("GET", url, true);
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				if (http_request.status == 200)
				{
					var xml = http_request.responseXML.documentElement;
					if (xml.hasChildNodes())
					{
						for (var i = 0; i < xml.childNodes.length; i++)
						{
							elemento = document.createElement("OPTION");
							elemento.value = xml.childNodes(i).getAttribute("id");
							elemento.text = xml.childNodes(i).getAttribute("value");
							combo2.add(elemento, combo2.options.length);
						}
					}
				}
			}
		}
		http_request.send(null);
	}
}

function ajax_combo_textbox(combo, textbox, url)
{
	textbox.value = "";
	var http_request = ajax_http_request();
	if (http_request)
	{
		http_request.open("GET", url, true);
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				if (http_request.status == 200)
				{
					var xml = http_request.responseXML.documentElement;
					if (xml.hasChildNodes())
					{
						for (var i = 0; i < xml.childNodes.length; i++)
						{
							textbox.value = xml.childNodes(i).getAttribute("value");
						}
					}
				}
			}
		}
		http_request.send(null);
	}
}

var array_http_request = new Array();

function ajax_http_request()
{
	var http_request;
	try
	{
		http_request = new XMLHttpRequest(); // Mozilla, Safari, ...
	}
	catch (e)
	{
		try
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP"); // IE
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP"); // IE
			}
			catch (e)
			{
				http_request = false;
			}
		}
	}
	adiciona_item_array_http_request(http_request);
	return(http_request);
}

function adiciona_item_array_http_request(http_request)
{
	array_http_request.push(http_request);
}

function remove_item_array_http_request(http_request)
{
	for (var i = 0; i < array_http_request.length; i++)
	{
		if (array_http_request[i] == http_request)
		{
			array_http_request.splice(i, 1);
			break;
		}
	}
}

function ajax_escape(parametros)
{
	var s = "";
	for (contador = 0; contador < parametros.length; contador++)
	{
		s += "%" + converte_base(parametros.charCodeAt(contador).toString(), 10, 16);
	}
	return(s);
}

function converte_base(numero, base, nova_base)
{
	// Created 1997 by Brian Risk.  http://members.aol.com/brianrisk
	numero = numero.toUpperCase();
	var array_caractere = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var digito = 0;
	for (var i = 0; i <= numero.length; i++)
	{
		digito += (array_caractere.indexOf(numero.charAt(i))) * (Math.pow(base , (numero.length - i - 1)));
	}
	numero = "";
	var magnitude = Math.floor((Math.log(digito)) / (Math.log(nova_base)));
	for (var i = magnitude; i >= 0; i--)
	{
		var quantidade = Math.floor(digito / Math.pow(nova_base, i));
		numero = numero + array_caractere.charAt(quantidade); 
		digito -= quantidade * (Math.pow(nova_base, i));
	}
	return(numero);
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}