////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////// FUNÇÕES GERAIS //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

//funções trim(), ltrim() e rtrim()
//O javascript não possui uma função nativa para eliminar espações em branco.
//É necessário usar as seguintes funções para executar o trim()
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
//fim

//Função para setar injection de código html ou mensagem na página
function setHTML(id, html){
	document.getElementById(id).innerHTML = html;
}
//fim

//Função para setar tipos de display em objetos html
function setDisplay(id, type){
	if(type == ""){
		var box = document.getElementById(id);
		if (box.style.display == "none"){
			box.style.display = "block";
		}else{
			box.style.display = "none";
		}
	}else{
		document.getElementById(id).style.display=type;
	}
}
//fim

//Função que configura visibilidade de um objeto html na pagina
function setVisible(id){
	var box = document.getElementById(id);
	if (box.style.visibility == "hidden"){
		box.style.visibility = "visible";
	}else{
		box.style.visibility = "hidden";
	}
}
//fim

//Iluminar linha quando passar o mouse em cima
//Parametros: Id do elemento, cor iluminada
function changeBGColor(id, cor){
	if (document.getElementById(id).style.backgroundColor != cor){
		document.getElementById(id).style.backgroundColor = cor;
	}
}
//fim

//Função para trocar a classe do elemento
//Parametros: Id do elemento, nova classe
function changeClass(id, classe){
	if (document.getElementById(id).className != classe){
		document.getElementById(id).className = classe;
	}
}
//fim

//Função flashbang - Usando em conjunto com jQuery, faz piscar um elemento na tela
function flashbang(id){
	$(document).ready(
		function (){
			$(id).fadeTo("slow", 0.4);
			$(id).fadeTo("slow", 1);
		}
	);
}

//função para abrir pop-up
function abrirPopup(URL,w,h){
	window.open(URL,'Endereço','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width='+w+',height='+h);
}
//fim

//Função pra tranformar letras em maiúsculas
function letraMaiuscula(id){
	document.getElementById(id).value = document.getElementById(id).value.toUpperCase();
}
//fim

//Função pra tranformar letras em maiúsculas
function letraMinuscula(id){
	document.getElementById(id).value = document.getElementById(id).value.toLowerCase();
}
//fim

//Função para imprimir
function imprimir(){
	window.print();
}
//fim

//limitador de campo textarea
function textCounter(id, contcampo, maxlimite){
	if (document.getElementById(id).value.length > maxlimite){ 
		document.getElementById(id).value = document.getElementById(id).value.substring(0, maxlimite);
	}else{ 
		document.getElementById(contcampo).value = maxlimite - document.getElementById(id).value.length;
	}
}
//fim

//Função para permitir digitar apenas números
function permiteNumeros(e){
    var tecla=(window.event)?event.keyCode/*ie*/:e.which/*outros*/;
    var keychar = String.fromCharCode(tecla);
	if (tecla != 8){//Verifica se foi digitado o backspace
		var numcheck = /\d/;//Aceitar apenas números
		return numcheck.test(keychar);
	}else{
		return true;
	}
}

//Função para permitir campo ser nulo ou em branco
function permiteNulo(valor){
	if((valor == "")||(valor == null)){
		return true;
	}else{
		return false;
	}
}

//bloqueia e desbloqueia o botão direito
function botaoDireito() {
	document.oncontextmenu = new Function("return false;");
	oncontextmenu='return false';
}
//bloqueia e desbloqueia o botão direito
function desbloquearBotaoDireito() {
	document.oncontextmenu = new Function("return true;");
	oncontextmenu='return true';
}

//fim

//funções para bloquear o comando Ctrl+C ou Ctrl+V
function bloquearCopiar(e){
	var tecla=(window.event)?e.keyCode/*ie*/:e.which/*outros*/;
	if((e.ctrlKey == 1) || (e.ctrlKey == 1) && (tecla==67)){
		e.returnValue=false;
		return false;
	}else{
		return true;
	}
}
function bloquearColar(e){
	var tecla=(window.event)?e.keyCode/*ie*/:e.which/*outros*/;
	if((e.ctrlKey == 1) || (e.ctrlKey == 1) && (tecla==86)){
		e.returnValue=false;
		return false;
	}else{
		return true;
	}
}
//fim

//Função para adicionar o site aos favoritos
function addToFavorites(url){
    var title = "Paramédica - A Maior Cooperativa de Trabalho na Área da Saúde";
    if (window.sidebar){
		window.sidebar.addPanel(title, url,"");
    }else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }else if(document.all){
		window.external.AddFavorite(url, title);
	}
}
//fim

//Pegar o valor de um radio buttom
function getRadioValue(nameRadio){
	var resposta = null;
	radio = document.getElementsByTagName("input");
	for(i=0; i<radio.length; i++) {
		if (radio[i].getAttribute("type") == "radio" && radio[i].getAttribute("name") == nameRadio && radio[i].checked == true){
			resposta = radio[i].value;
		}
	}
	return resposta;
}
//fim

//Função verifica se o conteúdo é um inteiro ou uma sequência de números
function onlyNumber(id, padrao){
	var box = document.getElementById(id);
	var inteiro = /^\d+$/;//Aceitar apenas números
	var numeral = /^\d{0,9}$/;//Aceitar numeros inteiro com . a cada 3 casas
	if(padrao = 'inteiro'){
		numcheck = inteiro;
	}else{
		numcheck = numeral;//Default sequência de números
	}
	if(!numcheck.test(box.value)){
		box.value = "";
	}
}//fim

//Função verifica se o conteúdo é um float
function onlyFloat(id, padrao){
	var reDecimalPt = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;//Português
	var reDecimalEn = /^[+-]?((\d+|\d{1,3}(\,\d{3})+)(\.\d*)?|\.\d+)$/;//Inglês
	var numcheck;
	if(padrao == 'en'){
		numcheck = reDecimalEn;
	}else{
		numcheck = reDecimalPt;//Default Padrão Português
	}
	var box = document.getElementById(id);
	if(!numcheck.test(box.value)){
		box.value = "";
	}
}//fim

//Função verifica se o conteúdo é um monetário
function onlyMoney(id, padrao){
	var reMoedaPt = /^\d{1,3}(\.\d{3})*\,\d{2}$/;;//Português
	var reMoedaEn = /^\d{1,3}(\,\d{3})*\.\d{2}$/;//Inglês
	var numcheck;
	if(padrao == 'en'){
		numcheck = reMoedaEn;
	}else{
		numcheck = reMoedaPt;//Default Padrão Português
	}
	var box = document.getElementById(id);
	if(!numcheck.test(box.value)){
		box.value = "";
	}
}//fim

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// COMPARADORES ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

function comparaData(data1, data2, type){//Compara duas datas de acrodo com o parametro type passado. type pode ser ==, >=, <=, >, <
	data1 = data1.split("/");
	data2 = data2.split("/");
	var d1 = new Date();
	var d2 = new Date();
	if(!(d1.setFullYear(data[2],data[1],data[0]) && d2.setFullYear(data[2],data[1],data[0]))){
		alert("Data inválida!");
		return false;
	}else{
		if(type == "=="){
			if(d1 == d2){
				return true;
			}else{
				return false;
			}
		}else if(type == ">="){
			if(d1 >= d2){
				return true;
			}else{
				return false;
			}
		}else if(type == "<="){
			if(d1 <= d2){
				return true;
			}else{
				return false;
			}
		}else if(type == "<"){
			if(d1 > d2){
				return true;
			}else{
				return false;
			}
		}else if(type == ">"){
			if(d1 < d2){
				return true;
			}else{
				return false;
			}
		}
	}
}
function comparaDataHoje(data1, data2, type){//Compara duas datas e a data corrente de acrodo com o parametro type passado. type pode ser ==, >=, <=, >, <
	data1 = data1.split("/");
	data2 = data2.split("/");
	var d1 = new Date();
	var d2 = new Date();
	var today = new Date();
	if(!(d1.setFullYear(data[2],data[1],data[0]) && d2.setFullYear(data[2],data[1],data[0]))){
		alert("Data inválida!");
		return false;
	}else{
		if(type == ">="){
			if((d1 >= d2)&&(d1 >= today)){
				return true;
			}else{
				return false;
			}
		}else if(type == "<="){
			if((d1 <= d2)&&(d1 <= today)){
				return true;
			}else{
				return false;
			}
		}else if(type == "=="){
			if((d1 == today)){
				return true;
			}else{
				return false;
			}
		}
	}
}

//Compara dois ou mais campos verificando se os campos possuem conteúdos iguais ou diferentes.
//Parametro type pode ter dois valores == representando igualdade ou <> representando desigualdade
function fieldsToCompare(campos, type, id){
	var check = campos.split(";");//Ex check[0] = "senha"; check[1] = "confirma_senha";
	if(check.length > 1){
		valor = trim(document.getElementById(check[0]).value);//Valor do campo, sem espaços em branco
		document.getElementById(check[0]).value = valor;//Retornando valor sem espaços em branco
		for(j = 1; j < check.length; j++){//Percorre todo o array sameFields

			next_valor = trim(document.getElementById(check[j]).value);//Valor do campo, sem espaços em branco
			document.getElementById(check[j]).value = next_valor;//Retornando valor sem espaços em branco

			if(type == "=="){
				if(valor != next_valor){//Verificando se há diferença nos campos
					setDisplay(id,"block");//Exibir alerta
				}else{
					setDisplay(id,"none");//Esconder alerta
				}
			}else if(type == "<>"){
				if(valor == next_valor){//Verificando se há diferença nos campos
					setDisplay(id,"block");//Exibir alerta
				}else{
					setDisplay(id,"none");//Esconder alerta
				}
			}
		}
	}
}

//Verifica se o campos ou os campos possuem o tamanho mínimo permitido
function minFieldLen(campos, len, id){
	var check = campos.split(";");//Ex check[0] = "senha"; check[1] = "confirma_senha";
	for(j = 0; j < check.length; j++){//Percorre todo o array sameFields
		valor = trim(document.getElementById(check[j]).value);//Valor do campo, sem espaços em branco
		document.getElementById(check[j]).value = valor;//Retornando valor sem espaços em branco
		if(valor.length < len){
			setDisplay(id,"block");//Exibir alerta
		}else{
			setDisplay(id,"none");//Esconder alerta
		}
	}
}

//Verifica se o campos ou os campos possuem o tamanho mínimo permitido
function minlength(field, valor){
	document.getElementById(field).value = valor;//Retornando valor sem espaços em branco
	len = document.getElementById(field).getAttribute("minlength");
	msg = document.getElementById(field).getAttribute("MSG_minlength");
	id = document.getElementById(field).getAttribute("minlengthDisplay");
	if(valor.length < len){
		if((id == "") || (id == null)){
			if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
				alert(msg);
			}
		}else{
			setDisplay(id,"block");
		}
		return false;
	}else{
		if(id != "" && id != null){
			setDisplay(id,"none");
		}
		return true;
	}
}

function igual(field, valor){//Compara se o valor do campo é igual a o valor de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("igual").split(";");
	msg = document.getElementById(field).getAttribute("MSG_igual");
	id = document.getElementById(field).getAttribute("igualDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array	
		if(valor == document.getElementById(compare[l]).value){
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}else{
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}
	}
}

function diferente(field, valor){//Compara se o valor do campo é diferente ao valor de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("diferente").split(";");
	msg = document.getElementById(field).getAttribute("MSG_diferente");
	id = document.getElementById(field).getAttribute("diferenteDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(valor != document.getElementById(compare[l]).value){
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}else{
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}
	}
}

function maiorIgual(field, valor){//Compara se o valor do campo é maior ou igual ao valor de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("maiorIgual").split(";");
	msg = document.getElementById(field).getAttribute("MSG_maiorIgual");
	id = document.getElementById(field).getAttribute("maiorIgualDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(valor >= document.getElementById(compare[l]).value){
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}else{
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}
	}
}

function menorIgual(field, valor){//Compara se o valor do campo é menor ou igual ao valor de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("menorIgual").split(";");
	msg = document.getElementById(field).getAttribute("MSG_menorIgual");
	id = document.getElementById(field).getAttribute("menorIgualDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(valor <= document.getElementById(compare[l]).value){
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}else{
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}
	}
}

function dataMaiorIgualHoje(field, valor){//Compara se o valor do campo é uma data maior ou igual a data de hoje e maior ou igual a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataMaiorIgualHoje").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataMaiorIgualHoje");
	id = document.getElementById(field).getAttribute("dataMaiorIgualHojeDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaDataHoje(valor, document.getElementById(compare[l]).value, ">=")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

function dataMenorIgualHoje(field, valor){//Compara se o valor do campo é uma data menor ou igual a data de hoje e menor ou igual a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataMenorIgualHoje").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataMenorIgualHoje");
	id = document.getElementById(field).getAttribute("dataMenorIgualHojeDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaDataHoje(valor, document.getElementById(compare[l]).value, "<=")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

function dataMaiorIgual(field, valor){//Compara se o valor do campo é uma data maior ou igual a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataMaiorIgual").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataMaiorIgual");
	id = document.getElementById(field).getAttribute("dataMaiorIgualDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaData(valor, document.getElementById(compare[l]).value, ">=")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

function dataMenorIgual(field, valor){//Compara se o valor do campo é uma data menor a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataMenorIgual").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataMenorIgual");
	id = document.getElementById(field).getAttribute("dataMenorIgualDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaData(valor, document.getElementById(compare[l]).value, "<=")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

function dataMaior(field, valor){//Compara se o valor do campo é uma data maior a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataMaior").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataMaior");
	id = document.getElementById(field).getAttribute("dataMaiorDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaData(valor, document.getElementById(compare[l]).value, ">")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

function dataMenor(field, valor){//Compara se o valor do campo é uma data menor a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataMenor").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataMenor");
	id = document.getElementById(field).getAttribute("dataMenorDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaData(valor, document.getElementById(compare[l]).value, "<")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

function dataIgual(field, valor){//Compara se o valor do campo é uma data igual a data de outro(s) campo(s)
	compare = document.getElementById(field).getAttribute("dataIgual").split(";");
	msg = document.getElementById(field).getAttribute("MSG_dataIgual");
	id = document.getElementById(field).getAttribute("dataIgualDisplay");
	for(l = 0;l < compare.length; l++){//Percorre todos os campos do array
		if(!comparaData(valor, document.getElementById(compare[l]).value, "==")){
			if((id == "") || (id == null)){
				if((msg != "")&&(msg != null)){//Verifica se possui mensagem personalizada para esta validação
					alert(msg);
				}
			}else{
				setHTML(id, msg);
				setDisplay(id,"block");
			}
			return false;
		}else{
			if(id != "" && id != null){
				setDisplay(id,"none");
			}
			return true;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////	VALIDADORES ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

//Função checkForm: subimente formulários em geral, validando os campos com a funcção fieldsValidator
function checkForm(campos, id_form, id, msg){
	if(fieldsValidator(campos)){
		document.getElementById(id_form).submit();
	}else{
		if(msg == null){
			msg = "Preencha os campos em vermelho!";
		}
		setDisplay(id, "block");
		setHTML(id,msg);
	}
}
/*
Validador de Campos de Formulários
Regras:.
Parametro campos: Armazena os campos a serem testados
Os campos devem ser passados separados por ; menos o último elelemento e devem estar entre aspas ""
Os tipos de validadores para um campo devem ser passado separados por ,
O esterótipo ! é usado para não validar um campo, caso este não tenha sido preenchido, mas válidá-o caso tenha algum valor
O esterótipo # é usado para validar um campo com valor nulo dentro de uma cláusula AND
O esterótipo || é usado como regra OR. Dados dois ou mais conjuntos de campos verifica se um deles está preenchido para validar
O esterótipo && é usado como regra AND dentro de uma condição OR. Verifica se um conjunto de campos, dentro de uma condição OR, estão preenchidos
Configurações de parametros:
type: utilizado quando há uma verificação && onde não deverá ser chamada a função flashbang
Esta função trabalha com atributos personalisados dentro das tags HTML.
Atributos:
- fvAlert: atributo usado para mudar estilo do css caso o campo não passar pela validação
- fvNormal: atributo usado para mudar estilo do css caso o campo passe pela validação
- fvMSG: pode se definir uma mensagem personalisada quando um ocorrencia OR tiver o resultado false
- fvDisplay: alternativa ao alert no qual pode se definir uma id para um campo com uma mensagem de alerta. Este campo por default deve ser invisível
- fvOrDisplay: alternativa para alet nos caso onde haver condição OR. Este campo por default deve ser invisível
Dependências de funções externas:
- Biblioteca jQuery
- trim()
- changeClass()
Variáveis
Developed by Diego Felipe Rombaldi diegofeliper@gmail.com - All Rights Reserved
Uso livre, apenas manter nome do autor
*/
var verificar = new Array();//Escopo global
function fieldsValidator(campos){
	//Primeiramente separamos os campos junto com seus validadores
	var check = campos.split(";");//Ex check[0] = "remetente, email"; check[1] = "data_inicial, date";
	var retorno = true;//Este retorno implica no resultado final do método
	var valor = "";

	for(i = 0; i < check.length; i++){//Percorre todo o array check[]
		orFields = check[i].split("||");//Array armazena campos para verificação OR
		if(orFields.length > 1){//Verifica se há mais de um elemento no array
			var orCondicional = false;//Por padrão a condicional OR inicia false caso passe pelas validações torna-se true
			var msg = "";//Armazena uma mensagem personalizada no alert() caso a condição OR precise
			var orDisplay = "";//Armazena o id de um 
			for(j = 0; j < orFields.length; j++){//Percorre todo o array orFields
				andFields = orFields[j].split("&&");//Array armazena campos para verificação AND
				if(andFields.length > 1){
					andCondicional = true;
					for(k = 0; k < andFields.length; k++){//Percorre todo o array andFields
						//Aqui separamos os campos de seus validadores
						fields = andFields[k].split(","); //Ex fields[0] = "remetente" - fields[1] = "email"
						validation(checkFields("&&"),"&&");
						takeToAlert();//Obtem confiruação do tipo de alerta se exitir
					}

					if(andCondicional == true){
						orCondicional = true;
					}
				}else{
					//Aqui separamos os campos de seus validadores
					fields = orFields[j].split(","); //Ex fields[0] = "remetente" - fields[1] = "email"
					field = fields[0];//Capturando nome do campo
					valor = document.getElementById(field).value;//Valor do campo
					takeToAlert();//Obtem confiruação do tipo de alerta se exitir

					if(valor != ""){
						orCondicional = true;
						validation(valor);
					}
				}
			}
			if(orCondicional == false){
				showAlertOr();//Exibir mensagem de alerta de acordo com o tipo configurado
				retorno = false;
			}else{
				hideAlertOr();//Esconder mensagem de alerta
			}
		}else{
			//Aqui separamos os campos de seus validadores
			fields = check[i].split(",");//Ex fields[0] = "remetente" - fields[1] = "email"
			validation(checkFields());
		}
	}
	return retorno;

	//Funções de de base complexa
	function checkFields(type){
		field = fields[0].replace("!","");//Elimina o esterótipo !
		field = field.replace("#","");//Elimina o esterótipo !
		valor = trim(document.getElementById(field).value);//Retirando possiveis espaços em branco do campo a ser válidadoo
		document.getElementById(field).value = valor;

		if(fields[0].match("!") == null){//Verifica se o campo possui o esterótipo ! para não validá-lo
			if(fields[0].match("#") == null){//Verifica se o campo possui o esterótipo # para validá-lo com valor nulo
				if(valor == ""){//Se não possuir o esterótipo verifica se esta em branco
					verify(false,type);//Caso o campos esteja branco alerta
					andCondicional = false;
				}else{
					verify(true,type);//Caso o campos não esteja em branco tira o alerta
				}
			}
		}else{
			verify(true,type);//Caso o campos possua o esterótipo ! tira o alerta
		}
		return valor;
	}

	function verify(test,type){//Verifica se a condição é falsa para emitir o alerta
		idDisplay = document.getElementById(field).getAttribute("fvDisplay");
		if(test != true){
			if(type != "&&"){
				changeClass(field,document.getElementById(field).getAttribute("fvAlert"));//Muda a classe para dar maior visibilidade ao campo que deve ser preenchido
				if(verificar[i] == null){//Verifica se o campo já está com o flashbang ativo
					verificar[i] = setInterval("flashbang('#"+field+"')",1500);
				}
				showAlert();//Exibir mensgem de alerta
				retorno = false;//Este retorno implica no resultado final do método
			}else{
				showAlert();//Exibir mensgem de alerta
				andCondicional = false;
			}
		}else{
			hideAlert();//Esconder mensgem de alerta
			changeClass(field,document.getElementById(field).getAttribute("fvNormal"));
			verificar[i] = window.clearInterval(verificar[i]);
		}
	}

	function validation(valor, type){//Verifica se os campos possuem validações especiais
		if(valor != ""){
			//Funções internas e externas personalizadas
			for(ii = 1; ii < fields.length; ii++){//Percorre todos os campos em busca dos validadores
				if((fields[ii] == "email"))//Validar email
					verify(validaEmail(valor), type);
				else if((fields[ii] == "data"))//Valida data
					verify(validaData(valor), type);
				else if((fields[ii] == "hora"))//Valida hora
					verify(validaHora(valor), type);
				else if((fields[ii] == "cnpj"))//Valida cnpj
					verify(validaCnpj(valor), type);
				else if((fields[ii] == "cpf"))//Valida cpf
					verify(validaCpf(valor), type);
				else if((fields[ii] == "fone"))//Valida máscara de telefone
					verify(validaMaskTelefone(valor), type);
				else if((fields[ii] == "foneSimples"))//Valida máscara de telefone sem DDD
					verify(validaMaskTelefoneSimples(valor), type);
				else if((fields[ii] == "money"))//Válida mascará de campo monetário
					verify(validaMoney(valor), type);
				else if((fields[ii] == "nulo"))//Válida mascará de campo monetário
					verify(permiteNulo(valor), type);
				else if((fields[ii] == "minlength"))//Válida tamanho mínimo de um campo
					verify(minlength(field, valor), type);
				else if((fields[ii] == "igual"))//Compara se o valor do campo é igual a o valor de outro(s) campo(s)
					verify(igual(field, valor), type);
				else if((fields[ii] == "diferente"))//Compara se o valor do campo é diferente a o valor de outro(s) campo(s)
					verify(diferente(field, valor), type);
				else if((fields[ii] == "maiorIgual"))//Compara se o valor do campo é maior ou igual a o valor de outro(s) campo(s)
					verify(maiorIgual(field,valor), type);
				else if((fields[ii] == "menorIgual"))//Compara se o valor do campo é menor ou igual a o valor de outro(s) campo(s)
					verify(menorIgual(field, valor), type);
				else if((fields[ii] == "dataMaiorIgualHoje"))//Válida se a data é maior ou igual a data de hoje
					verify(dataMaiorIgualHoje(field, valor), type);
				else if((fields[ii] == "dataMenorIgualHoje"))//Válida se a data é menor ou igual a data de hoje
					verify(dataMenorIgualHoje(field, valor), type);
				else if((fields[ii] == "dataMaiorIgual"))//Válida se a data é maior ou igual a uma outra data
					verify(dataMaiorIgual(field, valor), type);
				else if((fields[ii] == "dataMenorIgual"))//Válida se a data é menor ou igual a uma outra data
					verify(dataMenorIgual(field, valor), type);
				else if((fields[ii] == "dataMaior"))//Válida se a data é maior a uma outra data
					verify(dataMaior(field, valor), type);
				else if((fields[ii] == "dataMenor"))//Válida se a data é menor a uma outra data
					verify(dataMenor(field, valor), type);
				else if((fields[ii] == "dataIgual"))//Válida se a data é igual a uma outra data
					verify(dataIgual(field), type);
			}
		}
	}
	//Fim

	//Funções de de base simples
	function takeToAlert(){//Verificar qual o tipo de mensagem configurado para exibir
		if((msg == "") || (msg == null)){
			msg = document.getElementById(field).getAttribute("fvMSG");//Atributo que contem campo a mensagem a ser exibida no alert()
		}
		if((orDisplay == "") || (orDisplay == null)){
			orDisplay = document.getElementById(field).getAttribute("fvOrDisplay");//Atributo que contem id do campo onde esta a mensagem
		}
	}

	function showAlertOr(){//Exibir mensagem configurada em condicional OR
		if((msg != "")&&(msg != null)){
			alert(msg);
		}
		if(orDisplay != null && orDisplay != ""){//Verificando se o atributo contem valor
			setDisplay(orDisplay,"block");//Ativar visibilid1ade do id1 indicado
		}
	}

	function hideAlertOr(){//Esconder mensagem em condição OR
		if(orDisplay != null && orDisplay != ""){
			setDisplay(orDisplay,"none");
		}
	}

	function showAlert(){//Exibir alerta global
		if(idDisplay != null && idDisplay != ""){
			setDisplay(idDisplay,"block");
		}
	}

	function hideAlert(){//Esconder alerta global
		if(idDisplay != null && idDisplay != ""){
			setDisplay(idDisplay,"none");
		}
	}
	//fim
}
//fim

/*
Validador de Campos Checkbox
Regras:
São passados 2 parametros sendo o segundo opcional.
Parametro campos: Armazena os campos a serem testados
Os campos devem ser passados separados por ; menos o último elelemento
Parametro modo:
Este é um atributo opcional ao qual se passa true para começar a condição como verdadeira ou false
Developed by Diego Felipe Rombaldi diegofeliper@gmail.com - All Rights Reserved
*/
selecionados = ""; //Esta variável armazena todos valores dos checkbox selecionados
function checkboxValidator(campos){
	selecionados = "";
	//Primeiramente separamos os campos junto com seus validadores
	var check = campos.split(";");
	len = check.length - 1;
	retorno = false;
	for(i = 0; i < len; i++){//Percorre todo o array check[]
		if(document.getElementById(check[i]).checked){//Verifica se há um campo selecionado
			selecionados = selecionados+document.getElementById(check[i]).value+";";
			retorno = true;
		}
	}
	selecionados = selecionados.substring(0,selecionados.length-1);//Elimina o último esterótipo ;
	return retorno; //Caso não encontre nenhum item selecionado
}

//Função para validar campos radioButton
function radioButtonValidator(campos){
	//Primeiramente separamos os campos junto com seus validadores
	var check = campos.split(";");
	len = check.length - 1;
	retorno = true;

	for(i = 0; i < len; i++){//Percorre todo o array check[]
		checked = false;
		for(ii=0; ii < document.getElementsByName(check[i]).length;ii++){//Percorre todo o grupo radio
			if(document.getElementsByName(check[i])[ii].checked){//verifica esta selecionado
				checked = true;
			}
		}
		if(checked == false){//Caso tenha passado por um grupo radio não selecionado retorna false
			return false;
		}
	}
	return retorno;
}

//Função para validar CNPJ
function validaCnpj(campo){
    CNPJ = campo;
    erro = new String;
	if (CNPJ == "00.000.000/0000-00"){
		alert("CNPJ inválido!");
		return false;
	}
    if (CNPJ.length < 18){
		erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
	}
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
        if (erro.length == 0){
			erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
		}
    }
	//substituir os caracteres que não são números
    if(document.layers && parseInt(navigator.appVersion) == 4){
        x = CNPJ.substring(0,2);
        x += CNPJ. substring (3,6);
        x += CNPJ. substring (7,10);
        x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
        CNPJ = x; 
    }else{
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace ("-","");
        CNPJ = CNPJ. replace ("/","");
    }
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)){
		erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
	}
    var a = [];
    var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
        a[i] = CNPJ.charAt(i);
        b += a[i] * c[i+1];
	}
    if ((x = b % 11) < 2){
		a[12] = 0;
	}else{
		a[12] = 11-x;
	}
    
	b = 0;
    for (y=0; y<13; y++) {
             b += (a[y] * c[y]);
	}
    if ((x = b % 11) < 2) {
		a[13] = 0;
	}else{
		a[13] = 11-x;
	}
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="CNPJ inválido!";
    }
    if (erro.length > 0){
		alert(erro);
        return false;
    }
    return true;
}
//fim

//Função para validar CPF
function validaCpf(campo){
	var i;
	s = campo;

	//substituir os caracteres que não são números
    s = s.replace(".","");
	s = s.replace(".","");
	s = s.replace("-","");

	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;

	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(10-i);
	} 

	if ((s == 11111111111)||(s== 22222222222)||(s== 33333333333)||(s==44444444444)||(s==55555555555)||(s==66666666666)||(s==77777777777)||(s==88888888888)||(s==99999999999)||(s==00000000000)){
		alert("CPF inválido!");
		return false;
	}

	if (d1 == 0){
		alert("CPF Invalido!");
		return false;
	}

	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;

	if (dv.charAt(0) != d1){ 
		alert("CPF Invalido!");
		return false;
	}

	d1 *= 2; 
	for (i = 0; i < 9; i++) { 
		d1 += c.charAt(i)*(11-i);
	} 

	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;

	if (dv.charAt(1) != d1){
		alert("CPF Invalido!");
		return false;
	}
return true; 
}
//fim

//Função para validar campos de data com máscaras
var reDate5 = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/([1][9][0-9][0-9]|[2][0][0-9][0-9])$/;

var data = 2;
function validaData(valor){
	eval("reDate = reDate" + 5);
	if (reDate.test(valor)) {
		return true;
	} else if (valor != null && valor != "") {
		alert(valor + " NÃO é uma data válida!\n\nA data deve ter 10 digitos ex: XX/XX/XXXX\n\nA data não pode ser menor que 01/01/1900.");
		return false;
	}
}
//fim

//Função para validar campos de hora com máscaras
function validaHora(valor){
	var mask = /^([0-1][0-9]|[2][0-3]):[0-5][0-9]$/;
	if (mask.test(valor)){
		return true;
	}else{
		if(valor != "" && valor != null){
			alert(valor + " não é um horário válido!");
		}
		return false;
	}
}
//fim

//validar email
var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail = reEmail3;

function validaEmail(valor){
	if (reEmail.test(valor)){
		return true;
	} else if (valor != null && valor != "") {
		alert(valor + " não é um endereço de e-mail válido.");
		return false;
	}
}

function validaMaskTelefone(valor){
	var mask = /^\(\d{2}\)\d{4}-\d{4}$/;
	if (mask.test(valor)){
		return true;
	}else{
		alert(valor + " não é um telefone válido.\n\nExemplo de preenchimento: xxxx-xxxx");
		return false;
	}
}
function validaMaskTelefoneSimples(valor){
	var mask = /^\d{4}-\d{4}$/;
	if (mask.test(valor)){
		return true;
	}else{
		alert(valor + " não é um telefone válido.\n\nExemplo de preenchimento: xxxx-xxxx");
		return false;
	}
}
function validaMoney(valor){
	var mask = /^\d{1,3}(\.\d{3})*\,\d{2}$/;
	if (mask.test(valor)){
		return true;
	}else{
		alert(valor + " não é um valor monetário válido");
		return false;
	}
}
//fim

////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// MÁSCARAS /////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

//Máscara para CNPJ
function mascaraCNPJ(campo){
	
		campo = document.getElementById(campo);
		separador = '.';
		separador1 = '/';
		separador2 = '-';
		conjunto = 2;
		conjunto1 = 6;
		conjunto2 = 10;
		conjunto3 = 15;
		if (campo.value.length == conjunto){
			campo.value = campo.value + separador;
		}
		if (campo.value.length == conjunto1){
			campo.value = campo.value + separador;
		}
		if (campo.value.length == conjunto2){
			campo.value = campo.value + separador1;
		}
		if (campo.value.length == conjunto3){
			campo.value = campo.value + separador2;
		}
}
//Fim

//Máscara para CPF
function mascaraCPF(campo){
	campo = document.getElementById(campo);
	separador = '.';
	separador1 = '-';
	if (campo.value.length == 3){
		campo.value = campo.value + separador;
	}
	if (campo.value.length == 7){
		campo.value = campo.value + separador;
	}
	if (campo.value.length == 11){
		campo.value = campo.value + separador1;
	}
}
//fim

//Máscara para campos monetários
function mascaraMoney(campo,tammax) {
	box = document.getElementById(campo);
	vr = box.value;

	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;

		if ( (tam > 2) && (tam <= 5) ){
			box.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 6) && (tam <= 8) ){
			box.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 9) && (tam <= 11) ){
			box.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 12) && (tam <= 14) ){
			box.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 15) && (tam <= 17) ){
			box.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
}
//fim

//Máscara para campo Telefone
function mascaraFone(campo){
	campo = document.getElementById(campo);
	separador1 = '(';
	separador2 = ')';
	separador3 = '-';
	if (campo.value.length == 1){
		campo.value = separador1+campo.value;
	}
	if (campo.value.length == 3){
		campo.value = campo.value + separador2;
	}
	if (campo.value.length == 8){
		campo.value = campo.value + separador3;
	}
}
//Fim

//Máscara para campo Telefone
function mascaraFoneSimples(campo){
	campo = document.getElementById(campo);
	separador = '-';
	if (campo.value.length == 4){
		campo.value = campo.value + separador;
	}
}
//Fim

//Máscara para hora
function mascaraHora(campo){
	campo = document.getElementById(campo);
	separador = ':';
	conjunto = 2;
	if (campo.value.length == conjunto){
		campo.value = campo.value + separador;
	}
}
//Fim

//Máscara para data
function mascaraData(campo){
	campo = document.getElementById(campo);
	separador = '/';
	if (campo.value.length == 2){
		campo.value = campo.value + separador;
	}
	if (campo.value.length == 5){
		campo.value = campo.value + separador;
	}
}
//Fim

//Máscara para campo CEP
function mascaraCEP(campo){
	campo = document.getElementById(campo);
	separador = '-';
	conjunto = 5;
	if (campo.value.length == conjunto){
		campo.value = campo.value + separador;
	}
}
//Fim

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////  SELECT MULTIPLE  ////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

//Funções para mover opção de um combo Select Multiple para outro um outro combo Select Multiple
function move(MenuOrigem, MenuDestino){
    var arrMenuOrigem = new Array();
    var arrMenuDestino = new Array();
    var arrLookup = new Array();
    var i;
    for (i = 0; i < MenuDestino.options.length; i++){
        arrLookup[MenuDestino.options[i].text] = MenuDestino.options[i].value;
        arrMenuDestino[i] = MenuDestino.options[i].text;
    }
    var fLength = 0;
    var tLength = arrMenuDestino.length;
    for(i = 0; i < MenuOrigem.options.length; i++){
        arrLookup[MenuOrigem.options[i].text] = MenuOrigem.options[i].value;
        if (MenuOrigem.options[i].selected && MenuOrigem.options[i].value != ""){
            arrMenuDestino[tLength] = MenuOrigem.options[i].text;
            tLength++;
        }
        else{
            arrMenuOrigem[fLength] = MenuOrigem.options[i].text;
            fLength++;
        }
    }
    arrMenuOrigem.sort();
    arrMenuDestino.sort();
    MenuOrigem.length = 0;
    MenuDestino.length = 0;
    var c;
    for(c = 0; c < arrMenuOrigem.length; c++){
        var no = new Option();
        no.value = arrLookup[arrMenuOrigem[c]];
        no.text = arrMenuOrigem[c];
        MenuOrigem[c] = no;
    }
    for(c = 0; c < arrMenuDestino.length; c++){
        var no = new Option();
        no.value = arrLookup[arrMenuDestino[c]];
        no.text = arrMenuDestino[c];
        MenuDestino[c] = no;
   }
}
//fim

//Função importante - Após finalizar a escolha das opções do select multiple
//os itens escolhidos devem ser passado para um campo do tipo hidden
function readSelectMultiple(origem, destino){
	var len = document.getElementById(origem).length;
	var str = '';
	for(var i=0; i<len; i++){
		str += document.getElementById(origem).options[i].value + ',';
	}
	str = str.substring(0,str.length-1);
	document.getElementById(destino).value = str;
}
//fim

////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////  FUNÇÕES AJAX  //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

//Powered by Diego Felipe Rombaldi diegofeliper@gmail.com
var xmlHttp;
function GetxmlHttpObject(){
	try{
		objxmlHttp = new XMLHttpRequest();// Mozilla, Safari, Firefox, etc...
		try {
			if (objxmlHttp.overrideMimeType) {
				//Se possível, ignora cabecalho usado pelo servidor e forca o padrao "text/xml". Alguns navegadores exigem esse padrao e pode dar erro se o servidor nao utilizar ele
				objxmlHttp.overrideMimeType('text/xml');
			}
		}catch(e1){ };
	}catch(e2){
		try{
			objxmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// Internet Explorer
		}catch(e3){
			try{
				objxmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// Internet Explorer
			}catch(e4){
				//tratamento para alguma outra forma de implementar XMLHTTP
				objxmlHttp = false;
			}
		}
	}
	return objxmlHttp;
}

/*
URL: página onde o ajax vai ser executado
METODO: método de envio de página. Pode ser POST ou GET
MODO: modo de solicitação da pagina. Pode ser True(Assincrôno) ou False(Sincrôno)
PARAMETROS: parametros de envio caso método POST
*/
function goAjax(url, metodo, modo, parametros, retorno){
	xmlHttp = GetxmlHttpObject();
	if (xmlHttp != null){
		if(metodo == "GET"){
			xmlHttp.open("GET", url+"&rnd="+ Math.random(), modo);
		}else{
			xmlHttp.open("POST", url+"&rnd="+ Math.random(), modo);
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=ISO-8859-1;");
			xmlHttp.setRequestHeader("Encoding","ISO-8859-1"); 
			xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			xmlHttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
			xmlHttp.setRequestHeader("Pragma", "no-cache");
		}

		//Para firefox 3.0+, chrome, ie8+ ou novos browsers quando o parametro modo é false ele ignora esta função
		
		/*xmlHttp.onreadystatechange = function() {
			if((xmlHttp.readyState == 4) || (xmlHttp.readyState=="complete")){
				if(modo == false){
					feedback = unescape("" + xmlHttp.responseText);
				}else{
					document.getElementById(retorno).innerHTML = unescape("" + xmlHttp.responseText);
				}
			}
		}*/
		xmlHttp.onreadystatechange = function() {
			if((xmlHttp.readyState == 4) || (xmlHttp.readyState=="complete")){
				if(modo == true){
					document.getElementById(retorno).innerHTML = unescape("" + xmlHttp.responseText);
				}
			}
		}

		if(metodo == "GET"){
			xmlHttp.send(null);
		}else{
			xmlHttp.send(parametros);
		}

		if(modo == false){
			feedback = unescape("" + xmlHttp.responseText);//
			return feedback;
		}else{
			return true;
		}
	}else{
		alert ("Este browser não suporta as funcionalidades do sistema.");
		return false;
	}
}
function stateChanged(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		setHTML(destino, unescape("" + xmlHttp.responseText));
	} 
}

//Função AJAX para ComboBox
function ajaxComboBox(url, destino, parametro){
	var destino;
	xmlHttp = GetxmlHttpObject();
	if (xmlHttp == null){
		alert ("Este browser não suporta HTTP Request");
		return false;
	}else{
		url=url+parametro;
		url=url+"&sid="+Math.random();
		this.destino = destino;
		xmlHttp.onreadystatechange=stateChanged;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
}

//Função para deletar elementos
function ajaxExcluir(url, metodo, parametros, carregar, excluir, retorno){
	if (confirm("Tem certeza que deseja excluir este registro?")){
		if(carregar != ""){
			setHTML(carregar, '<div align="center" class="carregando"><img src="../../images/adm/carregando.gif" width="20" height="20"></div>')
		}
		setHTML(retorno, goAjax(url, metodo, false, parametros, ''));
		feedback = feedback.indexOf("sucesso");
		if (feedback > -1){
			setDisplay(excluir, 'none');
		}
		setDisplay(retorno, 'block');
		setTimeout("setDisplay('"+retorno+"', 'none')",15000);

		return true;
	}else{
		return false;
	}
}

//Função para alterar status de elementos no banco de dados
function ajaxAlteraStatus(url, metodo, parametros, retorno, id1, id2){
	if (confirm("Tem certeza que deseja alterar o status deste registro?")){
		setHTML(retorno, goAjax(url, metodo, false, parametros, ''));
		if(document.getElementById(id1).style.display == "none"){
			setDisplay(id2, 'none');
			setDisplay(id1, 'block');
		}else{
			setDisplay(id2, 'block');
			setDisplay(id1, 'none');
		}
		setDisplay(retorno, 'block');
		setTimeout("setDisplay('"+retorno+"', 'none')",15000);

		return true;
	}else{
		return false;
	}
}

//Função para carregar conteúdo utilizando ToolTip e Ajax
function ajaxToolTip(url, metodo, parametros, carregar, elemento, retorno){
	if(carregar != ""){
		document.getElementById(carregar).innerHTML='<div align="center" class="carregando"><img src="../../images/adm/carregando.gif" width="20" height="20"></div>';
	}
	document.getElementById(elemento).setAttribute("tptitle", unescape("" + goAjax(url, metodo, modo, parametros, retorno)));
	document.getElementById(retorno).innerHTML='<div align="center"><img src="../../images/adm/'+parametros+'" width="20" height="20"></div>';
}
//FIM


////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////  TOOLTIP  ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

/*funções ToolTip - a função ToolTip subistitui a ação da propriedade title das tags
principal motivo de subistituir é o limite de tempo de exibição que o atributo title tem
/* Configuração  - Powered by Diego Felipe Rombaldi diegofeliper@gmail.com*/
var id = "minhaTooltip";
var background = "#F2F4FF";
var border = "1px solid #999999";
var display = "none";
var font = "10px Verdana, Arial, Sans-serif";
var color = "#225DCE";
var marginX = -30; //distancia do mouse em x
var marginY = 20; //distancia do mouse em y
var opacity = 90; // 0 a 100
var padding = "2px 5px";
var position = "absolute";
var _x = -10;
var _y = -10;

//Capturar posição do mouse
function setPos(event){
	if (document.all) {//IE
		_x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
		_y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		_x += (window.event.clientX+marginX);
		_y += (window.event.clientY+marginY);
	} else {//Família NetScape
		_x = (event.pageX+marginX);
		_y = (event.pageY+marginY);
	}
}
//Exibir ToolTip
function showTip(text) {
	var t = document.getElementById(id);
	t.style.display = "block";
	document.onmousemove = function(event) {
		setPos(event);
		t.innerHTML = text;
		t.style.left = _x+"px";
		t.style.top = _y+"px";
	}
}
//Fechar ToolTip
function hideTip() {
	var t = document.getElementById(id).style;
	t.display = "none";
}
//Área do ToolTip
function tooltip(tag) {
	/*
		o evento onReadyStateChange gerencia a mudança de estado do readyState
		complete - O objeto está completamente inicializado;
		loaded - acabou de carregar os seus dados;
		loading - está carregando seus dados ainda;
		interactive - mesmo sem estar completamente carregado, vc já pode interagir com ele;
		uninitialized - não está inicializado;
	*/
	if ((document.readyState=="complete")||(!document.all)){//função readyState estilo buffer que verifica se o objeto já foi totalmente carregado

		var body = document.getElementsByTagName("body");
		body = body[0];
		body.innerHTML += "<div id='"+id+"' style='text-align:left;font-weight: bolder;display:block'></div>";
		var t = document.getElementById(id).style;
		t.background = background;
		t.border = border;
		t.display = display;
		t.font = font;
		t.fontWeight = "bolder";
		t.color = color;
		t.opacity = opacity/100;
		t.filter = "alpha(opacity="+opacity+")";
		t.padding = padding;
		t.position = position;
		title = ""
		var tagName = document.getElementsByTagName(tag);
		for (i=0; i<tagName.length; i++) {
			var title = tagName[i].getAttribute("title");
			if (title != ""){
				tagName[i].setAttribute("tptitle", title);
				tagName[i].removeAttribute("title");
				tagName[i].onmouseover = function() { showTip(this.getAttribute("tptitle")); }
			}
			tagName[i].onmouseout = function() { hideTip(); }
		}
	}
}
//fim

////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////  CALENDÁRIO  //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

//FUNÇÃO PARA EXIBIR UM CALENDÁRIO
function calendario(){
	calendar = new Date();
	day = calendar.getDay();
	month = calendar.getMonth();
	date = calendar.getDate();
	year = calendar.getYear();

	if (year < 1000){
		year+=1900;
	}
	cent = parseInt(year/100);
	g = year % 19;
	k = parseInt((cent - 17)/25);
	i = (cent - parseInt(cent/4) - parseInt((cent - k)/3) + 19*g + 15) % 30;
	i = i - parseInt(i/28)*(1 - parseInt(i/28)*parseInt(29/(i+1))*parseInt((21-g)/11));
	j = (year + parseInt(year/4) + i + 2 - cent + parseInt(cent/4)) % 7;
	l = i - j;
	emonth = 3 + parseInt((l + 40)/44);
	edate = l + 28 - 31*parseInt((emonth/4));
	emonth--;
	var dayname = new Array ("Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sabado");
	var monthname = new Array ("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Juho","Agosto","Setembro","Outubro","Novembro","Dezembro" );

	d = new Date();
	hour = d.getHours();
	if(hour < 5){
		document.write("Navegando de madrugada? ");
	}else if(hour < 8){
		document.write("Acordou cedo. Bom dia! ");
	}else if(hour < 12){
		document.write("Tenha um bom dia! ");
	}else if(hour < 18){
		document.write("Boa Tarde! ");
	}else{
		document.write("Boa Noite! ");
	}
	document.write(dayname[day] + ", ");
	if (date< 10){
		document.write("0" + date + " de ");
	}else{
		document.write(date + " de ");
	}
	document.write(monthname[month] + " de ");


	document.write(year + ".    <font color=#6F7797>");
	// Páscoa
	if ((month == emonth) && (date == edate)) document.write("Domigo de Páscoa");

	// Janeiro
	if ((month == 0) && (date == 1)) document.write("Ano Novo");
	if ((month == 0) && (day == 1) && (date > 14) && (date< 22)) document.write("");

	// Fevereiro

	// Março

	// Abril
	if ((month == 3) && (date == 1)) document.write("Dia da Mentira");
	if ((month == 3) && (date == 21)) document.write("Tiradentes");

	// Maio
	if ((month == 4) && (date == 1)) document.write("Dia do Trabalho");
	if ((month == 4) && (date == 12)) document.write("Dia da Enfermagem");

	// Junho
	if ((month == 5) && (date == 12)) document.write("Dia dos Namorados");

	// Julho
	if ((month == 6) && (date == 4)) document.write("Dia Internacional do Cooperativismo");

	// Agusto
	if ((month == 7) && (date == 15)) document.write("Dia da Informática");

	// setembro
	if ((month == 8) && (date == 7)) document.write("Dia da Independência do Brasil");

	// Outubro
	if ((month == 9) && (date == 12)) document.write("Dia das Crianças");
	if ((month == 9) && (date == 19)) document.write("Dia do Profissional da Informática");
	if ((month == 9) && (date == 31)) document.write("Halloween");

	// November
	if ((month == 10) && (date == 2)) document.write("Dia de Finados");
	if ((month == 10) && (date == 15)) document.write("Proclamação da República");
	if ((month == 10) && (date == 20)) document.write("Dia Nacional da Consciência Negra");

	// December
	if ((month == 11) && (date == 24)) document.write("Véspera de Natal");
	if ((month == 11) && (date == 25)) document.write("Natal");
	if ((month == 11) && (date == 31)) document.write("Véspera de Ano Novo");

	document.write("</font>");
}
//fim


////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////  CRIPTOGRAFIA  /////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      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 + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = 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);
      }
   } while (i < input.length);

   return output;
}
//fim

//Verifica qual o navegador + versão e o sistema operacional
function versionNavigator(){
	var detect = navigator.userAgent.toLowerCase(); 
	var OS,browser,version,total,thestring; 
	 
	if (checkIt('konqueror')){
		browser = "Konqueror"; 
		OS = "Linux"; 
	} 
	else if (checkIt('chrome')) browser = "Chrome";
	else if (checkIt('firefox')) browser = "FireFox";
	else if (checkIt('safari')) browser = "Safari";
	else if (checkIt('omniweb')) browser = "OmniWeb";
	else if (checkIt('opera')) browser = "Opera";
	else if (checkIt('webtv')) browser = "WebTV"; 
	else if (checkIt('icab')) browser = "iCab";
	else if (checkIt('msie')) browser = "Internet Explorer";
	else if (!checkIt('compatible')){
		browser = "Netscape Navigator" 
		version = detect.charAt(8); 
	}
	else browser = "Desconhecido"; 
	 
	if (!version) version = detect.charAt(place + thestring.length); 
	 
	if (!OS){
		if (checkIt('linux')) OS = "Linux"; 
		else if (checkIt('x11')) OS = "Unix"; 
		else if (checkIt('mac')) OS = "Mac" 
		else if (checkIt('win')) OS = "Windows" 
		else OS = "Desconhecido"; 
	} 
	 
	function checkIt(string){
		place = detect.indexOf(string) + 1; 
		thestring = string; 
		return place; 
	}
	versao = browser+";"+version+";"+OS;
	return versao;
}

//outras funções - imagens
function FP_preloadImgs() {//v1.0
 var d=document,a=arguments; if(!d.FP_imgs) d.FP_imgs=new Array();
 for(var i=0; i<a.length; i++) { d.FP_imgs[i]=new Image; d.FP_imgs[i].src=a[i]; }
}

function FP_swapImg() {//v1.0
 var doc=document,args=arguments,elm,n; doc.$imgSwaps=new Array(); for(n=2; n<args.length;
 n+=2) { elm=FP_getObjectByID(args[n]); if(elm) { doc.$imgSwaps[doc.$imgSwaps.length]=elm;
 elm.$src=elm.src; elm.src=args[n+1]; } }
}

function FP_getObjectByID(id,o) {//v1.0
 var c,el,els,f,m,n; if(!o)o=document; if(o.getElementById) el=o.getElementById(id);
 else if(o.layers) c=o.layers; else if(o.all) el=o.all[id]; if(el) return el;
 if(o.id==id || o.name==id) return o; if(o.childNodes) c=o.childNodes; if(c)
 for(n=0; n<c.length; n++) { el=FP_getObjectByID(id,c[n]); if(el) return el; }
 f=o.forms; if(f) for(n=0; n<f.length; n++) { els=f[n].elements;
 for(m=0; m<els.length; m++){ el=FP_getObjectByID(id,els[n]); if(el) return el; } }
 return null;
}