// JavaScript Document

 <!-- FORMATA DATA
	
	// EXEMPLO DE USO
	//	<form>	
	// 		<input type="Text" size="11" maxlength="10" onKeyDown="FormataData(9, event)" > 
	//	</form>
/*
function FormataData(Campo,evt) {
	var tecla = evt.keyCode  ? evt.keyCode  :
				evt.charCode ? evt.charCode :
				evt.which    ? evt.which    : void 0;
	//var tecla = teclapres.keyCode;
//	vr = document.form[Campo].value;
	vr = event.srcElement.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
		{
			event.srcElement.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		}
		if ( tam >= 5 && tam <= 10 )
		{
			event.srcElement.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
		}
	}
}
 */
 function Mascara(tipo, campo, teclaPress) {
	if (window.event)
	{
		var tecla = teclaPress.keyCode;
	} else {
		tecla = teclaPress.which;
	}
 
	var s = new String(campo.value);
	// Remove todos os caracteres à seguir: ( ) / - . e espaço, para tratar a string denovo.
	s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');
 
	tam = s.length + 1;
 
	if ( tecla != 9 && tecla != 8 ) {
		switch (tipo)
		{
		case 'CPF' :
			if (tam > 3 && tam < 7)
				campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
			if (tam >= 7 && tam < 10)
				campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
			if (tam >= 10 && tam < 12)
				campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
		break;
 
		case 'CNPJ' :
 
			if (tam > 2 && tam < 6)
				campo.value = s.substr(0,2) + '.' + s.substr(2, tam);
			if (tam >= 6 && tam < 9)
				campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,tam-5);
			if (tam >= 9 && tam < 13)
				campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,tam-8);
			if (tam >= 13 && tam < 15)
				campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,4)+ '-' + s.substr(12,tam-12);
		break;
 
		case 'TEL' :
			if (tam > 2 && tam < 4)
				campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,tam);
			if (tam >= 7 && tam < 11)
				campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,4) + '-' + s.substr(6,tam-6);
		break;
 
		case 'DATA' :
			if (tam > 2 && tam < 4)
				campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
			if (tam > 4 && tam < 11)
				campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);
		break;
		}
	}
}


 function DataHora(evento, objeto){
	var keypress=(window.event)?event.keyCode:evento.which;
	campo = eval (objeto);
	if (campo.value == '00/00/0000 00:00:00')
	{
		campo.value=""
	}

	caracteres = '0123456789';
	separacao1 = '/';
	separacao2 = ' ';
	separacao3 = ':';
	conjunto1 = 2;
	conjunto2 = 5;
	conjunto3 = 10;
	conjunto4 = 13;
	conjunto5 = 16;
	if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < (19))
	{
		if (campo.value.length == conjunto1 )
		campo.value = campo.value + separacao1;
		else if (campo.value.length == conjunto2)
		campo.value = campo.value + separacao1;
		else if (campo.value.length == conjunto3)
		campo.value = campo.value + separacao2;
		else if (campo.value.length == conjunto4)
		campo.value = campo.value + separacao3;
		else if (campo.value.length == conjunto5)
		campo.value = campo.value + separacao3;
	}
	else
		event.returnValue = false;
}
 //  FIM -->

 <!-- CHECKA A DATA

// EXEMPLO DE USO

// 	<form name="frm">
//		<input type=text name=data onBlur="checkadata()">
//	</form>


function checkadata(){
//	window.onerror=null // for all other strange errors
	var err=0
	a=document.frm.dtaNascimento.value
	//if (a.length != 10) err=1
	if (a.length >= 1) {
		d = a.substring(0, 2)// day
		b = a.substring(3, 5)// month
		f = a.substring(6, 10)// year
	
		//basic error checking
		if (b<1 || b>12) err = 1
		if (d<1 || d>31) err = 1
		if (f<0 || f>9999) err = 1
		
		//advanced error checking
	
		// months with 30 days
		if (b==4 || b==6 || b==9 || b==11){
			if (d==31) err=1
		}
	
		// february, leap year
		if (b==2){
			// feb
			var g=parseInt(f/8)
			if (isNaN(g)) {
				err=1
			}
	
			if (d>29) err=1
			if (d==29 && ((f/4)!=parseInt(f/8))) err=1
		}
	}

	if (err==1){
		alert('Data de nascimento inválida!');
		document.frm.dtaNascimento.focus();
		document.frm.dtaNascimento.value="";
	}
	//else{
		//alert('OK!');
	//}

}

 //  FIM -->

<!-- PERMITE SOMENTE NUMEROS
	
	// EXEMPLO DE USO
	//<input type=text name=txtPostalCode onKeypress="somenteNumeros();">

/*function somenteNumeros() {
	if (event.keyCode < 45 || event.keyCode > 57) 
		event.returnValue = false;
}*/

function somenteNumeros(evt)
{
	var key_code = evt.keyCode  ? evt.keyCode  :
				   evt.charCode ? evt.charCode :
				   evt.which    ? evt.which    : void 0;


	// Habilita teclas <DEL>, <TAB>, <ENTER>, <ESC> e <BACKSPACE>
	if (key_code == 8  ||  key_code == 9  ||  key_code == 13  ||  key_code == 27  ||  key_code == 46)
	{
		return true;
	}
	// Habilita teclas <HOME>, <END>, mais as quatros setas de navegação (cima, baixo, direta, esquerda)
	/*else if ((key_code >= 35)  &&  (key_code <= 40))
	{
		return true
	}*/
	// Habilita números de 0 a 9
	else if ((key_code >= 48)  &&  (key_code <= 57))
	{
		return true
	}	

	return false;
}


//  FIM -->

<!-- PROIBE O USO DE CARACTERES ESPECIAIS (!@#$%^&* ETC )
	
	// EXEMPLO DE USO
	//<textarea rows=2 cols=20 name=comments onKeypress="proibeCaracEspec();"></textarea>
	
function proibeCaracEspec(){
	if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97)) 
	event.returnValue = false;
}
//  FIM -->
<!-- FORMATA HORA

	// EXEMPLO DE USO
	//	<form>	
	// 		<input type="Text" size="11" maxlength="10" onKeyDown="FormataHora(4, event)" > 
	//	</form>


function FormataHora(Campo,teclapres) {
	var tecla = teclapres.keyCode;
//	vr = document.form[Campo].value;
	vr = event.srcElement.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
		{
			event.srcElement.value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
		}
	}
}


function validateEmail()
{
	email=document.frm.email.value
	var err=0;	
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    if (email != "") {
		var splitted = email.match("^(.+)@(.+)$");
		
		if(splitted == null) err=1;
		
		if (err != 1) {
			if(splitted[1] != null )
			{
			  var regexp_user=/^\"?[\w-_\.]*\"?$/;
			  if(splitted[1].match(regexp_user) == null) err=1;
			}
			if(splitted[2] != null)
			{
			  var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
			  if(splitted[2].match(regexp_domain) == null) 
			  {
				var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
				if(splitted[2].match(regexp_ip) == null) err=1;
			  }// if	  
			 // return true;	 
			}
		}
	}
	if (err==1) {		
		alert('O e-mail digitado é inválido!');
		document.frm.email.focus();
		document.frm.email.value="";
		//return false;
	}
}

/*===========================================================================
	Validação de preenchimento de campos obrigatórios
===========================================================================*/
function fncMaskCPF() {
	varCPF = document.frm.cpf.value; //recupera o valor do campo
	
	if (varCPF != '') { //caso o campo foi preenchido com algum valor
		if (varCPF.length < 11) { //verifica se o campo tem no mínimo 11 caracter
			alert('É necessario preencher corretamente o número do CPF!');
			document.frm.cpf.focus();
			document.frm.cpf.value="";
		}
		else
		{
			var x=1;
			var NroCPF = '';
			//For para pegar somente os números do campo
			for (i=0; i<varCPF.length; i++){
				if (!isNaN(varCPF.substring(i,x)))
					NroCPF += varCPF.substring(i,x);
				x++;
			}
			
			if (fnc_IsCPF_CNPJ(NroCPF)) { //verifica se o CPF é válido
				//formata a mascara para o campo CPF
				var maskCPF;
				
				maskCPF = NroCPF.substring(0,3) + '.';
				maskCPF += NroCPF.substring(3,6) + '.';
				maskCPF += NroCPF.substring(6,9) + '-';
				maskCPF += NroCPF.substring(9,11);
				
				//alert(maskCPF);
				document.frm.cpf.value = maskCPF;
			}
			else
			{
				alert('O número do CPF é inválido!');				
				document.frm.cpf.focus();
				document.frm.cpf.value="";
			}
		}
	}
}

function fnc_CPF_CNPJValido(str_IDCampoInput, str_NomeCampo, str_Mensagem, str_MensagemFinal, bitObrigatorio) {
	var str_DadoInput = document.getElementById(str_IDCampoInput).value; 
	
	if (bitObrigatorio) {
		if (Trim(str_DadoInput) == "") {
			alert(str_Mensagem + " " + str_NomeCampo + str_MensagemFinal);
			document.getElementById(str_IDCampoInput).focus();
			return(true);
		}
	}

	if (Trim(str_DadoInput) != "") {
		if (fnc_IsCPF_CNPJ(str_DadoInput) == false) {
			alert(str_Mensagem + " " + str_NomeCampo + str_MensagemFinal);
			document.getElementById(str_IDCampoInput).focus();
			return(true);			
		}
	}
}

function fnc_InputEmail(str_IDCampoInput, str_NomeCampo, str_Mensagem, str_MensagemFinal, bitObrigatorio) {
	var str_DadoInput = document.getElementById(str_IDCampoInput).value;
	
	if (bitObrigatorio) {
		if (Trim(str_DadoInput) == "") {
			alert(str_Mensagem + " " + str_NomeCampo + str_MensagemFinal);
			document.getElementById(str_IDCampoInput).focus();
			return(true);
		}
	}

	if (Trim(str_DadoInput) != "") {
		if (fnc_ValidaEmail(str_DadoInput) == false) {
			alert(str_Mensagem + " " + str_NomeCampo + str_MensagemFinal);
			document.getElementById(str_IDCampoInput).focus();
			return(true);
		}
	}
}

function fncInputPreenchido(str_IDCampoInput, str_NomeCampo, str_Mensagem, str_MensagemFinal) {
	var str_DadoInput = document.getElementById(str_IDCampoInput).value; 
	alert(str_DadoInput);
	if (Trim(str_DadoInput) == "") {	
		alert(str_Mensagem + " " + str_NomeCampo + str_MensagemFinal);
		document.getElementById(str_IDCampoInput).focus();
		return(true);
	}
}

function fncCheckRadioPreenchido(str_NameForm, str_NomeCampo, str_Mensagem) {
	var obj_Input = document.getElementsByTagName("input");
	var int_IndiceArr = 0;
	var bln_CheckboxSelecionado = false;

	for (int_IndiceArr = 0; int_IndiceArr < obj_Input.length; int_IndiceArr++) {		
		if (obj_Input[int_IndiceArr].name == str_NameForm) {
			if (obj_Input[int_IndiceArr].checked == true) {
				bln_CheckboxSelecionado = true;
			}
		}
	}
	
	if (bln_CheckboxSelecionado == false) {	
		alert(str_Mensagem + " " + str_NomeCampo + ".");
		return(true);
	}
	else {
		return(false);
	}
}

/*===========================================================================
Função para calcular CPF e CNPJ de acordo com a Receita Federal
===========================================================================*/
cst_NUM_DIGITOS_CPF  = 11;
cst_NUM_DIGITOS_CNPJ = 14;
cst_NUM_DGT_CNPJ_BASE = 8;

String.prototype.lpad = function(pSize, pCharPad) {
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif > 0; dif--) str = ch + str;
	return (str);
}

String.prototype.trim = function() {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/*--------------------------------------------------------------------------
	Faz a desformatação do padrão de CPF ou CNPJ
--------------------------------------------------------------------------*/
function fnc_DesformataNumero(str_Numero) {
	return String(str_Numero).replace(/\D/g, "").replace(/^0+/, "");
}

/*--------------------------------------------------------------------------
	Formata a string conforme o padrão de CPF ou CNPJ
--------------------------------------------------------------------------*/
function fnc_Formatar_CPF_CNPJ(str_CPF_CNPJ, bln_UsarSeparador, bln_IsCNPJ) {
	if (bln_IsCNPJ == null) bln_IsCNPJ = false;
	if (bln_UsarSeparador == null) bln_UsarSeparador = true;
	var int_MaxDigitos = bln_IsCNPJ ? cst_NUM_DIGITOS_CNPJ : cst_NUM_DIGITOS_CPF;
	var str_Numero = fnc_DesformataNumero(str_CPF_CNPJ);

	str_Numero = str_Numero.lpad(int_MaxDigitos, '0');
	if (!bln_UsarSeparador) return str_Numero;

	if (str_CPF_CNPJ)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		str_Numero = str_Numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		str_Numero = str_Numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return str_Numero;
}


/*--------------------------------------------------------------------------
	Faz o calculo para verificação da validade do CPF
--------------------------------------------------------------------------*/
function fnc_CalculaDigito(str_Base, bln_IsCNPJ) {
	if (bln_IsCNPJ == null) bln_IsCNPJ = false;
	var str_BaseCalculada = fnc_Formatar_CPF_CNPJ(str_Base, false, bln_IsCNPJ);
	var int_CicloPeso	= bln_IsCNPJ ? cst_NUM_DGT_CNPJ_BASE : cst_NUM_DIGITOS_CPF;
	var int_MaxDigitos	= bln_IsCNPJ ? cst_NUM_DIGITOS_CNPJ  : cst_NUM_DIGITOS_CPF;
	str_BaseCalculada = str_BaseCalculada.substring(2, int_MaxDigitos);
	var result = "";
	var i, j, k, soma, dv;

	for (j = 1; j <= 2; j++) {
		k = 2;
		soma = 0;
		for (i = str_BaseCalculada.length-1; i >= 0; i--) {
			soma += (str_BaseCalculada.charAt(i) - '0') * k;
			k = (k-1) % int_CicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		str_BaseCalculada += dv;
		result += dv
	}
	return result;
} 


/*--------------------------------------------------------------------------
	Verifica se o CPF é válido
--------------------------------------------------------------------------*/
function fnc_ValidarCPF(str_CPF) {
	var str_Numero = fnc_Formatar_CPF_CNPJ(str_CPF, false, false);
	var str_Base = str_Numero.substring(0, str_Numero.length - 2);
	var str_Digitos = fnc_CalculaDigito(str_Base, false);
	var algUnico, i;

	if (str_Numero != str_Base + str_Digitos) return false;

	algUnico = true;
	for (i = 1; i < cst_NUM_DIGITOS_CPF; i++) {
		algUnico = algUnico && (str_Numero.charAt(i - 1) == str_Numero.charAt(i));
	}
	return (!algUnico);
}

/*--------------------------------------------------------------------------
	Verifica se o CNPJ é válido
--------------------------------------------------------------------------*/
function fnc_ValidarCNPJ(pCnpj) {
	var numero = fnc_Formatar_CPF_CNPJ(pCnpj, false, true);
	var base = numero.substring(0, cst_NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(cst_NUM_DGT_CNPJ_BASE, 12);
	var digitos = fnc_CalculaDigito(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos) return false;

	algUnico = numero.charAt(0) != '0';
	for (i = 1; i < cst_NUM_DGT_CNPJ_BASE; i++) {
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	if (ordem == "0000") return false;
	return (base == "00000000" || parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
}

/*--------------------------------------------------------------------------
	Recebe o valor e verifica o tamnho da string para ver se é tratado como
	CPF ou CNPJ 
--------------------------------------------------------------------------*/
function fnc_IsCPF_CNPJ(str_ValueForm) {
	var str_Numero = str_ValueForm.replace(/\D/g, "");
	if (str_Numero.length > cst_NUM_DIGITOS_CPF) {
		return fnc_ValidarCNPJ(str_ValueForm)
	}
	else {
		return fnc_ValidarCPF(str_ValueForm);
	}
}

function fncInputPreenchido(str_IDCampoInput, str_NomeCampo, str_Mensagem, str_MensagemFinal) {	
	var str_DadoInput = document.getElementById(str_IDCampoInput).value; 	
	
	if (str_DadoInput == "") {		
		alert(str_Mensagem + " " + str_NomeCampo + str_MensagemFinal);
		document.getElementById(str_IDCampoInput).focus();
		return(true);
	}	
}

function fncCheckRadioPreenchido(str_NameForm, str_NomeCampo, str_Mensagem) {
	var obj_Input = document.getElementsByTagName("input");
	var int_IndiceArr = 0;
	var bln_CheckboxSelecionado = false;

	for (int_IndiceArr = 0; int_IndiceArr < obj_Input.length; int_IndiceArr++) {		
		if (obj_Input[int_IndiceArr].name == str_NameForm) {
			if (obj_Input[int_IndiceArr].checked == true) {
				bln_CheckboxSelecionado = true;
			}
		}
	}
	
	if (bln_CheckboxSelecionado == false) {	
		alert(str_Mensagem + " " + str_NomeCampo + ".");
		return(true);
	}
	else {
		return(false);
	}
}

function janelaCenter(url, nome, parms, width, height) {

 	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;

	if (parms != "") {
		str += ", " + parms;
	}

	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;
	} else {
		var xc = 0, xy = 0;
	}

	str += ",left=" + xc + ",screenX=" + xc;
	str += ",top=" + yc + ",screenY=" + yc;
	
	return window.open(url, nome, str);
}

