/**
 * Verifica se os campos do formulário são válidos
 */
function BENV_isCamposValidos(objForm) {
	//Varre o formulário procurando por campos obrigatórios
	var elementosParaDesabilitar = new Array();
	
	var length = objForm.length;
	for (var iCampo=0;iCampo<length;iCampo++) {
		var obj = objForm[iCampo];
		//procura por elementos que precisam ser desabilitados no submit
		if(new String(obj.getAttribute('desabilitaOnSubmit')).toUpperCase() == "TRUE"){
			elementosParaDesabilitar.push(obj);
		}
		var objName = obj.name;
        //verifica se não é a linha -1 da grid
    	if (objName != "" && objName != "null")  {
			//Verifica se não está com readonly ou disabled..
		    if(new String(obj.getAttribute('disabled')).toUpperCase() != "TRUE"){
	            //Faz a validação do campo
	            if (!C_verificaValor(obj)) {
            		if(obj.offsetHeight != 0 || C_exibeDivSubtitleCampo(obj)){
				    	obj.focus();    
				    }	
            		var formatType = obj.getAttribute('formatType');
            		exibeMensagem(formatType, obj);
            		return false;
        		}       		        		        		
	            if (new String(obj.getAttribute('obrigatorio')).toUpperCase() == "TRUE") {
	            	//verifica se o registro foi excluido.
	            	var isExcluido = false;
					var grid = getGrid(obj);
					if(grid != null){
						var index = getFieldIndex(obj.id);
						var idAcao = getColumnId(grid, "status", index);
						var acao = new String(document.getElementById(idAcao).value);
						isExcluido = (acao.charAt(0) == 'D');
					}
					//verifica se o campo faz parte da chave primária
					var pk = obj.getAttribute('pk');
					var isPk = false;
					if(pk != null){
						isPk = (new String(pk).toUpperCase() == "TRUE");
					}
					//Verifica se o valor do campo é valido
					//Verifica se o campo está preenchido
	                if(!isExcluido || isPk){
						if (!C_verificaObrigatorio(obj)) {
							return false;
						}
	    	        }
	            }	            	            	            	            
	        }
	        
	        //Verifica se é necessário a desformatação do campo numérico
        	if(new String (obj.getAttribute('formatType')).toUpperCase() == 'NUMBER' && new String (obj.getAttribute('desformataOnSubmit')).toUpperCase() == "TRUE"){
        		obj.value = CN_getValorDesformatado(obj.value);             		
        	}
	        
        }
	}
	
	//concatena o dia(first ou last) nas datas da tag formatedDate e verifica se o intervalo é válido	
	if(!verificaFormatedDate(objForm)){
		return false;	
	}
	
	var elementosParaDesabilitarLenght = elementosParaDesabilitar.length;
	for(var i = 0; i < elementosParaDesabilitarLenght; i++){
		var obj = elementosParaDesabilitar[i];
		obj.disabled = true;
	}
	
	
	//BENV_exibeProcessando();
    return true;
}

function applySubmit(objForm, apply){
	if(objForm != null){
		var objTarget = objForm.target;
		var tname_lc = new String(objTarget).toLowerCase();
		var isSameWindow = objTarget == "" || 
				tname_lc == "_self" || objTarget == window.name;
		if(apply && isSameWindow){
			FF_desabilitaBotoes(objForm);
		}
	}
	return apply;
}

function exibeMensagem(formatType, input){
	switch(formatType){
		case 'DATE': {
			alert(msgKey("label.js.dataInvalida",input.value));
		    break;
		}
		case 'CPF': {
			alert(msgKey("label.js.cpfInvalido",input.value));
		    break;
		}
		case 'CNPJ': {
			alert(msgKey("label.js.cnpjInvalido",input.value));
		    break;
		}
		case 'EMAIL': {
			alert(msgKey("label.js.emailInvalido",input.value));
		    break;
		}
		case 'NUMBER': {
			alert(msgKey("label.js.valorInvalido",input.value));
		    break;
		}
		case 'MASK': {
			alert(msgKey("label.js.valorInvalido",input.value));
		    break;
		}
		case 'FORMATEDDATE': {
			alert(msgKey("label.js.dataInvalida",input.value));
		    break;
		}
		case 'INTERVALO': {
			alert(msgKey("label.js.intervaloDatas",input.value));
		    break;
		}
		
	}
}

/**
 * Evento OnClick
 */
function BENV_CLK(ctrl) {
	//pega o objeto form mais proximo
	//objForm = FF_GetForm(ctrl);
    objClicado = ctrl;
}

/**
 * Exibe a imagem de processando no meio da tela
 */
function BENV_exibeProcessando() {
	objBody = document.getElementsByTagName("BODY")[0];
	objLayer = document.createElement("DIV");
	objLayer.className = "processando";

	alturaPag = document.body.clientHeight;
	larguraPag = document.body.clientWidth;
	posScroll = document.body.scrollTop;
	largura = 200
	altura = 40
	
	objLayer.style.left = (larguraPag - largura) / 2;
	objLayer.style.top = (alturaPag - altura) / 2 + posScroll;	

	objBody.appendChild(objLayer);
}

function verificaFormatedDate(objForm){
	var componentesAlterados = new Array();
	var length = objForm.length;
	for (var iCampo=0;iCampo<length;iCampo++) {
		var obj = objForm[iCampo];
		var objName = obj.name;
		var objValue = obj.value;
		//concatena o dia desejado à data informada
		if(new String(obj.getAttribute('appendDay')).toUpperCase() == "FIRST" || 
			new String(obj.getAttribute('appendDay')).toUpperCase() == "LAST"){
	       	obj.value = appendDay(objValue, new String(obj.getAttribute('appendDay')).toUpperCase());
	       	componentesAlterados.push(obj);
	    }
		//verifica o intervalo
	    var compareId = obj.getAttribute('compareId');
	    if(new String(compareId) != null && new String(compareId) != "" 
		   && new String(compareId) != "null" && new String(obj.getAttribute('formatType')) == "FORMATEDDATE"){
	    	var outroDate = document.getElementById(compareId);
	    	var intervaloValido = verificaIntervaloDatas(new String(outroDate.value), new String(obj.value));
	    	if(!intervaloValido){	    		
	    		var tamanhoComponentesAlterados = componentesAlterados.length;
	    		for(var i=0;i<tamanhoComponentesAlterados;i++){
	    			var componente = componentesAlterados[i];
	    			var componenteValue = componente.value;
	    			if(new String(componenteValue).length == 10 && 
	    				(new String(componente.getAttribute('appendDay')).toUpperCase() == "FIRST" || 
	    				new String(componente.getAttribute('appendDay')).toUpperCase() == "LAST")){
	            		componente.value = new String(componenteValue).substring(3);
	            	}
	    		}
	    		obj.focus();
	    		exibeMensagem("INTERVALO", obj);
	    		return false;
	    	}
	    }
	}
	return true;
}

function verificaIntervaloDatas(dtIni, dtFim){	
	if(dtIni.length == 7){
		dtIni = "01/"+dtIni;
	}
	if(dtFim.length == 7){
		dtFim = "01/"+dtFim;
	}
	if(!Date.strToDate(dtIni).before(Date.strToDate(dtFim))){
		return false;
	}
	return true;
}
