/* Função para mudar a  cor de fundo do site */
function  MudaCor(cor){
	document.body.style.background = '#' + cor;
}


/*Funcao para expandir o menu em categorias*/
function  MostraItens(id){
	d = document.getElementById(id);
	if (d.style.display == 'none'){
		d.style.display = 'block';
	}else{
		d.style.display = 'none';
	}
}

// Redireciona para uma nova janela, validado pelo W3C
function redirect(page,new_window){
	if (new_window)
		window.open (page);
	else
		window.top.document.location = page

	return false;
}

// Verifica campos vazios
function Vazios (campo,legend){
	c = document.getElementById(campo);
	if (c.value == ""){
		alert ('O campo ' + legend + " e obrigatorio.");
		c.focus();
		return false;
	}else{
		return true;
	}
}


// Verifica de o campo é numerico
function Numeros(e) 
{
	if (event.keyCode >= 48 && event.keyCode<= 57){
		alert('num')
		return true;		
	}
	else {
		alert('letra')
		return false;		
	}
}

// Valida campo de E-mail
//function ValidaEmail (campo){
//	c = document.getElementById(campo);
//	parte1 = c.value.indexOf("@");
//	parte2 = c.value.indexOf(".");
//	parte3 = c.value.length;
//	if (!(parte1 >= 3 && parte2 >= 6 && parte3 >= 9)) {
//		alert ("O campo E-Mail deve conter um endereco eletronico.");
//		c.focus();
//		return false;
//	}else{
//		return true;
//	}
//}

// Validar um campo de e-mail
function ValidaEmail(x){
	obj = document.getElementById(x);

	var MailExp = /^\w[A-Za-z0-9]*(\.\w[A-Za-z0-9]*)*@[A-Za-z0-9]+(\.[A-Za-z]+)+$/;
	
	if(!MailExp.test(obj.value)){
		alert('Insira um e-mail valido.');
		obj.focus();
		return false;
	}
}

// validar um campo de nome
function ValidaNome(x){
	obj = document.getElementById(x);
	var NomeExp = /\w([a-zA-Z]{2,})+/;

	if(!NomeExp.test(obj.value)){
		alert('Insira um nome valido.');
		obj.focus();
		return false;
	}
}


/* CONTATO AJAX */
// Tenta criar um objeto XMLHttpRequest
try{
	ajax = new XMLHttpRequest();
}catch(ee){
	try{
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			ajax = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			ajax = false;
		}
	}
}

function ajaxMail(){
	//var parametros = 'cont_assunto=' + document.getElementById('cont_assunto').value;
	var parameters = [
		'cont_nome=' + document.getElementById('cont_nome').value,
		'cont_email=' + document.getElementById('cont_email').value,
		'cont_area=' + document.getElementById('cont_area').value,
		'cont_assunto=' + document.getElementById('cont_assunto').value, 
		'cont_msg=' + document.getElementById('cont_msg').value,
	].join('&');
	ajax.open("POST","sub/contato.php?acao=enviar");
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.onreadystatechange = function(){
		if(ajax.readyState==1){
			document.getElementById('resposta').innerHTML = "enviando...";
			document.getElementById('resposta').className = "loading";
		}
		if(ajax.readyState==4){
			if (ajax.status==200){
				document.getElementById('resposta').innerHTML = ajax.responseText;
				if (ajax.responseText == "E-mail enviado com sucesso!"){
					document.getElementById('resposta').className = "loaded";
				}else{
					document.getElementById('resposta').className = "loaded_err";
				}	
			}else{
				document.getElementById('resposta').innerHTML = "ERRO!";
				document.getElementById('resposta').className = "loaded_err";
			}
		}	
	}
	ajax.send(parameters);
}

/* Funcao de validacao de CPF */
function validaCPF(x) {
		cpf = document.getElementById(x).value;
		valor = true;
		erro = new String;
		if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";	
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			  erro += "Numero de CPF invalido!"
		}
		var a = [];
		var b = new Number;
		var c = 11;
		for (i=0; i<11; i++){
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] *  --c);
		}
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] *  c--); 
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			alert(erro);
			return false;
		}
		return true;
}

/* Funcao para validar RG */
function ValRG(numero){

	var numero = document.getElementById(numero).value.split("");
	tamanho = numero.length;
	vetor = new Array(tamanho);
	
	if(tamanho>=1){
	 vetor[0] = parseInt(numero[0]) * 2;
	}
	if(tamanho>=2){
	 vetor[1] = parseInt(numero[1]) * 3;
	}
	if(tamanho>=3){
	 vetor[2] = parseInt(numero[2]) * 4;
	}
	if(tamanho>=4){
	 vetor[3] = parseInt(numero[3]) * 5;
	}
	if(tamanho>=5){
	 vetor[4] = parseInt(numero[4]) * 6;
	}
	if(tamanho>=6){
	 vetor[5] = parseInt(numero[5]) * 7;
	}
	if(tamanho>=7){
	 vetor[6] = parseInt(numero[6]) * 8;
	}
	if(tamanho>=8){
	 vetor[7] = parseInt(numero[7]) * 9;
	}
	if(tamanho>=9){
	 vetor[8] = parseInt(numero[8]) * 100;
	}
	
	 total = 0;
	
	if(tamanho>=1){
	 total += vetor[0];
	}
	if(tamanho>=2){
	 total += vetor[1];
	}
	if(tamanho>=3){
	 total += vetor[2];
	}
	if(tamanho>=4){
	 total += vetor[3];
	}
	if(tamanho>=5){
	 total += vetor[4];
	}
	if(tamanho>=6){
	 total += vetor[5];
	}
	if(tamanho>=7){
	 total += vetor[6];
	}
	if(tamanho>=8){
	 total += vetor[7];
	}
	if(tamanho>=9){
	 total += vetor[8];
	}
	
	resto = total % 11;
	if(resto!=0) { alert("RG Invalido!"); }
}

/* Formatacao  e  validacao de datas */
function Formata_Data(Campo,teclapres) {
	var tecla = teclapres.keyCode;

		vr = Campo.value;
		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 ); 
		}
}

/* 
- compara duas datas e retorna qual a maior
- parâmetros: dt1, dt2 (string com as datas, no formato dd/mm/aaaa
- retorno: 0=datas iguals, 1= dt1 > dt2, 2= dt1 < dt2 */


function Compara_Datas(dt1,dt2){
	arr1 = dt1.split('/');
	dt_format1 = arr1[2] + arr1[1] + arr1[0];
	arr2 = dt2.split('/');
	dt_format2 = arr2[2] + arr2[1] + arr2[0];
	
	if (dt_format1 <= dt_format2) {
		alert('A data de inicio nao pode ser maior que a data de fim.');
		return false;
	}
}

/* Valida e aplica uma mascara XXXX-XXXX em um campo de numero telefonico */
function validaTel(campo,e){
	var valor = campo.value;
	
	// Testa se a tecla foi segurada
	if (valor.length > 4 && !valor.match(/\-/)){
		valor = '';
	}else{
		// Pega o caracter ASCII
		if(window.event){
			keycode = window.event.keyCode;
		}else if (e){
			keycode = e.which;
		}
		
		// Testa o caracter verificando se é  letra, se for apaga
		if (!((keycode >= 48 && keycode <= 57) || (keycode >= 96 && keycode <= 105))){
			valor = valor.substr(0,valor.length - 1)
		}

		
		// Se for o quarto caracter, insere um hifem logo apos
		if (valor.length == 4){
			valor += '-';
		}
		
		campo.value = valor;
	}
}

