/* =================== */
function vazio(campo, mensagem)
// campo e mensagem dentro dos parenteses s�o VARI�VEIS!!!
/* =================== */
{
	//limpar cor de fundo
	if (document.getElementById(campo).value != '')
	document.getElementById(campo).style.backgroundColor='';
	if (document.getElementById(campo).value == '') {
		// VARI�VEL campo --> AQUELA DOS PARENTESES DA FUN��O L� EM CIMA!!!
		document.getElementById(campo).style.backgroundColor='#FAA';
		// VARI�VEL campo --> AQUELA DOS PARENTESES DA FUN��O L� EM CIMA!!!		
		alert('O campo ' + mensagem + ' deve ser preenchido!');
		// VARI�VEL mensagem --> AQUsELA DOS PARENTESES DA FUN��O L� EM CIMA!!!		
		// posiciona o cursor no campo
		document.getElementById(campo).focus();
		// VARI�VEL campo --> AQUELA DOS PARENTESES DA FUN��O L� EM CIMA!!!		
		//Retorna verdadeiro se estiver vazio
		return true;
	}
	//Retorna falso se estiver n�o-vazio (preenchido)
	return false;
}


/* =================== */
function chkmail(campo, nomeCampo)
/* =================== */
{
	if ( document.getElementById(campo).value=="" ) 
		{
			alert( "O campo"+ nomeCampo +"est� vazio. Por favor, preencha-o corretamente!" );
			document.getElementById(campo).style.backgroundColor='#FAA';
			document.getElementById(campo).focus();
						return false;
		}
	else if (document.getElementById(campo).value.indexOf('@')==-1 || document.getElementById(campo).value.indexOf('.')==-1 )
		{
			alert( "Preencha campo"+ nomeCampo +"corretamente!" );
			document.getElementById(campo).style.backgroundColor='#FAA';
			document.getElementById(campo).focus();
						return false;
		}
	else 
	{
		document.getElementById(campo).style.backgroundColor='#FFF';	
		return true;
	}
}

/* =================== */
function tamNasci()
/* =================== */
// lembrar de criar uma subfun��o aqui dentro de substring para validar as datas do dia e do m�s e do ano
{
	if (document.fmcadpf.Nascimento.value.length < 10)
	{
			alert("Data de Nascimento deve estar composta por 10 digitos, mas s� tem "+document.fmcadpf.Nascimento.value.length);
			document.fmcadpf.Nascimento.focus();
		return;
	}
	document.fmcadph.submit();
}


/* =================== */
function valida()
/* =================== */
{
	if (vazio('nome',' NOME ')) return false;
//	if (vazio('email',' E-MAIL')) return false;
//	if (!validaemail(document.getElementById('email')) return false;	
	if (!chkmail('email', ' E-MAIL ')) return false;	
	if (vazio('telFixo',' TELEFONE ')) return false;
	if (vazio('cidade',' CIDADE ')) return false;	
	if (!validacpf(document.getElementById('cpf'))) return false;
	if (vazio('cep',' CEP ')) return false;
	if (vazio('complemento',' COMPLEMENTO ')) return false;
	if (!tamNasci()) return false;
	
	if (vazio('obs',' OBS ')) return false;
	
	return true;
}

/* =================== */
function validaIndiqueAmigo()
/* =================== */
{
	if (vazio('seuNome',' SEU NOME ')) return false;
	if (!chkmail('seuEmail', ' Seu e-mail ' )) return false;
	if (vazio('nomeSeuAmigo',' NOME DO SEU AMIGO ')) return false;
	if (!chkmail('emailSeuAmigo', ' E-mail do seu amigo ')) return false;

	return true;
}


// JavaScript Document
// Fun��o - Cria uma biblioteca para ser usada em v�rias p�ginas


/* =================== */
function le_nro()
/* =================== */
{
	// var num --> a variavel num s� vai existir dentro dessa funcao
	// quando sair dessa funcao, essa variavel � eliminada
	var num;
	do {
		num = parseInt(prompt('Digite numero', ''));
		if (isNaN(num)) alert('Burro! Nao sabe ler? Digite um NUMERO!!!');
	}
	while (isNaN(num));
	// return variavel --> retorna o valor da variavel para quem chamou a funcao
	return num;
}


// ------------------------------------------------------------
function limpa_mask(campo)
{
	sValue = campo.value;
	while (sValue.indexOf('-')>=0)
		sValue = sValue.toString().replace( "-", "" );
	while (sValue.indexOf('.')>=0)
		sValue = sValue.toString().replace( ".", "" );
	while (sValue.indexOf('/')>=0)
		sValue = sValue.toString().replace( "/", "" );
	while (sValue.indexOf('(')>=0)
		sValue = sValue.toString().replace( "(", "" );
	while (sValue.indexOf(')')>=0)
		sValue = sValue.toString().replace( ")", "" );
	while (sValue.indexOf(' ')>=0)
		sValue = sValue.toString().replace( " ", "" );
	return sValue;
}

// ------------------------------------------------------------

function validacpf(campo)
{ 
	var i; 
	s = limpa_mask(campo);
	if (s.length==0)
		return true;
 	var c = s.substr(0,9); 
  	var dv = s.substr(9,2); 
  	var d1 = 0; 
  	for (i = 0; i < 9; i++) 
  		d1 += c.charAt(i)*(10-i); 
	if (d1 == 0)
	{ 
  		alert("CPF Invalido");
		campo.select();
  		return false; 
	}
  	d1 = 11 - (d1 % 11); 
  	if (d1 > 9) d1 = 0; 
  		if (dv.charAt(0) != d1) 
  		{ 
  			alert("CPF Invalido") 
			campo.select();
  			return false; 
  		} 
  	d1 *= 2; 
  	for (i = 0; i < 9; i++) 
  		d1 += c.charAt(i)*(11-i); 
	d1 = 11 - (d1 % 11); 
  	if (d1 > 9) d1 = 0; 
  		if (dv.charAt(1) != d1) 
  		{ 
  			alert("CPF Invalido") 
			campo.select();
			return false; 
		} 
  	return true; 
} 


// ------------------------------------------------------------
function validacnpj(campo) 
{ 
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais; 
    digitos_iguais = 1;
	cnpj = limpa_mask(campo);
    if (cnpj.length < 14 && cnpj.length < 15) 
	{ 
  		alert("CNPJ Invalido");
		campo.select();
  		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)) 
		{ 
			alert("CNPJ Invalido");
			campo.select();
			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)) 
		{ 
			alert("CNPJ Invalido");
			campo.select();
			return false; 
		}
        return true; 
    } 
    else 
	{ 
  		alert("CNPJ Invalido");
		campo.select();
  		return false; 
	}
}


// JavaScript Document
/*** 
* Descri��o.: formata um campo do formul�rio de 
* acordo com a m�scara informada... 
* Par�metros: - objForm (o Objeto Form) 
* - strField (string contendo o nome do textbox) 
* - sMask (mascara que define o formato que o dado ser� apresentado, 
* 		usando o algarismo "9" para definir n�meros e o s�mbolo "!" para 
* 		qualquer caracter... 
* - evtKeyPress (evento) 
* Uso.......: <input type="textbox" name="xxx"..... 
* onkeypress="return mask(document.rcfDownload, 'str_cep', '99999-999', event);"> 
* Observa��o: As m�scaras podem ser representadas como os exemplos abaixo: 
* CEP -> 99.999-999 
* CPF -> 999.999.999-99 
* CNPJ -> 99.999.999/9999-99 
* Data -> 99/99/9999 
* Tel Resid -> (99) 999-9999 
* Tel Cel -> (99) 9999-9999 
* Processo -> 99.999999999/999-99 
* C/C -> 999999-! 
***/
function mask(strField, sMask, evtKeyPress)
{
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
	
	if(document.all) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	}
	else {
        nTecla = evtKeyPress.which;
	}
	// bug do backspace
	if (navigator.appName != "Microsoft Internet Explorer")
        if (nTecla == 8) { 
           return true;
        }
	 
//	sValue = limpa_mask(objForm[strField]);
	sValue = limpa_mask(document.getElementById(strField));
	
	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) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
	
		if (bolMask)
		{
			sCod += sMask.charAt(i);
			mskLen++;
		}
		else
		{
			sCod += sValue.charAt(nCount);
			nCount++;
		}
		i++;
	}
	
	document.getElementById(strField).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
	return true;
}
// Fim da Fun��o M�scaras Gerais


//==========================================
// 			FUN��O DE MOSTRAR O ENDERE�O
// =========================================

function showHide (ID) 
{
	if (document.getElementById(ID).style.display == "none") {
	   document.getElementById(ID).style.display= "";
	}
}

// ===========================================
//  Fun��o contar caracteres 
// ===========================================

function conta_nro(counter, caixanome)
{
	$(counter).value = 200 - $(caixanome).value.length;
}
function conta_tam(e, counter)
{
	//pega a tecla pressionada
	if(window.event)tecla = e.keyCode; //ie
	else tecla=e.which;
	
	//nao deixa digitar mais exeto o backspace codigo 8
	if($(counter).value.length >= 200 && tecla != 8 )
	{
	alert('Limite de caracteres excedido! Pressione Backspace caso precise editar a mensagem!');
	$(counter).style.backgroundColor='#FAA';
	return false;
	} else if ($(counter).value.length < 200)
	$(counter).style.backgroundColor='#FFF';
}

// =============================================
// FUN��O REJEITA TECLAS INADEQUADAS PARA CLICAR
// =============================================
/*
function rejeitaTecla(oEvent){
    var oEvent = oEvent ? oEvent : window.event;
    var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
	if(tecla == 17){
		alerta();
		}
}

function alerta(){
	alert('Esta tecla � bloqueada.');
	return false;
}
*/
/*Agora definimos que de acordo com o evento na p�gina, ser� executado tal fun��o: 

document.oncontextmenu = alerta;
document.onkeypress = rejeitaTecla;
document.onkeydown = rejeitaTecla;
*/
