//Cria as validações
function ValidarControles(){
	for(var i=0; i<campos.length; i++){
	    //Pegando o nome do controle a ser validado.
		var controle = document.getElementById(campos[i][0]);
		if (controle == null)
			continue;
		//Verificando se não é o editor.
		if (campos[i][0]!="Editor"){
		    //Se o campo for vazio e o texto erroVazio dele for diferente de vazio.
		    //Dá o alert informando que o campo é obrigatorio.
			if(controle.value=="" && campos[i][1]!=""){
				alert(campos[i][1]);
				if(controle.type!="hidden")
					controle.focus();
				return false;
			}
			//Se for um dropdown, o valor for zero e o texto erroVazio dele for diferente de zero.
			//Dá um alert informando que o campo é obrigatorio.
			else if(controle.type=="select-one" && controle.value=="0" && campos[i][1]!=""){			    
			    alert(campos[i][1]);
			    controle.focus();
			    return false;	    
			}
			//Se não for nenhum dos casos acima, verifica se o campo tem validação especifica.
			else if(controle.value!=""){
				switch (campos[i][2]){
					case "EMAIL" : var resul = valida_email(controle); if(!resul) { alert(campos[i][3]);controle.focus(); return false; }
						break;
					case "DATA" : var resul = valida_data(controle);if(!resul){alert(campos[i][3]);controle.focus(); return false;} 
						break;
					case "CPF" : 
					    var resul = valida_CPF(controle); 
					    if(!resul) 
					    { 
					        alert(campos[i][3]); controle.focus();
					        return false;
					    }
					    var aux =  document.getElementById('userID');
					    if(aux.value == "$")
					        resul = VerificaCpfExistente(controle,"");
					     else
					        resul = VerificaCpfExistente(controle,aux.value);
					     if(!resul)
					     {
				            alert(campos[i][3]);
				            controle.focus();
				            return false;
					     }
						break;
					case "CNPJ" : var resul = valida_CNPJ(controle); if(!resul) { alert(campos[i][3]); controle.focus(); return false; }
						break;
					/*case "NUMERICO" : var resul = valida_somente_numero(controle);if(!resul){alert(campos[i][3]);controle.focus();return false;}
					    break;*/
					case "CEP" : var resul = valida_CEP(controle); if(!resul){alert(campos[i][3]);controle.focus();return false;}
						break;
					case "HORA": var resul = valida_hora(controle);if(!resul){alert(campos[i][3]);controle.focus();return false;}
						break;
					case "TELEFONE": var resul = valida_telefone(controle); if(!resul){alert(campos[i][3]);controle.focus();return false;}
						break;
				    case "LOGINUINET": 
				            var aux = document.getElementById('userID');
				            var resul;
				            if(aux.value == "$")	        
				                resul = VerificaLogUiNet(controle, "");
				            else
				                resul = VerificaLogUiNet(controle,aux.value);
				            if(!resul)
				            {
				                alert(campos[i][3]);
				                controle.focus();
				                return false;
				            }
				        break;
					default : break;
				}
			}
		}
		else{
			var resul = ValidaEditor(); if(!resul) { alert(campos[i][1]); return false; } break;
		}
	}
	return true;
}



//////////////////////////////////////////////////////////////////////////////////////////
////////						Biblioteca JavaScript							//////////
////////					Webroom Soluções Interativa							//////////
////////						A internet sob Medida							//////////
////////					http://www.webroom.com.br							//////////
////////					email:: webroom@webroom.com.br						//////////
//////////////////////////////////////////////////////////////////////////////////////////
////////				Criado por : Flávio Theruo Kaminisse					//////////
////////					E-Mail : flavio@webroom.com.br						//////////
////////						Data Criação : 28/09/2008						//////////
////////																		//////////
////////				- Compatível com MSIE, Firefox e Opera.					//////////
//////////////////////////////////////////////////////////////////////////////////////////


//Função simples para verificar senha.Não aceita uma senha com menos de seis caracteres.
function VerificaSenha(controle,erro){
   if(controle.value !='')
   {
        var senha = controle.value; 
        if(senha.length < 6){
            alert(erro);
            controle.value = "";
            controle.focus();
		    return false;
        }
    }
    return true;
}

function VerificaLogUiNet(controle,user)
{
    if(WRUinet.Configuracoes_Usuarios_usuario_ver.VerificaLoginUiNet(controle.value, user).value){
	    controle.value ="";
	    return false;
    }
    else{
	    return true;
    }
}
/*
function VerificaCpfExistente(controle,user)
{
    if(FunctionAjax.VerificaCpf(controle.value,user).value)
    {
        controle.value = "";
        return false;
    }
    return true;
}
*/

//Validacao de senha.
function validaSenha(campo)
{
  
  if(campo.value.length<6)
  {
     alert('A senha deve ter no mínimo 6 dígitos !');
     campo.value = "";
     campo.focus();
     return false;
  }

  if (!/^[a-zA-Z]{1}[\w\@\&\%\*\-\.\/\:\!\=]{0,250}$/.test(campo.value))
  {
     alert('A senha possui caracteres inválidos, ou não foi iniciada com uma letra !');
     campo.value = "";
     campo.focus();
     return false;
  }

  var i; 
  var num = 0, carac = 0;

  for (i = 0; i < campo.value.length; i++)
  {

     var c = campo.value.charAt(i);

     // ha um numero
     if (((c >= "0") && (c <= "9")))
                 num++;

     if (((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")))
                 carac++;
  }

  if (num < 3 || carac == 0)
  {

     alert("A senha deve conter letras e números (mínimo 3 números) !"); 
     campo.value = "";
     campo.focus(); 
     return false;
  }

  if (/(1234|4321)/.test(campo.value))
  {

     alert("A senha não pode conter os seqüenciais 1234 ou 4321 !");
     campo.value = "";
     campo.focus();
     return false;
  }

  s = campo.value
  hoje = new Date()
  ano = hoje.getYear()

  for (f=-2; f<=2; f++)
  {

     n = s.indexOf(ano + f,0)

     if (n > -1)
     {
         alert('Não é permitido colocar o ano como senha !');
         campo.value = "";
         campo.focus();
         return false;
     }
  }
  return true;
}




//Função responsável por verificar se o campo é igual à máscara
//se for igual, deixo o valor como vazio, caso contrário não faço nada
function trata_valor( campo ) {
	if ( campo.value == WBR_GetDisplayMask(campo,true) )
		campo.value = '';
}



function valida_data(campo_data) {    
	if ( campo_data.value != '' ) {
	    //alert(camp_data.value);
		var date = campo_data.value;
		var array_data = new Array;
		var ExpReg = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[1-3][0-9]{3}$");
		//vetor que contem o dia o mes e o ano
		array_data = date.split("/");
		erro = false;
		//Valido se a data esta no formato dd/mm/yyyy e se o dia tem 2 digitos e esta entre 01 e 31
		//se o mes tem d2 digitos e esta entre 01 e 12 e o ano se tem 4 digitos e esta entre 1000 e 2999
		if(array_data[2] < 1900){
		    erro = true;
		}
		else if ( date.search(ExpReg) == -1 )
			erro = true;
		//Valido os meses que nao tem 31 dias com execao de fevereiro
		else if ( ( ( array_data[1] == 4 ) || ( array_data[1] == 6 ) || ( array_data[1] == 9 ) || ( array_data[1] == 11 ) ) && ( array_data[0] > 30 ) )
			erro = true;
		//Valido o mes de fevereiro
		else if ( array_data[1] == 2 ) {
			//Valido ano que nao e bissexto
			if ( ( array_data[0] > 28 ) && ( ( array_data[2] % 4 ) != 0 ) )
				erro = true;
			//Valido ano bissexto
			if ( ( array_data[0] > 29 ) && ( ( array_data[2] % 4 ) == 0 ) )
				erro = true;
		}
		if ( erro ) {
			campo_data.focus();
			alert("Data Inválida");
			return false;
		}
		return true;
	}
}


function valida_email(campo_email) {
	if ( campo_email.value != '' ) {
		//Expressao Regular utilizada para validar o endereco de email
		var ExpReg = /^[a-zA-Z0-9_\.-]{2,}@([A-Za-z0-9_-]{2,}\.)+[A-Za-z]{2,4}$/;
		if ( !ExpReg.test(campo_email.value) ) {
			alert("E-MAIL inválido!");
			campo_email.focus();
			return false;
		}
		return true;
	}
}

function valida_hora(campo_hora) {
    trata_valor( campo_hora );
	if ( campo_hora.value != '' ) {
		//Expressao Regular utilizada para validar a hora
		var ExpReg = /^([0-1][0-9]|[2][0-3]):[0-5][0-9]$/;
		if ( campo_hora.value.search(ExpReg) == -1 ) {
			campo_hora.focus();
			alert("A hora é inválida");
			return false;
		}
		return true;
	}
}

function valida_somente_numero(campo_numero) {
	if ( campo_numero.value != '' ) {
		//Expressao Regular utilizada para validar se o campo possui somente numeros
		var ExpReg = /^\d{0,}$/;
		if ( campo_numero.value.search(ExpReg) == -1 ) {
			campo_numero.focus();
			alert("O campo não comtem apenas números");
			return false;
		}
		return true;
	}
}

function valida_telefone(campo_telefone) {
    trata_valor( campo_telefone );
	if ( campo_telefone.value != '' ) {
		//Expressao Regular utilizada para validar o telefone
		var ExpReg = /^\([0-9]{2}\) [0-9]{4}-[0-9]{4}$/;
		if ( campo_telefone.value.search(ExpReg) == -1 ) {
			campo_telefone.focus();
			alert("O Telefone é inválido");
			return false;
		}
		return true;
	}
}

function valida_CEP(campo_cep) {
    //trata_valor( campo_cep );
	if ( campo_cep.value != '' ) {
		//Expressao Regular utilizada para validar o formato do CEP
		var ExpReg = /^\d{2}\.\d{3}-\d{3}$/;
		if ( campo_cep.value.search(ExpReg) == -1 ) {
			campo_cep.focus();
			alert("Formatod do CEP inválido!");
			return false;
		}
		return true;
	}
}

function valida_CPF(campo_cpf) {
    //trata_valor( campo_cpf );
	if ( campo_cpf.value != '' ) {
		var soma;
		var multiplicador;
		var dig1 = 0;
		var dig2 = 0;
		var verifica;
		var cpf = campo_cpf.value;
		//Expressao Regular utilizada para validar o formato CPF
		var ExpReg = /^(\d{3}).(\d{3}).(\d{3})-(\d{2})$/;
		
		if ( cpf.search(ExpReg) == -1 ) {
			campo_cpf.focus();
			alert("O formato do CPF é inválido");
			return false;
		}
		
		//Remover os caracteres diferentes de número
		cpf = cpf.replace("\.","");
		cpf = cpf.replace("\.","");
		cpf = cpf.replace("-","");
		
		
		if(cpf.match("11111111111")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false
		}
		else if(cpf.match("22222222222")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false
		}
		else if(cpf.match("33333333333")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false
		}
		else if(cpf.match("44444444444")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false;
		}
		else if(cpf.match("55555555555")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false;
		}
		else if(cpf.match("66666666666")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false;
		}
		else if(cpf.match("77777777777")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false;
		}
		else if(cpf.match("88888888888")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false;
		}
		else if(cpf.match("99999999999")!=null)
		{
			alert("CPF Inválido!!!");
		    campo_cpf.focus();
		    return false;
		}
		
		verifica = cpf.match("00000000000");
		//Se todos os caracteres sao diferentes de zero
		if ( verifica == null ) {
			//Utilizo o algoritmo de calcular os digitos verificadores do CPF
			//Calculo o primeiro digito verificador
			soma = 0;
			multiplicador = 10;
			for ( i = 0; i < 9; i++ ) {
				soma += parseInt(cpf.substr(i,1) * multiplicador);
				multiplicador--;
			} //Fim do for
			dig1 = parseInt(11 - (soma % 11));
			if ( dig1 == 11 || dig1 == 10 )
				dig1 = 0;
			//Calculo o segundo digito verificador
			soma = 0;
			multiplicador = 11;
			for ( i = 0; i < 10; i++ ) {
				soma += parseInt(cpf.substr(i,1) * multiplicador);
				multiplicador--;
			} //Fim do for
			dig2 = parseInt(11 - (soma % 11));
			if ( dig2 == 11 || dig2 == 10 )
				dig2 = 0;
			//Se os dois digitos nao forem iguais o CPF e invalido
			if ( !( ( dig1 == parseInt(cpf.substr(9,1)) ) && ( dig2 == parseInt(cpf.substr(10,1)) ) ) ) {
				alert("CPF Inválido!!!");
				campo_cpf.focus();
				return false;
			} //if
		} //if
		else {
			campo_cpf.focus();
			alert("CPF Inválido!!!");
			return false;
		} //Fim do else
		return true;
	}
}

function valida_CNPJ(campo_cnpj) {
    var valor = campo_cnpj.value;
	var valor = campo_cnpj.value;
	var erro = false;
	if ( campo_cnpj. value != '' ) {
		if ( valor.length != 14 )
			erro = true;
		
		var numeros = valor.split('');
	
		var igual = true;
		for ( j = 1; j < 14; j++ ) {
			if ( numeros[j] != numeros[0] ) {
				igual = false;
				break;
			}
		} //Fim do for
			
		if ( igual )
			erro = true;
			
		var soma = 0;
		var fator = 5;
		for ( j = 0; j < 12 ; j++ ) {
			soma += fator * numeros[j];
			fator--;
			if ( fator == 1 )
				fator = 9;
		}
		
		var resultado = soma % 11;
		
		if ( resultado == 1 || resultado == 0 ) {
			if ( numeros[12] != 0 )
				erro = true;
		}
		else {
			if ( numeros[12] != 11 - resultado )
				erro = true;
		}
		
		soma = 0;
		fator = 6;
		for ( j = 0; j < 13 ; j++ ) {
			soma += fator * numeros[j];
			fator--;
			if ( fator == 1 )
				fator=9;
		} //Fim do for
		
		resultado = soma%11;
		
		if ( resultado == 1 || resultado == 0 ) {
			if ( numeros[13] != 0 )
				erro = true;
		}
		else {
			if ( numeros[13] != 11 - resultado )
				erro = true;
		}
		if ( erro == true ) {
			campo_cnpj.focus();
			alert("CNPJ inválido!");
			return false;
		}
		return true;
	}
}

function valida_valor(campo_valor) {
	if ( campo_valor.value != '' ) {
		var valor = campo_valor.value;
		//Expressao regular que garante que o numero nao comece com zero e que siga
		//os padroes do numero que sao apenas digitos e ponto (.) e virgula (,)
		var ExpReg = /^[^0]+[0-9\.,]{0,}$/;
		var count_virgula = 0;
		var count_ponto = 0;
		var coloquei_virgula = false;
		if ( valor.search(ExpReg) == -1 ) {
			campo_valor.focus();
			alert("O Valor não pode iniciar com zero (0)!");
			return false;
		}
		//Utilizo um algoritmo semelhante ao formatacao do numero para validar o campo
		//Iniciando da direita para a esquerda analiso o numero digito a digito
		//sendo que depois de dois digitos tenho que ter uma virgula (,)
		//e depois da virgula de tres em tres digitos tenho que ter um ponto (.)
		for ( i = valor.length - 1; i >= 0; i-- ) {
			if ( count_virgula == 2 && !coloquei_virgula ) {
				coloquei_virgula = true;
			} //if
			if ( count_virgula == 2 && !coloquei_virgula && valor.charAt(i) != "," ) {
				campo_valor.focus();
				alert("Formato Inválido (,)!");
				return false;
			} //if
			if ( count_ponto != 0 && valor.charAt(i) != "." && ( count_ponto % 4 ) == 0 ) {
				if ( !( valor.charAt(i) == "-" && i == 0 ) ) {
					campo_valor.focus();
					alert("Formato Inválido (.)!");
					return false;
				} //if ( !( valor.charAt(i) == "-" && i == 0 ) )
			} //if ( count_ponto != 0 && valor.charAt(i) != "." && ( count_ponto % 4 ) == 0 )
			if ( coloquei_virgula )
				count_ponto++;
			else
				count_virgula++;
		} //Fim do for
		return true;
	} //if ( campo_valor.value != '' )
}

function valida_valor2(campo_valor) {
	var valor = campo_valor.value;
	var ExpReg = /[-+]?[0-9]{1,3}(\.[0-9]{3})?(,[0-9]{2})?/;
	if ( valor.search(ExpReg) == -1 ) {
		alert("Valor inválido!");
		campo_valor.focus();
	}
}


// funcao que exibe a ajuda.
function exibe_help(msg,controle){  
    var aux = "help_"+controle.id;   
	document.getElementById(aux).className = "help_show";
	document.getElementById(aux).innerHTML = msg;
	
	
	
}

function oculta_help(controle)
{
    var aux = "help_"+controle.id;
	document.getElementById(aux).className = "help_hidden";
    document.getElementById(aux).innerHTML = "";
}


//Função responsável pela validação dos dígitos do cartão
function cartaoValido(st) {
	if ( st.length > 19 )
		return (false);
	
	sum = 0; mul = 1; l = st.length;
	for ( i = 0; i < l; i++ ) {

		digit = st.substring(l-i-1,l-i);
		tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
		if (mul == 1)
			mul++;
		else
			mul--;
	} //Fim do for
	
	if ( ( sum % 10 ) == 0 )
		return (true);
	else
		return (false);
}

//Função responsável pela remoção de caracteres diferentes de números
function strip(val) {
	val = "" + val;
	if ( val == null )
		return "";
	var result = "";
	for ( i = 0; i < val.length; i++ ) {
		character = val.charAt(i);
		if ( "0123456789".indexOf(character) != -1 )
			result += character;
	}
	return result;
}

//Função responsável pela validação de números de cartão de crédito
function valida_cartao(campo_cartao) {
	trata_valor( campo_cartao );
	if ( campo_cartao.value != '' ) {
		if ( !cartaoValido(strip(campo_cartao.value)) ) {
			campo_cartao.focus();
			alert("O número do cartão de crédito é inválido");
			return false;
		}
	}
}









//////////////////////////////////////////////////////////////////////////////////////////
////////				Uinet 1.0 [Update Information Internet ]				//////////
////////					Webroom Soluções Interativa							//////////
////////						A internet sob Medida							//////////
////////					http://www.webroom.com.br							//////////
////////					email:: webroom@webroom.com.br						//////////
//////////////////////////////////////////////////////////////////////////////////////////
////////				Criado por   : Flávio Theruo Kaminisse					//////////
////////					Data Criação : 28/09/2008							//////////
////////																		//////////
////////				- Compatível com MSIE, Firefox e Opera.					//////////
//////////////////////////////////////////////////////////////////////////////////////////

var $a;
//Mascara utilizada para letras
var mascaraAlpha = "a";
//Mascara utilizada para numeros
var mascaraNum = "n";
//Mascara utilizada para letras e numeros
var mascaraAlphaNum = "x";
//Variavel utilizada para pegar a posicao
//do cursor em um elemento de texto
var posGlobalCursor;

function WBR_Formata_OnImput(event,$b) {
	WBR_ValidaConteudo($b);
	WBR_FormataSeparador($b,WBR_GetInicioSelecao($b));
};

function WBR_ValidaConteudo($b) {
	var $c = "";
	var $d = $b.value;
	var $e = $b.getAttribute("mask");
	var $f = mascaraAlpha;
	var $g = mascaraNum;
	var $h = mascaraAlphaNum;
	var $i = $b.getAttribute("maskDisplay");
	for ( i = 0; i < $e.length; i++ ) {
		if ( $e.substring( i,( i + 1 ) ) == $f ) {
			while ( $d.length > 0 && ( !( ( $d.substring(0,1).charCodeAt(0) >= 65 && $d.substring(0,1).charCodeAt(0) <= 90 ) || ( $d.substring(0,1).charCodeAt(0) >= 97 && $d.substring(0,1).charCodeAt(0) <= 122 ) ) ) ) {
				$d=$d.substring(1);
			};
			if ( $d.length > 0 ) {
				$c += $d.substring(0,1);
				$d = $d.substring(1);
			}
			else {
				$c += $i;
			}
		}
		else if ( $e.substring(i,(i+1)) == $g ) {
			while ( $d.length > 0 && ( !( $d.substring(0,1).charCodeAt(0) >= 48 && $d.substring(0,1).charCodeAt(0) <= 57 ) ) ) {
				$d = $d.substring(1);
			};
			if ( $d.length > 0 ) {
				$c += $d.substring(0,1);
				$d = $d.substring(1);
			}
			else {
				$c+=$i;
			}
		}
		else if ( $e.substring(i,(i+1)) == $h ) {
			while ( $d.length > 0 && ( !( ( $d.substring(0,1).charCodeAt(0) >= 65 && $d.substring(0,1).charCodeAt(0) <= 90 ) || ( $d.substring(0,1).charCodeAt(0) >= 97 && $d.substring(0,1).charCodeAt(0) <= 122 ) || ( $d.substring(0,1).charCodeAt(0) >= 48 && $d.substring(0,1).charCodeAt(0) <= 57 ) ) ) ) {
				$d = $d.substring(1);
			};
			
			if ( $d.length > 0 ) {
				$c += $d.substring(0,1);
				$d = $d.substring(1);
			}
			else {
				$c += $i;
			}
		}
		else {
			$c += $e.substring(i,(i+1));
		}
	};
	$b.value = $c;	
};

function WBR_Valida_OnBlur($j,$b) {
	if ( $b == null ) {
		$b = $a;
	};
	WBR_FormataSeparador($b,$j);
};

function WBR_Formata_OnPaste($b) {
	var $d = window.clipboardData.getData("Text");
	var $j = WBR_MontaMascara($b,$d);
	$a=$b;
	window.setTimeout("WBR_Valida_OnBlur("+$j+")",10);
	WBR_StopEvent(event);
};

function WBR_Formata_OnCut($b) {
	var $k = WBR_GetInicioSelecao($b);
	var $l = WBR_GetSelectionEnd($b);
	if ( $k + $l == $b.value.length ) {
		window.clipboardData.setData("Text",$b.value);
		$b.value="";
		WBR_Formata_OnFocus($b,$msg);
	}
	else {
		var $i = $b.getAttribute("maskDisplay");
		window.clipboardData.setData("Text",$b.value.substring($k,($k+1)));
		WBR_UpdateChar($b,$k,$i);
		WBR_FormataSeparador($b,$k);
	};
	WBR_StopEvent(event);
};

function WBR_MontaMascara($b,$d) {
	var $c = "";
	if ( $d.length > 0 ) {
		var $e = $b.getAttribute("mask");
		var $f = mascaraAlpha;
		var $g = mascaraNum;
		var $h = mascaraAlphaNum;
		var $i = $b.getAttribute("maskDisplay");
		var $m = WBR_GetInicioSelecao($b);
		$c += $b.value.substring(0,$m);
		for ( i = $m; i < $e.length; i++ ) {
			if ( $e.substring(i,(i+1))==$f ) {
				while ( $d.length > 0 && ( !( ( $d.substring(0,1).charCodeAt(0) >= 65 && $d.substring(0,1).charCodeAt(0) <= 90 ) || ( $d.substring(0,1).charCodeAt(0) >= 97 && $d.substring(0,1).charCodeAt(0) <= 122 ) ) ) ) {
					$d = $d.substring(1);
				};
				if ( $d.length > 0 ) {
					$c += $d.substring(0,1);
					$d = $d.substring(1);
				}
				else {
					break;
				}
			}
			else if ( $e.substring( i,( i + 1 ) ) == $g) {
				while ( $d.length > 0 && ( !( $d.substring(0,1).charCodeAt(0) >= 48 && $d.substring(0,1).charCodeAt(0) <= 57 ) ) ) {
					$d = $d.substring(1);
				};
				if ( $d.length > 0 ) {
					$c += $d.substring(0,1);
					$d = $d.substring(1);
				}
				else {
					break;
				}
			}
			else if ( $e.substring( i,( i + 1 ) ) == $h ) {
				while ( $d.length > 0 && ( !( ( $d.substring(0,1).charCodeAt(0) >= 65 && $d.substring(0,1).charCodeAt(0) <= 90 ) || ( $d.substring(0,1).charCodeAt(0) >= 97 && $d.substring(0,1).charCodeAt(0) <= 122 ) || ( $d.substring(0,1).charCodeAt(0) >= 48 && $d.substring(0,1).charCodeAt(0) <= 57 ) ) ) ) {
					$d = $d.substring(1);
				};
				if ( $d.length > 0 ) {
					$c += $d.substring(0,1);
					$d = $d.substring(1);
				}
				else {
					break;
				}
			}
			else {
				$c += $e.substring(i,(i+1));
			}
		};
		$c += $b.value.substring(i,$e.length);
	};
	$b.value = $c;
	return i;
};

function WBR_PerdeFoco($b) {
	var $e = $b.getAttribute("mask");
	if ( $e != null && $b.value == WBR_GetDisplayMask($b,true) ) {
		$b.value="";
	}
	else {
		if ( $b.value != null && $b.value.length > 0 ) {
			var $n = $b.getAttribute("RegexPattern");
			var $o = $b.getAttribute("OnRegexMatch");
			var $p = $b.getAttribute("OnRegexNoMatch");
			if ( $n != null && $n.length > 0 ) {
				var re = new RegExp($n);
				if ( $b.value.match(re) ) {
					if ( $o != null && $o.length > 0) {
						eval($o);
					}
				}
				else {
					if ( $p != null && $p.length > 0 ) {
						eval($p);
					}
				}
			}
		}
	}
};

function WBR_Formata_OnKeyDown(event,$b) {
	var $e = $b.getAttribute("mask");
	if ( $e != null && $e.length > 0 ) {
		var k=WBR_GetKeyCode(event);
		if ( k == 8 || ( k >= 33 && k <= 40 ) || k == 46 ) {
			switch ( k ) {
				case 8  : WBR_KeyBackspace($b); break;
				case 33 : WBR_PushPosBegin($b); break;
				case 34 : WBR_PushPosEnd($b); break;
				case 35 : WBR_PushPosEnd($b); break;
				case 36 : WBR_PushPosBegin($b); break;
				case 37 : WBR_PushPosLeft($b); break;
				case 38 : WBR_PushPosLeft($b); break;
				case 39 : WBR_PushPosRight($b); break;
				case 40 : WBR_PushPosRight($b); break;
				case 46 : WBR_KeyDelete($b); break;
			};
			WBR_StopEvent(event);
		}
	}
};

function WBR_Formata_OnKeyPress(event,$b) {
	var $e = $b.getAttribute("mask");
	if ( $e != null && $e.length > 0 ) {
		var kc=WBR_GetKeyCode(event);
		var ss=WBR_GetInicioSelecao($b);
		if ( kc != 9 ) {
			if ( WBR_KeyIsValid($b,ss,kc) ) {
				var ks = String.fromCharCode(kc);
				WBR_UpdateChar($b,ss,ks);
				WBR_FormataSeparador($b,ss+1);
			}
			else {
				var $q = null;
				if ( $q != null && $q.length > 0) {
					eval($q);
				}
			};
			WBR_StopEvent(event);
		}
	}
};

function WBR_StopEvent(event) {
	if ( document.all ) {
		event.returnValue = false;
	}
	else if ( event.preventDefault ) {
		event.preventDefault();
	}
};

function WBR_StopEventPropagation(event) {
	event.cancelBubble = true;
	if ( event.stopPropagation ) {
		event.stopPropagation();
	}
};

function WBR_Formata_OnFocus($b,$msg) {
	var $e = $b.getAttribute("mask");
	//Como ao se formatar utiliza-se o evento OnFocus, perde-se a ajuda. Está foi
	//uma forma alternativa de exibir a ajuda.
	var $ajuda = $b.getAttribute("ajuda");
	if($ajuda !=null && $ajuda.length > 0){
	    var aux = "help_"+$b.id;
		document.getElementById(aux).innerHTML = $b.getAttribute("ajuda");
	}
	
	if ( $e != null && $e.length > 0 ) {
		var $r = WBR_GetInicioSelecao($b);
		var $j = WBR_GetValidPos($b,$r);
		if ( $j != -1 ) {
			if ( $b.value == null || $b.value.length == 0 ) {
				$b.value = WBR_GetDisplayMask($b,true);
			};
			WBR_FormataSeparador($b,$j);
		}
		else {
			$b.blur();
		}
	}
};

function WBR_Formata_OnClick(event,$b) {
	var $e = $b.getAttribute("mask");
	if ( $e != null && $e.length > 0 ) {
		var $s = WBR_GetInicioSelecao($b);
		WBR_FormataSeparador($b,$s);
	};
	WBR_StopEventPropagation(event);
};

function WBR_GetKeyCode(event){
	return ( event.keyCode ? event.keyCode : event.which ? event.which : event.charCode );
};

function WBR_KeyDelete($b) {
	var $k = WBR_GetInicioSelecao($b);
	var $l = WBR_GetSelectionEnd($b);
	if ( $k + $l == $b.value.length ) {
		$b.value = "";
		WBR_Formata_OnFocus($b);
	}
	else {
		var $i = $b.getAttribute("maskDisplay");
		WBR_UpdateChar($b,$k,$i);
		WBR_FormataSeparador($b,$k+1);
	}
};

function WBR_KeyBackspace($b) {
	var $k = WBR_GetInicioSelecao($b);
	var $l = WBR_GetSelectionEnd($b);
	if ( $k + $l == $b.value.length ) {
		$b.value = "";
		WBR_Formata_OnFocus($b);
	}
	else {
		var $i = $b.getAttribute("maskDisplay");
		WBR_UpdateChar($b,$k,$i);
		$j = WBR_GetValidPos($b,$k-1,true);
		WBR_FormataSeparador($b,$j);
	}
};

function WBR_PushPosLeft($b) {
	var k = WBR_GetInicioSelecao($b);
	if ( ( k -1 ) >= 0 ) {
		WBR_FormataSeparador($b,(k-1),true);
	}
};

function WBR_PushPosRight($b) {
	var k = WBR_GetInicioSelecao($b);
	if ( ( k + 1 ) < $b.value.length ) {
		WBR_FormataSeparador($b,(k+1));
	}
};

function WBR_PushPosBegin($b) {
	WBR_FormataSeparador($b,0);
};

function WBR_PushPosEnd($b) {
	WBR_FormataSeparador($b,$b.getAttribute("mask").length);
};

function WBR_UpdateChar($b,$j,ks) {
	var x = $b.value;
	var $t = x.substring(0,$j);
	var $u = x.substring($j+1,x.length);
	$b.value = $t + ks + $u;
};

function WBR_FormataSeparador($b,$j,$v) {
	if ( $j <= 0 ) {
		$j = 0;
	};
	if ( $j >= $b.value.length - 1 ) {
		$j = $b.value.length-1
	};
	$j = WBR_GetValidPos($b,$j,$v);
	if ( $j != -1 ) {
		if ( $b.createTextRange ) {
			var $w=$b.createTextRange();
			$w.moveStart("character",$j);
			$w.moveEnd('character',$j+1-$b.value.length);
			$w.select();
		}
		else if ( $b.setSelectionRange ) {
			$b.focus();
			$b.setSelectionRange($j,$j+1);
		}
	}
	else {
		$b.blur();
	}
};

function WBR_GetValidPos($b,$j,$v) {
	if ( $v == null ) {
		$v=false;
	};
	if ( WBR_PosIsValid($b,$j) ) {
		return $j;
	}
	else {
		var $e = $b.getAttribute("mask");
		if ( $v ) {
			while ( $j >= 0 ) {
				if ( WBR_PosIsValid($b,$j) ) {
					return $j;
				};
				$j--;
			};
			while ( $j < $e.length - 1 ) {
				if ( WBR_PosIsValid($b,$j) ) {
					return $j;
				};
				$j++;
			}
		}
		else {
			while ( $j < $e.length - 1 ) {
				if ( WBR_PosIsValid($b,$j) ) {
					return $j;
				};
				$j++;
			};
			while ( $j >= 0 ) {
				if ( WBR_PosIsValid($b,$j) ) {
					return $j;
				};
				$j--;
			}
		};
		return -1;
	}
};

function WBR_PosIsValid($b,$j) {
	var $e = $b.getAttribute("mask");
	var m = $e.split("");
	if ( m.length > $j ) {
		if ( m[$j] != null ) {
			var $f = mascaraAlpha;
			var $g = mascaraNum;
			var $h = mascaraAlphaNum;
			if ( m[$j] == $f || m[$j] == $g || m[$j] == $h ) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
};

function WBR_KeyIsValid($b,$j,$x) {
	var m = $b.getAttribute("mask").split("");
	if ( m.length > $j ) {
		var $y = m[$j];
		var $z = mascaraAlpha;
		var $A = mascaraNum;
		var $B = mascaraAlphaNum;
		if ( $y == $z ) {
			if ( ( $x >= 65 && $x <= 90 ) || ( $x >= 97 && $x <= 122 ) ) {
				return true;
			}
			else {
				return false;
			}
		}
		else if ( $y == $A ) {
			if ( $x >= 48 && $x <= 57 ) {
				return true;
			}
			else {
				return false;
			}
		}
		else if ( $y == $B ) {
			if ( ( $x >= 48 && $x <= 57 ) || ( $x >= 65 && $x <= 90 ) || ( $x >= 97 && $x <= 122 ) ) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
};

function WBR_GetInicioSelecao($b) {
	if ($b.createTextRange ) {
		$C = document.selection.createRange().duplicate();
		$C.moveEnd("character",$b.value.length);
		$j = $b.value.lastIndexOf($C.text);
		if ( $C.text == "" )
			$j = $b.value.length;
		return $j;
	}
	else {
		return $b.selectionStart;
	}
};

function WBR_GetSelectionEnd($b) {
	if ( $b.createTextRange ) {
		$C = document.selection.createRange().duplicate();
		$C.moveStart("character",-$b.value.length);
		$j = $C.text.length;
		return $j;
	}
	else {
		return $b.selectionEnd;
	}
};

function WBR_GetDisplayMask($b,$D) {
	var $e = $b.getAttribute("mask");
	if ( $D == true ) {
		var f = "";
		var $f = mascaraAlpha;
		var $g = mascaraNum;
		var $h = mascaraAlphaNum;
		var $i = $b.getAttribute("maskDisplay");
		var m = $e.split("");
		for ( mi = 0; mi < m.length; mi++ ) {
			if ( m[mi] == $f || m[mi] == $g || m[mi] == $h ) {
				f += $i;
			}
			else {
				f += m[mi];
			}
		};
		return f;
	}
	else {
		return $e;
	}
}

function formata_valor(campo_valor) {
	var valor = campo_valor.value;
	var nro_formatado = "";
	var count_virgula = 0;
	var count_ponto = 0;
	var coloquei_virgula = false;
	for ( i = valor.length - 1; i >= 0; i-- ) {
		if ( ( valor.charAt(i) >= "0" && valor.charAt(i) <= "9" ) || valor.charAt(i) == "-" ) {
			if ( valor.charAt(i) != "-" ) {
				if ( count_virgula == 2 && !coloquei_virgula ) {
					nro_formatado = "," + nro_formatado;
					coloquei_virgula = true;
				} //if
				if ( count_ponto != 0 && ( count_ponto % 3 ) == 0 )
					nro_formatado = "." + nro_formatado;
				if ( coloquei_virgula )
					count_ponto++;
				else
					count_virgula++;
			} //if ( valor.charAt(i) != "-" )
			nro_formatado = valor.charAt(i) + nro_formatado;
		} //if ( ( valor.charAt(i) >= "0" && valor.charAt(i) <= "9" ) || valor.charAt(i) == "-" )
	} //Fim do for
	campo_valor.value = nro_formatado;
}

function formata_campo(objeto, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;
	
	if ( document.all ) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	} //if
	else { // Nestcape
		nTecla = evtKeyPress.which;
	}
	
	sValue = objeto.value;
	
	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;
	
	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;
	
	while ( i <= mskLen ) {
		bolMask = ((sMask.charAt(i) == ":") || (sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
		
		if ( bolMask ) {
			sCod += sMask.charAt(i);
			mskLen++;
		} //if
		else {
			sCod += sValue.charAt(nCount);
			nCount++;
		} //Fim do else
		i++;
	} //Fim do while
	
	objeto.value = sCod;
	
	if ( nTecla != 8 ) { // backspace
		if ( sMask.charAt(i-1) == "9" ) { // apenas números...
			return ((nTecla > 47) && (nTecla < 58));
		} // números de 0 a 9
		else { // qualquer caracter...
			return true;
		} //Fim do else
	} //if
	else {
		return true;
	} //Fim do else
}

//Atribui a posição atual do cursor para a variável posGlobalCursor
//em cada alteração que ocorrer na textarea
function setPosCursor( campo ) {
	posGlobalCursor = getPosCursor( campo );
}

//Função que retorna a posição atual do cursor no elemento passado a ela
function getPosCursor( textElement ) {
	
	var sOldText = textElement.value;
	
	var objRange = document.selection.createRange();
	var sOldRange = objRange.text;
	
	var sWeirdString = '#%~';
	
	objRange.text = sOldRange + sWeirdString;
	objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length));
	
	var sNewText = textElement.value;
	
	objRange.text = sOldRange;
	
	for ( i = 0; i <= sNewText.length; i++ ) {
		var sTemp = sNewText.substring(i, i + sWeirdString.length);
		if ( sTemp == sWeirdString ) {
			var cursorPos = ( i - sOldRange.length );
			return cursorPos;
		} //if
	} //Fim do for
}

function auto_tab(campo1, tamanho, campo2) {
	var tam_campo1 = document.getElementById(campo1).value.length;
	if ( tam_campo1 >= tamanho )
		document.getElementById(campo2).focus();
}

