/* 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");



// ABRE A TELA "MEU CADASTRO"
function meucadastro(raiz) {
	location.href = raiz+"meucadastro/";
}


// EFETUA LOGOFF DO SISTEMA
function sair(raiz) {
	if (confirm("Deseja realmente sair do sistema?")) {
		location.href = raiz+"logoff.php";
	}
}


// 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;
	}
}


// LISTA OS DADOS DE UM CADASTRO
function list() {
	location.href = "index.php";
}


// CARREGA UMA PÁGINA DE CADASTRO
function add() {
	var pg = document.getElementById("pg").value;
	location.href = "cadastro.php?pg="+pg;
}


// 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 = "par over";
		} else {
			linha.className = "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 = "par";
		} else {
			linha.className = "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();
		}
	}
}


// 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 (FORMATO HH:MM) E HORAS INVÁLIDAS
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, "-");
	
	if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
		cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		cpf == "88888888888" || cpf == "99999999999") {
		return false;
	}
	
	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(needle,haystack) {
	return new RegExp('(^|\,)'+needle+'(\,|$)','gi').test(haystack);
}


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);
}


/**
 * 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) {
	div = document.getElementById(div);
	div.style.display = 'inline';
	div.style.position = 'absolute';
	div.style.width = '180';
	div.style.backgroundColor = '#FEFCD5';
	div.style.border = 'solid 1px #E7E3BE';
	div.style.padding = '5px';
	div.innerHTML = '<span class="helpTop"><b>' + title + '</b></span><img src="../img/1x1.gif" style="width:1px; height:5px"><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
 */


// 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 esqueci(raiz) {
	altura = 330;
	largura = 450;

	w = screen.width;
	h = screen.height;
	
	//divide a resolução por 2, obtendo o centro do monitor
	meio_w = w/2;
	meio_h = h/2;
	
	//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
	altura2 = altura/2;
	largura2 = largura/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;
	
	window.open(raiz+"esqueci.php", "", 'height=' + altura + ', width=' + largura + ', top='+meio1+', left='+meio2+ ', scrollbars=yes');
}


function validaesqueci(){
	
	var login  =  document.getElementById("login");
	var cpf   =  document.getElementById("cpf");
	
	if (Trim(login.value) == "") {
		alert("Informe seu login!");
		login.style.backgroundColor='#FFCDCA';
		login.focus();
		return false
	} else if (!validaCPF(cpf.value)) {
		alert("CPF inválido!");
		cpf.style.backgroundColor='#FFCDCA';
		cpf.focus();
		return false;
	} else {
		return true;
	}
}


function escreveSWF(file, width, height) {
	document.write('<object type="application/x-shockwave-flash" style="width:'+width+'px; height:'+height+'px" data="'+file+'">');
	document.write('<param name="movie" value="'+file+'" />');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="menu" value="false" />');
	document.write('<param name="wmode" value="opaque" />');
	//document.write('<param name="FlashVars" value="playerMode=embedded" />');
	document.write('</object>');
}


function verificarSenha(senha, obj) {
	if (Trim(senha) != "") {
		if (senha.match(/[A-z0-9]{6}/)) {
			document.getElementById(obj).innerHTML        = "Senha segura";
			document.getElementById(obj).style.background = "#008000";
			document.getElementById(obj).style.color      = "#FFFFFF";
		} else {
			document.getElementById(obj).innerHTML        = "Senha não segura";
			document.getElementById(obj).style.background = "#C00000";
			document.getElementById(obj).style.color      = "#FFFFFF";
		}
	}
}


