//////////////////////////////////////////////////////////////////////////////////////////////////////
// CLASSE DE MENSAGEM JAVASCRIPT / PROTOTYPE
//////////////////////////////////////////////////////////////////////////////////////////////////////
var Utilidades = 
{
	//////////////////////////////////////////////////////////////////////////
	// CSS QUE ESTÁ SENDO UTILIZADA
	//////////////////////////////////////////////////////////////////////////
	classe: 'saga',
	//////////////////////////////////////////////////////////////////////////
	
   validar: function(id_frm){
		var Valido = true;  // VORMULARIO VALIDO
		var Foco = false;   // ELEMENTO JÁ FOCADO
		
		// RETORNA TODOS OS ELEMENTOS DO FORMULARIO PASSADO
		$(id_frm).getElements().each
		( 
			function (Elemento) 
			{
				// VERIFICA SE O ELEMENTO É OBRIGATORIO
				if (Elemento.className.endsWith('_obrigatorio'))
				{
					// VERIFICA SE O ELEMENTO ESTÁ VAZIO
					if (Elemento.value.blank() || Elemento.value == '-1')
					{
						// CANCELA O FORMULARIO
						Valido = false;
						//_________________________________________________________
						
						// VERIFICA SE OUTRO ELEMENTO JÁ ESTÁ COM O FOCO
						if (!Foco)
						{
							Foco = true;
							if (Elemento.type != 'hidden')
							Elemento.focus();
						}
						//_________________________________________________________
						
						// VERIFCA SE EXISTE A IMAGEM ANIMADA
			            if (Elemento.id && $('img_'+Elemento.id)){
			                $('img_'+Elemento.id).show();
			            }else if ( $('img_'+Elemento.name) ){
			                $('img_'+Elemento.name).show();
			            }
						//_________________________________________________________						
					}
					else
					{
			            if (Elemento.id && $('img_'+Elemento.id)){
			                $('img_'+Elemento.id).hide();
			            }else if ( $('img_'+Elemento.name) ){
			                $('img_'+Elemento.name).hide();
			            }
						//_________________________________________________________
					}
					//_________________________________________________________
				}
				//_________________________________________________________
			} 
		);
		//_________________________________________________________
		
		// RETORNA SE O FORMULARIO É VALIDO
		return Valido;
		//_________________________________________________________
	}
	
,
	
	grid_checa_excluir_todos : function(frm,retorno)
	{
	 	$(frm).getInputs('checkbox').each(
	 		function (elemento, indice)
	 		{ 
	 			elemento.checked=retorno; 
	 		}
	 	); 
	}
	
,
	defineMascara : function(campo, mask, evt)
	{
 	
	 	if(navigator.appName.indexOf('Internet Explorer')>0){
			tecla = evt.keyCode;
		}else{
			tecla = evt.which;
		}
		
	   if (((tecla >= 48 && tecla <= 57) || tecla == 0 || tecla == 8 || tecla == 13 || tecla == 37 || tecla == 38 || tecla == 39 || tecla == 40 || tecla == 45 || tecla == 46 || tecla == 188) && (campo.value.length < mask.length+1)){
	   
 	   	if(tecla != 8 && tecla != 46 && tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40 && tecla != 0 && (campo.value.length <  mask.length)){

		    vCampo = campo.value;     
		    tCampo = vCampo.length;   
		    tMask = mask.length;        
		    vFinal = "";              
				   
			for (i=0; i<tCampo; i++) {
		        vCampo = vCampo.replace ("-", "");
				vCampo = vCampo.replace (".", "");
				vCampo = vCampo.replace (",", "");
		        vCampo = vCampo.replace ("/", "");
		        vCampo = vCampo.replace (" ","");
		        		
		    }  
		    
		    tCampo = vCampo.length;   
		    pMask = tMask-1;     
		    
		    for (i=0;i<tCampo;i++) {
		        pMask--;
		        while (mask.charAt(pMask) != "#") {
		            pMask--;
		        }		
		    }
		
		    cont = 0;
		    
		    for (i=pMask;i<tMask;i++) {  
		        if (mask.charAt(i) == "#") {            
		            vFinal = vFinal + vCampo.charAt(cont);            
		            cont++;
		        }
		        else {
		            vFinal = vFinal + mask.charAt(i);             
		        }
		    }    
		    
		    campo.value = "";
		    campo.value = vFinal;   
		}
		    return true;
		    
	    }else{

	    	return false;
	    	
	    }
	}
	
	
	/***********************************************************************************************
     * @name:		checaCaracterDigitado()
     * @params: 	evento	[integer]	Propriedade event da ação
     *				id	[string]		Atributo 'id' do campo onde está sendo digitado	
     * @abstract: 	função para validar caracteres permitidos
     * @return:		void		
     * @exemple:	onKeyPress = "return checaCaracterDigitado(event, this.value);"
     ************************************************************************************************/	
	,checaCaracterDigitado : function(evento, id){
		//Pegando o codigo da tecla digitada
		intCodigo = (evento.keyCode) ? evento.keyCode : evento.charCode;
		
		//Pegando o campo value do objeto
		valor = $F(id);

		// Verificando se a primeira casa é um '.'
		if (valor.length == 0 && intCodigo == 46){	
			return false;		
		}
	
		// Verificando a existencia do caracter '.'
		int = 0;
		if (intCodigo == 46){			
			for (i=0;i<valor.length;i++){
				if (valor[i] == '.'){
					int++;
					if (int>0){
						valor[i] = ''; 
						return false;	
					}					
				}
			}		
		}
		
		// Verificando caracteres permitidos [numeros]
		if ( (intCodigo < 48 && intCodigo != 8 && intCodigo != 0 && intCodigo != 13 && intCodigo != 46  && intCodigo != 9) || (intCodigo > 57) ){ return false; }
	}
	//------------------------------------------------------------------------------------------------------------------------------------------------------------------
	//FUNCAO PARA EXECUTAR AJAX
	,makeAjax : function(arquivo, div, parametros, pBar)
	{
		new Ajax.Request
			(arquivo,
			 {
			 	method		: 'post',
			 	parameters	: "AJAX=true&"+parametros,
			 	asynchronous: true,			 	
			 	onSuccess	: function (variavelRetorno) { $(div).innerHTML = variavelRetorno.responseText; Utilidades.extraiScript(variavelRetorno.responseText);},
			 	onFailure   : function () { MensagemPrototype.informacao('Erro na requisição do Ajax.') },
			 	onLoading   : function () { if (pBar) $(div).update("<center><img src='http://"+document.domain+"/saga/design/padrao/imagens/progressbar_saga.gif'></center>"); }
			 }
			);			
	}
	
	
	/***********************************************************************************************
     * @name:		marcaTodosValoresSelect()
     * @params: 	id		[string]	Atributo 'id' da select a ser trabalhada
     *				valor	[boolean]	Booleano para selecionar ou não os valores
     * @abstract: 	método para selecionar todos os valores de uma select multipla
     * @return:		void		
     * @example:	onClick = "Utilidades.marcaTodosValoresSelect('idSelect',this.checked);"
     ************************************************************************************************/	
	,marcaTodosValoresSelect : function(id, valor){
		var valores = $(id).options.length;
		for(i=0;i<valores;i++){ 
			$(id).options[i].selected = valor;
		}
	}
	
	/***********************************************************************************************
     * @name:		validaMarcaTodosValoresSelect()
     * @params: 	id		[string]	Atributo 'id' da select a ser trabalhada
     *				idAll	[string]	Atributo 'id' do checkbox 'Todos'
     * @abstract: 	método para validar se ao selecionar (ou não) o valor, irá marcar ou desmarcar o checkbox 'Todos'
     * @return:		void		
     * @example:	onClick = "Utilidades.validaMarcaTodosValoresSelect('idSelect', 'idChekboxTodos');"
     ************************************************************************************************/		
	,validaMarcaTodosValoresSelect : function(id, idAll){
		var CheckAll = true;
		var valores = $(id).options.length;
		for(i=0;i<valores;i++){ 
			if ($(id).options[i].selected == false){
				CheckAll = false;
			}
		}	
		$(idAll).checked = CheckAll;	
	}	
	
	,validarDatas: function(dataInicial, dataFinal, idImagem){
		//Inicializando variaveis
		var erro 		= false;
		var dataInicio 	= $F(dataInicial);
		var dataFim 	= $F(dataFinal);
		
		//Verificando se alguma data não foi preenchida
		if (dataInicio.blank() || dataFim.blank()){			
			erro = true;		
		}else{
			//Montando objeto date com as datas digitadas
			var dataVencimentoInicio = retornaObjDate(dataInicio);
			var dataVencimentoFim	 = retornaObjDate(dataFim);
			
			//Verificando se a data início é maior do que a data fim			
			if (dataVencimentoInicio > dataVencimentoFim){
				erro = true;
			}			
		}
		
		//Caso não tenha dado erro na validação das datas
		if (!erro){
			if ($(idImagem)) $(idImagem).hide();
			return true;
		}else{
			if ($(idImagem)) $(idImagem).show();
			return false;
		}
		
	}
	
	,
	
	/*
	 * Limita os caracteres de um textArea
	 * 
	 * @name	limitaCaracteresTextArea
	 * @param	idTextArea
	 * @param	idContadorRestante
	 * @param	limite
	 * @return	void
	 */
	limitaCaracteresTextArea : function(idTextArea,idContadorRestante,limite){
	    var textoInicial 			= $F(idTextArea);
	    var textoFinal 				= '';
	    var contadorRestante 		= limite;
	    textoFinal 					= textoInicial.substr(0,limite); 
	    contadorRestante			= limite - textoFinal.length;
	    $(idContadorRestante).update(contadorRestante);
	    $(idTextArea).value 		= textoFinal;    
	}
	
	
	
	
	,
	extraiScript : function(texto){
        // inicializa o inicio ><
        var ini = 0;
        // loop enquanto achar um script
        while (ini!=-1){
            // procura uma tag de script
            ini = texto.indexOf('<script', ini);
            // se encontrar
            if (ini >=0){
                // define o inicio para depois do fechamento dessa tag
                ini = texto.indexOf('>', ini) + 1;
                // procura o final do script
                var fim = texto.indexOf('</script>', ini);
                // extrai apenas o script
                codigo = texto.substring(ini,fim);
                // executa o script
                //eval(codigo);
                /**********************
                * Alterei pois com o eval não executava funções.
                ***********************/
                novo = document.createElement("script")
                novo.text = codigo;
                document.body.appendChild(novo);
            }
        }
    }	
	
}