var IsIE = false;
if('\v'=='v') IsIE = true;

function onlyLetters(e){var k;document.all?k=e.keyCode:k=e.which;return ((k>94&&k<91) ||(k==32)  || (k==219) || (k==59) || (k==222) || (k==16) || (k==192) || (k==190) || (k >140) || k ==37 || k ==39 ||k ==35 ||k ==36 ||k ==46 || (k>64&&k<91)||(k>96&&k<123)||k==8||k==0);}


var Key ={
	BACKSPACE : 8,
	NONE : 0		
}

function validaMaxLenght(e,fieldname, sizefield){
	var k;
	IsIE ? k = e.keyCode : k = e.which;
	field = document.getElementById(fieldname)
	if((sizefield-field.value.length)<=0){
		if (k==8 || k ==0){
			return true;
		} else {
			return false;
		}
	}
}


var DateValidator = {
	_epattern : new RegExp("[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9]"), isDateValid:function (date){
		if (DateValidator._epattern.test(date)) return true;
		return false;
	}
}



var NomeValidatorFull = {
	isNomeValid:function (nome,id){
		return (NomeValidator.isNomeValid(nome) && NomeValidatorSemNumero.isNomeValidSemNumero(nome) && repeticao3Caracteres(id));
	}
}

var NomeValidator = {	
	isNomeValid:function (nome){
		if(nome.length >= 6) return true;
		return false;
	}
}

var NomeValidatorSugestao = {
	_epattern : new RegExp("[\,\.\:\;\?\/\}\!\@\#\$\%\&\*\(/)\+\=]"), isNomeValid:function(nome){
		if(NomeValidatorSugestao._epattern.test(nome)) return false;
		if(nome.length >= 3) return true;		
		return false;
   }
}

var NomeValidatorSemNumero = {
	_epattern : new RegExp("[0-9]"), isNomeValidSemNumero:function (nome){
		if (NomeValidatorSemNumero._epattern.test(nome)) return false;
		return true;
	}	
}

function repeticao3Caracteres(id){
	var campo = document.getElementById(id);
	var texto = campo.value;
	for(var i=0;i<texto.length;i++){
		var temp = texto.charAt(i);
		//var iguais = false;
		if( ((i+1) < (texto.length -1)) && ((i+2) < (texto.length)) ){
			if((texto.charAt(i) == texto.charAt(i+1)) && (texto.charAt(i) ==texto.charAt(i+2)) ){
				//iguais = true;
				return false;
			}		
		}	
		return true;
	}
}

function repeticao4Caracteres(id){
	var campo = document.getElementById(id);
	var texto = campo.value;
	for(var i=0;i<texto.length;i++){
		var temp = texto.charAt(i);
		//var iguais = false;
		if( ((i+1) < (texto.length -1)) && ((i+2) < (texto.length)) && ((i+3) < (texto.length)) ){
			if((texto.charAt(i) == texto.charAt(i+1)) && (texto.charAt(i) ==texto.charAt(i+2))  && (texto.charAt(i) ==texto.charAt(i+3))   ){
				//iguais = true;
				return false;
			}		
		}	
		return true;
	}
}

var CharRepetido = {
	isCharRepetido:function(palavra){
		var teste = true
		var atual = 0;
		for (x=0;x<palavra.length;x++){
			if (palavra[x]==palavra[x+1]) {}
		}
		return teste;
	}
}

var DiaValidator = {
	isDiaValid:function(dia){
		return dia >=1 && dia <=31;
	}
}

var MesValidator = {
	isMesValid:function(mes){
		return mes >=1 && mes <=12;
	}
}

var AnoValidator = {
	isAnoValid:function(ano){
		return ano >=1900 && ano <=3000;
	}
}

var EmailValidator = {
	_epattern : new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+\\.+([a-zA-Z0-9]{2,4})+"), isEmailValid:function (email){
		if (EmailValidator._epattern.test(email)) return true;
		return false;
	}
}

var DateValidator = {
	_epattern : new RegExp("[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9]"), isDateValid:function (date){
		if (DateValidator._epattern.test(date)) return true;
		return false;
	}
}

var TelValidator = {
	_epattern : new RegExp(".([0-9]{2}.) [0-9]{4}-[0-9]{4}|.([0-9]{2}.) [0-9]{8}|.([0-9]{2}.) [0-9]{8}|[0-9]{2}-[0-9]{8}|[0-9]{8}"), isTelValid:function (tel){
		if (TelValidator._epattern.test(tel)) return !isNumberRedundant(tel);
		return false;
	}
}

function isNumberRedundant(value){
	value = value.replace("-","");value = value.replace(")","");value = value.replace("(","");
	value = recuperaTel(value);
	var vetor = new Array();
	for (i=0;i<=9;i++) {
		vetor[i]=0;
	}
	for (i=0;i<8;i++) {
		vetor[value.charAt(i)]++;
	}
	for(i=0;i<=9;i++){
		if (vetor[i]>=7 ){return true;}
	}
	return false;
}

function recuperaTel(tel){
	return tel.substring(tel.length-8,tel.length);
}

var TelValidatorWithLimitChar = {
	_epattern : new RegExp(".([0-9][0-9].) [0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|.([0-9][0-9].) [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|.([0-9][0-9].) [0-9][0-9][0-9][0-9][0-9][0-9][0-9]"), isTelValid:function (tel){
		if (TelValidator._epattern.test(tel)&& tel.length==14) return true;
		return false;
	}
}

var CEPValidator = {
	_epattern : new RegExp("[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"), isCEPValid:function (cep){
		if (CEPValidator._epattern.test(cep)) return true;
		return false;
	}
}

var CPFValidator = {
	isCPFValid:function(cpf) {
		var numeros, digitos, soma, i, resultado, digitos_iguais;
		digitos_iguais = 1;
		if (cpf.length < 11)
			return false;
		for (i = 0; i < cpf.length - 1; i++)
			if (cpf.charAt(i) != cpf.charAt(i + 1)) {
				digitos_iguais = 0;
				break;
			}
		if (!digitos_iguais) {
			numeros = cpf.substring(0,9);
			digitos = cpf.substring(9);
			soma = 0;
			for (i = 10; i > 1; i--)
				soma += numeros.charAt(10 - i) * i;
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(0))
				return false;
			numeros = cpf.substring(0,10);
			soma = 0;
			for (i = 11; i > 1; i--)
				soma += numeros.charAt(11 - i) * i;
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(1))
				return false;
			return true;
		} else
			return false;
	}
}

var CNPJValidator = {
	isCNPJValid:function(cnpj) {
		var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
		digitos_iguais = 1;
		if (cnpj.length < 14 && cnpj.length < 15)
			return false;
		for (i = 0; i < cnpj.length - 1; i++)
			if (cnpj.charAt(i) != cnpj.charAt(i + 1)) {
				digitos_iguais = 0;
				break;
			}
		if (!digitos_iguais) {
			tamanho = cnpj.length - 2
			numeros = cnpj.substring(0,tamanho);
			digitos = cnpj.substring(tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--) {
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2)
					pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(0))
				return false;
			tamanho = tamanho + 1;
			numeros = cnpj.substring(0,tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--) {
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2)
					pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(1))
				return false;
			return true;
		} else
			return false;
	}
}

var Validator = {
	_epattern : new RegExp("^([a-zA-Z0-9_\.\-])+\@\(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+"), isEmailValid : function (addr){
		var str = addr
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){return false}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){return false}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){return false}
		if (str.indexOf(at,(lat+1))!=-1){return false}
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){return false}
		if (str.indexOf(dot,(lat+2))==-1){
			var at="@"
			var dot="."
			var lat=str.indexOf(at)
			var lstr=str.length
			var ldot=str.indexOf(dot)
			if (str.indexOf(at)==-1){return false}
			if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){return false}
			if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){return false}
			if (str.indexOf(at,(lat+1))!=-1){return false}
			if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){return false}
			if (str.indexOf(dot,(lat+2))==-1){return false}
			if (str.indexOf(" ")!=-1){return false}
			return true	
			return false
		}
		if (str.indexOf(" ")!=-1){return false}
		if(Validator._epattern.test(addr)) {return true;}else {return false;}
		return true	
	}	
}

var Formatter = {
	dateFormat : function(obj) {
	// function formatDate(d,e) {var k;document.all?k=e.keyCode:k=e.which;if(!onlyNumbers(e)){return false;}else if(k==Key.BACKSPACE){return true;}value=d.value;if(value.length==2||value.length==5){value=value+"/";}d.value = value;}
},	

_formatField : function(campo, Mascara, evento) {
	var boleanoMascara;
	var Digitato = (!IsIE)?evento.which: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;
	}
},
telFormat : function(tel,e) {
	if(Formatter.isNumber(e) == false) {
		e.returnValue = false;
		return false;
	}		
	return Formatter._formatField(tel, '(00) 0000-0000', e);
},
currencyFormat : function(objTextBox, e) {
	// Autor: Gabriel Fróes - 15/02/2005 - Modificado por Fred Alves - 30/09/2006
	var sep=0;var key='';var milSep=".";var decSep=",";var i=j=0;var len=len2=0;var strCheck='0123456789';var aux=aux2='';
	var whichCode=(!IsIE)?e.which:e.keyCode;

	if(whichCode==13||whichCode==8 ||whichCode==9 || whichCode==0)return true;
	key=String.fromCharCode(whichCode);
	if(strCheck.indexOf(key) == -1) return false;
	len = objTextBox.value.length;
	for(i=0;i<len;i++) if((objTextBox.value.charAt(i)!='0')&&(objTextBox.value.charAt(i)!=decSep)) break;
	aux='';
	for(;i<len;i++) if(strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux+=objTextBox.value.charAt(i);
	aux+=key;
	len = aux.length;
	if(len==0) objTextBox.value='';
	if(len==1) objTextBox.value='0'+decSep+'0'+aux;
	if(len==2) objTextBox.value='0'+decSep+aux;
	if(len>2){aux2='';for(j=0,i=len-3;i>=0;i--) {if(j==3){aux2+=milSep;j=0;}aux2+=aux.charAt(i);j++;}objTextBox.value='';len2=aux2.length;for(i=len2-1;i>=0;i--) objTextBox.value+=aux2.charAt(i);objTextBox.value+=decSep+aux.substr(len-2,len);}
	return false;
},
CNPJFormat : function(el, e) {
	if(Formatter.isNumber(e) == false) {
		e.returnValue = false;
		return false;
	}
	return Formatter._formatField(el, '00.000.000/0000-00', e);		
},
dateFormat : function(d,e) {
	if(Formatter.isNumber(e) == false) {
		e.returnValue = false;
		return false;
	}
	return Formatter._formatField(d, '00/00/0000', e);		
},
isNumber : function(e) {
		var k;
		IsIE ? k = e.keyCode : k = e.which;
		return ( (k>47&&k<58) || k==Key.BACKSPACE||k==Key.NONE);
},
fncKeyStop: function(e){
	var k;
	IsIE ? k = e.keyCode : k = e.which;
	// Check if the control key is pressed.
	// If the Netscape way won't work (event.modifiers is undefined),
	// try the IE way (event.ctrlKey)
	var ctrl = e.ctrlKey;
	
	// Check if the 'V' key is pressed.
	// If the Netscape way won't work (event.which is undefined),
	// try the IE way (event.keyCode)
	var v = (k == 86) ;
	
	// If the control and 'V' keys are pressed at the same time
	if ( ctrl && v ) {
	// ... discard the keystroke and clear the text box
	document.getElementById('email_confirmacao').value = '';	
	return false;
	}
	return true;		
	}
}

function onlyNumber(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) 
    	return true;
    else{
    	if (tecla != 8) return false;
    	else return true;
    }
}

function bloqueiaEspeciais(e) {
	var tecla=(window.event)?event.keyCode:e.which;
	if ((tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122) || (tecla >= 48 && tecla <= 57) || (tecla == 46)) {
		//Não bloqueia
    } else {
		//Bloqueia
       	if (e.keyCode) e.returnValue = false;
        else e.preventDefault();
   	}
}

/*
   Valida string com caracteres repetidos
*/
function testStringRepeated(str){
	
	var validador = false;
	for(var i = 0; i < (str.length - 2); i++){
		//alert("1: "+i+" |char: "+str.charAt(i)+" |char2: "+str.charAt(i+1)+" |char2: "+str.charAt(i+2));
		if(str.charAt(i) == str.charAt(i+1))
			if(str.charAt(i+1) == str.charAt(i+2))
				validador = true;
	}
	return validador;
}

/*
  calcular a idade de uma pessoa
  recebe a data como um string em formato portugues
  devolve um inteiro com a idade. Devolve false em caso de que a data seja incorreta ou maior que o dia atual
*/
function returnAge(data){

	//calculo a data de hoje
	var hoje = new Date()
	//alert(data);

	//calculo a data que recebo
	//descomponho a data em um array
	var array_data = data.split("/");
	//se o array nao tem tres partes, a data eh incorreta
	if (array_data.length != 3)
		return false;

	//comprovo que o ano, mes, dia são corretos
	var ano;
	ano = parseInt(array_data[2]);
	if (isNaN(ano))
		return false;

	var mes;
	mes = parseInt(array_data[1]);
 	if (isNaN(mes))
 		return false;

 	var dia;
 	dia = parseInt(array_data[0]);
 	if (isNaN(dia))
 		return false;


 	//se o ano da data que recebo so tem 2 cifras temos que muda-lo a 4
 	if (ano <= 99)
 		ano += 1900;

 	//subtraio os anos das duas datas  
 	var idade = (hoje.getFullYear() - ano) - 1; //-1 porque ainda nao fez anos durante este ano

 	//se subtraio os meses e for menor que 0 entao nao cumpriu anos. Se for maior sim ja cumpriu
 	if ( ((hoje.getMonth() + 1) - mes) < 0 ) //+ 1 porque os meses comecam em 0
 		return idade;
 	if ( ((hoje.getMonth() + 1) - mes) > 0 )
 		return idade + 1;

 	//entao eh porque sao iguais. Vejo os dias
 	//se subtraio os dias e der menor que 0 entao nao cumpriu anos. Se der maior ou igual sim que já cumpriu
 	if ( (hoje.getUTCDate() - dia) >= 0 )
 		return idade + 1;
  
 	//alert(idade);
 	return idade;
}
