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

isNS = (navigator.appName == 'Netscape');


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

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

// VALIDA LOGIN NO SISTEMA ADMINISTRATIVO
function validaLogin() {
	var user = document.getElementById("user");
	var pass = document.getElementById("pass");
	
	if (Trim(user.value) == "") {
		alert("Informe o seu nome de usuário!");
		user.focus();
		return false;
	} else if (Trim(pass.value) == "") {
		alert("Informe a sua senha de acesso!");
		pass.focus();
		return false;
	} else {
		return true;
	}
}

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

// 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('check');
		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();
			}
		}
	}
}

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

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

// CONVERTE FLOAT PARA MOEDA
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;
}

// CONVERTE MOEDA PARA FLOAT
function moeda2float(moeda) {
	moeda = moeda.replace(".", "");
	moeda = moeda.replace(",", ".");
	
	return parseFloat(moeda);
}

/**
 * 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.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 HideHelp(div) {
	div = document.getElementById(div);
	div.style.display = 'none';
}


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

// ADICIONA A TAG TARGET="_BLANK" PARA LINKS QUE ABREM EM NOVA JANELA
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") == "external") { // <-- É 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 = Trim(title);
			}
		}
	}
}

// ADICIONA CONTEÚDO HTML EM TEXTOS
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 tratarFoco(obj, txt) {
	if (obj.value == txt) {
		obj.value = '';
		obj.style.color = '#000000';
	} else if (obj.value == '') {
		obj.value = txt;
		obj.style.color = '#999999';
	}
}

function validarAlbum() {
	var nome = $('#nome');
	
	if (Trim(nome.val()) == '') {
		alert('Informe um NOME para o álbum!');
		nome.focus();
		return false;
	} else {
		return true;
	}
}

function excluirCapaAlbum() {
	if (confirm('Confirma a exclusão da capa do álbum?')) {
		document.getElementById('action').value = 'excluirCapa';
		document.getElementById('form').submit();
	}
}

function excluirAlbum(id) {
	if (confirm('Confirma a exclusão do álbum?')) {
		document.getElementById('action').value = 'excluirAlbum';
		document.getElementById('codgaleria').value = id;
		document.getElementById('form').submit();
	}
}

function alterarLegenda(id) {
	var atual   = $('#legenda'+id).val();
	var legenda = window.prompt('Informe a nova legenda para a foto', atual);
	
	if (legenda) {
		$('#action').val('alterarLegenda');
		$('#codfoto').val(id);
		$('#aux').val(legenda);
		$('#form').submit();
	}
}

function excluirFoto(id) {
	if (confirm('Confirma a exclusão da foto?')) {
		$('#action').val('excluirFoto');
		$('#codfoto').val(id);
		$('#form').submit();
	}
}

function validarPerfil() {
	var nome  = $('#nome');
	var email = $('#email');
	
	if (Trim(nome.val()) == '') {
		alert('Informe o seu NOME completo!');
		nome.focus();
		return false;
	} else if (!checkMail(email.val())) {
		alert('Informe um EMAIL válido!');
		email.focus();
		return false;
	} else {
		return true;
	}
}

function validarRegistro() {
	var nome  = $('#nome');
	var email = $('#email');
	
	if (Trim(nome.val()) == '') {
		alert('Informe o seu NOME completo!');
		nome.focus();
		return false;
	} else if (!checkMail(email.val())) {
		alert('Informe um E-MAIL válido!');
		email.focus();
		return false;
	} else {
		return true;
	}
}

function validarSenha() {
	var senha     = $('#senha');
	var novasenha = $('#novasenha');
	var conf      = $('#conf');
	
	if (Trim(senha.val()) == '') {
		alert('Informe a sua SENHA ATUAL!');
		senha.focus();
		return false;
	} else if (Trim(novasenha.val()).length < 6) {
		alert('Informe a NOVA SENHA com no mínimo 6 caracteres!');
		novasenha.focus();
		return false;
	} else if (novasenha.val() != conf.val()) {
		alert('A confirmação de senha está diferente da nova senha informada!');
		conf.focus();
		return false;
	} else {
		return true;
	}
}

function validarFormEsqueci() {
	var email = $('#email');
	
	if (!checkMail(email.val())) {
		alert('Informe o endereço de e-mail corretamente!');
		return false;
		email.focus();
	} else {
		return true;
	}
}

function definirCapa(id) {
	if (confirm('Confirma a definição da foto como capa do álbum?')) {
		$('#action').val('definirCapa');
		$('#codfoto').val(id);
		$('#form').submit();
	}
}

addLoadEvent(createExternalLinks);

addLoadEvent(function() {
	$('.numeric').keypress(function(event) {
		if (event.charCode && (event.charCode < 48 || event.charCode > 57)) {
			event.preventDefault();
		}
	})
});

