
var regEmail = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

// descobe se é IE ou Mozilla
var isIE = (/\bmsie\b/i.test(navigator.userAgent) // é Internet Explorer?
            && document.all && !(/\bopera\b/i.test(navigator.userAgent)));

//faz um pré-load de algumas imagens para que apareçam sem problemas
function preloadImagens() {
	if (document.images) {
		var pic = new Array();
		var imgs = new Array('grav|10|10','excl|9|9','data|9|8','edit|10|10','excel|10|10',
			'volt|10|9','senha|8|10'); 
		for (var i=0; i<imgs.length; i++) {
			var val = imgs[i].split('|'); 
			pic[i] = new Image(val[1],val[2]);
			pic[i].src = 'img/ico_'+val[0]+'.gif';
		}
	}
	return null;
}

//preloadImagens();
	
// muda a cor da linha quando passa o mouse
function passa() {
	var ev = arguments[0] || window.event;
	var pai = ev.target || ev.srcElement;
	while (pai.tagName.toUpperCase() != 'TR' && pai.tagName.toUpperCase() != 'LI' && pai.tagName.toUpperCase() != 'DIV') pai = pai.parentNode;
	var stat = pai.style.backgroundColor.toLowerCase();
	if (ev.type == 'mouseout' || ev.type == 'click') {
		pai.style.backgroundColor = linhacor; // txt = '';
	} else {
		linhacor = stat; pai.style.backgroundColor = '#6699CC'; // txt = 'white'; // era '#006699'
	}
	return null;
}

// encontra o elemento "id" na página
function obj(id) {
	//return document.all(id);
	return document.getElementById(id);
	// o IE tem problemas em objetos que aceitam a propriedade "name". Testar e pesquisar...
	// HTMLCollection.namedItem(id);
}

// exibe ou oculta o div de "carregando informações, por favor aguarde..."
function mostraAguarde(mostra) {
	obj('aguarde').style.display = (mostra > 0) ? '' : 'none';
}


// recupera o elemento onde aconteceu o evento e sobe no DOM até o "tag"
// *************************************************************************************************
function origemEvento(tag, ev) {
	if (ev && ev.tagName) {
		// se o que foi passado no lugar no evento é um elemento:
		// se a tag do elemento passado é a própria tag solicitada, retorna o elemento
		// senão retorna o primeiro pai dele com a tag informada
		if (ev.tagName == tag) return ev;
		else return sobeDOM(ev, tag);
	} else {
		// se não foi passado nenhum parâmetro de evento (IE < 8), retorna o objeto evento do window
		if (!ev) ev = window.event;
		// se não tem objeto evento nem na window, não retorna nada
		if (!ev) return null;
		// encontra o elemento que gerou o evento (IE: srcElement, outros browsers: target)
		var evorigem = ev.srcElement || ev.target;
	}
	// sobe pela hieraquia DOM até encoontrar o primeiro pai do elemento clicado com a tag que foi informada
	return sobeDOM(evorigem, tag);
}
// *************************************************************************************************


// sobe na hierarquia do DOM desde "elemento" até a "tag"
function sobeDOM(elem, tag) {
	while (elem && elem.tagName && elem.tagName.toUpperCase() != tag.toUpperCase()) elem = elem.parentNode;
	return elem;
}

function achaStilo(nome) {
	var stilos = (isIE) ? document.styleSheets[0].rules : document.styleSheets[0].cssRules;
	for (var i=0; i<stilos.length; i++) if (stilos[i].selectorText == nome) return stilos[i];
	return null;
}

// tira os acentos de um dado "txt"
function tiracentos(txt) {
	txt = txt.replace(/[ÁÀÃÂÄ]/g,'A').replace(/[ÉÈÊË]/g,'E').replace(/[ÍÌÎÏ]/g,'I');
	txt = txt.replace(/[ÓÒÕÔÖ]/g,'O').replace(/[ÚÙÛÜ]/g,'U').replace(/Ñ/g,'N').replace(/Ç/g,'C');
	txt = txt.replace(/[áàãâä]/g,'a').replace(/[éèêë]/g,'e').replace(/[íìîï]/g,'i');
	txt = txt.replace(/[óòõôö]/g,'o').replace(/[úùûü]/g,'u').replace(/ñ/g,'n').replace(/ç/g,'c');
	return txt;
}

// transforma um texto em lower case e sem acentos
function textoPuro(txt) {
	return (txt) ? tiracentos(txt.toLowerCase()) : txt;
}

// remove um objeto de uma página
function removeObjeto(objeto) {
	if (objeto) objeto.parentNode.removeChild(objeto);
	return null;
}

// preenche as options de um select baseado em um array
// parâmetros: 
//	elem = select (objeto DOM) a ser preenchido
//	arei = array contento as options. Cada option deve ser um Array interno (id, nome)
//	ref = valor ao qual o value da option será comparado para selecionar a option ou não
//	vazio = true/false (ou null) indicando se o select contém a primeira option vazia (em branco)
//	limpaAntes = true/false (ou null) indicando se apaga ou não as options já existentes no select antes de colocar as novas
//	noinicio = true/false (ou null) indicando se coloca estas options no início (true) ou no final do select
function preencheSelect(elem, arei, ref, vazio, limpaAntes, noinicio, arraynomes) {
	if (limpaAntes) limpaSelect(elem, 0);
	if (vazio) newOption(elem, 0, "", "");
	for (var contselect = 0; contselect < arei.length; contselect++) {
		if (arraynomes) {
			val = arei[contselect].split('|').reverse();
		} else {
			val = arei[contselect];
		}
		var pos = (noinicio) ? 0 : elem.options.length;
		var valor = (val.length) ? val[0] : val.id;
		var nome = (val.length) ? val[1] : val.nome;
		newOption(elem, pos, nome, valor);
	}
	if (ref) for (var i = 0; i < elem.options.length; i++) elem.options[i].selected = (ref == elem.options[i].value);
	else elem.options[0].selected = true;
}

// remove todas as options de um select
// parâmetros: sel - objeto select
//			   ini - a partir de qual options começa a excluir
function limpaSelect(sel,ini) {
	/* Não é crossbrowser. */
	//var tot = sel.options.length;
	//for (i=ini; i<tot; i++) sel.options.remove(ini);
	//return null;
	
	//crossbrowser.
	while(sel.options[ini] != null) sel.options[ini] = null;
	return null;
}

//crossbrowser.
function newOption(sel, pos, text, value) {
	if (isIE) { // variavel global;
		var opt = new Option(text, value);
		if (pos == undefined) sel.add(opt);
		else sel.add(opt, pos);
		return opt;
	} else {
		var length = sel.options.length;
		if (pos == undefined) pos = length;
		if(length > 0)
			for(var i = length; i > pos; i--)
				sel.options[i] = sel.options[i-1].cloneNode(true);
		sel.options[pos] = new Option(text, value);
		return sel.options[pos];
	}
}
	
	

// exibe ou oculta elementos, usando visibility ou display
function exibeoculta(elem, exibe, visi) {
	if (exibe) {
		elem.className = elem.className.replace(/\bvisisome\b/g,'').replace(/\bdispsome\b/g,'');
	} else {
		elem.className += (visi) ? ' visisome' : ' dispsome';
	}
}

// pinta 'linha sim, linha não' de uma lista
function linhas(tab,ini) {
	tab = obj(tab);
	if (tab.rows.length > ini+1) {
		for (var i=ini; i<tab.rows.length; i++) {
			var cor = ((i % 2) == 0) ? '' : '#E8E8E8';
			tab.rows[i].style.backgroundColor = cor;
		}
	}
}

// navega entre os meses nas páginas que contém gráfico pelo tempo (utiliza a função filtra da página)
function mudames(dif) {
	ini += dif;
	filtra();
}

// OLD - função de troca do select pelo input text (Ex: novo local..., nova cidade...)
function mudasel(sel) {
	if (sel.value == 'nova') {
		sel.style.display = 'none';
		sel.nextSibling.style.display = '';
		if (sel.name == 'cid') {
			var est = sel.nextSibling.childNodes[1];
			for (var i=0; i<est.options.length; i++) {
				if (est.options[i].value == sel.est) { est.options[i].selected = true; break; }
			}
		}
		sel.nextSibling.childNodes[0].focus();
	}
}

// OLD - função que volta do input para o select
function voltasel(sel) {
	sel = sel.parentNode;
	sel.childNodes[0].value = '';
	sel.style.display = 'none';
	sel = sel.previousSibling;
	sel.style.display = '';
	sel.options[0].selected = true;
	for (var i=0; i<sel.options.length; i++)
		if (sel.options[i].value == sel.old) sel.options[i].selected = true;
}
	
// função de troca do select pelo input text (Ex: novo local..., nova cidade...)
function novaOption(elem, txtvolta) {
	if (elem.value.substring(0,4) == 'outr' || elem.value.substring(0,3) == 'nov') {
		var inp = document.createElement('INPUT');
		inp.style.width = elem.clientWidth + 10;
		inp.name = elem.name;
		var img = document.createElement('IMG');
		img.src = 'img/ico_sobe1.gif'; img.className = 'sobe';
		img.alt = txtvolta; img.onclick = voltaOption;
		elem.className += ' dispsome'; elem.disabled = true;
		var pai = elem.parentNode;
		if (elem.nextSibling) pai.insertBefore(img,elem.nextSibling);
		else pai.appendChild(img);
		pai.insertBefore(inp,img);
		inp.focus();
	}
}

// função que volta do input para o select
function voltaOption() {
	var elem = this.previousSibling.previousSibling;
	if (elem.old) elem.value = elem.old;
		else elem.options[0].selected = true;
	elem.disabled = false;
	elem.className = elem.className.replace(/\bdispsome\b/g,'');
	var pai = elem.parentNode;
	pai.removeChild(elem.nextSibling);
	pai.removeChild(elem.nextSibling);
}

// Verifica a validade de uma data string.
// se o parametro for string vazio retorna string vazio;
// se for uma data válida retorna array com dia, mês e ano; senão retorna -1.
function valida_data(dt) {
	var dias = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if (dt.length == 0) return '';

	dt = dt.replace(/\./g,'/').replace(/\\/g,'/').replace(/\-/g,'/');
	if (isNaN(parseInt(dt.replace(/\//g, '')))) return -1;
	
	dt = dt.split('/');
	if (dt.length < 2) return -1;
	
	var datavalida = 1;
	if (dt.length == 2 || dt[2].length == 0) {
		var dtano = new Date();
		dt[2] = dtano.getYear();
	}
	
	if (dt.length != 3) return -1;
	
	dt[0] = Number(dt[0]); dt[1] = Number(dt[1]); dt[2] = Number(dt[2]);
	if (dt[2] < 0 || dt[2] > 3000 || isNaN(dt[2])) return -1;
	
	if (dt[1] < 1 || dt[1] > 12 || isNaN(dt[1])) return -1;
	
	if (dt[1] == 2 && (dt[2]%400 == 0 || (dt[2]%4 == 0 && dt[2]%100 != 0))) dias[1] = 29;
	if (dt[0] < 1 || dt[0] > dias[dt[1]-1] || isNaN(dt[0])) return -1;
	
	if (dt[2] < 40) {
		dt[2] += 2000;
	} else if (dt[2] < 100) {
		dt[2] += 1900;
	}
	return dt
}

// calcula o valor da data para comparações 
// se o parametro "dia" for > 0:        12*31*ano + 31*mes + dia
// se não tiver o parâmetro "dia":    12*ano + mes
// se não passar o valida_data, retorna vazio
function dataCalc(dt, dia) {
	if (dt.indexOf(' ') > 0) dt = dt.substring(0,dt.indexOf(' '));
	validada = valida_data(dt);
	if (validada.length == 0 || validada == -1) return '';
	var calc = (dia) ? 12 * 31 * validada[2] + 31 * validada[1] + validada[0]
				   :  12 * validada[2] + validada[1];
	return calc;
}

//Formata a data para dd/mm/aa. ou dd/mm/aa " " + 2° parametro + " " + HH:MM
//Parametros do tipo dd/mm/aaaa e dd/mm/aaaa hh:mm:ss e String
function formataData(data, conector) {
	var dia, mes, ano, horario;
	var re = /^(\d+)\/(\d+)\/(\d+)(\s\d+\:\d+:\d+)?$/g;
	
	dia = data.replace(re,'00$1');
	mes = data.replace(re,'00$2');
	ano = data.replace(re,'00$3');
	horario = data.replace(re,'$4');
	
	data = dia.substring(dia.length-2) + '/' + mes.substring(mes.length-2) + '/' + ano.substring(ano.length-2);
	if(data.length < 4) data='';
	try{horario = horario.substring(0,6)}catch(e){} //tirando segundos
	if(horario.length > 0 && conector) data += " " + conector + horario;
	return data;
}

// ********** converte data do formato SQL em dd/mm/yyyy hh:mm:ss (se não tiver hora, só retorna a data)
function dmah(dtSQL) {
	var dt = dtSQL.split(' ');
	var data = dt[0].split('-');
	var dataCompleta = data[2] + '/' + data[1] + '/' + data[0];
	if (dt[1]) dataCompleta += ' ' + dt[1];
	return dataCompleta;
}

// ********** converte data do formato dd/mm/yyyy hh:mm:ss em formato SQL (yyyy-mm-dd hh:mm:ss) (se não for passada a hora, retorna com 00:00:00)
function dtSQL(dmah) {
	var dt = dmah.split(' ');
	var data = dt[0].split('/');
	if (data[2].length == 2) data[2] = '20' + data[2];
	var dataCompleta = data[2] + '-' + data[1] + '-' + data[0];
	dataCompleta += ' ' + ((dt[1]) ? dt[1] : '00:00:00');
	return dataCompleta;
}

// ********** converte data do formato Date em dd/mm/yyyy (se for true o parametro hora também retorna hh:mm:ss)
function dt_dma(dt, hora, anoDoisDigitos) {
	var ehData = new Date(dt);
	if (ehData.toString() == "NaN" || ehData.toString() == "Invalid Date") return;
	var dia = dt.getDate().toString();
	var mes = (dt.getMonth() + 1).toString();
	var ano = dt.getFullYear().toString();
	var data = digitos(dia, 2) + '/' + digitos(mes, 2) + '/' + digitos(ano, (anoDoisDigitos) ? anoDoisDigitos : 4);
	if (hora) {
		hora = dt.getHours().toString();
		var minuto = dt.getMinutes().toString();
		var segundo = dt.getSeconds().toString();
		data += ' ' + digitos(hora, 2) + ':' + digitos(minuto, 2) + ':' + digitos(segundo, 2);
	}
	return data;
}

// ********** dataConverte_sql_dt
// ********** converte uma data de SQL para objeto Date (só data, sem horas)
function dataConverte_sql_dt(sql) {
	if (!sql || sql.length == 0) return '';
	var anomesdia = sql.split(' ')[0].split('-');
	return new Date(anomesdia[0], anomesdia[1]-1, anomesdia[2]);
}

// ********** dateDiff
// ********** calcula a diferença entre duas datas (datafim - dataini) (objetos Date)
// ********** aproximada (não é exata - mes = 30 dias, ...)
// ********** periodo = 'd': dias
// **********		 'm': meses
// **********		 'a': anos
// **********		 'h': horas
// **********		 'mm': minutos
// **********		 's': segundos
function dateDiff(datafim, dataini, periodo) {
	var fim = datafim.getTime();
	var ini = dataini.getTime();
	var dif = fim - ini;
	var periodoEmMilisegundos;
	switch (periodo) {
		case 's': periodoEmMilisegundos = 1000; break;
		case 'mm': periodoEmMilisegundos = 1000*60; break;
		case 'h': periodoEmMilisegundos = 1000*60*60; break;
		case 'd': periodoEmMilisegundos = 1000*60*60*24; break;
		case 'm': periodoEmMilisegundos = 1000*60*60*24*30; break;
		case 'a': periodoEmMilisegundos = 1000*60*60*24*365; break;

	}
	return Math.round(dif / periodoEmMilisegundos);
}

/***************************************
 *		Função. Passou de func.js para funcoes.js
			Função para comparar datas;
 *		Parâmetros.
			d1: (String) dd/mm/aaaa
			d2: (String) dd/mm/aaaa
 *		Retorno.
			(undefined) Caso algumas das datas estejem mal formatadas.
			(int)	se d1 < d2 = n° positivo
					se d1 == d2 = 0
					se d1 > d2 = n° negativo
 *		Comentários.
****************************************/
function comparaData(d1,d2){
	d1 = valida_data(d1);
	d2 = valida_data(d2);
	if(d1 == -1 || d2 == -1)return undefined;
	if(d2[2]-d1[2]!=0)return d2[2]-d1[2];
	else if(d2[1]-d1[1]!=0)return d2[1]-d1[1];
	else return d2[0]-d1[0];
}

// Verifica a validade de um cpf.
// se o parametro for string vazio retorna string vazio;
// se for um cpf válido retorna o cpf só números; senão retorna -1.
function valida_cpf(num) {
	num = num.replace(/\./g,'').replace(/\,/g,'').replace(/\-/g,'').replace(/\ /g,'');
	if (num.length > 0) {
		if ((isNaN(num)) || (num.length > 11)) { return -1 } else {
			var cpfvalido = 1;
			num = '00000000000' + num.toString();
			num = num.substring(num.length-11, num.length);
				//não permite numeros iguais como cpf.
				//333.333.333-33, etc...
				var regExpNumIguais = /^(\d)\1{10}$/;
				if(regExpNumIguais.test(num))return -1;
			var digito = new Array(10); for (i=0; i<=8; i++) { digito[i] = num.substr(i,1) }
			// 1º dígito verificador
			var mult = 10; var tot = 0;
			for (var i=0; i<=8; i++) { tot = tot + (digito[i]*mult); mult -= 1; }
			digito[9] = 11 - (tot % 11); if (digito[9] > 9)	{ digito[9] = 0 }
			// 2º dígito verificador
			mult = 11; tot = 0;
			for (i=0; i<=9; i++) { tot = tot + (digito[i]*mult); mult -= 1; }
			digito[10] = 11 - (tot % 11); if (digito[10] > 9)	{ digito[10] = 0 }
			// compara com o informado
			if (num.substr(9,2) != (digito[9]*10+digito[10]))	{ return -1 } else {
				while (num.substring(0,1) == '0') { num = num.substring(1,num.length) }
				return num
			}
		}
	} else { return '' }
}

// ********** converte um numero em string com N dígitos (completando com zeros à esquerda)
function digitos(num, N) {
	var zeros = '';
	for (var i=0; i<N; i++) zeros += '0';
	num = zeros + num.toString();
	return num.substring(num.length - N, num.length);
}

// Verifica a validade de um cep.
// se o parametro for string vazio retorna string vazio;
// se for um cep válido retorna o cep só números; senão retorna -1.
function valida_cep(num) {
	num = num.replace(/\./g,'').replace(/\,/g,'').replace(/\-/g,'').replace(/\ /g,'').replace(/\//g,'');
	if (num.length > 0) {
		if ((isNaN(num)) || (num.length > 8)) { return -1 } else {
			num = '00000000' + num.toString();
			num = num.substring(num.length-8, num.length);
			return num
		}
	} else { return '' }
}

// Só deixa digitar valor numérico: 0-9, ',' ou '.'.
// se não for numérico retorna false.
function numero(){
	var k = event.keyCode;
	if ((k < 45 || k > 57) && (k < 96 || k > 105) && (k < 37 || k > 40) && (k < 8 || k > 13)
			&& (k != 190) && (k != 194) && (k != 188) && (k != 110)) return false;
	return true;
}

// Só deixa digitar valor numérico 0-9.
// se não for numérico retorna false.
function sonum(ev) {
	if (!ev) var ev = event;
	var k = ev.keyCode;
	if ((k < 45 || k > 57) && (k < 96 || k > 105) && (k < 37 || k > 40) && (k < 8 || k > 13)) return false;
	return true;
}

// exportar planilha Excel
function exp() {
	var act = obj('ft').action;
	var targ = obj('ft').target;
	var url = window.location.href;
	var pos = url.indexOf('.asp');
	var pos1 = url.substring(0,pos).lastIndexOf('/') + 1;
	var orig = url.substring(pos1,pos);
	var querystring = url.substring(pos+4,url.length);
	var sel = 1;
	var txt = '';
	switch (orig) {
	//	case 'prof': sel = obj('ft').pr.value; txt = ' professor'; break;
	//	case 'alun': sel = obj('ft').al.value; txt = ' aluno'; break;
		case 'curs': sel = obj('ft').ce.value; txt = ' curso/estágio'; break;
	//	case 'emp': sel = obj('ft').em.value; txt = 'a empresa'; break;
		case 'lic': querystring += '&mes=' + arguments[0] + '&tema=' + arguments[1]; break;
		case 'pag': querystring += '&lingueta=' + lingueta + '&periodo=' + obj('ft').periodo.value; break;
	}
	txt = 'Selecione um'  + txt + ' para exportar sua planilha de aulas.';
	if ((sel == 0) && (obj('ft').submenu.value == 1)) { alert(txt) } else {
		var ativTesta = orig.split('_');
		if(ativTesta[0] == 'ativ')
		{
			var path = 'ativ_plan.asp' + querystring;
		}
		else
		{
			var path = orig + '_plan.asp' + querystring;
		}
		
		var param = 'location=no,resizable=yes,scrollbars=yes,width=700,height=320,top=10,left=10';
		obj('ft').action = path;
		obj('ft').target = 'planilha';
		var janela = window.open('','planilha',param);
		obj('ft').submit();
		janela.focus();
		obj('ft').action = act;
		obj('ft').target = targ;
	}
}

// abrir janela com formato adaptado para impressão
/*
function imp() {
	act = obj('ft').action;
	url = window.location.href;
	pos = url.indexOf('.asp');
	orig = url.substring(pos-4,pos);
	querystring = url.substring(pos+4,url.length);
	if (orig == 'prof') { sel = obj('ft').pr.value; txt = 'professor' } else {
		if (orig == 'alun') { sel = obj('ft').al.value; txt = 'aluno' } else {
			if (orig == 'curs') { sel = obj('ft').ce.value; txt = 'curso/estágio' } else { sel = 0 } } }
	txt = 'Selecione um ' + txt + ' para imprimir sua planilha de aulas.';
	if ((obj('ft').submenu.value == 1) && (sel == 0)) { alert(txt) } else {
		path = orig + '_imp.asp' + querystring;
		param = 'location=no,resizable=yes,scrollbars=yes,width=700,height=320,top=10,left=10';
		obj('ft').action = path;
		obj('ft').target = 'apoio';
		janela = window.open('','apoio',param);
		janela.focus();
		obj('ft').submit();
		obj('ft').action = act;
		obj('ft').target = '';
	}
}
*/


// tamanho de um campo textarea
// informa o tamanho e limita a 500 caracteres
// obj. pode ser obj ou evento.
function tam(obj){
	if (obj == undefined) obj = window.event.srcElement;
	else if(obj.tagName == undefined) obj = obj.target; //caso obj for um evento! firefox.
	var max = (obj.getAttribute('max')) ? parseInt(obj.getAttribute('max')) : 500;
	var qtde = obj.value.length;
	if (qtde > max) obj.value = obj.value.substring(0,max);
	var td = sobeDOM(obj, 'TD');
	td = td.parentNode.previousSibling.cells[td.cellIndex+1];
	var txt = td.innerHTML;
	txt = txt.substring(txt.indexOf(' '),txt.length);
	td.innerHTML = obj.value.length + txt;
}

// arredonda um número deixando-o com "X" casas decimais
function arredonda(numero,X) {
	return Math.round(Math.pow(10,X) * numero) / Math.pow(10,X);
}

// formata um número transformando-o em texto com "X" casas decimais
function formataNumero(numero, X, separador) {
    if (!X) X = 2;
	numero = parseFloat(numero.toString().replace(/\,/g,'.'));
    if(isNaN(numero))return ''; //<------------------------------------------------
	numero = arredonda(numero,X).toString().replace(/\./,',');
	if (numero.indexOf(',') < 0) numero += ',';
	for (contformat = 0; contformat < X; contformat++) numero += '0';
	numero = numero.substring(0,numero.indexOf(',')+X+1);
	if (separador) { // coloca separador de milhar (.)
		X += 4;
		len = numero.replace(/|-/g,'').length;
		while (numero.replace(/|-/g,'').length > X) {
			numero = numero.substring(0,len-X) + separador + numero.substring(len-X,len);
			X += 4;
			len = numero.replace(/|-/g,'').length;
		}
	}
	return numero;
}

// formata um campo de valor monetário utilizando a função formataNumero. Geralmente no evento "onblur" do campo.	
function formata() {
	var inp = window.event.srcElement;
	if (inp.value.length > 0) inp.value = formataNumero(parseFloat(inp.value.replace(/,/g,'.')),2);
}
	
// descobre a posição do elemento (retorna .left e .top)
function getElementPosition(elem) {
	var offsetTrail = elem;
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && 
		typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft, top:offsetTop};
}

var imgs = new Array();
function imagensFalhas() {
	var img = document.images;
	for (var i=0; i<img.length; i++)
		if (img[i].src.indexOf('/fotos/') > 0) imgs.push(img[i]);//img[i].onerror = trocaImagemFalha;
	setTimeout("trocaImagemFalha()",1000);
}

function trocaImagemFalha(ele) {
	if (ele) {
		var span = document.createElement('SPAN');
		span.id = 'foto';
		span.className = 'foto';
		span.innerHTML = '<p>imagem não disponível</p>';
		var pai = ele.parentNode;
		pai.replaceChild(span, ele);
		return ;
	}
    
	while (imgs.length) {
		ele = imgs.pop();
		var te = (ele.fileSize) ? (ele.fileSize == -1) : (ele.naturalHeight == 0);
		if (te) {
			var div = document.createElement('DIV');
			div.className = 'foto';
			div.innerHTML = '<p>imagem não disponível</p>';
			var pai = ele.parentNode;
			pai.replaceChild(div,ele)
		}
	}
}

// funçôes que escondem e mostram qualquer elemento DOM (escolher se utiliza visibility ou display)
function dispsome(elem) { elem.className += ' dispsome' }
function visisome(elem) { elem.className += ' visisome' }
function mostra(elem) {
	elem.className = elem.className.replace(/\bdispsome\b/g,'').replace(/\bvisisome\b/g,'')
}

// função que codifica as aspas para transmitir via HTTP
function trocaspas(txt) {
	txt = txt.replace(/\'/g,'|aspaunica|').replace(/\"/g,'|aspadupla|');
	//txt = txt.replace(/\n/g,'<br>');
	return escape(txt);
}

// cria uma caixa com "carregando informações" e com gif animado
function mostraCarregando(aparece, onde) {
	if (!onde) onde = obj('areainfo');
	if (aparece) {
		if (!obj('carregando')) {
			var span = cria('span', { id: 'carregando' });
			span.appendChild(cria('txt', 'carregando informações,'));
			span.appendChild(cria('br'));
			span.appendChild(cria('txt', 'por favor aguarde...'));
			if (onde.childNodes.length > 0) onde.insertBefore(span, onde.firstChild);
			else onde.appendChild(span);
		}
	} else {
		span = obj('carregando');
		if (span) span.parentNode.removeChild(span);
	}
}



// =======================================================================================
// funções para habiltar e desabilitar um ícone, deixando ele meio transparente
// =======================================================================================
function desabilitaBot(botao) {
	if (botao.onclick) botao.old_onclick = botao.onclick;
	botao.onclick = null;
	//if (botao.alt.indexOf('(desabilitado)') != 0) botao.alt = '(desabilitado)\n' + botao.alt;
	if (botao.alt) {
		botao.old_alt = botao.alt;
		botao.alt = '';
	}
	if (botao.title) {
		botao.old_title = botao.title;
		botao.title = '';
	}
	botao.className += ' disabled';
	botao.style.cursor = 'default';
}

function habilitaBot(botao) {
	botao.className = botao.className.replace(/ disabled/gi,'');
	if (botao.old_onclick) botao.onclick = eval(botao.old_onclick);
	//if (botao.alt.indexOf('(desabilitado)') == 0) botao.alt = botao.alt.substring(15,botao.alt.length);
	if (botao.old_alt) botao.alt = botao.old_alt;
	if (botao.old_title) botao.title = botao.old_title;
	botao.style.cursor = 'pointer';
}
// =======================================================================================


// =======================================================================================
// funções para colocar e tirar eventos de um objeto
// criado por John Resig (http://ejohn.org/projects/flexible-javascript-events/)
// e melhorada em http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
// PROBLEMA COM MOOTOOLS. Funções com mesmo nome. addEvent e removeEvent (alterado o nome das funções)
// 
// realizadas alterações para incluir mouseenter e mouseleave cross-browser
// ** baseado em http://blog.stchur.com/2007/03/15/mouseenter-and-mouseleave-events-for-firefox-and-other-non-ie-browsers/
// ** modificado por KAITS em janeiro/2010
// =======================================================================================

function adicionaEvento( obj, type, fn ) {
	if (obj.addEventListener) {
		if (type === 'mouseenter') obj.addEventListener( 'mouseover', evento_fazFuncao(fn), false );
		else if (type === 'mouseleave') obj.addEventListener( 'mouseout', evento_fazFuncao(fn), false );
		else obj.addEventListener( type, fn, false );
	} else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvento( obj, type, fn ) {
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent) {
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

function evento_fazFuncao(fn) {
	return function(evt) {
		var relTarget = evt.relatedTarget;
		if (this === relTarget || evento_ehFilhoDe(this, relTarget)) return;
		fn.call(this, evt);
	}
}

function evento_ehFilhoDe(pai, filho) {
   if (pai === filho) return false;
   while (filho && filho !== pai) try { filho = filho.parentNode; } catch(e) { break; }
   return filho === pai;
}
// =======================================================================================

// ********************************************************************************************************************************************* //
// ********************************************************************************************************************************************* //
//** 
/*
function eventoMouse(_elem, _evtName, _fn) {
	if (typeof _elem.addEventListener != 'undefined') {
		if (_evtName === 'mouseenter') adicionaEvento(_elem,'mouseover', eventoMouse_fazFuncao(_fn));
		else if (_evtName === 'mouseleave') adicionaEvento(_elem,'mouseout', eventoMouse_fazFuncao(_fn));
		else adicionaEvento(_elem,_evtName, _fn);
	} else if (typeof _elem.attachEvent != 'undefined') {
		adicionaEvento(_elem,_evtName, _fn);
	} else {
		_elem['on' + _evtName] = _fn;
	}
}

function eventoMouse_fazFuncao(_fn) {
	return function(_evt) {
		var relTarget = _evt.relatedTarget;
		if (this === relTarget || eventoMouse_ehFilhoDe(this, relTarget)) return;
		//alert('chama a função');
		_fn.call(this, _evt);
	}
}

function eventoMouse_ehFilhoDe(_pai, _filho) {
   if (_pai === _filho) return false;
   while (_filho && _filho !== _pai) _filho = _filho.parentNode;
   return _filho === _pai;
}
*/
// ********************************************************************************************************************************************* //
// ********************************************************************************************************************************************* //
// ********************************************************************************************************************************************* //
// ********************************************************************************************************************************************* //



/*Variáveis globais do calendário*/
var escondesel;
var dd,mm,yy;
var qual;
var divcal = document.createElement("DIV");
	divcal.id = 'calendario';
	adicionaEvento(divcal,'click',paraPropag);

var _inputcal;
// funções do calendário para preencher a data ********************************************************
	function calendario() {
		qual = (window.event) ? window.event.srcElement : this;
		//for (var i=0; i<arguments.length; i++) alert(i + ': ' + arguments[i] + ' : ' + (arguments[i] == '[object MouseEvent]'));
		paraPropag(arguments[0]);
		fechacal();
		escondesel = new Array();
		_inputcal = qual.previousSibling;
		divcal.innerHTML = '';		
		// ********************************************************************************** //
		// ********** acerta a posição do calendário *************************************** //
		// ********************************************************************************** //
				var y = 0;
				var x = 0;
				var elem = qual;
				while (elem.tagName != "BODY") {
					if (elem.tagName == "IMG" || elem.tagName == "TD" || elem.tagName == "TABLE" ) {
						y += elem.offsetTop;
						x += elem.offsetLeft;
					}
					if (elem.tagName == "DIV") {break}
					elem = elem.parentNode;
				}
				if (arguments.length > 1 && arguments[1] != 0) x += arguments[1];
				if (arguments.length > 2 && arguments[2] != 0) y += arguments[2];
				divcal.style.top = y + 10;
				divcal.style.left = x - 100;
				//divcal.style.top = getElementPosition(qual).top + 9;
				//divcal.style.left = getElementPosition(qual).left - 80; //  - divcal.offsetWidth
				
				if (arguments.length > 3 && arguments[3].length > 0) {
					if (arguments[3].indexOf('|id|') >= 0) {
						form = sobeDOM(qual, 'FORM');
						id = inputcal.name; id = id.substring(id.indexOf('_'),id.length);
						arguments[3] = arguments[3].replace(/\|id\|/g,id);
					}
					escondesel = arguments[3].split(';');
				}
		// ********************************************************************************** //
		// ********************************************************************************** //
		
		var txt = qual.previousSibling.value.split('/');
		var datavalida = 1;
		if (txt.length != 3) { datavalida = 0 } else {
			if (txt[2] < 0 || txt[2] > 3000 || isNaN(parseInt(txt[2]))) { datavalida = 0 } else {
				if (txt[1] < 1 || txt[1] > 12 || isNaN(parseInt(txt[1]))) { datavalida = 0 } else {
					if (txt[1] == 2 && (txt[2]%400 == 0 || (txt[2]%4 == 0 && txt[2]%100 != 0))) {	dias[1] = 29 }
					if (txt[0] < 1 || txt[0] > dias[txt[1]-1] || isNaN(parseInt(txt[0]))) { datavalida = 0 }
				}
			}
		}
		if (datavalida == 0) { 
			var valor = new Date();
		} else {
			var valor = new Date(txt[2], txt[1]-1, txt[0]);
		}
		dd = valor.getDate();
		mm = valor.getMonth();
		yy = valor.getYear();
		if (yy.toString().length < 4) yy = (yy < 20) ? 2000+yy : 1900+yy;
		montaDatas(valor);
	}
	
	function montaDatas(valor) {
		var mes = valor.getMonth();
		var ano = valor.getYear();
		if (ano.toString().length < 4) { ano = (ano < 20) ? 2000+ano : 1900+ano }
		var tabela = colocaElemento(divcal,'table');
		tabela.cellPadding = 0;
		tabela.cellSpacing = 2;
		var tbody = colocaElemento(tabela,'tbody');
		
		// linha do mês/ano
		var tr = colocaElemento(tbody,'tr','linhames');
		tr.valor = valor;
		var td = colocaElemento(tr,'td');
		td.colSpan = 2;
		td.appendChild(criaLinkMes(valor,-1,'mês anterior','<'));
		td.appendChild(criaLinkMes(valor,-12,'ano anterior','<<'));
		
		td = colocaElemento(tr,'td','celulames');
		td.colSpan = 5;
		td.appendChild(document.createTextNode(meses[mes]));
		colocaElemento(td,'br');
		td.appendChild(document.createTextNode(ano));
		
		td = colocaElemento(tr,'td','direita');
		td.colSpan = 2;
		td.appendChild(criaLinkMes(valor,1,'próximo mês','>'));
		td.appendChild(criaLinkMes(valor,12,'próximo ano','>>'));
		
		// linha com os dias da semana
		tr = colocaElemento(tbody,'tr','linhasemana');
		for(var i=0; i<9; i++) {
			td = colocaElemento(tr,'td');
			if(i>=1 && i<=7) {
				td.className = 'dia';
				td.appendChild(document.createTextNode(semana[i-1].substring(0,1)));
			}
		}
		
		// dias do mês
		var dia = 0;
		var prim = new Date(ano,mes,1);
		var tot = dias[mes];
		// se for fevereiro e o ano for bissexto, passa o total de dias para 29
		if(mes == 1 && (ano % 400 == 0 || (ano % 4 == 0 && ano % 100 != 0))) tot = 29;
		
		while (dia <= tot) {
			tr = colocaElemento(tbody,'tr');
			td = colocaElemento(tr,'td');
			for (var j=0; j<7; j++) {
				td = colocaElemento(tr,'td');
				// avança sem colocar os dias até chegar no dia da semana do primeiro dia do mês
				if(dia==0 && j==prim.getDay()) dia ++;
				
				if(dia>0 && dia<=tot) {
					if(dd == dia && mm == mes && yy == ano) td.className = 'selec';
					a = colocaElemento(td,'a');
					a.href = "javascript:void(0)";
					a.dia = dia; a.mes = mes; a.ano = ano;
					a.title = semana[j] + ", " + dia + " de " + meses[mes] + " de " + ano;
					adicionaEvento(a,'click',clicacal);
					a.appendChild(document.createTextNode(dia));
					dia++;
				}
			}
		}
		
		//qual.parentNode.appendChild(divcal);
		document.body.appendChild(divcal);
		
		
		//fix do calendario para internet explorer. 20/07/09
		if(document.body.attachEvent && document.body['click'+fechacal] == undefined)
			adicionaEvento(document.body,'click',fechacal);
		
		if (escondesel && escondesel.length && escondesel.length >= 0)
			for (var i=0; i<escondesel.length; i++) {
				//if(obj(escondesel[i])) obj(escondesel[i]).style.visibility = 'hidden';
				//if(eval(escondesel[i])) eval(escondesel[i]).style.visibility = 'hidden';
				try{ obj(escondesel[i]).style.visibility = 'hidden'; } catch(e) {
					try{ eval(escondesel[i]).style.visibility = 'hidden'; } catch(e) {
					}
				}
			}
	}
	
	function mescal() {
		var tr = sobeDOM(this,'tr');
		var valor = tr.valor;
		var quant = this.dif;
		if (typeof(valor) != 'object') valor = new Date(valor);
		var mes = valor.getMonth();
		var ano = valor.getFullYear();
		mes += quant;
		if (mes < 0) { mes += 12; ano--; }
		else if (mes > 11) { mes -= 12; ano++; }
		valor.setMonth(mes);
		valor.setYear(ano);
		divcal.removeChild(divcal.childNodes[0]);
		montaDatas(valor);
	}
	
	function clicacal() {
		var dia = this.dia;
		dia = (dia.toString().length == 1) ? '0'+dia : dia;
		var mes = this.mes + 1;
		mes = (mes.toString().length == 1) ? '0'+mes : mes;
		var ano = this.ano.toString().substring(2,4);
		fechacal();
		_inputcal.value = dia + '/' + mes + '/' + ano;
		_inputcal.focus();
		//_inputcal.blur();
		//_inputcal.change();
		
		if (!temClasse(_inputcal, 'naoGrava')) {
			if (obj('botoes') && obj('botoes').firstChild) habilitaBot(obj('botoes').firstChild);
			//Para página de alun/prof/emp
			try { habilitaGravar(); } catch(e) {}
		}
		// para a página de comunicações, nos campos de data do filtro de e-mails
		try { emailEnv.filtra(); } catch(e) {}
		// para a página de setup, nos campos de data do filtro de alunos excluídos
		try { filtroAlunoExcluido(); } catch(e) {}		
	}
	
	function fechacal() {
		try{ removeEvento(document.body,'click',fechacal); } catch(e) {}
		var div = obj('calendario');
		if (div) div.parentNode.removeChild(div);
		if (escondesel && escondesel.length && escondesel.length >= 0)
			for (var i=0; i<escondesel.length; i++){
				if (obj(escondesel[i])) obj(escondesel[i]).style.visibility = 'visible';
				try{ eval(escondesel[i]).style.visibility = 'visible' } catch(e) { }
				//else if (typeof(escondesel[i]) != string) eval(escondesel[i]).style.visibility = 'visible';
			}
	}
	
	function criaLinkMes(valor, dif, tit, txt) {
		var a = document.createElement('a');
		a.href = "javascript:void(0)";
		a.dif = dif;
		a.title = tit;
		adicionaEvento(a,'click',mescal);
		a.appendChild(document.createTextNode(txt));
		return a;
	}
//****************************************************************************************************


// aplica a função cancelBubble (para de propagar pelos elementos DOM acima) para todos browsers
function paraPropag(ev) {
	if (window.event) window.event.cancelBubble = true;
	else if (ev && ev == '[object MouseEvent]') ev.stopPropagation();
}

// ******************************************************************************************************
// cria um elemento com texto puro dentro e coloca dentro de um pai
//
// obs: quando é um elemento 'input' não dá para mudar o type depois de feito o append,
//      então usa-se esta função sem o pai (pai = null) e depois de setar o type faz o appendChild.
// ******************************************************************************************************
function colocaElemento(pai, tag, classe, txt) {
	var elem = document.createElement(tag);
	if (classe) elem.className = classe;
	if (txt) elem.appendChild(document.createTextNode(txt));
	if (pai) pai.appendChild(elem);
	return elem;
}
// ******************************************************************************************************




// ******************************************************************************************************
// cria um novo elemento com propriedades e estilos parametrizáveis
// tag: a tag do elemento em syring (se for 'txt' vai criar um textNode com o texto do segundo argumento)
// prop: lista de propriedades em um array associativo (Exemplo {id:'xxx',className:'xxx',type:'xxxx'})
// estilo: lista de estilos em um array associativo (Exemplo {width:'xxx',display:'xxx',backgroundColor:'xxxx'})
// ******************************************************************************************************
function cria(tag, prop, estilo, txt) {
	if (tag == 'txt') return document.createTextNode(prop);
	var elem = document.createElement(tag);
	// atributos que podem ser incluídos direto como em HTML (elemento[nomeAtributo] = valorAtributo) ou tratadores de evento
	var atributosHTML = '| className | colSpan | rowSpan | border | innerHTML | text | htmlFor |' +
										'| onchange | onclick | onmouseover | onmouseout | onmouseenter | onmouseleave | onkeyup | onkeydown |';
	// outros atributos são incluídos pelo método "setAttribute"
	if (prop) for (var i in prop) {
		if (atributosHTML.indexOf(i) > 0) elem[i] = prop[i];
		else elem.setAttribute(i, prop[i]);
	}
	if (estilo) for (var i in estilo) elem.style[i] = estilo[i];
	//if (txt) elem.appendChild(document.createTextNode(txt));
	if (txt != undefined && txt != null && txt != false) elem.appendChild(document.createTextNode(txt));
	return elem;
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** Utilizado para criar concatenação de strings **********************************************
// http://www.softwaresecretweapons.com/jspwiki/javascriptstringconcatenation
// 
// Exemplo de utilização:
// 
// var buf = new StringBuffer();
// buf.append("hello");
// buf.append("world");
// alert(buf.toString());
// ******************************************************************************************************
function StringBuffer() { 
	this.buffer = []; 
}

StringBuffer.prototype.append = function append(string) { 
	this.buffer.push(string); 
	return this; 
};

StringBuffer.prototype.antes = function antes(string) { 
	this.buffer.unshift(string); 
	return this; 
};

StringBuffer.prototype.toString = function toString() { 
	return this.buffer.join(""); 
};
// ******************************************************************************************************


// ******************************************************************************************************
// ********** cria um nome diferente a cada segundo para a janela de exportação *************************
// ******************************************************************************************************

function nomeJanela() {
	var agora = new Date();
	var nome = 'exporta_Kaits_' + agora.getTime().toString();
	return nome;
}

// ******************************************************************************************************

// ******************************************************************************************************
// ********** cria o método trim para strings ***********************************************************
// ******************************************************************************************************
String.prototype.trim = function() {   
    return this.replace( /^\s+|\s+$/g, "");
}
// ******************************************************************************************************



// ******************************************************************************************************
// ********** impedimentos e avisos sobre a gravação da aula ********************************************
// ******************************************************************************************************
function testa_grava_aula(tipo,retorno) {
	//	mensagens:	1.sala ocupada (na primeira semana deixa gravar, depois não deixa mais - 29/11/2008)(extendido jun/09)
	//				2.professor alocado
	//				3.aluno com aula
	//				4.turma com aula
	//				5.próximo de aula externa (< 1 hora)
	//				6.esta aula é externa e tem outra aula próxima (< 1 hora) 
	//				7.o professor não está habilitado a lecionar neste curso e estágio
	var msggrava = new Array('A aula não pode ser gravada pois:', 'Atenção:', 'Deseja gravar esta aula?');
	var mensagens = new Array('',
		'esta sala já está ocupada neste horário.',
		'este professor já está alocado neste horário.',
		'este aluno tem outra aula neste horário.',
		'esta turma tem outra aula neste horário.',
		'o mesmo professor tem uma aula externa a menos de uma hora desta\n' +
			'   (verifique se o horário é suficiente para o deslocamento).',
		'essa aula é externa e o mesmo professor tem outra aula a menos de uma hora desta\n' +
			'   (verifique se o horário é suficiente para o deslocamento).',
		'este professor não está habilitado a lecionar neste curso e estágio\n' +
			'   (use a ferramenta de professores para alterar esta configuração).');
	
	if (!retorno) retorno = this;
	var resp = unescape(retorno.req.responseText.replace(/\+/g,' '));
	//alert(resp);
	
	var pos = resp.indexOf('|grava|');
	if (pos < 1) { alert(resp); return; }

	// grava = 0 >> avisa e nao grava
	// grava = 1 >> avisa e pede confirmacao se quer gravar
	// grava = 2 >> nao avisa e grava
	var grava = parseInt(resp.split('|grava|')[0]);
	resp = resp.split('|grava|')[1];
	
	if (resp.indexOf('|idaula|') > 0) {
		var idaula = resp.split('|idaula|')[0];
		resp = resp.split('|idaula|')[1];
	}
	
	if (resp.indexOf('|data|') > 0) {
		var data = resp.split('|data|')[0];
		resp = resp.split('|data|')[1];
	}
	
	var msg = resp.split('|msg|');
	var listamsg = (grava == 0) ? msg[1] : ((grava == 1) ? msg[0] : '');
	msg = (listamsg.length > 0) ? listamsg.split(',') : new Array();
	
	var txtMsg = '';
	for (var i=0; i<msg.length; i++) txtMsg += '- ' + mensagens[msg[i]] + '\n\n';
	var txt = msggrava[grava] + '\n\n' + txtMsg;
	if (grava == 1) txt += msggrava[2];
	
	
	tipo = parseInt(tipo,10);
	if (tipo == 1) {//Multiplas
		montaRespostaTeste(grava,txtMsg,idaula,data);
	} else if(tipo == 2){
		montaRespostaTestePeriodico(grava,txtMsg,data);
	} else {
		if (grava == 0) alert(txt); // se não puder gravar avisa o motivo
		if (grava == 1) if (confirm(txt)) grava = 2; // pergunta se quer que grave
			
		realiza_grava((grava == 2)); // se grava = 2, gravar, senão retorna ao estado anterior.
	}
}
// ******************************************************************************************************


// ******************************************************************************************************
// **********    bloqueia a tela com um div preto transparente     **************************************
// ******************************************************************************************************
function bloqueiaTela() {
	var divBloq = cria('div',{id:'bloqueio'});
	adicionaEvento(divBloq,'click',paraPropag);
	document.body.appendChild(divBloq);
}
// ******************************************************************************************************



// ******************************************************************************************************
// **********    pedir senha para completar uma operação           **************************************
// **********                                                      **************************************
// **********    bloqueia a tela com um div preto transparente     **************************************
// **********    o usuário informa a senha e envia                 **************************************
// **********    via Ajax testa a senha com o usuário logado       **************************************
// **********    se não bateu, cancela a operação                  **************************************
// **********    se bateu, executa a função do parâmetro           **************************************
// ******************************************************************************************************
function pedeSenha(funcao) {
	bloqueiaTela();
	divPede = document.createElement('div');
	divPede.id = 'pedeSenha';
	divPede.innerHTML = "<p>Por favor insira sua senha novamente<br />para confirmar esta operação:<br /><br />" +
		"<input type='password' id='senhaconf' /><a href='javascript:void(0)' id='enviasenhaconf'>enviar</a></p>" +
		"<a href='javascript:void(0)' id='enviasenhacanc'>cancelar</a>" +
		"<div id='aguardaPedeSenha' class='dispsome'>verificando a senha...</div>";
	document.body.appendChild(divPede);
	adicionaEvento(obj('enviasenhaconf'), 'click', function () { verificaPedeSenha(funcao); });
	adicionaEvento(obj('senhaconf'), 'keydown', function () { if (event.keyCode == 13) verificaPedeSenha(funcao); });
	adicionaEvento(obj('enviasenhacanc'), 'click', cancelaPedeSenha);
	
	// inclui a função de criptografia (incluindo uma tag "<script>" nova no head da página e linkando com o código da função)
	// erro para carregar no ie6. colocado direto no horas_edit.asp
	
	var novoscript = document.createElement('script');
	novoscript.language = 'javascript';
	novoscript.type = 'text/javascript';
	novoscript.src = 'func_sha1.js';
	document.getElementsByTagName('head')[0].appendChild(novoscript);

	obj('senhaconf').focus();
	obj('senhaconf').select();
}
	
function verificaPedeSenha(funcao) {
	//BUG IE6
	//Verificando se a funcao SHA1 já foi carregada.
	try{
		SHA1('');
	}catch(e){
		var t = setTimeout("verificaPedeSenha("+funcao+");",500);
		return false;
	}

	var conf = obj('senhaconf').value;
	if (conf.length == 0) {
		alert('Por favor informe uma senha.');
		obj('senhaconf').focus();
		return;
	}
	
	// codifica a senha utilizando o algoritmo SHA1 para enviá-la via AJAX
	var info = 'conf=' + SHA1(obj('senhaconf').value);
	obj('aguardaPedeSenha').className = obj('aguardaPedeSenha').className.replace(/\bdispsome\b/,'');
	
	var url = 'testaPermissao_fx.asp';
	var salva = new cnx.carrega(url, function() { verificouPedeSenha(this, funcao) }, null ,'POST',info);
}

function verificouPedeSenha(resp, funcao) {
	var confereSenha = resp.req.responseText;
	if (confereSenha == 1) {
		obj('aguardaPedeSenha').firstChild.nodeValue = 'executando a operação...';
		eval(funcao());
	} else {
		obj('aguardaPedeSenha').className += ' dispsome';
		alert('A senha não confere. Por favor verifique.');
	}
}

function cancelaPedeSenha() {
	obj('pedeSenha').parentNode.removeChild(obj('pedeSenha'));
	obj('bloqueio').parentNode.removeChild(obj('bloqueio'));
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** limpa todos os elementos filhos de um elemento
// ********** (exceto os elementos no array "exceto", se existir)
// ******************************************************************************************************
function limpaConteudo(pai, exceto) {
	if(!pai || !pai.childNodes) return;
	var filhos = pai.childNodes;
	for (var i=filhos.length-1; i>=0; i--) {
		var tira = true;
		if (exceto) {
			for (var j=0; j<exceto.length; j++) {
				if (filhos[i] == exceto[j]) {
					tira = false;
					break;
				}
			}
		}
		if (tira) removeObj(filhos[i]);
	}
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** exclui um elemento do DOM
// ******************************************************************************************************
// exclui um elemento do DOM
function removeObj(obj) {
	if (obj) obj.parentNode.removeChild(obj);
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** exibe ou oculta todos os elementos filhos de um elemento
// ********** pai (element DOM): elemento pai cujos filhos serão alterados
// ********** exibe (bool): exibe(true) ou oculta(false) os filhos
// ********** excecao (array): array simples ([]) com os elementos que devem ser ignorados nesta ação
// ********** estiloForte (bool): se a classe "some" não for suficiente, forçar o estilo dos filhos com display:'none'
// ******************************************************************************************************
function exibeFilhos(pai,exibe,excecao,estiloForte) {
	var filhos = pai.childNodes;
	if (filhos.length == 0) return;
	for (var i=0; i<filhos.length; i++) {
		var cadaFilho = filhos[i];
		var aplica = true;
		for (var j=0; j<excecao.length; j++) if (cadaFilho == excecao[j]) aplica = false;
		if (aplica) {
			if (estiloForte) {
				if (exibe) {
					cadaFilho.displayOld = cadaFilho.style.display;
					cadaFilho.style.display = 'none';
				} else {
					cadaFilho.style.display = cadaFilho.displayOld;
				}
			} else {
				if (exibe) cadaFilho.className = cadaFilho.className.replace(/\bsome\b/,'');
					else cadaFilho.className += ' some';
			}
		}
	}
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** Carrega dinamicamente uma página de estilos ou de script (javascript)
// ********** nome: nome do arquivo com a extensão
// ******************************************************************************************************
function carregaArquivo(nome) {
	var extensao = nome.substring(nome.indexOf('.')+1,nome.length);
	var arquivo;
	if (extensao == 'js') { //  || extensao == 'asp' || extensao = 'php'
		arquivo = document.createElement('script');
		arquivo.setAttribute('type', 'text/javascript');
		arquivo.setAttribute('src', nome);
	} else if (extensao == 'css') { //if filename is an external CSS file
		arquivo = document.createElement('link');
		arquivo.setAttribute('rel', 'stylesheet');
		arquivo.setAttribute('type', 'text/css');
		arquivo.setAttribute('href', nome);
	}
	if (arquivo) document.getElementsByTagName('head')[0].appendChild(arquivo);
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** funções para manipular as classes de um elemento
// ********** colocaClasse: inclui uma classe ao elemento
// ********** tiraClasse: exclui uma classe do elemento
// ********** temClasse: testa se o elemento possui uma classe. Retorna true ou false
// ******************************************************************************************************
function colocaClasse(elem, classe) {
	elem.className +=  ' ' + classe;
}

function tiraClasse(elem, classe) {
	classe = new RegExp('\\b' + classe + '\\b','gi');
	elem.className = elem.className.replace(classe,'');
}

function temClasse(elem, classe) {
	if (!elem) return false;
	if (!elem.className) return false;
	return (elem.className.indexOf(classe) >= 0);
}
// ******************************************************************************************************






// ******************************************************************************************************
// ********** função para pegar a posição do mouse em relação à tela do browser (cross-browser)
// ********** alteração baseada em http://www.quirksmode.org/js/events_properties.html
// ******************************************************************************************************
function mousePos(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	return { left: posx, top: posy };
}
// *************************************************************************************************





// ******************************************************************************************************
// ********** função para inserir um elemento no DOM, após outro elemento
// ********** Parametros:
// **********			newElement: (elemento DOM) elemento a ser inserido
// **********			targetElement: (elemento DOm) newElement será inserido após o elemento targetElement
// ******************************************************************************************************
function insertAfter(newElement,targetElement) 
{
	var parent = targetElement.parentNode;
	if(parent.lastchild == targetElement)
		parent.appendChild(newElement);		
	else 
		parent.insertBefore(newElement, targetElement.nextSibling)
}
// *************************************************************************************************





// ******************************************************************************************************
// ********** função para apagar todos os elementos filhos do elemento passado no parametro
// ********** Parametro: 
// **********			obj: (elemento DOM) elemento que terá todos os seus elementos filho apagados.
// ******************************************************************************************************
function clearChildren(obj)
{
	if(obj.hasChildNodes() && obj.childNodes) 
	{
		while(obj.firstChild) 
		{
			obj.removeChild(obj.firstChild);
		}
	}
}
// *************************************************************************************************



// ******************************************************************************************************
// ********** função que pega todos os elmentos com o className escolhida
// ********** Parametros: 
// **********			  classname: nome da classe dos elementos desejados
// **********				
// **********			  tag:  especificação da tag dos elementos desejados (caso não exista especificação
// **********					serão percorridos todos os elementos do nó)
// **********
// **********  	     	  node: especificação do nó onde estão os elementos desejados 
// **********					(caso não exista especificação o elemento será o nó inicial)
// ******************************************************************************************************
function getElementsByClassName(classname, tag, node)  
{
	if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName(tag);
    for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className)) a.push(els[i]);
	return a;
}
// *************************************************************************************************




// ******************************************************************************************************
// ********** funçao cross-browser para incluir uma option em um select (é diferente no IE)
// ********** Parametros: 
// **********			objSelect: select onde será incluida a option
// **********			objOption: o elemento option a ser incluído
// **********			posicao: se quiser incluir no meio, posicao indica onde será incluído. Se nao tiver, será incluído no final
// ******************************************************************************************************
function addOption(objSelect, objOption, posicao) {
	var item = (posicao) ? objSelect.options[posicao] : null; 
	try {
		// todos os browsers (fora o IE)
		objSelect.add(objOption, item);
	} catch(e) {
		// IE
		if (posicao) objSelect.add(objOption, posicao);
		else objSelect.add(objOption);
	}
}
// *************************************************************************************************




// ******************************************************************************************************
// ********** funçao mostraLinha, que pinta (e despinta) uma linha inteira (TR, LI ou DIV) ao passar o mouse
// ********** colocando (ou tirando) a classe "pintado"
// ******************************************************************************************************
function mostraLinha(ev) {
	if (!ev) var ev = window.event;
	var elem = ev.target || ev.srcElement;
	var pai = elem;
	while (pai.tagName.toUpperCase() != 'TR' && pai.tagName.toUpperCase() != 'LI' && pai.tagName.toUpperCase() != 'DIV') pai = pai.parentNode;
	
	if (ev.type == 'mouseout' || ev.type == 'click') {
		tiraClasse(pai, 'pintado');
	} else {
		colocaClasse(pai, 'pintado');
	}
	
	return null;
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** funçao formataHora, recebe int ou string contendo o total de tempo em minutos, e 
// ********** retorna um vetor 'dados' onde dados[0] contem o total de horas e dados[1] o total de minutos
// ******************************************************************************************************
function formataHora(tempoTot)
{
	var horas = parseInt(tempoTot);
	if(horas >= 60)
	{
		var minutos = horas%60;
		horas = horas/60;
		horas = parseInt(horas);
	}
	else
	{
		minutos = horas;
		horas = '00';
	}
	var dados = new Array();
	dados[0] = horas;
	dados[1] = minutos;

	if(dados[1] == 0)
		dados[1] = '00';
		
	return dados;
}
// ******************************************************************************************************


// ******************************************************************************************************
// ********** funçao isBissexto, recebe int ou string contendo o ano, verifica se esse ano é bissexto e
// ********** em caso positivo retorna true, ja em caso negativo retorna false
// ******************************************************************************************************
function isBissexto(ano)
{
	var bissexto = false;
	
	ano = ano.toString();
	var anoDigitosFinais = ano.substring(2);
	
	if(ano%4 == 0)
	{
		if(anoDigitosFinais != '00')
		{
			bissexto = true;
		}
		else
		{
			if(ano%400 == 0)
				bissexto = true;
		}
	}
	
	return bissexto;
}
// ******************************************************************************************************


//*****************************************************************************************************
// ** função cross-browser (strict ou não) para pegar o tamanho da janela onde está o browser
// ** já desconsiderando as barras de scroll quando houver
// ** retorna .altura e .largura
function tamanhoTela() {
	var largura = 0, altura = 0;
	if ( typeof( window.innerWidth ) == 'number' ) {
		// outros browsers fora o IE
		largura = window.innerWidth;
		altura = window.innerHeight;
	} else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		// IE 6+ sem Strict
		largura = document.documentElement.clientWidth;
		altura = document.documentElement.clientHeight;
	} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		// IE < 6
		largura = document.body.clientWidth;
		altura = document.body.clientHeight;
	}
	return { largura: largura, altura: altura };
}
// ******************************************************************************************************


//******************************************************************************************************
// ** função cross-browser (strict ou não) para pegar o quanto já houve de scroll na página
// ** retorna .top e .left
// ** baseado em http://stackoverflow.com/questions/871399/cross-browser-method-for-detecting-the-scrolltop-of-the-browser-window
function quantScroll() {
    if (typeof pageYOffset != 'undefined') { // maioria dos browsers
        return { top: pageYOffset, left: pageXOffset }; 
    } else {
        var referencia = document.documentElement; // IE with doctype 
        var corpo = document.body; // IE 'quirks' 
        referencia = (referencia.clientHeight) ? referencia : corpo; 
        return { top: referencia.scrollTop, left: referencia.scrollLeft }; 
    }
}
// ******************************************************************************************************


//******************************************************************************************************
// ** função que retorna o texto de dentro de um elemento (se o primeiro filho for o nó de texto. Senão retona string vazia.)
function nohTexto(elem) {
	return (elem && elem.firstChild && elem.firstChild.nodeValue) ? elem.firstChild.nodeValue : '';
}
// ******************************************************************************************************


//******************************************************************************************************
// ** função que verifica se um campo tem uma data válida e altera o estilo conforme o resultado
// ** deve ser colocada tanto no onkeyup quanto no onchange
function verificaData(e) {
	var input = origemEvento('input', e);
	var data = valida_data(input.value);
	tiraClasse(input, 'valida');
	tiraClasse(input, 'invalida');
	if (data == -1) {
		colocaClasse(input, 'invalida');
	} else if (data.length > 1) {
		colocaClasse(input, 'valida');
	}
}
// ******************************************************************************************************


//******************************************************************************************************
// ** função para a ordenação (algoritmo quicksort)
// ** (para ser utlizado nos casos onde o array.sort() não funciona)
// ** parametros:
// **		origem = array linear para ser ordenado
// **		limMin = 0
// **		limMax = (length - 1) do array
// **		col = numero ou nome do campo a ser usado para a ordenação
function ordenaQuicksort(origem, limMin, limMax, col) {
	var pivo, corteInf, corteSup;
	// dois itens para ordenar (apenas compara e troca se for necessário)
	if (limMax - limMin == 1) {
		if (origem[limMin][col] > origem[limMax][col]) sortTroca(origem, limMin, limMax);
		return;
	}

	// três ou mais itens para ordenar (quebra em dois e ordena cada uma das sessões)
	pivo = origem[parseInt((limMin + limMax) / 2)][col];
	origem[parseInt((limMin + limMax) / 2)][col] = origem[limMin][col];
	origem[limMin][col] = pivo;
	corteInf = limMin + 1;
	corteSup = limMax;

	do {
		while (corteInf <= corteSup && origem[corteInf][col] <= pivo) corteInf++; // encontra o corteInf
		while (origem[corteSup][col] > pivo) corteSup--; // encontra o corteSup
		if (corteInf < corteSup) sortTroca(origem, corteInf, corteSup);
	} while (corteInf < corteSup);

	origem[limMin][col] = origem[corteSup][col];
	origem[corteSup][col] = pivo;

	// 2 ou mais itens na primeira sessão
	if (limMin < corteSup - 1) ordenaQuicksort(origem, limMin, corteSup - 1, col);
	// 2 ou mais itens na segunda sessão
	if (corteSup + 1 < limMax) ordenaQuicksort(origem, corteSup + 1, limMax, col);
}

function sortTroca (arei, a, b) {
	var temp = arei[a];
	arei[a] = arei[b];
	arei[b] = temp;
}
//******************************************************************************************************


//******************************************************************************************************
// ** função que altera o pagamento se já foi emitido um boleto
// ** (para ser utlizado nas páginas com matrículas - alun.asp e turm_edit.asp)
    function boletoEmitido(ele, data, valor, id) {
        data = formataData(data);
        ele.className += ' emitido';
        var imgs = ele.getElementsByTagName('img');
        for (var i = 0; i < imgs.length; i++){
            if (imgs[i].className.search(/dispsome/) > 0){
                imgs[i].alt = 'boleto referente a este pagamento já emitido em '+ data;
				if(valor) imgs[i].alt += ', no valor de R$' +  formataNumero(valor);
                if(id){
					imgs[i].style.cursor = 'pointer';
					imgs[i].onclick = function (){
						var url = 'pag_sel.asp?idpagto=' + id + '&idesc=' + idesc + '&idPerm=4';
						var param = 'location=no,scrollbars=yes,width=682,height=340,top=10,left=10';
						var janela = window.open(url,'apoio',param);
						janela.focus();
					}				
				}
				mostra(imgs[i]);
            }
        }
    }
//******************************************************************************************************



//******************************************************************************************************
// ** função que formata uma data, convertendo de YYYY-MM-DD para dd/mm/yy
	function diamesano(data) {
		if (data.length == 0) return '';
		var dia, mes, ano;
		var re = /^(\d+)\-(\d+)\-(\d+)$/g;
		ano = data.replace(re,'00$1');
		mes = data.replace(re,'00$2');
		dia = data.replace(re,'00$3');
		return dia.substring(dia.length-2) + '/' + mes.substring(mes.length-2) + '/' + ano.substring(ano.length-2);
	}
//******************************************************************************************************



//******************************************************************************************************
// ** função que retorna o valor da option selecionada de um select
	function selValue(sel) {
		if (!sel || !sel.childNodes) return false;
		var indice = (sel.selectedIndex) ? sel.selectedIndex : 0;
		var valor = (sel.childNodes[indice]) ? sel.childNodes[indice].value : null;
		return valor;
	}
//******************************************************************************************************




// *******************************************  formCPF  ****************************************************************************
//			Converte CPF de apenas numerico para o formato 000.000.000-00
//			parâmetros: num (numero - ou texto numérico - de até 11 dígitos)
// *************************************************************************************************************************************
	function formCPF(num) {
		// var cpf = num.replace(/[\,\.\-\/\\\;\:]/gi, '');
		var cpf = num.replace(/\D/g,'');  // tira tudo que não for dígito
		if (cpf.length > 2) cpf = cpf.substring(0, cpf.length - 2) + '-' + cpf.substring(cpf.length - 2);
		if (cpf.length > 6) cpf = cpf.substring(0, cpf.length - 6) + '.' + cpf.substring(cpf.length - 6);
		if (cpf.length > 10) cpf = cpf.substring(0, cpf.length - 10) + '.' + cpf.substring(cpf.length - 10);
		if (cpf.length > 14) cpf = cpf.substring(cpf.length - 14);
		return cpf;
	}
// *************************************************************************************************************************************




// *******************************************  formCNPJ  **************************************************************************
//			Converte CNPJ de apenas numerico para o formato 000.000.000/0000-00
//			parâmetros: num (numero - ou texto numérico - de até 15 dígitos)
// *************************************************************************************************************************************
	function formCNPJ(num) {
		// var cnpj = num.replace(/[\,\.\-\/\\\;\:]/gi, '');
		var cnpj = num.replace(/\D/g,'');  // tira tudo que não for dígito
		if (cnpj.length > 2) cnpj = cnpj.substring(0, cnpj.length - 2) + '-' + cnpj.substring(cnpj.length - 2);
		if (cnpj.length > 7) cnpj = cnpj.substring(0, cnpj.length - 7) + '/' + cnpj.substring(cnpj.length - 7);
		if (cnpj.length > 11) cnpj = cnpj.substring(0, cnpj.length - 11) + '.' + cnpj.substring(cnpj.length - 11);
		if (cnpj.length > 15) cnpj = cnpj.substring(0, cnpj.length - 15) + '.' + cnpj.substring(cnpj.length - 15);
		if (cnpj.length > 19) cnpj = cnpj.substring(cnpj.length - 19);
		return cnpj;
	}
// *************************************************************************************************************************************




//*******************************************************************************************************************************************************************
// ** trata campos de input e texarea para prevenir códigos SQL (deve ser tratado também na chegada ao servidor)
//*******************************************************************************************************************************************************************
function trataSQL(campo) {
	var expressao = new RegExp('declare|script|(\-\-)|(\%[0-9])','gim');
	if (campo && expressao.test(campo.value)) {
		alert('Caracteres inválidos.');
		return false;
	}
	return true;
	//return campo.value;
}
//*******************************************************************************************************************************************************************






	


	

