/*função: SomenteNumero
 *Sintaxe: onkeypress="somenteNumero(event);"
 *Só deixa digitar numerico em formulario. */
function somenteNumero(teclapres){
	if (teclapres.keyCode < 45 || teclapres.keyCode > 57) {
		teclapres.returnValue = false;
	}
}

/*função: FormataData
 *Sintaxe:  onkeyup="FormataData(this, event);"
 *Formata a data digitada no formato dd/mm/aaaa. */
function FormataData(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Campo.value;
	vr = vr.replace(".","");
	vr = vr.replace("/","");
	vr = vr.replace("/","");
	vr = vr.replace("/","");
	tam = vr.length + 1;

	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5){
			Campo.value = vr.substr(0,tam-2)+'/'+vr.substr(tam-2,tam);
		}
		if (tam >= 5 && tam <= 10){
			Campo.value = vr.substr(0,2)+'/'+vr.substr(2,2)+'/'+vr.substr(4,4);
		}
	}
}

/*função: FormataMesAno
 *Sintaxe:  onkeyup="FormataMesAno(this, event);"
 *Formata a data digitada no formato mm/aaaa. */
function FormataMesAno(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Campo.value;
	vr = vr.replace(".","");
	vr = vr.replace("/","");
	vr = vr.replace("/","");
	vr = vr.replace("/","");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam > 2){
			Campo.value = vr.substr(0,2)+'/'+vr.substr(2);
		}
	}
}

/*função: FormataHora
 *Sintaxe:  onkeyup="FormataHora(this, event);"
 *Formata a hora digitada no formato 99:99. */
function FormataHora(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Campo.value;
	vr = vr.replace("-","");
	vr = vr.replace(".","");
	vr = vr.replace(":","");
	vr = vr.replace(":","");
	vr = vr.replace(":","");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5){
			Campo.value = vr.substr(0,tam-2)+':'+vr.substr(tam-2,tam);
		}
	}
}

/*função: FormataCPF
 *Sintaxe:  onkeyup="FormataCPF(this, event);"
 *Formata o CPF digitado no formato 999.999.999-99. */
function FormataCPF(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Campo.value;
	vr = vr.replace(".","");
	vr = vr.replace(".","");
	vr = vr.replace(".","");
	vr = vr.replace(".","");
	vr = vr.replace("-","");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam <= 3){ Campo.value = vr ; }
	 	if ((tam > 3) && (tam <= 6)){
	 		Campo.value = vr.substr(0,3)+'.'+vr.substr(3,tam);
		}
	 	if ((tam > 6) && (tam <= 9)){
	 		Campo.value = vr.substr(0,3)+'.'+vr.substr(3,3)+'.'+vr.substr(6,tam);
		}
	 	if ((tam > 9) && (tam <= 11)){
		 	Campo.value = vr.substr(0,3)+'.'+vr.substr( 3, 3 )+'.'+vr.substr(6,3)+'-'+vr.substr(9,tam);
		}
	}
}

/*função: FormataCEP
 *Sintaxe:  onkeyup="FormataCEP(this, event);"
 *Formata o CEP digitado no formato 99999-999. */
function FormataCEP(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Campo.value;
	vr = vr.replace("-","");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam <= 5){ Campo.value = vr ; }
		if (tam > 5 && tam <= 9){
			Campo.value = vr.substr(0,5)+'-'+vr.substr(5,tam);
		}
	}
}

/*função: FormataValor
 *Sintaxe:  onkeypress="FormataValor(this,12,event);"
 *Formata o valor(R$) digitado no formato 9.999.999,99. */
function FormataValor(Campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Campo.value;
	sinal = "";
	if (vr.substring(0,1) == "0"){
		vr = vr.replace("0,0","");
		vr = vr.replace("0,","");
	}
	vr = vr.replace(".","");
	vr = vr.replace(".","");
	vr = vr.replace(".","");
	vr = vr.replace(".","");
	vr = vr.replace(",","");
	tam1 = vr.length;
	tam = vr.length+1;
	
	if (tam >= tammax){
		teclapres.returnValue = false;
	}else{
		if (tecla != 9 && tecla != 8){
			//if ( tam <= 3 ){ valorFormatado = vr ; }
			if (tam > 0 && tam < 2)
				Campo.value = '0,0'+vr.substr(0,tam-1);
			if (tam >= 2 && tam < 3)
				Campo.value = '0,' + vr.substr(0,tam);
			if ((tam >= 3) && (tam <= 5)){
				Campo.value = vr.substr(0,tam-2)+','+vr.substr(tam-2,tam);
			}
			if ((tam > 5) && (tam <= 8)){
		 		Campo.value = vr.substr(0,tam-5)+'.'+vr.substr(tam-5,3)+','+vr.substr(tam-2,tam);
			}
		 	if ((tam > 8) && (tam <= 11)){
			 	Campo.value = vr.substr(0,tam-8)+'.'+vr.substr(tam-8,3)+'.'+vr.substr(tam-5,3)+','+vr.substr(tam-2,tam);
			}
			if ((tam > 11) && (tam <= 14)){
				Campo.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);
			}
		}
	}
}

/*função: verificaEmail
 *Sintaxe:  verificaEmail(emailDigitado);"
 *Verifica se um email é válido */
function verificaEmail(email) {
	var s = new String(email);
	// { } ( ) < > [ ] | \ /
	if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	if (vogalAcentuada(email))
		return false;
	// & * $ % ? ! ^ ~ ` ' "
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )
		return false;
	// , ; : = #
	if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) )
		return false;
	// procura se existe apenas um @
	if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )
		return false;
	// verifica se tem pelo menos um ponto após o @
	if (s.lastIndexOf(".") < s.indexOf("@"))
		return false;
	return true;
}

/*função: verificaCEP
 *Sintaxe:  verificaCEP(cepDigitado);"
 *Verifica se um cep é válido */
function verificaCEP(cep) {
	s = new String(cep);
	cep = cep.replace("-","");
	if ((s.length > 9) || (s.length < 5))
		return false;
	if (!isInteger(cep))
		return false;
	return true;
}

/*função: verificaCPF
 *Sintaxe:  verificaCPF(cpfDigitado);"
 *Verifica se um CPF é válido */
function verificaCPF(cpf){
	if(cpf == "") {
		return true;
	}
	cpf = cpf.replace(".","");
	cpf = cpf.replace(".","");
	cpf = cpf.replace(".","");
	cpf = cpf.replace("-","");
	var dac = "", inicio = 2, fim = 10, soma, digito, i, j
	for (j=1;j<=2;j++) {
		soma = 0
		for (i=inicio;i<=fim;i++) {
			soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)
		}
		if (j == 2) { soma += 2*digito }
		digito = (10*soma) % 11
		if (digito == 10) { digito = 0 }
		dac += digito
		inicio = 3
		fim = 11
	}
	validacao = (dac == cpf.substring(cpf.length-2,cpf.length))
	if(cpf == "11111111111"){ validacao = false; }
	if(cpf == "22222222222"){ validacao = false; }
	if(cpf == "33333333333"){ validacao = false; }
	if(cpf == "44444444444"){ validacao = false; }
	if(cpf == "55555555555"){ validacao = false; }
	if(cpf == "66666666666"){ validacao = false; }
	if(cpf == "77777777777"){ validacao = false; }
	if(cpf == "88888888888"){ validacao = false; }
	if(cpf == "99999999999"){ validacao = false; }
	
	return validacao
}

/*função: verificaCGC
 *Sintaxe:  verificaCGC(cgcDigitado);"
 *Verifica se um CGC é válido */
function verificaCGC(scgc) {
	cgc = trimtodigits(scgc);
	if ((cgc.indexOf("-") != -1) || (cgc.indexOf(".") != -1) || (cgc.indexOf("/") != -1)){
		return( false )
	}
	var df, resto, dac = ""
	df = 5*cgc.charAt(0)+4*cgc.charAt(1)+3*cgc.charAt(2)+2*cgc.charAt(3)+9*cgc.charAt(4)+8*cgc.charAt(5)+7*cgc.charAt(6)+6*cgc.charAt(7)+5*cgc.charAt(8)+4*cgc.charAt(9)+3*cgc.charAt(10)+2*cgc.charAt(11)
	resto = df % 11
	dac += ( (resto <= 1) ? 0 : (11-resto) )
	df = 6*cgc.charAt(0)+5*cgc.charAt(1)+4*cgc.charAt(2)+3*cgc.charAt(3)+2*cgc.charAt(4)+9*cgc.charAt(5)+8*cgc.charAt(6)+7*cgc.charAt(7)+6*cgc.charAt(8)+5*cgc.charAt(9)+4*cgc.charAt(10)+3*cgc.charAt(11)+2*parseInt(dac)
	resto = df % 11
	dac += ( (resto <= 1) ? 0 : (11-resto) )
	return (dac == cgc.substring(cgc.length-2,cgc.length))
}

/* function warnInvalid
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert */
function warnInvalid (theField, warnText)
{   theField.focus()
    theField.select()
	alert(warnText)
    return false
}

// Verrifica o tem caracteres invalidos
function checkField(s) {
	if ((s.indexOf("&")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	return true;
}

// Verifica se uma string tem vogais acentuadas
function vogalAcentuada(s) {
	ls = s.toLowerCase();
	if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
		return true;
}

/*função: isInteger
 *Sintaxe:  isInteger(numero);"
 *Verifica se um campo é inteiro, inclui dígitos de 0 a 9, vírgula, ponto, espaços e - */
function isInteger(s){
	var i;
	if (isEmpty(s))
		return false;
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (!isNumber(c)) return false;
	}
	return true;
}

/*função: isNumber
 *Sintaxe:  isNumber(numero);"
 *Verifica se a string possui apenas caracteres numéricos */
function isNumber(strNumber) {
	for(var i = 0; i < strNumber.length; i++) {
		if(strNumber.charAt(i) < '0' || strNumber.charAt(i) > '9'){return(false)}
	}
	return(true);
}

/*função: isEmpty
 *Sintaxe:  isEmpty(str);"
 *Retorna verdadeiro se a string for vazia ou composta apenas de espaços */
function isEmpty(str) { 
	if (str==null) return true;
	if (str.length == 0) return true;
	for (var intLoop = 0; intLoop < str.length; intLoop++){
		if (" " != str.charAt(intLoop)){
			return false;
		}
	}	            
	return true;
}

function bissexto(year) {
	if (year % 4 == 0) // regra básica
		return true // se o ano é bissexto
	/* else */ // neste caso o else não é necessario
	return false // se o ano não é bissexto
}

// Verifica se a string representa um valor do tipo date
function IsDate(strDate){
	barras = strDate.split("/");
	if (barras.length == 3){
		dia = parseInt(barras[0], 10);
		mes = parseInt(barras[1], 10);
		ano = parseInt(barras[2], 10);
		strAno = barras[2];
		bi = bissexto(ano) ? 29 : 28;
		diasmes = [31,bi,31,30,31,30,31,31,30,31,30,31];
		
		if (isNaN(dia) || (dia <= 0) || (dia > diasmes[mes-1])){return(false)}
		if (isNaN(mes) || (mes <= 0) || (mes > 12)){return(false)}
		if (isNaN(ano) || (strAno.length != 4) || (ano > 2100) || (ano < 1900)){return(false)}
	} else {
		return(false);
	}
	return(true);
}
/*
function IsDate(strDate) {
	var i, intDay, intMonth, intYear;
	strFormat = "/dmy";
	if(strDate.length < 8){return(false)}
	
	intSep1 = strDate.indexOf(strFormat.charAt(0));
	intSep2 = strDate.lastIndexOf(strFormat.charAt(0));
	strParts = new Array(strDate.substring(0, intSep1), strDate.substring(intSep1 + 1, intSep2), strDate.substr(intSep2 + 1, 4));
	for(i = 0; i < 3; i++) {
		switch(strFormat.charAt(i + 1)) {
			case "d": intDay = parseInt(strParts[i], 10); break;
			case "m": intMonth = parseInt(strParts[i], 10); break;
			case "y": intYear = parseInt(strParts[i], 10); break;
		}
	}
	if(!isNumber(intYear)){return(false)}
	return(IsBetween(intDay, 1, MonthDays(intMonth, intYear)));
}
*/

// Verifica se um valor está dentro da faixa representada por outros dois
function IsBetween(intValue, intMin, intMax) {
	return(intValue >= intMin && intValue <= intMax);
}

function dataMaiorIgual(dt1,dt2){
	barra1 = dt1.split("/");
	dia = parseInt(barra1[0], 10);
	mes = parseInt(barra1[1], 10);
	ano = parseInt(barra1[2], 10);
	var data1 = new Date(ano,mes - 1,dia);
	barra2 = dt2.split("/");
	dia = parseInt(barra2[0], 10);
	mes = parseInt(barra2[1], 10);
	ano = parseInt(barra2[2], 10);
	var data2 = new Date(ano,mes - 1,dia);
	//alert(dt1 +" - "+ dt2 +" - "+ data1 +" - "+ data2);
	if(data1 >= data2){
		return true;
	}else{
		return false;
	}
}

function dataMaior(dt1,dt2){
	barra1 = dt1.split("/");
	dia = parseInt(barra1[0], 10);
	mes = parseInt(barra1[1], 10);
	ano = parseInt(barra1[2], 10);
	var data1 = new Date(ano,mes - 1,dia);
	barra2 = dt2.split("/");
	dia = parseInt(barra2[0], 10);
	mes = parseInt(barra2[1], 10);
	ano = parseInt(barra2[2], 10);
	var data2 = new Date(ano,mes - 1,dia);
	//alert(dt1 +" - "+ dt2 +" - "+ data1 +" - "+ data2);
	if(data1 > data2){
		return true;
	}else{
		return false;
	}
}

// Retorna o nº de dias de um mês num certo ano
function MonthDays(intMonth, intYear){
	switch(intMonth)	{
		case 1: //conJan
		case 3: //conMar
		case 5: //conMay
		case 7: //conJul
		case 8: //conAug
		case 10: //conOct
		case 12: return(31); //conDec
		case 4: //conApr
		case 6: //conJun
		case 9: //conSep
		case 11: return(30); //conNov
		case 2: return((((intYear - 96) % 4) == 0) ? 29 : 28); //conFeb
		default: return(-1);
	}
}

/*função: proximoCampo
 *Sintaxe:  proximoCampo(this);"
 *Passa o foco para o proximo campo do formulario quando o campo atinge o maxlength */
function proximoCampo(f){
	if(f.value.length==f.maxLength){
  	for(var i=0;i<f.form.length;i++){
    	if(f.form[i]==f){f.form[i+1].focus();break}
		}
	}
}
