// JavaScript Document

// FUNÇÕES GERAIS;

function randomico() {
	return "?rnd="+Math.random();
}

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;
		}
	}
}
}

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; 
}

function focaCampo(campo) {
	campo.focus();
}

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);
	
}

function checaCPF(cpf)
      {
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            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;
      }


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;
        }
}

function checaCNPJ(cnpj)
      {
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            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))
                  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))
                  return false;
            return true;
            }
      else
            return false;
      } 




// FUNÇÕES ESPECÍFICAS;

function alternaFormularioContato(id) {
	if (id == "Aluno") {
		document.getElementById("parteAluno").style.display = "block";
		document.getElementById("parteOutros").style.display = "none";
		document.getElementById("parteEmpresa").style.display = "none";
	}
	if (id == "Empresa") {
		document.getElementById("parteAluno").style.display = "none";
		document.getElementById("parteOutros").style.display = "none";
		document.getElementById("parteEmpresa").style.display = "block";
	}
	if (id == "Outros") {
		document.getElementById("parteAluno").style.display = "none";
		document.getElementById("parteOutros").style.display = "block";
		document.getElementById("parteEmpresa").style.display = "none";
	}
}

function contaCaracteres(campo, retorno, total) {	
	var restante = (total - campo.value.length);	
	if (restante <= 1) {
		campo.value = campo.value.substring(0, total-1);
	}	
	retorno.innerHTML = restante ;
}

function validaFormContato() {
	
	var nome 		= document.getElementById("nome");
	var email 		= document.getElementById("email");
	var tipoContato = document.getElementById("tipoContato");
	var cnpj 		= document.getElementById("cnpj");
	var ra 			= document.getElementById("ra");
	var cpf 		= document.getElementById("cpf");
	var cidade 		= document.getElementById("cidade");
	var estado 		= document.getElementById("estado");
	var mensagem 	= document.getElementById("mensagem");
	var btEnviar 	= document.getElementById("btEnviar");
	var assunto		= document.getElementById("assunto");
	var nomeAluno	= document.getElementById("nomeAluno");
	var cursoAluno	= document.getElementById("cursoAluno");
	var captcha		= document.getElementById("txtCaptcha");
	
	
	if (nome.value.length < 3) {
		alert("Por favor, informe seu nome corretamente.");
		alteraCor(nome);
		return false;
	}
	
	if(!checaMail(email.value)) {
		alert("Por favor, verifique a digitação de seu e-mail.");
		alteraCor(email);
		return false;
	}
	
	switch(tipoContato.value) {		
		case 'Empresa': 
			if(!checaCNPJ(cnpj.value)){
				alert("Por favor, verifique a digitação do CNPJ da empresa.");
				alteraCor(cnpj);
				return false;
			}			
			break;
			
		case 'Aluno':
			if (ra.value.length < 5) {
				alert("Por favor, verifique a digitação de seu R.A.");
				alteraCor(ra);
				return false;
			}
			break;
		
		case 'Outros':		
			if (!checaCPF(cpf.value)) {
				alert("Por favor, verifique a digitação de seu CPF.");
				alteraCor(cpf);
				return false;
			}
			break;		
	}
	
	if (cidade.value.length < 3) {
		alert("Por favor, informe corretamente o nome de sua cidade.");
		alteraCor(cidade);
		return false;
	}
	
	if (mensagem.value.length < 10) {
		alert("Por favor, preencha a mensagem a ser enviada.");
		alteraCor(mensagem);
		return false;
	}
	
	if (captcha.value.length != 6) {
		alert("Por favor, preencha o campo indicado conforme as letras e números da imagem.");
		alteraCor(captcha);
		return false;
	}

	if (assunto.value == "contrato") {
		if(nomeAluno.value.length < 5 || nomeAluno.value == "informe o nome completo do aluno") {
			alert("Por favor, preencha o NOME COMPLETO do aluno.");
			alteraCor(nomeAluno);
			return false;
		}
	}

	if (assunto.value == "contrato") {
		if (cursoAluno.value.length < 3 || cursoAluno.value == "informe o curso do aluno") {
			alert("Por favor, preencha o CURSO do aluno.");
			alteraCor(cursoAluno);
			return false;
		}
	}

}


// FUNÇÕES DE LOGIN

function login() {
	// capturo os campos
	var usuario = document.getElementById("usuario");
	var senha = document.getElementById("senha");

	// validação
	if (usuario.value.length < 3) {
		alert("Por favor, verifique o seu nome de usuário.");
		alteraCor(usuario);
		return false;
	}
	
	if (senha.value.length < 3) {
		alert("Por favor, verifique a digitação de sua senha.");
		alteraCor(senha);
		return false;
	}
}


function popupExpiradas(qt, larg, alt, contato) {
	
	var container = document.getElementById("container");
	var novaDiv = document.createElement("div");

	//fundo negro
	novaDiv.setAttribute("id", "fundoNegro");
	var fundoNegro = container.appendChild(novaDiv);
	
	with(fundoNegro.style) {
		position = "absolute";
		backgroundColor = "#000000"
		height = getViewportHeight() + "px";
		width = getViewportWidth() + "px";
		top = getScrollTop() + "px";
		left = 0;
		opacity = 0.5;
		filter = "alpha(opacity=50)";
		zIndex = 1;
	}
	

	//quadro branco
	var novaDiv = document.createElement("div");
	novaDiv.setAttribute("id", "popBranco");
	var popBranco = container.appendChild(novaDiv);
	
	with(popBranco.style) {
		position = "absolute";
		backgroundColor = "#FFFFFF";
		height = parseInt(alt) + "px"; // tamanho passado pela função
		width = parseInt(larg) + "px"; // tamanho passado pela função
		top = getScrollTop() + (getViewportHeight()/2) - (parseInt(alt)/2) + "px"; // altura / 2
		left = "50%";
		marginLeft = ((parseInt(larg) /2)* -1) + "px"; // largura /2 * -1 (pra ficar negativo);
		zIndex = 2;
		padding = "5px";
		borderTop = "2px solid #CCCCCC";
		borderLeft= "2px solid #CCCCCC";
		borderBottom = "3px solid #666666";
		borderRight = "3px solid #666666";
	}
	
	window.onscroll=function(){
		fundoNegro.style.top = getScrollTop() + "px";
		popBranco.style.top = getScrollTop() + (getViewportHeight()/2) - 100 + "px";
	}	
	
	// REMOVE O POPUP QUANDO CLICAR NO FUNDO NEGRO
	fundoNegro.onclick=function() {
		container.removeChild(fundoNegro);
		container.removeChild(popBranco);
		window.onscroll=null;
	}
	
	html  = "<p>Prezado(a) <b>" + contato + "</b>, "
	html += "<p>"
	if (qt > 1) {
		html += "Existe";
	} else {
		html += "Existem";
	}
	
	mensagem = "VAGAS EXPIRADAS	\\n\\nQuando uma vaga expira, é importante a empresa informar o que aconteceu e o que quer fazer com essa vaga.\\n\\nVocê poderá reativá-la, excluí-la ou desativá-la de acordo com suas necessidades.\\n\\nPor favor, acesse a página de Vagas Expiradas e informe qual o andamento destas vagas.\\n\\nAtt,\\nCentral de Estágios.";
	
	html += " <b>" + qt + "</b> vagas expiradas em seu cadastro.</p>"
	html += "<p align=\"center\"><input type=\"button\" value=\"Visualizar Vagas\" onclick=\"document.location.href='/?pg=listaVagasExpiradas&dir=vagas'\"></p>";
	html += "<p align=\"right\"><a href=\"#.\" onclick='alert(\"" + mensagem + "\");'>Qual a importância?</a></p>";
	
	
	popBranco.innerHTML = html;
	

}


function permanecerLogado(usuario, senha) {
	setInterval(function() {
						
			url = "/inc/pgLogin.asp";
			url += randomico();
			url += "&u=" + usuario;
			url += "&s=" + senha;
			
			AjaxRequest();
			Ajax.open("GET", url, true);
			Ajax.send(null);							
						
						
						}, 1000000);
}
