/* ---------------------------------------------------------------------- *\
  GERAL.js
  Funções que poderão ser acessadas de qualquer arquivo
  Ex: Validação, PopUp, Sair do sistema
\* ---------------------------------------------------------------------- */


/* ---------------------------------------------------------------------- *\
  Função    : deletarRegistros (campos,divResposta,funcRetorno,cpoOpt)
  Descrição : Deleta Registros 
\* ---------------------------------------------------------------------- */
function deletarRegistros (campos,divResposta,funcRetorno,cpoOpt) {
	campoOpt = document.getElementById(cpoOpt);
	//divResposta = document.getElementById(divResposta);
	if (campoOpt.value == "Escolha") {msgErro(divResposta,"ESCOLHA ALGUMA A&Ccedil;&Atilde;O");}
	else {
		// Ver se tem algum checado
		if (campos == 'undefined' || campos == '') {return false;}
		else {
			// VER QUANTOS ESTÃO MARCADOS
			var marcados = 0;
			var params = "";
			// ==== VER QTOS ESTÃO CHECADOS
			for ( var i = 0; i < document.getElementsByName(campos+"[]" ).length; i++ ) { 
				if (document.getElementsByName(campos+"[]")[i].checked == true) {
					marcados++;
					params+="&idDelete"+i+"="+document.getElementsByName(campos+"[]")[i].value;
				}
			}
			if (marcados==0) {msgErro(divResposta,"ESCOLHA ALGUM &Iacute;TEM");return false;}
			// FIM MARCADOS
			// FAZER A PERGUNTA
			pergunta = input_box=confirm("TEM CERTEZA?");
			if (pergunta == false) { return false;	}
			
			connAjax();
			if(ajax) {
				ajax.open("POST", "act_geral.php?action=deletarRegistro&idFunction="+campoOpt.value, true);
				ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				ajax.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate");
				ajax.setRequestHeader("Cache-Control","post-check=0, pre-check=0");
				ajax.setRequestHeader("Pragma", "no-cache");
				
				ajax.onreadystatechange = function() {
					if(ajax.readyState == 1) { document.getElementById(divResposta).innerHTML = carregando(); }
					if(ajax.readyState == 4 ) {
						if (ajax.status == 200) {
							var resultado = ajax.responseText;
							resultado = resultado.replace(/\+/g," "); // Resolve problema de acentuação
							resultado = unescape(resultado);
							// Tratamento:
							var Erro = trataErro (resultado);
							if (Erro != true) {
								document.getElementById(divResposta).innerHTML = resultado.substring((Erro+5),resultado.length);
							} 
							// - Sucesso
							else { 
								eval(funcRetorno);
							}
						} 
						else { alert('erro no carregamento'); }
					}
				} // fim função onreadystatechange
				ajax.send(params);
			} // fim if
		} //Else (campos existem)
	} // else (tem alguma ação selecionada)
} // = fim deletar registro


/* ---------------------------------------------------------------------- *\
  Função    : paginar(acao)
  Descrição : Paginar, mais uma ou menos 1
\* ---------------------------------------------------------------------- */
function paginar(acao) {
	document.getElementById('pg').value = Number(document.getElementById('pg').value) + acao; 
} // FIM DE PAGINAR

/* ---------------------------------------------------------------------- *\
  Função    : pular(acao)
  Descrição : Pula direto para a página XX
\* ---------------------------------------------------------------------- */
function pular(acao) {
	document.getElementById('pg').value = acao;
} // FIM PULAR

/* ---------------------------------------------------------------------- *\
  Função    : checaTudo(obj,nome)
  Descrição : Marca todos os checkbox de uma lista
\* ---------------------------------------------------------------------- */
function checaTudo(obj,nome) {
	if (obj == 'undefined' || obj == '' || nome == '' || nome == 'undefined') {return false;}
	else {
		if (obj.checked == true ) { 
			for ( var i = 0; i < document.getElementsByName(nome+"[]" ).length; i++ ) { document.getElementsByName(nome+"[]")[i].checked = true; }
		} else { 
			for ( var i = 0; i < document.getElementsByName(nome+"[]" ).length; i++ ) { document.getElementsByName(nome+"[]")[i].checked = false; }
		}
	}	
} // FIM CHECAR TUDO


/* ---------------------------------------------------------------------- *\
  Função    : escreveData()
  Descrição : Escrever data no formato padrão
\* ---------------------------------------------------------------------- */
function escreveData() {
	var d=new Date()
	var weekday=new Array("Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado")
	var monthname=new Array("Janeiro","Fevereiro","Março","Abril","Março","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro")
	document.write(weekday[d.getDay()] + ", ")
	document.write(d.getDate() + " de ")
	document.write(monthname[d.getMonth()] + " de ")
	document.write(d.getFullYear())
}

/* ---------------------------------------------------------------------- *\
  Função    : isNumber(numero)
  Descrição : Verificar se campo é numérico ou não
\* ---------------------------------------------------------------------- */
function isNumber(numero){
	var CaractereInvalido = false;
	for (i=0; i < numero.length; i++){
		var Caractere = numero.charAt(i);
			if(Caractere != "." && Caractere != "," && Caractere != "-"){
				if (isNaN(parseInt(Caractere))) CaractereInvalido = true;
		}
	}
	return !CaractereInvalido;
}

/* ---------------------------------------------------------------------- *\
  Função    : popUp(janela,pagina,largura,altura,scrolls)
  Descrição : Abre pop up centralizado
\* ---------------------------------------------------------------------- */
function popUp(janela,pagina,largura,altura,scrolls)	{
	if (scrolls == 'undefined' || scrolls == null) {scrolls = 'no';}
	else {scrolls = scrolls;}

	var altura = altura;
	var largura = largura;
	var a = (screen.height/2)-(altura/2);
	var l = (screen.width/2)-(largura/2);
	window.open(pagina,janela,'width='+largura+',height='+altura+',top='+a+',left='+l+',scrollbars='+scrolls+',statusbar=0,resizable=no');
}

/* ---------------------------------------------------------------------- *\
  Função    : pergunta (perg,destino)
  Descrição : Faz pergunta e depois vai pra uma página
\* ---------------------------------------------------------------------- */
function pergunta (perg,destino) {
	input_box=confirm(perg);
	if (input_box==true) {document.location = destino;}
}

/* ---------------------------------------------------------------------- *\
  Função    : sair ()
  Descrição : Sair do sistema
\* ---------------------------------------------------------------------- */
function sair () {
	input_box=confirm("DESEJA MESMO SAIR?");
	if (input_box) {document.location.href='guia_logoff.php';}
}

/* ---------------------------------------------------------------------- *\
  Função    : desabCampo(campo,sit)
  Descrição : Desab/hab campo
\* ---------------------------------------------------------------------- */
function desabCampo (campo,sit) {
	if (!(document.getElementById(campo) == null || document.getElementById(campo) == 'undefined')) {
		document.getElementById(campo).className='formulario_box';
		if (sit == 'on') {	document.getElementById(campo).disabled = "";	}
		else { document.getElementById(campo).disabled = "disabled";  }
	}
}

/* ---------------------------------------------------------------------- *\
  Função    : _CloseOnEsc()
  Descrição : Fechar o Pop Up ao dar Esc
\* ---------------------------------------------------------------------- */
function _CloseOnEsc() {
	if (event.keyCode == 27) { window.close(); return; }
}

/* ---------------------------------------------------------------------- *\
  Função    : HandleError(message, url, line)
  Descrição : Controle de Erro, caso ocorra um erro é exibido por Pop Up
\* ---------------------------------------------------------------------- */
function HandleError(message, url, line) {
  var str = "Um erro ocorreu na sua página." + "\n\n"
  + "Linha: " + line + "\n Erro:" + message;
  alert(str);
  window.close();
  return true;
}
