var xmlHttp = ajaxInit();

function getElmBI(campo){     
	var elemento = document.getElementById(campo);
	return elemento;
}

function ajaxInit() {
  var xmlHttp;
  // trabalha com todos os browsers, menos IE
  try
  {
	// tenta criar o objeto XMLHttpRequest
	xmlHttp = new XMLHttpRequest( );
  }
  catch(e)
  {
	var XmlHttpVersoes = [ 
		"MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.5.0",
		"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
		"MSXML2.XMLHttp","Microsoft.XMLHttp"
		];

	// procura a melhor versão para o IE
	for (var i=0; i< XmlHttpVersoes.length; i++) 
	{
	  try 
	  { 
		//tenta criar o objeto XMLHttpRequest 
		xmlHttp = new ActiveXObject(XmlHttpVersoes[i]);
	  } 
	  catch (e) {}
	}
  }
  //retorna o objeto criado ou um erro
  if (!xmlHttp)
	alert("Seu navegador não suporta os recursos dessa aplicação. Tente usar uma versão mais atual!");
  else 
	return xmlHttp;
}

function getDados(objForm){
	var params = new Array();
	for (var i=0; i<objForm.elements.length; i++){
		var parametro = encodeURIComponent(objForm.elements[i].name);
		parametro +="=";
		parametro +=encodeURIComponent(objForm.elements[i].value);
		params.push(parametro);
	}
	return params.join("&");
}


// recupera o nome do professor na tela de LOGIN
function buscaProfessor(cpf){
	if(xmlHttp){
		url = "obterProfessor.php?cpf="+cpf+"&sid="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
     				//if (document.getElementById("nomeProfessor").hasChildNodes()){
					//	document.getElementById("nomeProfessor").removeChild(document.getElementById("nomeProfessor").lastChild);      				
					//}
     				//document.getElementById("nomeProfessor").appendChild(document.createTextNode(xmlHttp.responseText)); 
     				document.getElementById("nomeProfessor").innerHTML=xmlHttp.responseText; 
     			} else {
     				document.getElementById("nomeProfessor").appendChild(document.createTextNode("")); 
     			}
     		}
 		}	
		xmlHttp.send(null);
	}
}


//******** PARA A TELA DE CADASTRO DE SENHAS **********//////

// verifica se o codprofessor é valido
function identificarProfessor(){

    cpf=retiraCaracteresInvalidos(document.getElementById('cpf').value);
    codprof = retiraCaracteresInvalidos(document.getElementById('codprof').value);
	if(xmlHttp){
		url = "idProfessor.php?cpf="+cpf+"&codprof="+codprof+"&sid="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
     				if (xmlHttp.responseText!='ok'){
     					alert('Código do professor incorreto! Informe o código sem o dígito');
     					document.getElementById("codprof").value="";
     					document.getElementById("codprof").focus();
     				}
     			}
     		}
 		}	
		xmlHttp.send(null);
	}
}


//******** PARA A TELA DE CADASTRO DE NOTAS **********//////

// busca a lista de alunos existentes para a disciplina lecionada
function buscarAlunos(objSelect, pLetivo, codCurso, codGrade, serie, turma, codDisc, idCasa){
	var nota = objSelect.options[objSelect.selectedIndex].value;
	
	var idElemento=codCurso+codDisc+serie+turma;
	var insereListaAlunos = document.getElementById(idElemento);
	var divAlunos;
	
	if(document.getElementById("divAlunos")){
		divAlunos =document.getElementById("divAlunos");
		noPai = divAlunos.parentNode
		while (noPai.hasChildNodes()){
			noPai.removeChild(noPai.lastChild);
		}
	}
	if (nota!=0){	
		divAlunos = document.createElement("div");
		divAlunos.setAttribute("id", "divAlunos");
		
		imagem = document.createElement("img");
		imagem.setAttribute("src","../img/loading.gif");
		
		noImagem =document.getElementById("img"+idElemento);
		noImagem.appendChild(imagem);
		if(xmlHttp){
			xmlHttp.open("POST","obterAlunos.php",true);
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-2");
			var dados = "pletivo="+pLetivo+"&idcasa="+idCasa+"&curso="+codCurso+"&grade="+codGrade+"&serie="+serie+"&turma="+turma+"&disc="+codDisc+"&nota="+nota;
			xmlHttp.onreadystatechange=function() { 
	     		if(xmlHttp.readyState==4) { 
	     			if (xmlHttp.status == 200) {
	     				noImagem.removeChild(noImagem.lastChild);
	     				divAlunos.innerHTML=xmlHttp.responseText; 
	   					insereListaAlunos.appendChild(divAlunos);
	   				} else {
	   					alert('Ocorreu um erro:'+xmlHttp.statusText);
	   				}
	     		}
	 		}	
			xmlHttp.send(dados);
		}
	}
}
function buscarDiscLecionadas(pLetivo,cpf){
	imagem = document.createElement("img");
	imagem.setAttribute("src","../img/loading.gif");
		
	noImagem =document.getElementById("imgPLetivo");
	noImagem.appendChild(imagem);

   	if(xmlHttp){
		url = "gerarDiscLecionadas.php?cpf="+cpf+"&pLetivo="+pLetivo+"&sid="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
	     			noImagem.removeChild(noImagem.lastChild);
   					document.getElementById("digitarNotas").innerHTML=xmlHttp.responseText;
     			}
     		}
 		}	
		xmlHttp.send(null);
	}
}

function salvarNotas(formulario, acao){
	// acao 1- SALVAR | 2- ENVIAR
	//var resultado = confirm("Prezado Professor(a).\nAo salvar essas notas elas serão submetidas à secretaria do Unisalesiano.\nAs alterações nas notas somente poderão ser feitas junto à secretaria do Unisalesiano.\nVocê confirma o envio das notas?");
	//if (resultado) {

	imagem = document.createElement("img");
	imagem.setAttribute("src","../img/loading.gif");
		
	noImagem =document.getElementById("aguardeSalvar");
	noImagem.appendChild(imagem);
	var msg="";
		if(xmlHttp){
			var dados = getDados(formulario);
			if(acao==1){
				xmlHttp.open("POST","salvarNotas.php",true);
				msg="Todas as notas foram SALVAS com sucesso!";
			}else{
				xmlHttp.open("POST","enviarNotas.php",true);
				msg="Todas as notas foram ENVIADAS ao SISTEMA ACADEMICO com sucesso!";				
			}
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
			xmlHttp.onreadystatechange=function() { 
	     		if(xmlHttp.readyState==4) { 
	     			if (xmlHttp.status == 200) {
						if (parseInt(xmlHttp.responseText)==1){
							if(document.getElementById("divAlunos")){
								var divExclui =document.getElementById("divAlunos");
								var noPai = divExclui.parentNode
								while (noPai.hasChildNodes()){
									noPai.removeChild(noPai.lastChild);
								}
							}
							alert(msg);
						} else {
							alert(xmlHttp.responseText);
						}
	   				} else {
	   					alert('Ocorreu um erro:'+xmlHttp.statusText);
	   				}
	     		}
 			}	
			xmlHttp.send(dados); 			
		}
	//}
}

//** PLANOS DE ENSINO *****
function buscarDiscLecionadasPlanoEnsino(pLetivo,cpf){
	imagem = document.createElement("img");
	imagem.setAttribute("src","../img/loading.gif");
		
	noImagem =document.getElementById("imgPlano");
	noImagem.appendChild(imagem);

   	if(xmlHttp){
		url = "gerarDiscPlanoEnsino.php?cpf="+cpf+"&pLetivo="+pLetivo+"&sid="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
	     			noImagem.removeChild(noImagem.lastChild);
	     			document.getElementById("planoEnsino").style.display="block";
   					document.getElementById("planoEnsino").innerHTML=xmlHttp.responseText;
     			}
     		}
 		}	
		xmlHttp.send(null);
	}
}


// busca a lista de alunos existentes para a disciplina lecionada
function buscarPlano(codImg, pLetivo, codCurso, codGrade, serie, turma, codDisc, idCasa){
	var inserePlano = document.getElementById("exibePlanoEnsino");
	var conteudoPlano;
	getElmBI('status'+codImg).src="../img/aguardo.png"
	if(document.getElementById("conteudoPlano")){
		conteudoPlano=document.getElementById("conteudoPlano");
		noPai = conteudoPlano.parentNode
		while (noPai.hasChildNodes()){
			noPai.removeChild(noPai.lastChild);
		}
	}

	conteudoPlano= document.createElement("div");
	conteudoPlano.setAttribute("id", "conteudoPlano");

	imagem = document.createElement("img");
	imagem.setAttribute("src","../img/loading.gif");

	noImagem =document.getElementById("img"+codImg);
	noImagem.appendChild(imagem);
	if(xmlHttp){
		xmlHttp.open("POST","obterPlano.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-2");
		var dados = "pletivo="+pLetivo+"&idcasa="+idCasa+"&curso="+codCurso+"&grade="+codGrade+"&serie="+serie+"&turma="+turma+"&disc="+codDisc;
		xmlHttp.onreadystatechange=function() { 
			if(xmlHttp.readyState==4) { 
				if (xmlHttp.status == 200) {
					noImagem.removeChild(noImagem.lastChild);
					conteudoPlano.innerHTML=xmlHttp.responseText; 
					inserePlano.appendChild(conteudoPlano);
					inserePlano.style.display="block";
				} else {
					noImagem.removeChild(noImagem.lastChild);
					alert('Ocorreu um erro:'+xmlHttp.statusText);
				}
			}
		}	
		xmlHttp.send(dados);
	}
		
}


// **** MÒDULO DE ALUNOS ALUNOS ****
function geraBoletim(formulario){
	var	imagem = document.createElement("img");
	imagem.setAttribute("src","../img/loading.gif");
		
	var noImagem =getElmBI("carregando");
	noImagem.appendChild(imagem);

	if(xmlHttp){
		var dados = getDados(formulario);
		xmlHttp.open("POST","gerarBoletim.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
	    	if(xmlHttp.readyState==4) { 
	    		if (xmlHttp.status == 200) {
					var divBoletim =getElmBI("exibeBoletim");
					divBoletim.innerHTML=xmlHttp.responseText;
     				noImagem.removeChild(noImagem.lastChild);
	   			} else {
	   				alert('Ocorreu um erro:'+xmlHttp.statusText);
	   				noImagem.removeChild(noImagem.lastChild);

	   			}
	    	}
 		}	
		xmlHttp.send(dados); 			
	}
}

function geraFaltas(formulario, codDisc){
	var	imagem = document.createElement("img");
	imagem.setAttribute("src","../img/loading.gif");
		
	var noImagem =getElmBI("carregando");
	noImagem.appendChild(imagem);

	if(xmlHttp){
		var dados = getDados(formulario);
		dados+= "&codDisc="+codDisc;
		xmlHttp.open("POST","gerarFaltas.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
	    	if(xmlHttp.readyState==4) { 
	    		if (xmlHttp.status == 200) {
					var divFaltas =getElmBI("exibeFaltas");
					divFaltas.innerHTML=xmlHttp.responseText;
					divFaltas.style.display='block';
     				noImagem.removeChild(noImagem.lastChild);
	   			} else {
	   				alert('Ocorreu um erro:'+xmlHttp.statusText);
	   				noImagem.removeChild(noImagem.lastChild);
	   			}
	    	}
 		}	
		xmlHttp.send(dados); 			
	}

}

function exibirDivConteudo(nome){
	divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; i++){
		if (divs[i].className=="conteudo"){
			divs[i].style.display='none'
		}
		if (divs[i].className=="divFlutuante"){
			divs[i].style.display='none'
		}
	}
	
	document.getElementById(nome).style.display='block'
	$('#'+nome).css({'height':$(document).height()})
}

function exibirDivConteudoAjax(nome){
	divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; i++){
		if (divs[i].className=="conteudo"){
			divs[i].style.display='none'
		}
		if (divs[i].className=="divFlutuante"){
			divs[i].style.display='none'
		}
	}
	
	if(xmlHttp){
		url = nome+".php?&sid="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
					document.getElementById(nome).style.display='block'
					$('#'+nome).css({'height':$(document).height()})
     				document.getElementById(nome).getElementsByTagName('div')[0].innerHTML=xmlHttp.responseText; 
     			} else {
     				document.getElementById(nome).appendChild(document.createTextNode("Problemas com a comunicação com o servidor!")); 
     			}
     		}
 		}	
		xmlHttp.send(null);
	}
}


function salvarPlanoEnsino(formulario){
	if(xmlHttp){
		var dados = getDados(formulario);
		xmlHttp.open("POST","salvarPlanos.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
					if (parseInt(xmlHttp.responseText)==1){
						alert('Todas as alterações foram salvas com sucesso!');
						getElmBI('exibePlanoEnsino').style.display='none'						
					} else {
						alert(xmlHttp.responseText);
					}
   				} else {
   					alert('Ocorreu um erro:'+xmlHttp.statusText);
   				}
     		}
		}	
		xmlHttp.send(dados); 			
	}
}



/*************************************************************/
/****************** BIBLIOGRAFIAS ***************************/
function buscarLivros(idCampo, indice){
	var valorPesquisa = document.getElementById(idCampo).value
	if (valorPesquisa.length < 3){
		alert("Informe ao menos 3 letras do TÍTULO para iniciar a pesquisa!")
	} else {
		var	imagem = document.createElement("img");
		imagem.setAttribute("src","../img/loading.gif");
		
		var noImagem =getElmBI("imgPesquisa"+indice);
		noImagem.appendChild(imagem);
	
		var pesquisa = getElmBI("pesquisaLivro"+indice);
	
		if(xmlHttp){
			var dados = "titulo="+valorPesquisa+"&indice="+indice+"&id="+Math.random();
			xmlHttp.open("POST","buscarLivros.php",true);
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
			xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4){
					if (xmlHttp.status==200){
						noImagem.removeChild(noImagem.lastChild);
						pesquisa.innerHTML=xmlHttp.responseText;
						pesquisa.style.display='block';
					} else {
						alert('Ocorreu um erro:'+xmlHttp.statusText);
						noImagem.removeChild(noImagem.lastChild);
					}
				}
			}
			xmlHttp.send(dados); 	
		}
	}
}

function preencheBibliografia(indice, titulo, subtitulo, cidade, edicao, anoEdicao, editora, sobrenome1, nome1, sobrenome2, nome2, sobrenome3, nome3, etal ){
//	getElmBI("inicioTitulo"+indice).value = inicio;
	getElmBI("titulo"+indice).value = titulo;
    getElmBI("subtitulo"+indice).value = subtitulo;
	getElmBI("cidade"+indice).value = cidade;
	getElmBI("edicao"+indice).value = edicao;
	getElmBI("anoEdicao"+indice).value = anoEdicao;
	getElmBI("editora"+indice).value = editora;
    getElmBI("sobrenome1"+indice).value = sobrenome1;
    getElmBI("nome1"+indice).value = nome1;    
    getElmBI("nome2"+indice).value = nome2;   
    getElmBI("sobrenome2"+indice).value = sobrenome2; 
    getElmBI("nome3"+indice).value = nome3;   
    getElmBI("sobrenome3"+indice).value = sobrenome3; 
    if (etal=='S'){
    	getElmBI("autorAtAl"+indice).checked='checked';
    }
    getElmBI("pesquisaLivro"+indice).style.display='none';

}

function mudarFundo(obj, classe){
	obj.className=classe;
}

//*************************************************************
//******************** UPLOAD DE MATERIAL *********************
function enviarMaterial(formulario){
	var continua = validarEnvioMaterial();
	if (continua){
		var dados = getDados(formulario);
		formulario.submit();
		getElmBI("iframeUpload").style.display="block";
		formulario.reset();
		obtemListaMateriais(dados);
	}
}

function validarEnvioMaterial(){
	var continua = true;
	var msg="";
	if (getElmBI('matDisciplina').value==0){
		continua=false;
		msg = "É preciso selecionar uma disciplina.\n";
		getElmBI('matDisciplina').style.backgroundColor="#FFFFCC";
	} else {
		getElmBI('matDisciplina').style.backgroundColor="#FFFFFF";
	}
	
	if (eNulo(getElmBI('matNome').value)){
		continua=false;	
		msg = msg + "Informe o nome do material a ser disponibilizado.\n";
		getElmBI('matNome').style.backgroundColor="#FFFFCC";
	} else {
		getElmBI('matNome').style.backgroundColor="#FFFFFF";
	}
	
	if (eNulo(getElmBI('matArquivo').value)){
		continua=false;
		msg = msg+ "É preciso selecionar um arquivo.";
		getElmBI('matArquivo').style.backgroundColor="#FFFFCC";
	} else {
		getElmBI('matArquivo').style.backgroundColor="#FFFFFF";
	}
	
	if (!continua){
		alert(msg);
	}
	return continua;
}

function obtemListaMateriais(dados){
	dados = dados+"&id="+Math.random();
	if (xmlHttp){
		xmlHttp.open("POST","materiaisProfessores.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
	     			getElmBI('materiaisEnviados').innerHTML=xmlHttp.responseText;
   				} else {
   					alert('Ocorreu um erro:'+xmlHttp.statusText);
   				}
     		}
		}	
		xmlHttp.send(dados); 			
	}
}

function removerMateriais(codDisc, codMaterial, idCasa, codProf, formulario){
	if (xmlHttp){
		//var dados = getDados(formulario);
		var dados = "codDisc="+codDisc+"&codMaterial="+codMaterial+"&codProf="+codProf+"&idCasa="+idCasa;
		xmlHttp.open("POST","removerMateriais.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
	     			obtemListaMateriais(getDados(formulario));
   				} else {
   					alert('Ocorreu um erro:'+xmlHttp.statusText);
   				}
     		}
		}	
		xmlHttp.send(dados); 			
	}
}

function defineDisciplina(disciplina, cpf){
	if (xmlHttp){
		var dados = "codDisc="+disciplina+"&cpf="+cpf+"&id="+Math.random();
		xmlHttp.open("POST","obterCodProfeIdCasa.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
	     			var resposta = xmlHttp.responseText;
	     			getElmBI('matIdCasa').value=resposta.substr(0,2);
	     			getElmBI('matProf').value=resposta.substr(2,resposta.length);
   				} else {
   					alert('Ocorreu um erro:'+xmlHttp.statusText);
   				}
     		}
		}	
		xmlHttp.send(dados); 			
	}
}

function exportarPlanoWeb(){
	if (xmlHttp){
		xmlHttp.open("GET","exportarPlanos.php",true);
		xmlHttp.onreadystatechange=function() { 
     		if(xmlHttp.readyState==4) { 
     			if (xmlHttp.status == 200) {
	     			getElmBI('conteudo').innerHTML=xmlHttp.responseText;
   				} else {
   					alert('Ocorreu um erro:'+xmlHttp.statusText);
   				}
     		}
		}	
		xmlHttp.send(null); 			
	}
}

//****************************************************** //
//************  Solicitação de Documentos ************** //
function solicitarDocumento(formulario){
	var dados = getDados(getElmBI(formulario));
	if (xmlHttp){
		xmlHttp.open("POST","gerarProtocolo.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
			if(xmlHttp.readyState==4) { 
	   			if (xmlHttp.status == 200) {
	     			var resposta = xmlHttp.responseText;
	     			if (resposta=='ok'){
						alert('Solicitação realizada com sucesso! Verifique a situação da sua solicitação na lista de slicitações');		     		
						getElmBI('documentos').style.display='none'		
					} else {
						getElmBI('documentos').innerHTML=resposta;
					}
				} else {
					alert('Ocorreu um erro:'+xmlHttp.statusText);
				}
	   		}
		}	
		xmlHttp.send(dados); 			
	}

}


function pesquisarDocs(formulario){
	var dados = getDados(getElmBI(formulario));
	if (xmlHttp){
		xmlHttp.open("POST","obterSolicitacoes.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
			if(xmlHttp.readyState==4) { 
	   			if (xmlHttp.status == 200) {
					getElmBI('resultado').innerHTML= xmlHttp.responseText;
				} else {
					alert('Ocorreu um erro:'+xmlHttp.statusText);
				}
	   		}
		}	
		xmlHttp.send(dados); 			
	}
}

function atualizaDoc(situacao, protocolo, responsavel){
	var dados = "situacao="+situacao+"&protocolo="+protocolo+"&responsavel="+responsavel;
	if (xmlHttp){
		xmlHttp.open("POST","atualizarDoc.php",true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlHttp.onreadystatechange=function() { 
			if(xmlHttp.readyState==4) { 
	   			if (xmlHttp.status == 200) {
					alert(xmlHttp.responseText);
					getElmBI('resultado').innerHTML="";
				} else {
					alert('Ocorreu um erro:'+xmlHttp.statusText);
				}
	   		}
		}	
		xmlHttp.send(dados); 			
	}
}

