//Bloqueia Tecla
function rejeitaTecla(){    
    //by Micox - elmicox.blogspot.com - www.ievolutionweb.com

    var oEvent=arguments[0];

    //filtrando o evento
    var oEvent = oEvent ? oEvent : window.event;
    var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
    
    if(oEvent.type=="keydown" && navigator.appName.indexOf('Internet Explorer')<0 ){
        //se for keydown e não for o IE, vazarei pois o keypress já foi executado
        return false;
    }
    
    for(var i=1; cod_tecla=arguments[i]; i++){
        if (tecla == cod_tecla){
            if (typeof(oEvent.preventDefault)=='function'){
                oEvent.preventDefault();
            } else {
                oEvent.returnValue = false;
                oEvent.keyCode = 0;
            }
        }
    return false;}
}
function rejeitaTeclas(){
    var tecla = 0;
    var args_eval = "e, ";
    for(var i=0; tecla=arguments[i]; i++)
        {args_eval += tecla + ", ";}
    args_eval += "0";
    eval("document.onkeypress=function(e){rejeitaTecla("+args_eval+");}\n"+
        "document.onkeydown=function(e){rejeitaTecla("+args_eval+");}");
}
//rejeitaTeclas(116, 48, 50); //Chama assim com as teclas que deseja rejeitar



//Validar Email
function ValidaEmail(email)
{
  if ((email.value.length != 0) && ((email.value.indexOf("@") < 1) || (email.value.indexOf('.') < 7)))
  {
    alert('Email incorreto');
	document.email.focus();
  }
}

//Apenas caracteres Strings
function blockString(e) {
	
	var key;
	var keychar;
	var reg;

	if(window.event) {
	  // Para IE, e.keyCode ou window.event.keyCode pode ser usado
	  key = e.keyCode;
	} else if(e.which) {
	  // Netscape
	  key = e.which;
	} else {
	  // Se nao tiver evento, entao passa direto
	  return true;
	}
	if(key != 8){
		keychar = String.fromCharCode(key);
		reg = /\d/;
		//return !reg.test(keychar); //===> para tirar numeros eh necessario tirar o exclamacao (!)
		return !reg.test(keychar);
	} else {
		return true;
	}
}

//Apenas caracteres numericos
function blockNumbers(e) {
	
	var key;
	var keychar;
	var reg;

	if(window.event) {
	  // Para IE, e.keyCode ou window.event.keyCode pode ser usado
	  key = e.keyCode;
	} else if(e.which) {
	  // Netscape
	  key = e.which;
	} else {
	  // Se nao tiver evento, entao passa direto
	  return true;
	}
	if(key != 8){
		keychar = String.fromCharCode(key);
		reg = /\d/;
		// return !reg.test(keychar); ===> para tirar nÃºmeros Ã© necessÃ¡rio tirar o exclamaÃ§Ã£o (!)
		return reg.test(keychar);
	} else {
		return true;
	}
}


// Input com apenas caracteres numericos
function apenasNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 45 && tecla < 58) ) 
		return true;
    else{
	    if (tecla != 8) return false;
    	else return true;
    }
}

// Acha o tamanho da strig e passa para o prÃ³ximo campo
function proximoCampo(tamanho,id_atual,id_proximo){
	var tam = document.getElementById(id_atual).value.length;
	if (tam == tamanho){
		document.getElementById(id_proximo).focus();
    }
}

// Validacao de formularios genericos
function valida(formulario) {
   var mensagem = '';
   var primeiro = 0;
   for (var i = 0; i < formulario.length; i++) {
       if (formulario.elements[i].getAttribute('erro')) {
          if ((formulario.elements[i].value == '') ||
             (formulario.elements[i].value.length == 0) ||
             (formulario.elements[i].selectedIndex <= 0)
             ) {
             mensagem = mensagem + formulario.elements[i].getAttribute('erro') + "\n";
             // troca a cor da borda do campo
             formulario.elements[i].style.border = '1px solid #F00000';
             if (primeiro == 0) { var primeiro = i; }
          }
      }
   }
   if (mensagem != '') {
      formulario.elements[primeiro].focus();
      alert(mensagem);
      return false;
   } else {
       return true;
   }
} 


// Ajax gererica
function get(tI) { // Esta funcao pega o elemento pelo ID
  if (document.getElementById) { return document.getElementById(tI); }
  else if (document.all) { return document.all[tI]; } else return false;
}

function ajax(valor,url,div,valor2){ 
	req = null; 
	if (window.XMLHttpRequest){ 
		req = new XMLHttpRequest(); 
		req.onreadystatechange = function() {
			if(req.readyState == 4){
				if (req.status == 200){
					get(div).innerHTML = "Carregando....";
					get(div).innerHTML = req.responseText;
				} else{ 
					alert("Houve um problema ao obter os dados:\n" + req.statusText);
				}
			}
		}
		req.open("GET", url+'?valor='+valor+'&valor2='+valor2, true); 
		req.send(null);
	} else if (window.ActiveXObject){ 
				req = new ActiveXObject("Microsoft.XMLHTTP"); 
				if (req){ 
					req.onreadystatechange = function() {
						if(req.readyState == 4){
							if (req.status == 200){
								get(div).innerHTML = "Carregando....";
								get(div).innerHTML = req.responseText;
							} else{ 
								alert("Houve um problema ao obter os dados:\n" + req.statusText);
							}
						}
					}
					req.open("GET", url+'?valor='+valor+'&valor2='+valor2, true); 
					req.send();
				}
		}
}

// Seleciona todos os checkbox de um formulario
function checkbox() {

	// Pega todos os campos do formulï¿½rio
    campos = document.form.elements;

	// Verifica se o checkbox "todos" esta checado
	if(document.form.todos.checked == true){
    for (x=0; x<campos.length; x++)
      if (campos[x].type == "checkbox") campos[x].checked = true;
	}
	// Se o checkbox "todos" nï¿½o tiver checado
	else{
	for (x=0; x<campos.length; x++)
      if (campos[x].type == "checkbox") campos[x].checked = false;	
	}

}

// JUMP MENU com REFRESH na pagina para combobox
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

// Abre uma nova janela com opÃ§Ãµes pecificas (popup)
function popup(popup_url,name,Xlargura,Xaltura,Xbarra,bstatus,Xbarramenu,Xdimensao) {
 size = 'status=' + bstatus + ',menubar=' + Xbarramenu + ',resizable=' + Xdimensao + ',width=' + Xlargura + ',height=' + Xaltura + ',scrollbars=' + Xbarra;
 window.open(popup_url,name,'directories=no, location=no, toolbar=no, ' + size);
}


// Fecha popup
function fecha(valor){
	this.opener.location="conteudo_editar.php?conteudo="+valor;
	window.setInterval("close();window.opener.focus();",1000);
}


// FunÃ§Ã£o Confirmacao de operacao
function confirmacao() {
	var answer = confirm("Tem certeza que deseja apagar?")
	if (answer){
		return true;
	}
	else{
		return false;
	}
}

//	Funcao Javascript para formatar campo monetario
function formataValor(id,tammax,teclapres) {

	// Internet Explorer
	if(window.event) { 
		var tecla = teclapres.keyCode;
	} 
	// Nestcape / firefox
	else if(teclapres.which) {
		var tecla = teclapres.which;
	}

	vr = document.getElementById(id).value;
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;
	
	if (tam < tammax && tecla != 8){
		tam = vr.length + 1; 
	}
	
	if (tecla == 8 ){ 
		tam = tam - 1; 
	}
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
			document.getElementById(id).value = vr; 
		}
		if ( (tam > 2) && (tam <= 5) ){
			document.getElementById(id).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); 
		}
		if ( (tam >= 6) && (tam <= 8) ){
			document.getElementById(id).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}
		if ( (tam >= 9) && (tam <= 11) ){
			document.getElementById(id).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) ){
			document.getElementById(id).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) ){
			document.getElementById(id).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 );
		}
	} 
}

// Validacao de CPF

// Calculo do Digito do CPF/CNPJ
function DigitoCPFCNPJ(numCIC) {
var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
var novoCIC = numCIC.substring(0, numCIC.length-2);
switch (numCIC.length){
 case 11 :
  numLim = 11;
  break;
 case 14 :
  numLim = 9;
  break;
 default : return false;
}
var numSoma = 0;
var Fator = 1;
for (var i=novoCIC.length-1; i>=0 ; i--) {
 Fator = Fator + 1;
 if (Fator > numLim) {
  Fator = 2;
 }
 numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
}
numSoma = numSoma/11;
var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
   if (numResto > 1) {
 numResto = 11 - numResto;
   }
   else {
 numResto = 0;
   }
   //-- Primeiro dï¿½gito calculado.  Farï¿½ parte do novo cï¿½lculo.
   
   var numDigito = String(numResto);
   novoCIC = novoCIC.concat(numResto);
   //--
numSoma = 0;
Fator = 1;
for (var i=novoCIC.length-1; i>=0 ; i--) {
 Fator = Fator + 1;
 if (Fator > numLim) {
  Fator = 2;
 }
 numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
}
numSoma = numSoma/11;
numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
   if (numResto > 1) {
 numResto = 11 - numResto;
   }
   else {
 numResto = 0;
   }
//-- Segundo dï¿½gito calculado.
numDigito = numDigito.concat(numResto);
if (numDigito == numDois) {
 return true;
}
else {
 return false;
}
}
//--< Fim da Funï¿½ao >--

//-- Retorna uma string apenas com os nï¿½meros da string enviada
function ApenasNum(strParm) {
strParm = String(strParm);
var chrPrt = "0";
var strRet = "";
var j=0;
for (var i=0; i < strParm.length; i++) {
 chrPrt = strParm.substring(i, i+1);
 if ( chrPrt.match(/\d/) ) {
  if (j==0) {
   strRet = chrPrt;
   j=1;
  }
  else {
   strRet = strRet.concat(chrPrt);
  }
 }
}
return strRet;
}
//--< Fim da Funï¿½ao >--

//-- Somente aceita os caracteres vï¿½lidos para CPF e CNPJ.
function PreencheCIC(objCIC) {
var chrP = objCIC.value.substring(objCIC.value.length-1, objCIC.value.length);

if ( !chrP.match(/[0-9]/) && !chrP.match(/[\/.-]/) ) {
 objCIC.value = objCIC.value.substring(0, objCIC.value.length-1);
 return false;
}
return true;
}
//--< Fim da Funï¿½ao >--

function FormataCIC (numCIC) {
numCIC = String(numCIC);
switch (numCIC.length){
case 11 :
 return numCIC.substring(0,3) + "." + numCIC.substring(3,6) + "." + numCIC.substring(6,9) + "-" + numCIC.substring(9,11);
case 14 :
 return numCIC.substring(0,2) + "." + numCIC.substring(2,5) + "." + numCIC.substring(5,8) + "/" + numCIC.substring(8,12) + "-" + numCIC.substring(12,14);
default :
 alert("Tamanho incorreto do CNPJ!");
 return false;
}
}

//-- Remove os sinais, deixando apenas os nï¿½meros e reconstroi o CPF ou CNPJ, verificando a validade
//-- Recebe como parï¿½metros o nï¿½mero do CPF ou CNPJ, com ou sem sinais e o atualiza com sinais ï¿½ validado.
function ConfereCIC(objCIC) {
if (objCIC.value == null) {
 alert("Preenchimento obrigatï¿½rio do CNPJ");
 objCIC.value='';
 objCIC.focus();
 return false;
}
var strCPFPat  = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
var strCNPJPat = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;

numCPFCNPJ = ApenasNum(objCIC.value);

if (!DigitoCPFCNPJ(numCPFCNPJ)) {
 alert("AtenÃ§Ã£o: DÃ­gito verificador do CNPJ ï¿½ invÃ¡ido!");
 objCIC.value='';
 objCIC.focus();
 return false;
}

objCIC.value = FormataCIC(numCPFCNPJ);

if (objCIC.value.match(strCNPJPat)) {
 return true;
}
else if (objCIC.value.match(strCPFPat)) {
 return true;
}
else {
 alert("Digite um CNPJ vï¿½lido!");
 objCIC.value='';
 objCIC.focus();
 return false;
}
}


