/* IDENTIFICAÇÃO DE BROWSER--------------------------------------------------------------*/
var isNav4, isNav, isIE;

if (parseInt(navigator.appVersion.charAt(0)) >= 4) {
  isNav = (navigator.appName == "Netscape") ? true : false;
  isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
}

if (navigator.appName == "Netscape") {
	isNav4 = (parseInt(navigator.appVersion.charAt(0)) == 4);
}
/*FIM IDENTIFICAÇÃO DE BROWSER------------------------------------------------------------*/



isNS = (navigator.appName == "Netscape");
//isIE = (navigator.appName == "Microsoft Internet Explorer");

// ADICIONA EVENTOS ONLOAD
function addLoadEvent(func) {
	var oldonload = window.onload;
	
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			
			func();
		}
	}
}

// CRIA O OBJETO DE REQUISIÇÃO AJAX
function createRequest() {
	var request = null;
	
	try {
	    request = new XMLHttpRequest();
	} catch(trymicrosoft) {
	    try {
	        request = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch(othermicrosoft) {
	        try {
	            request = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch(failed) {
	            request = null;
	        }
	    }
	}
	
	if (request == null) {
		alert('Erro ao criar objeto request!');
	}
	else {
		return request;
	}
}


// REDIRECIONA A PÁGINA
function redirect(page) {
	location.href = page;
}


// ATUALIZA A PÁGINA
function refresh() {
	location.reload();
}


// RETIRA OS ESPAÇOS DO INÍCIO E DO FIM DA STRING
function Trim(str) {
	while (str.charAt(0) == " ") {
		str = str.substr(1,str.length -1);
	}

	while (str.charAt(str.length-1) == " ") {
		str = str.substr(0,str.length-1);
	}

	return str;
}


// VERIFICAÇÃO DE EMAIL VÁLIDO
function checkMail(mail) {
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if (typeof(mail) == "string") {
		if (er.test(mail)) {
			return true;
		}
	}
	else if (typeof(mail) == "object") {
		if (er.test(mail.value)) {
			return true;
		}
	}
	else {
		return false;
	}
}


// FUNÇÃO CHAMADA NA GRID QUANDO O MOUSE PASSA POR CIMA DE UMA LINHA
function gridOver(linha, id) {
	if (linha.className != "checked") {
		if ((id%2) == 0) {
			linha.className = "dados par over";
		} else {
			linha.className = "dados impar over";
		}
	}
}


// FUNÇÃO CHAMADA NA GRID QUANDO O MOUSE SAI DE CIMA DE UMA LINHA
function gridOut(linha, id) {
	if (linha.className != "checked") {
		if ((id%2) == 0) {
			linha.className = "dados par";
		} else {
			linha.className = "dados impar";
		}
	}
}


// SELECIONA TODOS OS REGISTROS DE UMA GRID
function selectAll(name) {
	var input = document.getElementsByTagName("input");
	var check = document.getElementById("ckbselectall").checked;
	var j     = 0;
	
	// marca ou desmarca todos os checkbox's das CIs
	for (i=0; i<input.length; i++) {
		
    	if (input[i].getAttribute("name") == name) {
			input[i].checked = check;
			
			if (check) {
				//document.getElementById("linec"+j).style.backgroundColor = "#FFFFCC";
				document.getElementById("linec"+j).className = "checked";
			} else {
				//document.getElementById("linec"+j).style.backgroundColor = "";
				if ((j%2) == 0) {
					document.getElementById("linec"+j).className = "par";
				} else {
					document.getElementById("linec"+j).className = "impar";
				}
			}
			
			j++;
		}
	}
}


// CHAMA O FORM QUE EXCLUI OS REGISTROS SELECIONADOS DE UMA GRID
function deleteSelected(name) {
	var input   = document.getElementsByTagName("input");
	var qtde    = 0;
	var codigos = "";
	
	// captura a qtde e os códigos dos checkbox's que estão marcados
	for (i=0; i<input.length; i++) {
    	if (input[i].getAttribute("name") == name) {
			if (input[i].checked == true) {
				qtde++;
				
				codigos += parseInt(input[i].value, 10) + ",";
			}
		}
	}
	
	// tira a última vírgula
	codigos = codigos.substr(0, codigos.length-1);
	
	if (qtde == 0) {
		alert("Nenhum registro foi selecionado!");
	} else {
		if (confirm("Confirma a exclusão de "+qtde+" registro(s)?")) {
			document.getElementById("id").value = codigos;
			document.getElementById("delete").submit();
		}
	}
}


// ENVIA OS REGISTROS SELECIONADOS DE UMA GRID VIA POST
function enviaFormGrid(id) {
	var combo = document.getElementById(id);
	
	if (combo.value == '') {
		alert('Selecione uma ação na caixa de seleção!');
		como.focus();
	} else {
		var checks = document.getElementsByName('checkbox');
		var itens  = '';
		var msg    = '';
		var i, qtde = 0;
		
		for (i=0; i<checks.length; i++) {
			if (checks[i].checked) {
				itens += checks[i].value+',';
				qtde++;
			}
		}
		
		if (qtde == 0) {
			alert('Nenhum registro foi selecionado!');
		} else {
			if (qtde == 1) {
				msg = 'Confirma a ação com o registro selecionado?';
			} else {
				msg = 'Confirma a ação com os '+qtde+' registros selecionados?';
			}
			
			itens = itens.substr(0, itens.length-1);
			
			if (confirm(msg)) {
				document.getElementById('id_grid').value     = itens;
				document.getElementById('action_grid').value = combo.value;
				document.getElementById('Fgrid').submit();
			}
		}
	}
}


// CHAMA O FORM QUE EXCLUI UM REGISTRO CARREGADO NO FORMULÁRIO
function deleteCurrent() {
	if (confirm("Confirma a exclusão do registro?")) {
		document.getElementById("delete").submit();
	}
}


// MUDA A COR DA LINHA DA GRID QUANDO SELECIONA O REGISTRO
function changeColor(cb, id) {
	var elemento = document.getElementById("line"+cb.id);
	
	if (cb.checked) {
		elemento.className = "checked";
	} else {
		if ((id%2) == 0) {
			elemento.className = "par";
		} else {
			elemento.className = "impar";
		}
	}
}


// VALIDAÇÃO DE DATA (FORMATO dd/mm/aaaa) E DATAS INVÁLIDAS
function validaData(data) {
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	
	var msgErro = 'Formato inválido de data.';
	
	if ((data.match(expReg)) && (data!='')) {
		var dia = data.substring(0,2);
		var mes = data.substring(3,5);
		var ano = data.substring(6,10);
		
		if (((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) && (dia > 30)) {
			//alert("Dia incorreto!!! O mês especificado contém no máximo 30 dias.");
			return false;
		} else {
			if ( (ano%4!=0) && (mes == 2) && (dia > 28)) {
				//alert("Data incorreta!!! O mês especificado contém no máximo 28 dias.");
				return false;
			} else {
				if ((ano%4 == 0) && (mes == 2) && (dia > 29)) {
					//alert("Data incorreta!!! O mês especificado contém no máximo 29 dias.");
					return false;
				} else {
					//alert ("Data correta!");
					return true;
				}
			}
		}
	} else {
		//alert(msgErro);
		//campo.focus();
		return false;
	}
}


// VALIDAÇÃO DE HORA NO FORMADO HH:MM
function validaHora(horario) {
    var hora, min;
	
    if (!(horario.match(/^[0-9]{2,2}[:]{0,1}[0-9]{2,2}$/))) {
        return false;
    } else {
	    hora = parseInt(horario.substr(0,2));
	    min  = parseInt(horario.substr(3,2));
		
	    if ((hora < 0) || (hora > 23)) {
	        return false;
	    } else if ((min < 0) || (min > 59)) {
	        return false;
	    } else {
			return true;
		}
	}
}


// FUNÇÃO DE SUPORTE À FUNÇÃO "validaCPF"
function removeStr(str, sub) {
	i = str.indexOf(sub);
	r = "";
	
	if (i == -1) {
		return str;
	}
	
	r += str.substring(0,i) + removeStr(str.substring(i + sub.length), sub);
	
	return r;
}


// VALIDAÇÃO DE CPF (TESTA O DÍGITO VERIFICADOR)
function validaCPF(cpf) {
	var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	
	if (!filtro.test(cpf)) {
		return false;
	}
	
	cpf = removeStr(cpf, ".");
	cpf = removeStr(cpf, "-");
	
	var i;
	var c = cpf.substr(0,9); 
	var dv = cpf.substr(9,2);
	var d1 = 0;
 	
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(10-i);
 	}
	
	if (d1 == 0) {
		return false;
	}
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9) {
		d1 = 0;
	}
	
	if (dv.charAt(0) != d1) {
		return false;
	}
	
	d1 *= 2;
	
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(11-i);
	}
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9) {
		d1 = 0;
	}
	
	if (dv.charAt(1) != d1) {
		return false;
	}
	
	return true;
}


function setCursor(cursor) {
	// coloca o cursor em todos os elementos <input>
	var input = document.getElementsByTagName("input");
	
	document.body.style.cursor = cursor;
	
	for (i=0; i<input.length; i++) {
		if (input[i].type != "text") {
			input[i].style.cursor = cursor;
		}
	}
}


function float2moeda(num) {
	x = 0;
	
	if (num < 0) {
		num = Math.abs(num);
		x = 1;
	}
	
	if (isNaN(num)) {
		num = "0";
	}
	
	cents = Math.floor((num*100+0.5)%100);
	
	num = Math.floor((num*100+0.5)/100).toString();
	
	if (cents < 10) {
		cents = "0" + cents;
	}
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3)) + '.' + num.substring(num.length-(4*i+3));
	}
	
	ret = num + ',' + cents;
	
	if (x == 1) ret = ' - ' + ret;
	return ret;
}


function moeda2float(moeda) {
	moeda = moeda.replace(".", "");
	moeda = moeda.replace(",", ".");
	
	return parseFloat(moeda);
}


function in_array (x, matriz) {
	var txt = "¬" + matriz.join("¬") + "¬";
	var er = new RegExp ("¬" + x + "¬", "gim");
	return ( (txt.match (er)) ? true : false );
}


/**
 * FUNÇÕES PARA EXIBIÇÃO E OCULTAÇÃO DA JANELA DA AJUDA. INSTRUÇÕES DE USO:
 *
 * <div style="display:none" id="id_do_div"></div>
 * onmouseout="HideHelp('id_do_div')"
 * onmouseover="ShowHelp('id_do_div', 'titulo', 'texto_da_ajuda')"
 */
function ShowHelp(div, title, desc, aux) {
	div = document.getElementById(div);
	
	div.style.display = 'inline';
	div.style.position = 'absolute';
	div.style.backgroundColor = '#FEFCD5';
	div.style.borderLeft = 'outset 1px #000';
	div.style.borderRight = 'outset 2px #AAA';
	div.style.borderTop = 'outset 1px #000';
	div.style.borderBottom = 'outset 2px #AAA';
	div.style.padding = '7px';
	
	if (desc == "") {
		desc = document.getElementById(aux).innerHTML;
	}
	
	div.innerHTML = '<span class="helpTop"><b>' + title + '</b></span><div style="padding:10px 0 0 0" class="helpTop">' + desc + '</div>';
}

function ShowHelp2(div, title, desc, aux, posX, posY) {
	div = document.getElementById(div);
	
	div.style.display = 'inline';
	div.style.position = 'absolute';
	div.style.backgroundColor = '#FEFCD5';
	div.style.border = 'solid 1px #E7E3BE';
	div.style.padding = '5px';
	div.style.left = posX;
	div.style.top = posY;
	
	if (desc == "") {
		desc = document.getElementById(aux).innerHTML;
	}
	
	div.innerHTML = '<span class="helpTop"><b>' + title + '</b></span><div style="padding:5px 0 0 0" class="helpTop">' + desc + '</div>';
}

function HideHelp(div) {
	div = document.getElementById(div);
	div.style.display = 'none';
}

/**
 * FIM DA FUNÇÕES DE AJUDA
 */



 /**
  * CRONÔMETRO REGRESSIVO
  */
function StartCrono(obj, hor, min, seg) {
	if (seg >= 60) {
		seg = 0;
	}
	
	//timeCrono  = (hor < 10) ? "0" + hor : hor;
	timeCrono = ((min < 10) ? "0" : "") + min;
	timeCrono += ((seg < 10) ? ":0" : ":") + seg;
	
	document.getElementById(obj).innerHTML = timeCrono;
	
	if (seg <= 0) {
		seg  = 59;
		min -= 1;
	} else {
		seg -= 1;
	}
	
	if (min < 0) {
		min = 0;
		seg = 0;
	}
	
	setTimeout("StartCrono('"+obj+"', "+hor+", "+min+", "+seg+")", 980);
}
/**
 * FIM DO CRONÔMETRO REGRESSIVO
 */
 
 
 
// SELECIONA TODOS OS REGISTROS DE UMA GRID (DEVE SER USADO QUANDO NÃO USADA A CLASSE DA GRID)
function selecionaTudo(checkbox, name) {
	var input = document.getElementsByTagName("input");
	var check = checkbox.checked;
	var j     = 0;
	
	// MARCA OU DESMARCA TODOS OS CHECKBOX'S
	for (i=0; i<input.length; i++) {
    	if (input[i].getAttribute("name") == name) {
			input[i].checked = check;
			j++;
		}
	}
}


function habilitaBotao(id, css) {
	document.getElementById(id).className = css;
	document.getElementById(id).removeAttribute("disabled");
}


function desabilitaBotao(id) {
	document.getElementById(id).className = "b0";
	document.getElementById(id).setAttribute("disabled", true);
}

// Adiciona conteúdo HTML em campos textarea
function addHTML(obj, codigo) {
	var texto1, texto2;
	var obj = document.getElementById(obj);
	
	if (codigo == '1') {
		texto1 = prompt('Texto em negrito (o texto será inserindo no final do campo)', '');
		
		if (texto1 != null) {
			obj.value += '<b>'+texto1+'</b>';
		}
	} else if (codigo == '2') {
		texto1 = prompt('Texto em itálico (o texto será inserindo no final do campo)', '');
		
		if (texto1 != null) {
			obj.value += '<i>'+texto1+'</i>';
		}
	} else if (codigo == '3') {
		texto1 = prompt('Texto sublinhado (o texto será inserindo no final do campo)', '');
		
		if (texto1 != null) {
			obj.value += '<u>'+texto1+'</u>';
		}
	} else if (codigo == '4') {
		texto1 = prompt('Endereço completo do link, inclusive com o "http://", se for o caso');
		
		if (texto1 != null) {
			texto2 = prompt('Descrição para o link', '');
			
			if (texto2 != null) {
				obj.value += '<a href="'+texto1+'" rel="external">'+texto2+'</a>';
			}
		}
	}
	
	obj.focus();
}

function calculaIdade(data) {
	var dt       = new Date();
	var dia      = dt.getDate();
	var mes      = dt.getMonth();
	var ano      = dt.getFullYear();
	var dataHoje = dia+"/"+(mes+1)+"/"+ano;

	x = data.split("/");
	h = dataHoje.split("/");

	anosProvisorio = h[2] - x[2];

	if(h[1] < x[1]) {
		anosProvisorio -= 1;
	}
	else if(h[1] == x[1]) {
		if(h[0] < x[0]) {
			anosProvisorio -= 1;
		}
	}
	
	return anosProvisorio;
}


function hhEffect(act, obj) {
	obj.style.cursor = "default";
	
	//var s = obj.getElementsByTagName("td")
	
	if (!act) {
		ctmp = 	obj.style.color;
		obj.style.backgroundColor = "#E8FFE9";
	} else {
		obj.style.backgroundColor = ctmp;
	}
}


function abreAjuda(raiz, id) {
	window.open(raiz+"files/php/saibamais.php?id="+id, "", "width=600,height=500,scrollbars=yes");
}


function setarTexto(obj, text) {
	if (obj.value == "") {
		obj.style.color = "#AAAAAA";
		obj.value = text;
	}
}


function removerTexto(obj) {
	if (obj.value == "Pesquisar") {
		obj.style.color = "black";
		obj.value = '';
	}
}


function createExternalLinks() {
    if (document.getElementsByTagName) {
        var anchors = document.getElementsByTagName('a');
        for (var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if (anchor.getAttribute('href') && anchor.getAttribute('rel') == 'externo') { // <-- É necessário inserir rel="externo" no link
                anchor.target = '_blank';
                //var title = anchor.title + ' (Este link abre uma nova janela)'; // <-- Insere este texto no final do Title do link
                //anchor.title = title;
            } else if (anchor.getAttribute('form') && anchor.getAttribute('rel') == 'externo') {
            	anchor.target = '_blank';
            }
        }
    }
}


function abreCalendario(raiz) {
	window.open(raiz+"files/misc/pdf/calendario-academico-2010-1.pdf");
}

function desabilitarBotoes(id) {
	var buttons = document.getElementById(id).getElementsByTagName('input');
	var i;
	
	for (i=0; i<buttons.length; i++) {
		if ((buttons[i].type == 'submit') || (buttons[i].type == 'button') || (buttons[i].type == 'reset')) {
			buttons[i].setAttribute('disabled', true);
		}
	}
}

addLoadEvent(createExternalLinks);

addLoadEvent(function() {
	$('.numeric').keypress(function(event) {
		if (event.charCode && (event.charCode < 48 || event.charCode > 57)) {
			event.preventDefault();
		}
	});
	
	$('.cpf').mask('999.999.999-99');
	
	$('.cnpj').mask('99.999.999/9999-9');
	
	$('.date').mask('99/99/9999');
	$('.date').css('width', '70px');
	
	$('.time').mask('99:99:99');
	$('.time').css('width', '55px');
	
	$('.float').priceFormat({
		prefix: '',
		centsSeparator: ',',
		thousandsSeparator: '.',
		centsLimit: 2,
		limit: 8
	});
	
	$('.focus').focus();
}); 
