// JavaScript Document

//	BUSCA DE DADOS SOBRE O NAVEGADOR
function getScrollTop() {
	if (self.pageYOffset) // all except Explorer
	{
		return self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollTop;
	}
}

function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 

	return window.undefined; 
}

function getViewportWidth() {
	var offset = 17;
	var width = null;
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
}


// FOCA OBJETOS
function focaCampo(objeto) {
	objeto.focus();
}


// ALTERA COR DE FUNDO DE OBJETO
function alteraCor(objeto) {
	
	corAtual = objeto.style.color;
	fundoAtual = objeto.style.backgroundColor;
	
	objeto.style.color = "#FFFFFF";
	objeto.style.backgroundColor = "#FF0000";
	
	focaCampo(objeto);
	
	setTimeout(function(){						
						objeto.style.color = corAtual;
						objeto.style.backgroundColor = fundoAtual;						
						}, 2000);
	
}

// OBJETO AJAX
function AjaxRequest() {

	try	{
		// Firefox, Opera 8.0+, Safari
		Ajax=new XMLHttpRequest();
	}

	catch (e)
	{
		// Internet Explorer
		try
		{
		Ajax=new ActiveXObject("Msxml2.XMLHTTP");
		}
	catch (e)
		{
		try
			{
			Ajax=new ActiveXObject("Microsoft.XMLHTTP");
			}
		catch (e)
		{
			alert("Your browser does not support AJAX!");
			return false;
		}
	}
}
}

// RETORNA NÚMERO RANDOMICO
function randomico() {
	return "?rnd=" + Math.random();
}


// VALIDA E-MAIL POR JAVASCRIPT
function checaMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

	if(typeof(mail) == "string"){
		if(er.test(mail)){ 
			return true;
		}
    } else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
			return true;
		}
    } else {
		return false;
    }
}

// FUNÇÃO PARA ALTERAR O TÍTULO DA PÁGINA.
function setSubTitle(sub) {	
	document.title = "PÓS-GRADUAÇÃO - " + sub + " - COMPLEXO EDUCACIONAL FMU";	
}

// FUNÇÃO PARA SETAR A ETAPA
function setEtapa(etapa) {
	document.getElementById("nuEtapa").innerHTML = etapa;
}

// FUNÇÃO PARA O INÍCIO DA INSCRIÇÃO
function iniciaInscricao(turno, idCurso, campus) {
	if (!turno) {
		alert("Erro no processamento.");
		return false;
	}
	
	if (!idCurso) {
		alert("Erro no processamento.");
		return false;
	}
	
	if (!campus) {
		campus = 0;
	}
	
	document.location.href="/pos/ler.asp?dir=inscricao&pg=etapa1&cod=" + idCurso + "&periodo=" + escape(turno) + "&campus=" + campus;
}

// DESATIVANDO CAMPOS PARA ESTRANGEIROS
function desativaCampoEstrangeiros(valor) {
	var estadoNasc	= document.getElementById("estadoNasc");
	if (parseInt(valor) != 1) {
		estadoNasc.disabled = true;
	} else {
		estadoNasc.disabled = false;
	}
}


// FUNÇÃO PARA VALIDAR CPF
function checaCPF(cpf)
      {
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
	  		alert('CPF Inválido!');
            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;
}


// FUNÇÕES DO COMBO DE PRÉ-REQUISITOS, SE HOUVER
function showHideCampoOutroCurso(valor) {
	// buscando os campos
	var cursoOutro 	= document.getElementById("cursoOutro");	
	var curso		= document.getElementById("curso");
	
	if (valor == 1) {
		cursoOutro.style.display 	= "block";
		curso.style.color 			= "#999";
		cursoOutro.focus();
	} else {
		cursoOutro.style.display 	= "none";
		cursoOutro.value			= "";
		curso.style.color 			= "#000";
	}
}


// VALIDANDO FORMULÁRIO
function validaFormulario() {
	
	// VERIFICANDO SE ALGUM CAMPO INPUT DEIXOU DE SER PREENCHIDO
	
	var campos = document.getElementsByTagName("input");
	
	for (i=0; i < campos.length; i++) {
		
		if (campos[i].value == campos[i].title) {
			if (campos[i].id != "dddfonecom" && campos[i].id != "fonecom" && campos[i].id != "nomePai" && campos[i].id != 'txt_usuario' && campos[i].id != 'txt_senha' ) {
				alert("ATENÇÃO, TODOS OS CAMPOS DEVEM SER PREENCHIDOS.\n\nObs.: Exceção para os campos de Telefone Comercial e nome do pai.")
				alteraCor(campos[i]);
				return false;
			}
		}
		
	}
	
	
	// buscando os objetos
	var nome 		= document.getElementById("nome");
	var dataNasc	= document.getElementById("dtNasc");
	var endereco	= document.getElementById("endereco");
	var bairro		= document.getElementById("bairro");
	var cidade		= document.getElementById("cidade");
	var cep			= document.getElementById("cep");
	var zonacep		= document.getElementById("zonacep");
	var dddfoneres	= document.getElementById("dddfoneres");
	var foneres		= document.getElementById("foneres");
	var dddfonecom	= document.getElementById("dddfonecom");
	var fonecom		= document.getElementById("fonecom");
	var dddcel		= document.getElementById("dddcel");
	var cel			= document.getElementById("cel");
	var rg			= document.getElementById("rg");
	var cpf			= document.getElementById("cpf");
	var cidadeNasc	= document.getElementById("cidadeNasc");
	var estadoNasc	= document.getElementById("estadoNasc");
	var estadoCivil = document.getElementById("estadoCivil");
	var nomeMae		= document.getElementById("nomeMae");
	var email		= document.getElementById("email");
	var exAluno		= document.getElementById("exAluno");
	var faculdade	= document.getElementById("faculdade");
	var curso		= document.getElementById("curso");
	var outroCurso	= document.getElementById("cursoOutro");
	var cidadeFacul	= document.getElementById("cidadeFacul");
	var estadoFacul = document.getElementById("estadoFacul");
	var anoFormacao = document.getElementById("anoFormacao");
	
	
	if (nome.value.length < 3) {
		alert("Por favor, preencha seu nome completo.");
		alteraCor(nome);
		return false;
	}
	
	if (dataNasc.value.length < 10) {
		alert("Por favor, digite sua Data de Nascimento. Ex. 05/05/1978");
		alteraCor(dataNasc);
		return false;
	}
	
	if (endereco.value.length < 5) {
		alert("Por favor, preencha o seu Endereço corretamente. Ex. Av. São João, 150");
		alteraCor(endereco);
		return false;
	}
	
	if (bairro.value.length < 2) {
		alert("Por favor, preencha o seu Bairro corretamente.");
		alteraCor(bairro);
		return false;
	}
	
	if (cidade.value.length < 3) {
		alert("Por favor, preencha sua Cidade.");
		alteraCor(cidade);
		return false;
	}
	
	if (cep.value.length < 5) {
		alert("Por favor, digite seu CEP completo.");
		alteraCor(cep);
		return false;
	}
	
	if (isNaN(cep.value)) {
		alert("Por favor, digite apenas números no campo CEP.");
		alteraCor(cep);
		return false;
	}
	
	if (zonacep.value.length < 3) {
		alert("Por favor, digite a Zona de seu CEP completa.");
		alteraCor(zonacep);
		return false;
	}
	
	if (isNaN(zonacep.value)) {
		alert("Por favor, digite apenas números na área ZONA do CEP.");
		alteraCor(zonacep);
		return false;
	}
	
	if (dddfoneres.value.length < 2) {
		alert("Por favor, digite o DDD de sua residência.");
		alteraCor(dddfoneres);
		return false;
	}
	
	if (isNaN(dddfoneres.value)) {
		alert("Por favor, digite apenas números no DDD residencial.");
		alteraCor(dddfoneres);
		return false;
	}
	
	if (foneres.value.length < 8) {
		alert("Por favor, digite seu telefone corretamente. Ex.: 33556655");
		alteraCor(foneres);
		return false;
	}
	
	if (isNaN(foneres.value)) {
		alert("Por favor, digite apenas números no campo Telefone Residencial.");
		alteraCor(foneres);
		return false;
	}

	if (isNaN(dddfonecom.value)) {
		alert("Por favor, digite apenas números no DDD Comercial.");
		alteraCor(dddfonecom);
		return false;
	}
	
	if (isNaN(fonecom.value)) {
		alert("Por favor, digite apenas números no campo Telefone Comercial.");
		alteraCor(fonecom);
		return false;
	}

	if (dddcel.value.length < 2) {
		alert("Por favor, digite o DDD de sel Celular.");
		alteraCor(dddcel);
		return false;
	}
	
	if (isNaN(dddcel.value)) {
		alert("Por favor, digite apenas números no DDD Celular.");
		alteraCor(dddcel);
		return false;
	}
	
	if (cel.value.length < 8) {
		alert("Por favor, digite seu Celular corretamente. Ex.: 33556655");
		alteraCor(cel);
		return false;
	}
	
	if (isNaN(cel.value)) {
		alert("Por favor, digite apenas números no campo Celular.");
		alteraCor(cel);
		return false;
	}
	
	if (rg.value.length < 5) {
		alert("Por favor, reencha corretamente o seu RG. Não utilize pontos ou traços.");
		alteraCor(rg);
		return false;
	}
	
	if (cpf.value.length < 11) {
		alert("Por favor, preencha corretamente o seu número de CPF.");
		alteraCor(cpf);
		return false;
	}
	
	if (!checaCPF(cpf.value)) {
		alert("CPF inválido.");
		alteraCor(cpf);
		return false;
	}
	
	if (cidadeNasc.value.length < 3) {
		alert("Por favor, digite o nome da sua cidade de Nascimento");
		alteraCor(cidadeNasc);
		return false;
	}
	
	if (estadoCivil.value == 0) {
		alert("Selecione seu estado Civil.");
		alteraCor(estadoCivil);
		return false;
	}
	
	if (nomeMae.value.length < 3) {
		alert("Por favor, preencha o campo Nome da Mãe.");
		alteraCor(nomeMae);
		return false;
	}

	if (!checaMail(email.value)) {
		alert("Por favor, verifique a digitação de seu endereço de E-mail.");
		alteraCor(email);
		return false;
	}
	
	if (exAluno.value == 0) {
		alert("Por favor, selecione uma opção no campo Ex-Aluno.");
		alteraCor(exAluno);
		return false;
	}
	
	if (faculdade.value.length < 3) {
		alert("Por favor, preencha o nome de sua faculdade de formação.");
		alteraCor(faculdade);
		return false;
	}

	// VALIDAÇÃO DO CURSO	
	if (curso.type == "select-one") { // se for um curso com pré requisito...
		if (curso.value == 0) { // verifica se não foi escolhido o curso...
			alert("Por favor, selecione o seu curso de formação.");
			alteraCor(curso);
			return false;
		}
		
		if (curso.value == 1) { // e se foi escolhida a opção 'OUTRO'...
			if (outroCurso.value.length < 5) { // verifica se o nome do curso de formação foi preenchido.
				alert("Por favor, preencha com o nome do seu curso de formação.");
				alteraCor(outroCurso);
				return false;
			}			
		}		
	} else { // se não for curso com pré requisito
		if (curso.value.length < 5) {// verifica se o nome do curso de formação do candidato foi preenchido.
			alert("Por favor, preencha o nome do seu curso de formação.");
			alteraCor(curso);
			return false;
		}
	}

	if (cidadeFacul.value.length < 3) {
		alert("Por favor, preencha com o nome da cidade onde você se formou.");
		alteraCor(cidadeFacul);
		return false;
	}
	
	if (anoFormacao.value == 0) {
		alert("Por favor, selecione seu ano de formação.");
		alteraCor(anoFormacao);
		return false;
	}	
}

function testaTecla(e) {
	
	var cancelar = true;
	
	var tecla = e.keyCode||e.charCode;
	
	if (tecla == 8) {
		cancelar = false;
	}

	if (tecla == 9) {
		cancelar = false;
	}

	if (tecla >= 48 && tecla <= 57) {
		cancelar = false;
	}

	if (tecla >= 96 && tecla <= 105) {
		cancelar = false;
	}
	
	if (cancelar == true) {
		return false;
	}
}

function validaCPFBoleto() {
	var campoCPF = document.getElementById("cpf");
	
	if (checaCPF(campoCPF.value) == false) {
		alert("Por favor, verifique a digitação de seu CPF. Utilize apenas os números.");
		alteraCor(campoCPF);
		return false;
	}
}

function showHideInfo(objeto) {
	if (objeto.style.display == "none") {
		objeto.style.display = "block";
	} else {
		objeto.style.display = "none";
	}
}

function abrePopImpressao(html) {
	var janela = window.open("", "janela", "width=600,height=400");
	janela.document.write("<img src=\"/pos/interfaces/img/logopos_impressao.jpg\"><br />" + html + "<script>window.print(); window.self.close();</script>");
}

function contaMotivacao(e) {
	var campo 	= document.getElementById("motivacao");
	var cont	= document.getElementById("contador");	
	cont.innerHTML = 200-campo.value.length;	
}

function contaMonografia(e) {
	var campo 	= document.getElementById("monografia");
	var cont	= document.getElementById("contador_monografia");	
	cont.innerHTML = 1000-campo.value.length;	
}

function travaCampoMotivacao(e) {
	
	var tecla = e.keyCode||e.charCode;
	var campo 	= document.getElementById("motivacao");
	if (campo.value.length >= 200 && tecla !=8) {
		return false;
	}
}

function travaCampoMonografia(e) {
	
	var tecla = e.keyCode||e.charCode;
	var campo 	= document.getElementById("motivacao");
	if (campo.value.length >= 1000 && tecla !=8) {
		return false;
	}

}

function mascaraData(e) {

	var cancelar = true;
	
	var tecla = e.keyCode||e.charCode;
	
	if (tecla == 8) {
		cancelar = false;
	}

	if (tecla == 9) {
		cancelar = false;
	}
	
	if (tecla == 111 || tecla == 193) {
		cancelar = false;
	}

	if (tecla >= 48 && tecla <= 57) {
		cancelar = false;
	}

	if (tecla >= 96 && tecla <= 105) {
		cancelar = false;
	}
	
	if (cancelar == true) {
		return false;
	}
	
}

function adicionaBarrasData(obj, e) {
	var tecla = e.keyCode||e.charCode;

	if(obj.value.length == 2 || obj.value.length == 5) {
		if (tecla != 8)  {
			obj.value = obj.value + "/";
		}
	}
}

// FUNÇÃO PARA LIMPAR COMBO
function limpaCombo(objeto, bloqueio, padrao) {

	if (!objeto.type) {
		objeto = document.getElementById(objeto);
	}
	
	if (!padrao) {
		padrao = "-- Selecione --";
	}	

	for (i=objeto.length; i >= 0; i--) {
		objeto.remove(i);
	}
	
	if (bloqueio) {
		objeto.disabled = true;
	} else {
		objeto.disabled = false;
	}

	objeto.options[0] = new Option(padrao, "0", true, true);	

}



function tipoAvaliacao() {
	
	var tipo		= document.getElementById("tipo");
	var agendamento = document.getElementById("agendamento");
	
	if (tipo.value == 0) {
		limpaCombo(agendamento, true, "-- Selecione -- ");
		
	} else {
		
		limpaCombo(agendamento, false, "-- Selecione --");
		
		AjaxRequest();
		
		switch(parseInt(tipo.value)) {			
			case 1:
				var url = "/pos/inscricao/proximaAvaliacao.asp"
			break;
			
			case 2:	
				var url = "/pos/inscricao/listaAgendadoDisponivel.asp"
			break;
		}
		
		Ajax.open("GET", url + randomico(), true);
		Ajax.send(null);
		
		Ajax.onreadystatechange=function() {
			if (Ajax.readyState == 4) {
				var opcoes = Ajax.responseText.split("|");
				for (i=0; i < opcoes.length; i++) {
					if (opcoes[i].length > 0) {
						var opcao = opcoes[i].split(",");
							agendamento.options[agendamento.options.length] = new Option(opcao[0] + ' - ' + opcao[1], opcao[0] + ' ' + opcao[1], 0, 0);
					}
					
				}
			}
		}
	}
}


function validaTipoProva() {
	
	var tipo		= document.getElementById("tipo");
	var agendamento	= document.getElementById("agendamento");
	
		if (tipo.value == 0) {
			alert("Você precisa selecionar um tipo de Avaliação disponível");
			alteraCor(tipo);
			return false;
		}
		
		if (agendamento.value == 0) {
			alert("Você deve selecinar uma data conveniente.");
			alteraCor(agendamento);
			return false;
		}
}

function somentenumeros(e)
	{
		var key = window.event ? e.keyCode : e.which;
		var keychar = String.fromCharCode(key);
		reg = /^\d+$/;
		return reg.test(keychar);
	}
	
function isNum(passedVal)
{
	var str = passedVal.value;
	if (passedVal == "")
	{
		return false;
    }
	for (var i = 0; i < passedVal.length; i++) 
	{
		var ch = passedVal.substring(i, i + 1);
		if ((ch < "0" || "9" < ch)) 
		{
			return false;
		}
	}
	return true;
}
	
//valida o CPF
	function ValidarCPF(campo)
	{
			var CPF = campo.value; 
		if ((CPF == "00000000000")||(CPF == "11111111111")||(CPF == "22222222222")||(CPF == "33333333333")||(CPF == "44444444444")||(CPF == "55555555555")||(CPF == "66666666666")||(CPF == "77777777777")||(CPF == "88888888888")||(CPF == "99999999999")||((CPF.length > 0)&&(!isNum(CPF)))||((CPF.length > 0)&&(CPF.length != 11)))
		{
			alert('CPF inválido. Digite somente números!');
			campo.value = "";
			return false;
		}
		var POSICAO, I, SOMA, DV, DV_INFORMADO;
		var DIGITO = new Array(10);
		DV_INFORMADO = CPF.substr(9, 2);
		for (I=0; I<=8; I++)
		{
			DIGITO[I] = CPF.substr( I, 1);
		}
		POSICAO = 10;
		SOMA = 0;
		for (I=0; I<=8; I++)
		{
			SOMA = SOMA + DIGITO[I] * POSICAO;
			POSICAO = POSICAO - 1;
		}
		DIGITO[9] = SOMA % 11;
		if (DIGITO[9] < 2)
		{
			DIGITO[9] = 0;
		}
		else
		{
			DIGITO[9] = 11 - DIGITO[9];
		}
		POSICAO = 11;
		SOMA = 0;
		for (I=0; I<=9; I++)
		{
			SOMA = SOMA + DIGITO[I] * POSICAO;
			POSICAO = POSICAO - 1;
		}
		DIGITO[10] = SOMA % 11;
		if (DIGITO[10] < 2)
		{
			DIGITO[10] = 0;
		}
		else
		{
			DIGITO[10] = 11 - DIGITO[10];
		}
		DV = DIGITO[9] * 10 + DIGITO[10];
		if (DV != DV_INFORMADO)
		{
			alert('CPF inválido. Digite somente números!');
			campo.value = "";
			return false;
		} 
	}

