function somente_numero(campo){
var digits="0123456789"
var campo_temp 
for (var i=0;i<campo.value.length;i++){
  campo_temp=campo.value.substring(i,i+1) 
  if (digits.indexOf(campo_temp)==-1){
     campo.value = campo.value.substring(0,i);
     break;
   }
}
}


/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {	
/*
Previne a ação padrão nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {	
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessário para o opera
	obj.value += y;
	
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}

function mascaraData(campoData)
{
var data = campoData.value;
if (data.length == 2){
    data = data + '/';
	document.forms[0].EventDate.value = data; 
	return true; 
}
if (data.length == 5){
   data = data + '/'; 
   document.forms[0].EventDate.value = data;
   return true;
}
}


// JavaScript Document
//adiciona mascara de cnpj
function MascaraCNPJ(cnpj){
    if(mascaraInteiro(cnpj)==false){
        event.returnValue = false;
    }    
    return formataCampo(cnpj, '00.000.000/0000-00', event);
}

//adiciona mascara de cep
function MascaraCep(cep){
        if(mascaraInteiro(cep)==false){
        event.returnValue = false;
    }    
    return formataCampo(cep, '00.000-000', event);
}

//adiciona mascara de data
function MascaraData(data){
    if(mascaraInteiro(data)==false){
        event.returnValue = false;
    }    
    return formataCampo(data, '00/00/0000', event);
}

//adiciona mascara ao telefone
function MascaraTelefone(tel){    
    if(mascaraInteiro(tel)==false){
        event.returnValue = false;
    }    
    return formataCampo(tel, '(00) 0000-0000', event);
}

//adiciona mascara ao telefone sem DDD
function MascaraTelefone2(tel){    
    if(mascaraInteiro(tel)==false){
        event.returnValue = false;
    }    
    return formataCampo(tel, '0000-0000', event);
}

//adiciona mascara ao telefone sem DDD - Firefox - não funcionou
function MascaraTelefone3(event,tel){    
    if(mascaraInteiro(tel)==false){
        event.returnValue = false;
    }    
    return formataCampo(tel, '0000-0000', event);
}

//adiciona mascara ao CPF
function MascaraCPF(cpf){
    if(mascaraInteiro(cpf)==false){
        event.returnValue = false;
    }    
    return formataCampo(cpf, '000.000.000-00', event);
}

//valida telefone
function ValidaTelefone(tel){
    exp = /\(\d{2}\)\ \d{4}\-\d{4}/
    if(!exp.test(tel.value)&& (tel.value != '') )
        alert('Numero de Telefone Invalido!');
}

//valida telefone sem DDD
function ValidaTelefone2(tel){
    exp = /\d{4}\-\d{4}/
    if(!exp.test(tel.value)&& (tel.value != '') )
        alert('Numero de Telefone Invalido!');
}

//valida telefone sem DDD - Firefox
function ValidaTelefone3(tel){
    exp = /\d{8}/
    if(!exp.test(tel.value)&& (tel.value != '') )
        alert('Numero de Telefone Invalido!');
}


//valida CEP
function ValidaCep(cep){
    exp = /\d{2}\.\d{3}\-\d{3}/
    if(!exp.test(cep.value) && (cep.value != '') )
        alert('Numero de Cep Invalido!');        
}

//valida data
function ValidaData(data){
    exp = /\d{2}\/\d{2}\/\d{4}/
    if(!exp.test(data.value))
        alert('Data Invalida!');            
}

//valida o CPF digitado SEM ponto e hifen
function ValidarCPF(Objcpf){
    var cpf = Objcpf.value;
    exp = /\.|\-/g
    cpf = cpf.toString().replace( exp, "" ); 
    var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
    var soma1=0, soma2=0;
    var vlr =11;
    
    for(i=0;i<9;i++){
        soma1+=eval(cpf.charAt(i)*(vlr-1));
        soma2+=eval(cpf.charAt(i)*vlr);
        vlr--;
    }    
    soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));
    soma2=(((soma2+(2*soma1))*10)%11);
    
    var digitoGerado=(soma1*10)+soma2;
    if(digitoGerado!=digitoDigitado)    
        alert('CPF Invalido!');  
	 
	
}

//valida o CPF digitado COM ponto e hifen
 function validarCPF_2(Objcpf){

	
   //var cpf = document.cadastro.cpf.value;
   var cpf = Objcpf.value;
   if (cpf.length > 0)
   {
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
     window.alert("CPF inválido. Tente novamente.");
	 document.form3.CPF.focus();
	 //document.form3.CPF.select();
	 return false;
   }
   
   cpf = remove(cpf, ".");
   cpf = remove(cpf, "-");
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  window.alert("CPF inválido. Tente novamente.");
	   	 document.form3.CPF.focus();
	 //document.form3.CPF.select();

	  return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 window.alert("CPF inválido. Tente novamente.");
		 document.form3.CPF.focus();
	 //document.form3.CPF.select();
	return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF inválido. Tente novamente.");
		 document.form3.CPF.focus();
	 //document.form3.CPF.select();
	 return false;
   }
   }
   return true;
 }

 function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
 }





//valida numero inteiro com mascara
function mascaraInteiro(){
    if (event.keyCode < 48 || event.keyCode > 57){
        event.returnValue = false;
        return false;
    }
    return true;
}

//valida o CNPJ digitado
function ValidarCNPJ(ObjCnpj){
    var cnpj = ObjCnpj.value;

    if (cnpj.length > 0)
    {
    var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
    var dig1= new Number;
    var dig2= new Number;
    
    exp = /\.|\-|\//g
    cnpj = cnpj.toString().replace( exp, "" ); 
    var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
        
    for(i = 0; i<valida.length; i++){
        dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);    
        dig2 += cnpj.charAt(i)*valida[i];    
    }
    dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
    dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
    
      if(((dig1*10)+dig2) != digito)   
  	  {
        alert('CNPJ Invalido! Tente novamente.');
	    document.form3.CNPJ.focus();
		return false;
      }
   }
   return true;

}

//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) { 
    var boleanoMascara; 
    
    var Digitato = evento.keyCode;
    exp = /\-|\.|\/|\(|\)| /g
    campoSoNumeros = campo.value.toString().replace( exp, "" ); 
   
    var posicaoCampo = 0;     
    var NovoValorCampo="";
    var TamanhoMascara = campoSoNumeros.length;; 
    
    if (Digitato != 8) { // backspace 
        for(i=0; i<= TamanhoMascara; i++) { 
            boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                || (Mascara.charAt(i) == "/")) 
            boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(") 
                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " ")) 
            if (boleanoMascara) { 
                NovoValorCampo += Mascara.charAt(i); 
                  TamanhoMascara++;
            }else { 
                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); 
                posicaoCampo++; 
              }            
          }     
        campo.value = NovoValorCampo;
          return true; 
    }else { 
        return true; 
    }
}


function checa(nform) {
	if (nform.email.value == "") {
		alert("Informe seu e-mail.");
		nform.email.focus();
		nform.email.select();
		return false;
	} else {
		prim = nform.email.value.indexOf("@")
		if(prim < 2) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("@",prim + 1) != -1) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(".") < 1) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(" ") != -1) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("zipmeil.com") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("hotmeil.com") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(".@") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("@.") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(".com.br.") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("/") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("[") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("]") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("(") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(")") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("..") > 0) {
			alert("O e-mail informado parece não estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
	}
		return true;
}


function mascara_tel_firefox(event,campo){   
     if(event.keyCode<48 || event.keyCode>57){   
        event.returnValue=false;
	 }   

	 if(event.keyCode!=8){   

        if(campo.value.length==4){   
           campo.value+="-";   
        }
	 }	

}  

function mascara_cep_firefox(event,campo){   
     if(event.keyCode<48 || event.keyCode>57){   
        event.returnValue=false;
	 }   

 	 if(event.keyCode!=8){   
        if(campo.value.length==2){   
           campo.value+=".";   
        }   
	    if(campo.value.length==6){   
           campo.value+="-";   
        }   
     }
}  


function mascara(event,campo){   
     if(event.keyCode<48 || event.keyCode>57){   
        event.returnValue=false;
	 }   


     if(event.keyCode!=8){   

        if(campo.value.length==2 || campo.value.length==6){   
              campo.value+=".";   
        }   
        if(campo.value.length==10){   
              campo.value+="/";   
        }   
        if(campo.value.length==15){   
              campo.value+="-";   
        }  
	 } 	
}    

function mascara_cpf(event,campo){  
	
	
     if(event.keyCode<48 || event.keyCode>57){   
        event.returnValue=false;
	 } 

	 
	 if(event.keyCode!=8){   

         if(campo.value.length==3 || campo.value.length==7){   
              campo.value+=".";   
         }   
         if(campo.value.length==11){   
              campo.value+="-";   
         }   
     }   
}  

function mascara_dddtel_firefox(event,campo){   
     if(event.keyCode<48 || event.keyCode>57){   
        event.returnValue=false;
	 } 
	 
	 if(event.keyCode!=8){   
        if(campo.value.length==0){   
           campo.value+="(";   
        }   
        if(campo.value.length==3){   
           campo.value+=")";   
        }   
        if(campo.value.length==4){   
           campo.value+=" ";   
        }   
	    if(campo.value.length==9){   
           campo.value+="-";   
        }   
     }
}  
