/* 
	Mascaras para formatação
*/
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}
function numerico(v){
	v = v.replace(',','.');
    return v.replace(/[^0-9.]/g,"")
}

function data(v){
    v=v.replace(/\D/g,"")                 			//Remove tudo o que não é dígito
    v=v.replace(/(\d{2})(\d)/,"$1/$2")    //Coloca hífen entre o quarto e o quinto dígitos
    v=v.replace(/(\d{2})(\d)/,"$1/$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d{3})(\d)/,"$1.$2-$3") //Esse é tão fácil que não merece explicações
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function Moeda(v){
        v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
        v=v.replace(/^([0-9]{3}\.?){3}-[0-9]{2}$/,"$1.$2");
//        v=v.replace(/(\d{3})(\d)/g,"$1.$2")
        v=v.replace(/(\d)(\d{2})$/,"$1,$2") //Coloca ponto antes dos 2 últimos digitos
        return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

/* Biblioteca : validateLib.js
	Autor : Jefferson Petilo( jefferson@netdom.com.br )
	
	Biblioteca Predecessora
		1 - utilLib.js
*/
var cor_primaria  = '#C4D3DF';

Date.prototype.Dtos = function() {
  var dd = this.getDate();
  var mm = this.getMonth() + 1;
  var yy = this.getFullYear();
	
  return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) );
}

Array.prototype.hasEmptyElements = function() {
  for( var i = 0 ; i < this.length ; i++ )
   if( ( this[ i ] == '' ) || ( this[ i ] == null ) || ( this[ i ] == undefined ) )
	  return( true );
			
   return( false );
}

String.prototype.isNumber = function() {
  return( !isNaN( this.split( '.' ).join( '' ).split( ',' ).join( '' ).split( '-' ).join( '' ) ) );
}

String.prototype.isDate = function() {
  if( this.split( '/' ).length != 3 ) return( false );

   var dd = Number( this.split( '/' )[ 0 ] );
   var mm = Number( this.split( '/' )[ 1 ] );
   var yy = Number( this.split( '/' )[ 2 ] );
   var dt = new Date( yy , mm -1 , dd  );
	
  return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) == dt.Dtos() );
}

String.prototype.isMail = function() {
 var test;
 var pt1    = this.split( '@' );
 var valid  = '.-_@';
		
	if( ( pt1.length != 2 ) || ( pt1[ 0 ].length == 0 ) || ( pt1[ 1 ].length == 0 ) ) 
		return( false );
	else {
	  for( var i = 0 ; i < valid.length - 1 ; i++ ) {
		if( pt1[ 0 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
		if( pt1[ 1 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
	   }			
	}
	for( var i = 0 ; i < this.length ; i++ ) {
	  var charac = this.toUpperCase().charCodeAt( i );
	  
		if( valid.indexOf( String.fromCharCode( charac ) ) == -1 )
		if(!( ( ( charac >= 65 ) && ( charac <= 90 ) ) || ( ( charac >= 48 ) && ( charac <= 57 ) ) ) ) 
		   return( false );
	}	
	
  return( true );
}

String.prototype.isCPF = function(){
	var numcpf = this.replace('-','');
	numcpf = numcpf.replace('.','');
	numcpf = numcpf.replace('.','');
	numcpf = numcpf.replace('.','');

	x = 0;
	soma = 0;
	dig1 = 0;
	dig2 = 0;
	texto = "";
	numcpf1="";
	len = numcpf.length; x = len -1;
	// var numcpf = "12345678909";
	for (var i=0; i <= len - 3; i++) {
		y = numcpf.substring(i,i+1);
		soma = soma + ( y * x);
		x = x - 1;
		texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1=0 ;
	if (dig1 == 11) dig1=0 ;
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	x = 11; soma=0;
	for (var i=0; i <= len - 2; i++) {
		soma = soma + (numcpf1.substring(i,i+1) * x);
		x = x - 1;
	}
	dig2= 11 - (soma % 11);
	if (dig2 == 10) dig2=0;
	if (dig2 == 11) dig2=0;
	//alert ("Digito Verificador : " + dig1 + "" + dig2);
	if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
		return true;
	}
	return false;
}


/*
	var Objcpf = this;
    var cpf = Objcpf;

    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)    
        return false;
	
	return true;
}
*/

String.prototype.isCEP = function() {
            // Caso o CEP não esteja nesse formato ele é inválido!
            var objER = /^[0-9]{2}\.[0-9]{3}-[0-9]{3}$/;
            strCEP = this;
            if(strCEP.length > 0)
                {
                    if(objER.test(strCEP))
                        return true;
                    else
                        return false;
                }
            else
                return false;

}

String.prototype.isTelefone = function() {
	var er = /\([0-9]{2}\) [0-9]{3,4}-?[0-9]{4}/;

	var c = this;
	
	if (!c.match (er))
        return false;
		
	return true;
}

String.prototype.isCNPJ = function() {
 var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;

  if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return ( false );
  for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
  if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return ( false );
  for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
  if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return ( false );

  return ( true );
}

String.prototype.isRG = function() {
	var numero = this;
 /*
 ##  Igor Carvalho de Escobar
 ##    www.webtutoriais.com
 ##   Java Script Developer
 */
 	var numero = numero.split("");
	 tamanho = numero.length;
	 vetor = new Array(tamanho);

	if(tamanho>=1)
	{
		 vetor[0] = parseInt(numero[0]) * 2; 
	}
	if(tamanho>=2){
		 vetor[1] = parseInt(numero[1]) * 3; 
	}
	if(tamanho>=3){
		vetor[2] = parseInt(numero[2]) * 4; 
	}
	if(tamanho>=4){
		 vetor[3] = parseInt(numero[3]) * 5; 
	}
	if(tamanho>=5){
		 vetor[4] = parseInt(numero[4]) * 6; 
	}
	if(tamanho>=6){
		vetor[5] = parseInt(numero[5]) * 7; 
	}
	if(tamanho>=7){
		vetor[6] = parseInt(numero[6]) * 8; 
	}
	if(tamanho>=8){
		vetor[7] = parseInt(numero[7]) * 9; 
	}
	if(tamanho>=9){
		vetor[8] = parseInt(numero[8]) * 100; 
	}

	 total = 0;

	if(tamanho>=1){
		total += vetor[0];
	}
	if(tamanho>=2){
		total += vetor[1]; 
	}
	if(tamanho>=3){
		total += vetor[2]; 
	}
	if(tamanho>=4){
		total += vetor[3]; 
	}
	if(tamanho>=5){
		total += vetor[4]; 
	}
	if(tamanho>=6){
		total += vetor[5]; 
	}
	if(tamanho>=7){
		total += vetor[6];
	}
	if(tamanho>=8){
		total += vetor[7]; 
	}
	if(tamanho>=9){
		total += vetor[8]; 
	}
	
	resto = total % 11;
	if(resto!=0)
	{
		return false;
	}
	return true;
}

function fnc_controla_campos() {
  for( var j = 0; j <  document.forms.length; j++ ) { 
    var formulario = eval( document.forms[ j ] );
	for( var i = 0; i < formulario.length; i++ ) {	
		addEvent( formulario.elements[ i ] , 'focus' , setBackgroundColor , false );    // adicionar evento na foco do campo	
	    addEvent( formulario.elements[ i ] , 'blur'   , clearBackgroundColor , false ); // adicionar evento na blur do campo
	}	
  }
}	

function fnc_pega_checkbox_valor(c){
	var listaVal = '';
	c = document.principal.elements[c];
	if(c){
		for ( var i = 0; i < c.length; i++ ){
			if (c[i].checked) {
				listaVal = listaVal + ',' + c[i].value;
			}
		}
	}
	else 
		return false;

	return listaVal;
}

function fnc_verifica_tipo( p_campo ) {
  if( p_campo && ( !p_campo.readOnly  || p_campo.type != 'button' || p_campo.type != 'hidden' ) ) return( false );
 return( true );																						   
}

function fnc_verifica_form( form ) {
 var showMessage = function(p_msg, p_campo ){ alert( p_msg ); /*if( tip ) tip.show( p_msg );*/ p_campo.focus();  return false; }
 var temSecao    = ( fnc_verifica_form.arguments.length == 2 )?true:false;
 var secao	     = ( temSecao )?fnc_verifica_form.arguments[ 1 ]:'';
 var mensagem    = '';

 for( var i = 0; i < form.length; i++ ) {

	  var campo 	= form.elements[ i ];
  	  var tipo  	= campo.getAttribute('tipo');
  	  var requerido = campo.getAttribute('obrigatorio');
  	  var display	= campo.getAttribute('display');
  	  var valor 	= campo.value;

	  if (campo.type == 'checkbox')
	  	valor = fnc_pega_checkbox_valor(campo.name);

//	  alert(campo.type + '-' + valor);

  	  var erro	    = false ;
  
	  // verificação se existe seção ou não 
	  if ( ( temSecao && secao == campo.getAttribute('secao') ) || !temSecao )  { 
		  // se o campo for requerido
		  if ( requerido == 1 ) { 
		  	 // validação simples
    			if ( !valor ) {
				   mensagem =  'O campo ' + display + ' ' + String.fromCharCode( 233 ) + '  requerido.';  
				   return( showMessage( mensagem , campo  ) );		
				} 
		  }
		// validação dos tipos
		if( tipo && valor ) { 
		   mensagem = 'O valor do campo ' + display  + ' deve ser ';
			if( tipo == 'numerico' && !valor.isNumber() ){
				erro = true;
				mensagem += ' num' + String.fromCharCode( 233 ) + 'rico.';
			} else if ( tipo == 'data' && !valor.isDate() ) {
				erro = true;
				mensagem += ' uma data v' + String.fromCharCode( 225 ) + 'lida.';
			} else if( tipo == 'email' && !valor.isMail() ){ 
				erro = true;
				mensagem += ' um e-mail v'+ String.fromCharCode( 225 ) + 'lido.';
			} else if( tipo == 'cnpj' && !valor.isCNPJ()) {
				erro = true;
				mensagem += 'um CNPJ v' + String.fromCharCode( 225 ) + 'lido.';
			} else if( tipo == 'cpf' && !valor.isCPF()) {
				erro = true;
				mensagem += 'um CPF v' + String.fromCharCode( 225 ) + 'lido.';
			} else if( tipo == 'cep' && !valor.isCEP()) {
				erro = true;
				mensagem += 'um CEP v' + String.fromCharCode( 225 ) + 'lido.';
			} else if( tipo == 'telefone' && !valor.isTelefone()) {
				erro = true;
				mensagem += 'um telefone v' + String.fromCharCode( 225 ) + 'lido.';
			} 
		   // mostra erro
		   if( erro ) return( showMessage( mensagem , campo  ) );
	   } 	 			
	}
 }
 return ( true );
}
