function setFocus(caixa) {document.getElementById(caixa).focus();}

function redireccionar(endereco)
{
    var destino=endereco;
    var versao_browser = navigator.appVersion;

       if (versao_browser.indexOf("MSIE") >= -1) // IE
       {
          window.location.href=destino;
       }
       else // outros
       {
          window.open(destino, target="_self");
       }   
}

function muda(node,imagem,imagem2)
{
	// Para abrir
	// nextSibling: indica o próximo elemento após o elemento em questão
	if (node.nextSibling.style.display == 'none')
	{
		// Muda a imagem (caso exista)
		if (node.childNodes.length > 0)
		{
			if (node.childNodes.item(0).nodeName == "IMG")
			{
				node.childNodes.item(0).src = imagem2; //menos
			}
		}

		node.nextSibling.style.display = 'block';
	}
	// Para fechar
	else
	{
		// Muda a imagem (caso exista)
		if (node.childNodes.length > 0)
		{
			if (node.childNodes.item(0).nodeName == "IMG")
			{
				node.childNodes.item(0).src = imagem; //mais
			}
		}

		node.nextSibling.style.display = 'none';
	}

}

// abrir janela (utilizado para calendário e para janelas de comunicação com formulários)
function abre(pag,altura,largura,scroll)
{
var janlargura = (screen.width - largura) / 2;
var janaltura= (screen.height - altura) / 2;
winprops = 'toolbar=no,width='+largura+',height='+altura+',top='+janaltura+',left='+janlargura+',scrollbars='+scroll+',noresizable,statusbar=0'
window.open(pag,'geral',winprops);
}




// alert de confirmação
function confirma(texto,endereco) {
	var resposta = confirm(texto)
	if (resposta){
		window.location = endereco;
	}
}

function letras(e) {
	var k;
	document.all ? k = e.keyCode : k = e.which;
	//return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 9);
	if (k==0)
		document.getElementById('password').focus();
	return (k > 96 && k < 123 || k == 8 || k == 9);
}

function numeros(e) {
	var k;
	document.all ? k = e.keyCode : k = e.which;
	return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 9);
	/*
	if (k==0)
		document.getElementById('topo_esq').focus();
	return (k > 47 && k < 58 || k == 8 || k == 9);
	*/
}

function fechaRefrescaParent(ficheiro) {
	window.opener.location.href=ficheiro;  
	window.close();	
}

//// para impressão de iframes a partir da parent
function CheckIsIE()
{
if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER') { return true;}
else { return false; }
}


function imprimirIframe(nomeFrame)
{

if (CheckIsIE() == true)
{
eval("document." + nomeFrame).focus();
eval("document." + nomeFrame).print();
}
else
{
window.frames[nomeFrame].focus();
window.frames[nomeFrame].print();
}

}

function isNumero(evt)
{
 var charCode = (evt.which) ? evt.which : event.keyCode
 if (charCode > 31 && (charCode < 48 || charCode > 57))
	return false;

 return true;
}

function isNumeroLimitado(evt)
{
 
 if (evt.which != 0) {
	 var charCode = (evt.which) ? evt.which : event.keyCode
	 if (charCode > 31 && (charCode < 49 || charCode > 53))
		return false;
 }

 return true;
}


// melhoria da isNumero
// permite a o separador decimal
// apenas se casas_decimais = true
function isNumero_v2(evt,casas_decimais)
{
 
 var codigoCaractere;
 
 // var codigoCaractere = (evt.which) ? evt.which : event.keyCode
 if (evt.which) {
 	codigoCaractere = evt.which;
 }
 else {
 	 if (evt.keyCode == 0) {
	 	codigoCaractere = event.keyCode;
	 }
 }

 if (codigoCaractere > 31 && (codigoCaractere < 48 || codigoCaractere > 57)) {
 	if (casas_decimais && codigoCaractere != 46)
	   return false;
 }

 return true;
}




function pre_submit_v2(id_form,params) {
	document.getElementById(id_form).action = params;
	document.getElementById(id_form).submit();
}

function mudaImagem(nome,source)
{
  document.getElementById(nome).src = source;
}



///////////////////////////////////////////////////////////////////

function controlaImagens(erro1,erro2,erro3,erro4,erro5) {
	
	if (erro1)
		document.getElementById('progr1').src = 'imgs/progr1_erro.png';	
	else
		document.getElementById('progr1').src = 'imgs/progr1.png';	
	
	if (erro2)
		document.getElementById('progr2').src = 'imgs/progr2_erro.png';	
	else
		document.getElementById('progr2').src = 'imgs/progr2.png';	
	
	if (erro3)
		document.getElementById('progr3').src = 'imgs/progr3_erro.png';	
	else
		document.getElementById('progr3').src = 'imgs/progr3.png';	
	
	if (erro4)
		document.getElementById('progr4').src = 'imgs/progr4_erro.png';	
	else
		document.getElementById('progr4').src = 'imgs/progr4.png';	
	
	if (erro5)
		document.getElementById('progr5').src = 'imgs/progr5_erro.png';	
	else
		document.getElementById('progr5').src = 'imgs/progr5.png';	
}

function displayErro(erro,seccao) {
	
	var seccaoerro = document.getElementById('seccaoerro'+seccao);
	
	if (erro.length == 0)
		seccaoerro.style.display = 'none';
	else {
		document.body.scrollTop = 0;
		seccaoerro.style.display = 'block';
	}
		
	seccaoerro.innerHTML = erro;
	
}


function in_array( what, where ){
  var a=false;
  for(var i=0;i<where.length;i++){
  	if(what == where[i]){
  		a=true;
  		break;
  	}
  }
  return a;
}

function pre_submit(id_form) {

	var aviso_gravacao = document.getElementById('aviso_gravacao');

	var erro1 = false;
	var erro2 = false;
	var erro3 = false;
	var erro4 = false;
	var erro5 = false;
	
	var txt_erro1 = '';
	var txt_erro2 = '';
	var txt_erro3 = '';
	var txt_erro4 = '';
	var txt_erro5 = '';
	
	var erro;
	var tipo_perfil;
	var contador_erros;
	
	var elemento;
	var formulario = document.getElementById('formulario');
	var txt_alinea;
	var id_alinea;
	var num_alinea;
	
	var cor_erro   = '#FF0000';
	var cor_normal = '#005A92';

	// limpar qualquer aviso de gravação
	aviso_gravacao.style.display = 'none';

//////////////////////////////////////////////////////////////////////
/// VALIDA situação face à instituição
//////////////////////////////////////////////////////////////////////
	
	txt_erro2 = '';

	contador_erros = 0;
	for (i=0;i<6;i++) {
		id_alinea = eval("document.formulario.situacao_instituicao[" + i + "]").checked;
		if (!id_alinea)
			contador_erros++;
	}
	if (contador_erros == 6) {
		txt_erro2 += ' &nbsp; <b>Situação face à instituição</b> (em cima) é de selecção obrigatória.<br/>';
	}


//////////////////////////////////////////////////////////////////////
/// VALIDA situação face à instituição
//////////////////////////////////////////////////////////////////////

	contador_erros = 0;
	for (i=0;i<6;i++) {
		//if (!document.formulario.r1a1[i].checked)
		id_alinea = eval("document.formulario.escola_avaliada[" + i + "]").checked;
		if (!id_alinea)
			contador_erros++;
	}
	if (contador_erros == 6) {
		txt_erro2 += ' &nbsp; <b>Escola a que se refere a sua avaliação</b> (em cima) é de selecção obrigatória.<br/>';
	}


//////////////////////////////////////////////////////////////////////
/// VALIDA SECÇÃO 2
//////////////////////////////////////////////////////////////////////

	var num_perguntas = 4;
	var pergunta;
	
	var num_alineas=new Array(); 
	var num_possibilidades=new Array(); 
	var excepcoes=new Array(); 
	var resposta;

	num_alineas[1]=9;
	num_alineas[2]=5;
	num_alineas[3]=8;
	num_alineas[4]=1;
	/*
	num_alineas[4]=7;
	num_alineas[5]=8;
	num_alineas[6]=3;
	num_alineas[7]=5;
	//num_alineas[8]=3;
	num_alineas[9]=1;
	num_alineas[10]=6;
	num_alineas[11]=1;
	*/
	
	num_possibilidades[1] = 6;
	num_possibilidades[2] = 6;
	num_possibilidades[3] = 6;
	num_possibilidades[4] = 6;
	/*
	num_possibilidades[4] = 6;
	num_possibilidades[5] = 6;
	num_possibilidades[6] = 6;
	num_possibilidades[7] = 6;
	//num_possibilidades[8] = 6;
	num_possibilidades[9] = 5;
	num_possibilidades[10] = 5;
	*/
	
	excepcoes = new Array();
	/*
	excepcoes[0] = 'r1a8';
	excepcoes[1] = 'r2a8';
	excepcoes[2] = 'r5a8';
	excepcoes[3] = 'r11a1';
	*/
	
	
	for (pergunta = 1; pergunta <= num_perguntas; pergunta++) {
	
			for (num_alinea = 1; num_alinea <= num_alineas[pergunta] ; num_alinea++) {
		
				contador_erros = 0;
				txt_alinea = document.getElementById('area_alinea_r' + pergunta + 'a' + num_alinea);
				resposta = 'r'+pergunta+'a'+num_alinea;
				
				
				if (in_array(resposta,excepcoes)) {

					if (document.getElementById(resposta).value == '') {
						txt_alinea.style.color = cor_normal; // redundância para ignorar erro
						//txt_alinea.style.color = cor_erro;
					}
					else {
						txt_alinea.style.color = cor_normal;
					}
				}
				
				else {

					for (i=0;i<num_possibilidades[pergunta];i++) {
						//if (!document.formulario.r1a1[i].checked)
						id_alinea = eval("document.formulario.r" + pergunta + "a" + num_alinea + "[" + i + "]").checked;
						if (!id_alinea)
							contador_erros++;
					}
				
					if (contador_erros == num_possibilidades[pergunta]) {
						txt_erro1 = ' &nbsp; As <b>alíneas assinaladas a vermelho</b> são de preenchimento obrigatório e ainda não estão preenchidas.<br/>';	
						txt_alinea.style.color = cor_erro;
					}
					else {
						txt_alinea.style.color = cor_normal;
					}
					
				}

			
			}
		
	}
	
	
	displayErro(txt_erro2 + txt_erro1,1);
	
//////////////////////////////////////////////////////////////////////

	
	if (txt_erro1.length != 0) erro1 = true;
	if (txt_erro2.length != 0) erro2 = true;
	if (txt_erro3.length != 0) erro3 = true;
	if (txt_erro4.length != 0) erro4 = true;
	if (txt_erro5.length != 0) erro5 = true;
	
	// controlaImagens(erro1,erro2,erro3,erro4,erro5);
	
	// submit do formulário
	if (!erro1 && !erro2 && !erro3 && !erro4 && !erro5) { 
		formulario.action = 'index2.php?act=ins';
		formulario.submit();
	}
	
}

function controlaSeparador(separador) {
	
	// indicador
	var indicador_activo = document.getElementById("sepactivo"+separador);
	var seccao_activa = document.getElementById("seccao"+separador);
	var indicador;
	var seccao
	
	// indicador + seccao
	for (i=1;i<=5;i++) {
		indicador = document.getElementById("sepactivo"+i);
		seccao = document.getElementById("seccao"+i);
		indicador.style.display = 'none';
		seccao.style.display = 'none';
	}
	
	indicador_activo.style.display = 'block';
	seccao_activa.style.display = 'block';
}

function alteraPerfil(perfil) {
	
	var perfil2;
	
	if (perfil == 'aluno') {
		perfil2='restantes';
		document.getElementById("r1a2s1").selectedIndex = 0;
		document.getElementById("r1a2s2").value='';
		document.getElementById("r1a2s3").selectedIndex = 0;
		document.getElementById("r1a2s4").value='';
	}
	else {
		perfil2='aluno';
		//var subtipo = document.getElementById("r1a1s3").options[document.getElementById("r1a1s3").selectedIndex].value
		document.getElementById("r1a1s3").selectedIndex = 0;
		document.getElementById("r1a1s4").checked = false;
		document.getElementById("r1a1s5").value='';
		document.getElementById("r1a1s6").selectedIndex = 0;
	}
	
	var perfil_activo   = document.getElementById("perfil_"+perfil);
	var perfil_inactivo = document.getElementById("perfil_"+perfil2);
	
	perfil_activo.style.display   = 'block';
	perfil_inactivo.style.display = 'none';
	
}

function controlaRedes(valor) {
	var subalinea    = valor.substr(5,1);
	var subsubalinea = valor.substr(8,1);
	var seleccao  = document.getElementById(valor);
	var subsubalinea_h;
	var subsubalinea_v;
	
	for (i=1;i<=5;i++) {
		subsubalinea_v  = 'r5a3s' + i + 'ss' + subsubalinea;
		if (i != subalinea)
			document.getElementById(subsubalinea_v).checked = false;
	}
	
	/*
	(subsubalinea==1)?subsubalinea_h=2:subsubalinea_h=1
	
	subsubalinea_h  = 'r5a3s' + subalinea + 'ss' + subsubalinea_h // outra alinea na horizontal
	
	document.getElementById(subsubalinea_h).checked = !seleccao.checked;	
	*/
	
}

function controlaAlineas(cxs_controlo,alineas) {
	
	var conjunto_alineas = document.getElementById(alineas);
	var operacao         = document.getElementById(cxs_controlo) // sim ou não 
	var elemento;

	if (operacao.checked) 
		conjunto_alineas.style.display = 'block';	
	else {
		conjunto_alineas.style.display = 'none';
		
		// limpeza de valores
		
		if (alineas == 'perguntas22a25') {
			// limpar 2.2
			for (lin=1;lin<=5;lin++) {
				elemento = 'r2a2s'+lin;
				document.getElementById(elemento).value='';
			}
			
			// limpar 2.3
			linhas = 10; colunas = 5;
			for (lin=1;lin<=linhas;lin++) {
				for (col=1;col<=colunas;col++) {
					elemento = 'r2a3s'+lin+'ss'+col;
					document.getElementById(elemento).value='';
				}
			}
			
			// limpar 2.4
			linhas = 11; colunas = 5;
			for (lin=1;lin<=linhas;lin++) {
				for (col=1;col<=colunas;col++) {
					elemento = 'r2a4s'+lin+'ss'+col;
					document.getElementById(elemento).value='';
				}
			}
			
			// limpar 2.5
			linhas = 5;
			for (lin=1;lin<=linhas;lin++) {
				elemento = 'r2a5s'+lin
				document.getElementById(elemento).value='';
			}
		}
		
		else if (alineas == 'perguntas27') {
					
			// limpar 2.7
			linhas = 13; colunas = 5;
			for (lin=1;lin<=linhas;lin++) {
				for (col=1;col<=colunas;col++) {
					elemento = 'r2a7s'+lin+'ss'+col;
					document.getElementById(elemento).value='';
				}
			}
			
		}
		
		else if (alineas == 'perguntas32a33') {
					
			// limpar 3.2
			document.formulario.r3a2[0].checked = false;
			document.formulario.r3a2[1].checked = false;
			
			for (i=0;i<5;i++) 
				document.formulario.r3a3[i].checked = false;

		}
		
		else if (alineas == 'perguntas42a43') {
					
			// limpar 4.2
			for (i=0;i<6;i++) 
				document.formulario.r4a2[i].checked = false;
			// limpar 4.3
			for (i=0;i<5;i++) 
				document.formulario.r4a3[i].checked = false;

		}
		
		else if (alineas == 'perguntas45') {
					
			// limpar 4.5
			linhas = 5;
			for (lin=1;lin<=linhas;lin++) {
				elemento = 'r4a5s'+lin
				document.getElementById(elemento).value='';
			}

		}

	}
	
}

function processaItemCheckbox(nitem,valor,txt_area_aviso,txt_aviso) {
	
	var tipo = nitem;	

	if (document.getElementById("item"+nitem).style.display == 'none' && valor == '1') {
		document.getElementById("item"+nitem).style.display = 'block';

	}
	else if (document.getElementById("item"+nitem).style.display == 'block' && valor == '1') {
		document.getElementById("item"+nitem).style.display = 'block';	

	}
	else {

		document.getElementById("item"+nitem).style.display = 'none';	

		switch (tipo) {
			case ('aluno'):
				document.getElementById('aluno_curso').value = '';
				document.getElementById('aluno_ano').value = '';
				break;
			default:
				
				break;
		}
	}
		
	document.getElementById(txt_area_aviso).innerHTML = txt_aviso;
	
}

function contadorTexto(campo, area_contagem, limite) {
	var          c = document.getElementById(campo);
	var area_conta = document.getElementById(area_contagem);
	
	if (c.value.length > limite) 
		c.value = c.value.substring(0, limite);
	else 
		area_conta.innerHTML = limite - c.value.length;
}