/**
* Biblioteca com funções genéricas JavaScript
* 
* 
**/


function Impressao( preVisualizar ) 
{
	document.body.innerHTML = ImprimirConteudo.innerHTML;
	if( preVisualizar ) 
	{
		PreVisualizar();
	} 
	else 
	{
		window.print();
	}
	document.body.innerHTML = CorpoMensagem;
}

remover = function(form,acao,modulo) {
	if (confirm("Deseja realmente excluir ?")) {
		form.method="post";
		form.action = "?acao="+acao+"&modulo="+modulo;
		form.submit();
	}

}

desabilita = function(codigo,modulo) {
	if (confirm("Essa ação impossibilitará que o item seja lido no sistema. \n\n Continuar ?")) {
		var form = document.forms[0];
		form.action = "?acao=desabilita&modulo="+modulo;
		form.submit();
	}
}

removerInterface = function(form,acao,modulo) {
	form.target = "processador";
	remover(form,acao,modulo);
}

removerPassandoCodigo = function(form,acao,modulo,codigo,processaParalelo) {
	
	form.codigo.value = codigo;
	if (processaParalelo) {
		removerInterface(form,acao,modulo);
	} else {
		remover(form,acao,modulo);
	}
}

getValorCheckBox = 
	function(form,nomeDoGrupo) {
		for (var i=0;i<form.elements[nomeDoGrupo].length;i++) {
			if (form.elements[nomeDoGrupo][i].checked) {
				return form.elements[nomeDoGrupo][i].value;
			}
		}
}


/* Marca/desmarca todos os checks com o nome no formato "[nome]_#"
 * Onde # é um número sequencial iniciado por 1
 */
function marcarTudo(objControle,nomeObj) {
	var i = 1;
	if (objControle == null) {
		while (document.getElementById(nomeObj+"_"+i) != null) {
			
			document.getElementById(nomeObj+"_"+i).checked = true;
			i++;
		}
	} else {
		
		while (document.getElementById(nomeObj+"_"+i) != null) {
			
			if (objControle.checked) {
					document.getElementById(nomeObj+"_"+i).checked = true;
			} else {
					document.getElementById(nomeObj+"_"+i).checked = false;
			}
		
			i++;
		}
	}
}

/* Retorna verdadeiro caso os campos com o nome no formato "[nome]_#" estejam preenchidos ou selecionados
 * Onde # é um número sequencial iniciado por 1
 */
function temItemSelecionado(nomeObj) {
	
	var i = 1;
	while (document.getElementById(nomeObj+"_"+i) != null) {
		if (!vazio(document.getElementById(nomeObj+"_"+i), ""))
			return true;
		i++;
	}
	return false;
}


// Verifica se o campo está vazio
// No caso de tipo checkbox, verifica se o mesmo está marcado
// Caso exista mensagem e o resultado seja falso, exibe-a ao usuário
function vazio(obj, mensagem) {
	var result = true;
	if (obj != null) {
		if ((obj.type == "text") || (obj.type == "hidden") || (obj.type == "file") || (obj.type == "select-one") || (obj.type == "password") || (obj.type == "textarea"))
			result = (obj.value == "");
		else {
			// Validação de select com multipla opções
			if (obj.type == "select-multiple") {
				for (var i = 0; i < obj.length; i++)
					if (obj[i].selected) result = false;
			}
			else {
				if (obj.type == "checkbox") {
					result = (!obj.checked);					
				}
				else {
					// Validação de radio button
					if ((obj.length > 0) && (obj(0).type == "radio"))
						for (var i = 0; i < obj.length; i++)
							if (obj[i].checked) result = false;
				}
			}
		}
		if (result) { 
			if (mensagem != "") {
				alert(mensagem);
				obj.focus();
			}
		}
	}
	return result;
}

//========================================================
// REQUIRES http://www.jsfromhell.com/geral/event-listener
//========================================================

MaskInput = function(f, m){ //v1.0
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[?-?]/i, "8": /./ },
			rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};


enterAsTab = function(){ //v1.0
    function next(e){
        var l, i, f, j, o = e.target;
        if(e.key == 13 && !/textarea|select/i.test(o.type)){
            for(i = l = (f = o.form.elements).length; f[--i] != o;);
            for(j = i; (j = (j + 1) % l) != i && (!f[j].type || f[j].disabled || f[j].readOnly););
            e.preventDefault(), j != i && f[j].focus();
        }
    }
    for(var f, i = (f = document.forms).length; i; addEvent(f[--i], "keypress", next));
};


<!-- // Funcoes de tratamento de campos de formulario -->
/*
**************************************
* Event Listener Function v1.3       *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/

addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? a.call(o, e) : (o._ = a, o._(e), o._ = null)));
		e = null;
	}
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

getPagina = function(acao,modulo,parametro,pagina) {
		location.href = "?"+parametro+"&pagina="+pagina+"&modulo="+modulo+"&acao="+acao;
}


// FUNÇÃO PARA VALIDAR E-MAIL
function checaEmail(Email) {
  var expreMail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if (expreMail.test(Email)) {
    return true;
  }
  else {
	return false;
  }
}


function getDiferenca(ddata1, ddata2){
	arrData1 = ddata1.split("/");
	arrData2 = ddata2.split("/");
	var data1 = new Date(arrData1[2],arrData1[1],arrData1[0]);
	var data2 = new Date(arrData2[2],arrData2[1],arrData2[0]);
    var dif =
        Date.UTC(data1.getYear(),data1.getMonth(),data1.getDate(),0,0,0)
      - Date.UTC(data2.getYear(),data2.getMonth(),data2.getDate(),0,0,0);
    var dias = Math.abs((dif / 1000 / 60 / 60 / 24));

	
	return Math.round(dias);
	
}
function validaData(pObj) {
  var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
  var aRet = true;
  if ((pObj) && (pObj.value.match(expReg)) && (pObj.value != '')) {
        var dia = pObj.value.substring(0,2);
        var mes = pObj.value.substring(3,5);
        var ano = pObj.value.substring(6,10);
        if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30) 
          aRet = false;
        else 
          if ((ano % 4) != 0 && mes == 2 && dia > 28) 
                aRet = false;
          else
                if ((ano%4) == 0 && mes == 2 && dia > 29)
                  aRet = false;
  }  else 
        aRet = false;  
  return aRet;
}
/*
* FUN??O PARA ABRIR POPUP
*
* @param pagina - path da p?gina a ser aberta do tipo String
* @param nomePopup - nome do popup do tipo String
* @param largura - largura do popup do tipo Integer
* @param altura - altura do popup do tipo Integer
*/


function popUp(pagina,nomePopup,largura,altura)
{
  	var telaLargura = screen.width;
	var telaAltura  = screen.height;
	var eixoX = (telaLargura / 2) - (largura / 2);
	var eixoY = (telaAltura / 2) - (altura / 2);
	janela=window.open(pagina,nomePopup,' scrollbars=yes,menubar=yes, width='+largura+', height='+altura);

	if (janela == null) {
			alert("Por favor desabilite o seu bloqueador de pop-ups");
	}
}

function formatCurrency(o, n, dig, dec){
    new function(c, dig, dec, m){
        addEvent(o, "keypress", function(e, _){
            if((_ = e.key == 45) || e.key > 47 && e.key < 58){
                var o = this, d = 0, n, s, h = o.value.charAt(0) == "-" ? "-" : "",
                    l = (s = (o.value.replace(/^(-?)0+/g, "$1") + String.fromCharCode(e.key)).replace(/\D/g, "")).length;
                m + 1 && (o.maxLength = m + (d = o.value.length - l + 1));
                if(m + 1 && l >= m && !_) return false;
                l <= (n = c) && (s = new Array(n - l + 2).join("0") + s);
                for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += dig);
                n && n < l && (s[l - ++n] += dec);
                _ ? h ? m + 1 && (o.maxLength = m + d) : s[0] = "-" + s[0] : s[0] = h + s[0];
                o.value = s.join("");
            }
            e.key > 30 && e.preventDefault();
        });
    }(!isNaN(n) ? Math.abs(n) : 2, typeof dig != "string" ? "." : dig, typeof dec != "string" ? "," : dec, o.maxLength);
}



function validaCpf(cpf) {
   erro = new String;
   if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
                var nonNumbers = /\D/;
               if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
                 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                         erro += "Numero de CPF invalido!"
             }
             var a = [];
             var b = new Number;
             var c = 11;
             for (i=0; i<11; i++){
                     a[i] = cpf.charAt(i);
                     if (i < 9) b += (a[i] * --c);
             }
          if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
            b = 0;
             c = 11;
              for (y=0; y<10; y++) b += (a[y] * c--);
             if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
              if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
                      erro +="Digito verificador com problema!";
            }
            if (erro.length > 0){
                   return false;
               }
            return true;
       }

/**
* MÃ©todo que popula o form de acordo com o objeto passado
* @param obj
* @param nomeObj
* @return
*/
function populaForm(obj, nomeObj) {
	for (var item in obj) {
		var value = obj[item];
		if (value != null) {
			//Verificando se o value Ã© um objeto
			if (typeof(value) == 'object' && value != null) {
				for (var subItem in value) {
					var subValue = value[subItem];
					if (subItem == 'id') {
						$("#" + nomeObj + "\\." + item + "\\.id").val(subValue);
		
						//Verificando se o elemento Ã© um select(combo)
						if ($("#" + nomeObj + "\\." + item + "\\.id").attr('type') == 'select-one') {
							$("#" + nomeObj + "\\." + item + "\\.id").change();
						}
					}	
				}
			} else if (item != 'class') {
				//Verificando se o elemento Ã© do tipo datePicker
				if ($("#" + nomeObj + "\\." + item).attr('class') == 'hasDatepicker') {
					$("#" + nomeObj + "\\." + item).datepicker('setDate', value);
				} else {
					$("#" + nomeObj + "\\." + item).val(value);
				}
			}	
		}
    }
} 

preencheComboBox = 
   function(sep, text, value, obj, etiqueta) {
        var clear, obj, t, v, x;
		clear = preencheComboBox.arguments[3] ? preencheComboBox.arguments[3] : true;
        obj = document.getElementById(obj).options, t = text.split(sep), v = value.split(sep);
        if(clear)
            while(obj.length > 0)
                obj[0] = null;
		
		obj[0] = new Option(etiqueta, "");
		
		for(var i = 0; i < t.length; i++) {
    		obj[i+1] = new Option(t[i], v[i]);
	    }
		
    }    

getComboBox = function(objeto) {
	var opt;
	var nomeSelecionado;
	var valorSelecionado;
	
	opt = objeto.options[objeto.selectedIndex];
	textoSelecionado = objeto.options[objeto.selectedIndex].text;
	valorSelecionado = objeto.options[objeto.selectedIndex].value;
	var obj = {  
				texto: textoSelecionado,
				valor: valorSelecionado,
				opcoes:opt
			}
	
	return obj;	
}

toggle = function(id) {
	obj = document.getElementById(id);
	if (obj.style.display == 'block') {
		obj.style.display = 'none';	
	} else if (obj.style.display == 'none') {
		obj.style.display = 'block';	
	}
}

function validaImagem(arquivo) {
	if (!isImagem(arquivo)) {
		alert("Imagem em formato inválido. Formatos aceitos: JPG, JPEG, GIF, PNG");
		return false;	
	} else {
		return true;
	}
}

function isImagem(arquivo) {
	if (arquivo != "") {
		var expreImagem = /^(jpg)|(jpeg)|(gif)|(png) $/
		crtArquivo = arquivo.split(".");
		extensao = crtArquivo[1];
		if (!expreImagem.test(extensao)) {
			return false;
		}
	}
		
	return true;
}

function isBannerValido(arquivo) {
	if (arquivo != "") {
		var expreImagem = /^(jpg)|(jpeg)|(gif)|(png)|(swf) $/
		crtArquivo = arquivo.split(".");
		extensao = crtArquivo[crtArquivo.length];
		if (!expreImagem.test(extensao.toLowerCase())) {
			return false;
		}
	}
		
	return true;
}

function max(txarea,restante,digitado,numeroCaracter)
{
	total = numeroCaracter;	 
	tam = txarea.value.length;	 
	str="";	 
	str=str+tam;
	Digitado = document.getElementById(digitado);
	Restante = document.getElementById(restante);
	Digitado.innerHTML = str;	 
	Restante.innerHTML = total - str; 
	if (tam > total){		 
		aux = txarea.value;		 
		txarea.value = aux.substring(0,total);		 
		Digitado.innerHTML = total;	 
		Restante.innerHTML = 0;
	}
} 

function marcarCampos(obj,tipo) {
	if (obj.checked) {
		document.getElementById(tipo+"_"+_PORTUGUES).checked = true;		
		document.getElementById(tipo+"_"+_INGLES).checked = true;
		document.getElementById(tipo+"_"+_ESPANHOL).checked = true;
	} else {
		document.getElementById(tipo+"_"+_PORTUGUES).checked = false;		
		document.getElementById(tipo+"_"+_INGLES).checked = false;
		document.getElementById(tipo+"_"+_ESPANHOL).checked = false;
	}
}
