// JavaScript Document 
// 

/**     Versão: 1-1-1 a
	O arquivo validacao.js contem as principais funções, utilizadas pelos validadores produzidos para o JSF, 
	necessárias para validacao no cliente dos formulários.
        
*/



/**
        Função que subimete a página sem validá-la
        Ideal para o uso do imediate.

*/

function submitSemValidacao(elemento){
    
    while ((elemento.tagName != "FORM") && (elemento.tagName !="BODY")){
        elemento = elemento.parentNode;
    }
    if (elemento.tagName == "FORM"){
        elemento.validadorMestre.validar = false;
        elemento.submit();
    }
}

/**	
	Classe que contém todos os outros validadores e que chama os métodos de validação de cada objeto e
	gerencia a comunicação entre o MensageiroMestre
*/

function ValidadorMestre(){
	this.validar = true;
	this.validadores = new Array();
	this.mensageiro = new MensageiroMestre();
	this.foco;

	// Adiciona um validador a lista de validadores
	this.adicionarValidador = function (obj){
		if (this.validadores.length == null) this.validadores[0] = obj;
		else  this.validadores[this.validadores.length] = obj;
	}

	//Testa se o validador passou na validação caso contrário ele passa para os parâmetros ErrorDetail, ErrorSumary e clientIdComponente
	//para o MensageiroMestre.
	this.testarValidador = function (){
                this.resultado = true;
		this.mensageiro.limparMensagens();
		if (this.validar){
			for (var i=0; i < this.validadores.length; i++){				
				if (this.validadores[i].testar() == false){
                                        this.resultado = false;
					this.mensageiro.setMensagem(this.validadores[i].getErrorDetail(), this.validadores[i].getErrorSummary(), this.validadores[i].getClientIdComponent());
					if (this.foco==null){
                                                // não funcionou no IE7                                                
						//this.foco = document.getElementById(this.validadores[i].getClientIdComponent());
                                                this.foco = 1;
                                                document.getElementById(this.validadores[i].getClientIdComponent()).focus();
                                        }
				}
			}
			this.mensageiro.exibePopup();
                        // não funcionou no IE7    
			//this.foco.focus()
			this.foco = null;
		}

            return this.resultado;
            //document.getElementById('form').submit();
	}
	
	this.setValidar = function (newValue){
		this.validar = newValue;
	}
	
	// Métodos Get e Set das variáveis
	this.getValidar=function (){
		return this.validar;
	}
}


/** 
	Classe que valida os objetos 
*/
function Validador (errorDetail,errorSummary,clientIdComponent){
	this.errorDetail = errorDetail;
	this.errorSummary = errorSummary;
	this.clientIdComponent = clientIdComponent;
	
	this.getErrorDetail = function (){
		return this.errorDetail;		
	}
		this.getErrorSummary = function (){
		return this.errorSummary;		
	}
		this.getClientIdComponent = function (){
		return this.clientIdComponent;		
	}
}
/**	
	Classe que contém todos os outros mensageiros e que chama os métodos de exibição de mensagens
	e exibe o alert final.
*/
function MensageiroMestre(){
	this.mensagens = new Array();
	this.mensagemPopup = "";
	this.mensagensGlobais = new Array();

	this.adicionarMensagemGlobal = function (obj){
	
		if (this.mensagensGlobais.length == null)
			this.mensagensGlobais[0] = obj;
		else
			this.mensagensGlobais[this.mensagensGlobais.length] = obj;
	}

	// Método que exibi a mensagem de popup
	this.exibePopup = function (){
		for (i=0;i<this.mensagensGlobais.length;i++){
			this.mensagemPopup += this.mensagensGlobais[i].getMensagemPopup();
		}
		if ((this.mensagemPopup != "undefined") && (this.mensagemPopup != ""))
			alert (this.mensagemPopup);
	}
	
	// Este método limpa as mensagens de erro exibidas 
	this.limparMensagens = function (){
		this.mensagemPopup="";
		for(var i=0; i < this.mensagens.length; i++){
			var objeto = document.getElementById(this.mensagens[i].getClientIdMensagem());
			while(objeto.hasChildNodes()){
				objeto.removeChild(objeto.firstChild);
			}
		}
		for (i=0;i<this.mensagensGlobais.length;i++){
                        var objeto = document.getElementById(this.mensagensGlobais[i].getClientIdMensagem());
                        while(objeto.hasChildNodes()){
				objeto.removeChild(objeto.firstChild);
                                this.mensagensGlobais[i].setMensagemPopup("");
                        }
                }
	}
	
	// Adiciona um novo objeto mensagem a lista de mensagens
	this.adicionarMensagem = function (obj){
		if (this.mensagens.length == null)
				this.mensagens[0] = obj;
		else
				this.mensagens[this.mensagens.length] = obj;
		
	}
	// Seta a mensagem para cada componente mensagem fazendo um for em todas as mensagems existentes
	this.setMensagem = function (errorDetail , errorSummary , clientIdComponent){
		for(var i=0; i < this.mensagens.length; i++){
			if (this.mensagens[i].getClientIdComponent() == clientIdComponent){
				this.mensagemPopup += this.mensagens[i].exibeMensagem(errorDetail,errorSummary);
			}
		}
		for (i=0;i<this.mensagensGlobais.length;i++){
			this.mensagensGlobais[i].exibeMensagem(errorDetail,errorSummary);
		}
	}
}


function MensagemGlobal (clientIdMensagem, popup, display, showSummary, showDetail, title){
	this.clientIdMensagem = clientIdMensagem;
	this.popup = popup;
        this.title = title;
	this.display = display;
	this.showSummary = showSummary;
	this.showDetail = showDetail;
	this.mensagemPopup = "";

	this.setMensagemPopup = function(newValue){
		this.mensagemPopup = newValue;
	}
	this.getMensagemPopup = function(){
		return this.mensagemPopup;
	}
	// Método que exibi a mensagem de erro via display
	// e se showPopup for true ele retorna a mensagem que será exibida via alert
	this.exibeMensagem = function (errorDetail, errorSummary){
			this.texto = document.createTextNode("");
			if (this.display){
				if (this.showSummary){
					this.texto.appendData(errorSummary+"-");
				}
				if (this.showDetail){
					this.texto.appendData(errorDetail);
				}
				document.getElementById(this.clientIdMensagem).appendChild(this.texto);						
			}
		
			// necessário para a Classe MensagemMestre concatenear as mensagens de alerta
		if (this.popup){
			if (this.showSummary){
				this.mensagemPopup += errorSummary + "\n";
			}
			if (this.showDetail){
				this.mensagemPopup += errorDetail + "\n";
			}
		
		}
	}
	this.getClientIdMensagem = function (){
		return this.clientIdMensagem;		
	}
}

function Mensagem (clientIdComponent, clientIdMensagem, popup, display, showSummary, showDetail){
	this.clientIdComponent = clientIdComponent;
	this.clientIdMensagem = clientIdMensagem;
	this.popup = popup;
	this.display = display;
	this.showSummary = showSummary;
	this.showDetail = showDetail;
	
	// Método que exibi a mensagem de erro via display
	// e se showPopup for true ele retorna a mensagem que será exibida via alert
	this.exibeMensagem = function (errorDetail, errorSummary){
		this.texto = document.createTextNode("");
		if (this.display){
			if (this.showSummary){
				this.texto.appendData(errorSummary+" ");
			}
			if (this.showDetail){
				this.texto.appendData(errorDetail);
			}
			document.getElementById(this.clientIdMensagem).appendChild(this.texto);						
		}
		// necessário para a Classe MensagemMestre concatenear as mensagens de alerta
		if (this.popup){
			this.mensagem = "";
			if (this.showSummary){
				this.mensagem += errorSummary + "\n";
			}
			if (this.showDetail){
				this.mensagem += errorDetail + "\n";
			}
			return this.mensagem;			
		}
	}
	this.getClientIdComponent = function (){
		return this.clientIdComponent;		
	}
        
        this.getClientIdMensagem = function (){
            return this.clientIdMensagem;
        }

	
}
