// - Compatível com MSIE e Netscape.
////////////////////////////////////////////////////////////////////////////////// 

//Muda Cor da tabela
	function MudaCor(tabela,box,todosBox,Modo,Total_Reg){
		if (Total_Reg == "31"){
			var Total_reg = "30";
		}
		if (todosBox == "Todos"){
			for (i = 0; i < Total_Reg; i++)

					if (document.FormUinet.selecionar.checked == true){
						document.getElementById('tb_'+i).className = 'TabonClick';
					}else{
						if (Modo == "sim"){
							document.getElementById('tb_'+i).className = '';
						}else{
							document.getElementById('tb_'+i).className = 'TabnoClick';
					}
			}
		}else{			

			if ( eval('document.FormUinet.'+box+'.checked') == true)
				document.getElementById(tabela).className = 'TabonClick';
			else
					if (Modo == "sim"){
						document.getElementById(tabela).className = '';
					}else{
						document.getElementById(tabela).className = 'TabnoClick';
					}
		}   
	}		


//Redireciona default

	function FechaPop(retorno){
		window.opener.location = 'default.php?logoff=sair&session.abandon&retorno='+retorno;
		window.close();

		}


//Drop-Down do ver projetos
	function BuscaGeral(){
		if (FormBusca.palavraBusca.value == ""){
			alert("Você precisa escrever uma palavra para fazer uma busca. Tente outra vez !!!");
			return (false);
		}
		return (true);
	}
	

//Barra de status do explorer
	
	
//PopAjuda , tamanho padrão

	function PopAjuda(topico,modulo){
		window.open('ajuda.php?topico='+topico+'&modulo='+modulo,'Ajuda','width=600,height=300');
	}


//Popup que abra a tela de lembrança de senha

	function EscqueciSenha(){
		window.open('Entrada/esqueci.php','EsqueciSenha','width=500,height=250');
	}

//Popup Relogar

	function PopRelogar(retorno){
//		window.open('../relogar.php?retorno='+retorno,'Relogar','width=600,height=400');
		window.location = '../relogar.php?retorno='+retorno;		
	}

//Popup Configuravel

	function PopConf(url,nome,tamanho){
		oWindow = window.open(url,nome,tamanho);
		//Posicao da janela no browser.
		oWindow.moveTo(300,80);
	}

//Popup padrão

	function PopPadrao(url,nome){
		window.open(url,nome,'width=600,height=400');
	}


//Função que seleciona varios campos de uma so vez.

	function mudacheck(campo, quanto, flag) 
	{
		for (i = 0; i < quanto; i++) 
			if (campo[i].disabled == false){
				campo[i].checked = flag; 
			}
	} 

	function Validacao() {
		assunto_vazio=1;
		for (var i = 0; i < document.FormUinet.a.length; i++) {
			if (document.FormUinet.a[i].checked == true) {
				assunto_vazio=0;
				i = document.FormUinet.a.length;
			}
		}

		return true;
	}


//Função que verifica se algum campo foi selecionado para exclusao
	function VerificaExclusao(){
		contaexc	= 1
		strPK		= ''
		for (o = 1; o < document.FormUinet.CheckExcluir.length; o++){
			if (document.FormUinet.CheckExcluir[o].checked && document.FormUinet.CheckExcluir[o].disabled == false ){
				strPK = document.FormUinet.CheckExcluir[o].value+','+strPK
				contaexc++;
			}}
			contaexc = contaexc -1;
			if (contaexc != 0){
				var name = confirm("Você tem certeza que deseja realizar esta ação em "+contaexc+" registro(s) selecionado(s) ?")
				if (name == 1){
					return (true);
			    }else{
					mudacheck(document.FormUinet.CheckExcluir, document.FormUinet.CheckExcluir.length, false);
					document.FormUinet.selecionar.checked = false;
					for (n = 0; n < document.FormUinet.CheckExcluir.length-1; n++){
						document.getElementById('tb_'+n).className = 'TabnoClick';
					}
					return (false);
				}
			}else{
				alert("É necessário selecionar pelo menos um registro !");
				return (false);
			}
	}

	
	
//Função que verifica se algum campo foi selecionado
	function VerificaBloqueio(){
		contaexc	= 1
		strPK		= ''
		for (o = 1; o < document.FormUinet.CheckBloqueio.length; o++){
			if (document.FormUinet.CheckBloqueio[o].checked){
				strPK = document.FormUinet.CheckBloqueio[o].value+','+strPK
				contaexc++;
			}}
			contaexc = contaexc -1;
			if (contaexc != 0){
				var name = confirm("Você tem certeza que deseja bloquear permanentemente o(s) "+contaexc+" registro(s) selecionado(s) ?")
				if (name == 1){
					return (true);
			    }else{
					mudacheck(document.FormUinet.CheckBloqueio, document.FormUinet.CheckBloqueio.length, false);
					document.FormUinet.selecionar.checked = false;
					return (false);
				}
			}else{
				alert("E necessário selecionar um registro !!!");
				return (false);
			}
	}


//-------------------------------------------------------------
//Para validar o input da HORA com o evento : onblur

function ValidarHora(obj_hora){ 
//Pega o id do objeto.
var Id_hora = document.getElementById(obj_hora);
//Pega o valor do objeto.
var Hora = Id_hora.value;

	
	if (Hora.length == 5){	

		hrs=Hora.substring(0,2); 
		min=Hora.substring(3,5);
		//seg=Hora.substring(6,9); 
		
	  //alert('hrs '+ hrs); 
	  //alert('min '+ min); 
	  //alert('seg '+ seg); 
	  	  
		if( hrs>23 || min>59 || hrs<0 || min<0 ){ 		
			alert("Atenção, a hora está incorreta!"); 
			document.getElementById(obj_hora).value = '';
			document.getElementById(obj_hora).focus();
			return false; 
		} 
	}else if(Hora.length != 0){
		alert("Atenção, a hora está incorreta!"); 
		document.getElementById(obj_hora).value = '';
		document.getElementById(obj_hora).focus();
		return false; 
	}
	

	return Hora; 
} 


//-------------------------------------------------------------
//Para validar o input da DATA como o evento : onblur

function check_date(field) 
{

var checkstr = "0123456789"; 
var DateField = field; 
var Datevalue = ""; 
var DateTemp = ""; 
var seperator = "/"; 
var day; 
var month; 
var year; 
var leap = 0; 
var err = 0; 
var i; 
err = 0; 
DateValue = DateField.value; 

/* Deletando todos os caracteres exceto o 0..9 */ 
for (i = 0; i < DateValue.length; i++) 
{ 
if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) 
{ 
DateTemp = DateTemp + DateValue.substr(i,1); 
} 
} 
DateValue = DateTemp; 
/* Exectutando a data para 8 digitos - string*/ 
/* if entrada do ano com 2-digitos / exemplo 20xx */ 
if (DateValue.length == 6) 
{ 
DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); 
} 
if (DateValue.length != 8) 
{ 
err = 19; 
} 
/* Se o ano for errado = 0000 */ 
year = DateValue.substr(4,4); 
if (year == 0) 
{ 
err = 20; 
} 
/* Validando o mês*/ 
month = DateValue.substr(2,2); 
if ((month < 1) || (month > 12)) 
{ 
err = 21; 
} 
/* Validando o dia*/ 
day = DateValue.substr(0,2); 
if (day < 1) 
{ 
err = 22; 
} 
/* Validando ano Bissexto / fevereiro / dia */ 
if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) 
{ 
leap = 1; 
} 
if ((month == 2) && (leap == 1) && (day > 29)) 
{ 
err = 23; 
} 
if ((month == 2) && (leap != 1) && (day > 28)) 
{ 
err = 24; 
} 
/* Validando o mês */ 
if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) 
{ 
err = 25; 
} 
if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) 
{ 
err = 26; 
} 
/* if 00 houvendo entrada, sem erros */ 
if ((day == 0) && (month == 0) && (year == 00)) 
{ 
err = 0; day = ""; month = ""; year = ""; seperator = ""; 
} 
/* if sem erros, escrevo a data completa no Input-Field (e.x. 13/12/2001) */ 
if (err == 0) 
{ 
DateField.value = day + seperator + month + seperator + year; 
} 
/* Mensagem de erro if err != 0 */ 
else 
{ 
alert("Atenção, a data está incorreta!"); 
DateField.select(); 
DateField.focus();
} 
}

//-------------------------------------------------------------
//Para validar o input da DATA como o evento : onKeyUp

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
var keyCode = (isNN) ? e.which : e.keyCode; 
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(input.value.length >= len && !containsElement(filter,keyCode)) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}
function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}

//-------------------------------------------------------------
//Para validar o input da DATA como o evento : onkeypress

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
	nTecla = evtKeyPress.keyCode; 
}else{ // Nestcape
	nTecla = evtKeyPress.which;
}

sValue = objForm[strField].value;

// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
bolMask = ((sMask.charAt(i) == ":") || (sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

if (bolMask) {
sCod += sMask.charAt(i);
mskLen++; }
else {
sCod += sValue.charAt(nCount);
nCount++;
}

i++;
}

objForm[strField].value = sCod;

if (nTecla != 8) { // backspace
if (sMask.charAt(i-1) == "9") { // apenas números...
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
return true;
} }
else {
return true;
}
}

//-------------------------------------------------------------
//Para validar um campo inteiro como o evento : onkeypress

function JavaInteiro()
{

if(document.all) { // Internet Explorer
	if(((event.keyCode>=0x30)&&(event.keyCode<=0x39))||(event.keyCode==8)||(event.keyCode==13))
	{
	return true;
	}
	event.keyCode=0;
}
else{ // Nestcape
	if(((event.which>=0x30)&&(event.which<=0x39))||(event.which==8)||(event.which==13))
	{
	return true;
	}
	event.which=0;
}
}

//---------------------------------------------------------------
//Validacao de senha.
function valida_senha()
{
	campo = document.getElementById("senha_hash");
	document.getElementById("senha_ok").value="";
	if(campo.value.length<6){
		alert('A senha deve ter no mínimo 6 dígitos !');
		document.getElementById('v_senha_ok').style.display='';
		campo.focus();
		return;
	}

	if (!/^[a-zA-Z]{1}[\w\@\&\%\*\-\.\/\:\!\=]{0,250}$/.test(campo.value)){
		alert('A senha possui caracteres inválidos, ou não foi iniciada com uma letra !');
		document.getElementById('v_senha_ok').style.display='';
		campo.focus();
		return;
	}

	var i; 
	var num = 0, carac = 0;

	for (i = 0; i < campo.value.length; i++){
		var c = campo.value.charAt(i);
		// ha um numero
		if (((c >= "0") && (c <= "9")))
			num++;
		if (((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")))
			carac++;
	}

	if (num < 3 || carac == 0){
		alert("A senha deve conter letras e números (mínimo 3 números) !"); 
		document.getElementById('v_senha_ok').style.display='';
		campo.focus();	
		return;
	}

	if (/(1234|4321)/.test(campo.value)){
		alert("A senha não pode conter os seqüenciais 1234 ou 4321 !");
		document.getElementById('v_senha_ok').style.display='';
		campo.focus();
		return;
	}

	s = campo.value
	hoje = new Date()
	ano = hoje.getYear()

	for (f=-2; f<=2; f++){
		n = s.indexOf(ano + f,0)
		if (n > -1){
			alert('Não é permitido colocar o ano como senha !');
			document.getElementById('v_senha_ok').style.display='';
			campo.focus();
			return;
		}
	}
	document.getElementById('v_senha_ok').style.display='none';
	document.getElementById("senha_ok").value="ok";
}

//--------------------------------------------------------------------
//Validacao de controles.

function ValidarControles()
{
	var b = true;
	for(i=0; i<valida.length; i++)
	{
		var controle = document.getElementById(valida[i].value);
		if(controle.value=="")
		{
			if(b)
			{
				alert(valida[i].text);
				if(controle.type!="hidden")
					controle.focus();
			}

			if(document.getElementById("v_"+valida[i].value)!=null)
				document.getElementById("v_"+valida[i].value).style.display='';
			b = false;
		}
		else
			if(document.getElementById("v_"+valida[i].value)!=null)
				document.getElementById("v_"+valida[i].value).style.display='none';
	}
	return b;
}

//--------------------------------------------------------------------
//Validacao de data.
function ValidaData(valor)
{
/*	alert( "Não tem barra: "+(valor.indexOf("/")<=0) );
	alert( "Tem menos de 2 barras: "+(valor.split("/").length<3) );
	alert( "Tem mais de 31 dias: "+(parseInt(valor.split("/")[0])>31) );
	alert( "Tem menos de 1 dia:"+(parseInt(valor.split("/")[0])<1) )
	alert( "Tem mais de 12 meses: "+(parseInt(valor.split("/")[1])>12) );
	alert( "Tem menos de 1 meses:"+(parseInt(valor.split("/")[1])<1) );
	alert( "O ano tem um número de caracteres diferente de 2 ou 4:"+(valor.split("/")[2].length!=4 && valor.split("/")[2].length!=2) );
	alert( "O ano é numérico:"+ (Inteiro(valor.split("/")[2])) );
*/
	if(valor.indexOf("/")<=0 || valor.split("/").length<3)
		return false;
	else
	{
		if(valor.split("/")[0].charAt(0)=="0")
			valor=valor.split("/")[0].charAt(1)+"/"+valor.split("/")[1]+"/"+valor.split("/")[2];
		if(valor.split("/")[1].charAt(0)=="0")
			valor=valor.split("/")[0]+"/"+valor.split("/")[1].charAt(1)+"/"+valor.split("/")[2];
		if(parseInt(valor.split("/")[0])>31 || parseInt(valor.split("/")[0])<1 || parseInt(valor.split("/")[1])>12 || parseInt(valor.split("/")[1])<1 || (valor.split("/")[2].length!=4 && valor.split("/")[2].length!=2) || !Inteiro(valor.split("/")[2]))
			return false;

		return true;
	}
}

//--------------------------------------------------------------------
//Validacao de inteiros - utilizado na funcao : ValidaData();
function Inteiro(valor)
{
	for(i=0; i<valor.length; i++)
	{
		if(isNaN(parseInt(valor.charAt(i))))
			return false;
	}
	return true;
}

//--------------------------------------------------------------------

//================================================================================================
// Verifica periodo final é menor que inicial.
//================================================================================================	

function IntervaloDatas(obj_data_entrada, obj_hora_entrada, obj_data_saida, obj_hora_saida){
//Pega o id do objeto.
var Id_data_entrada = document.getElementById(obj_data_entrada);
//Pega o valor do objeto.
var data_entrada = Id_data_entrada.value;
//Inicializa hora entrada.
hora_entrada = ''; 

//Pega o id do objeto.
var Id_data_saida = document.getElementById(obj_data_saida);
//Pega o valor do objeto.
var data_saida = Id_data_saida.value;
//Inicializa hora saida.
hora_saida = '';

	//Verifica se e para comparar horas.
	if((obj_hora_entrada != '')&&(obj_hora_saida != '')){
		//Pega o id do objeto.
		var Id_hora_entrada = document.getElementById(obj_hora_entrada);
		//Pega o valor do objeto.
		var hora_entrada = Id_hora_entrada.value;
		//Pega o id do objeto.
		var Id_hora_saida = document.getElementById(obj_hora_saida);
		//Pega o valor do objeto.
		var hora_saida = Id_hora_saida.value;
	}	

	 if ((data_entrada != '') && (data_saida != ''))
	 {
		var str_data_inicial = data_entrada;
		var str_data_final = data_saida;
	
		//Verifica se é uma data com horas ou nao.
		if((hora_entrada != '') && (hora_saida != '')){
			var str_hora_inicial = hora_entrada;
			var str_hora_final = hora_saida;		
			
			data_inicial = new Date(str_data_inicial.substr(6,4),str_data_inicial.substr(3,2)-1,str_data_inicial.substr(0,2),str_hora_inicial.substr(0,2),str_hora_inicial.substr(3,2),str_hora_inicial.substr(6,2));
			data_final = new Date(str_data_final.substr(6,4),str_data_final.substr(3,2)-1,str_data_final.substr(0,2),str_hora_final.substr(0,2),str_hora_final.substr(3,2),str_hora_final.substr(6,2));
		}else{
			data_inicial = new Date(str_data_inicial.substr(6,4),str_data_inicial.substr(3,2)-1,str_data_inicial.substr(0,2));
			data_final = new Date(str_data_final.substr(6,4),str_data_final.substr(3,2)-1,str_data_final.substr(0,2));	
		}
			
	/*	alert(str_data_inicial.substr(6,4));
		alert(str_data_inicial.substr(3,2)-1);
		alert(str_data_inicial.substr(0,2));
		alert(data_inicial);
		alert(str_data_final.substr(6,4));
		alert(str_data_final.substr(3,2)-1);
		alert(str_data_final.substr(0,2));
		alert(data_final);			

		alert(data_inicial);
		alert(data_final);
	*/		
		 //Compara datas.
		 if (data_inicial > data_final)
		  {
			alert('A data de saída não pode ser menor que a data de entrada!');
			//Limpa data de saida.
			document.getElementById(obj_data_saida).value = '';		
			if (hora_saida != ''){
				//Limpa hora de saida.
				document.getElementById(obj_hora_saida).value = '';					
			}
			document.getElementById(obj_data_saida).focus();
			return(false);
		  }     
			
		return(true);
	 }
}	 
//================================================================================================

//================================================================================================
// Mensagem depois do post dos dados.
//================================================================================================	
function espera()
{
	document.getElementById("enviar").innerHTML="Processando...<br><br>";
	document.getElementById("enviar2").style.display='none';
	
	return true;
}
//================================================================================================

//================================================================================================
// Mensagem se o post dos dados obteve algum erro.
//================================================================================================	
function espera_Post()
{
	document.getElementById("enviar").style.display='none';
	document.getElementById("enviar2").style.display='';
		
	return false;
}
//================================================================================================

//================================================================================================
//Exibe o codigo do flash caso se o tipo do arquivo for FLASH.
// arquivo : tipo de arquivo imagem ou flash.
// caminho : caminho relativo do arquivo.
// campo_valor : id do campo com o nome do arquivo.
// campo_destino : id do campo onde sera armazenado o codigo html do arquivo flash.
//================================================================================================
function TipoArquivo(arquivo, caminho, campo_valor, campo_destino){
	if (arquivo == "flash"){
		document.getElementById(campo_destino).value = '<object type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"  width="100%" height="100%"><param name="movie" value="'+caminho+'/'+document.getElementById(campo_valor).value+'"><param name="quality" value="high"><param name="wmode" value="transparent"><embed src="'+caminho+'/'+document.getElementById(campo_valor).value+'" quality="high" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="100%" height="100%"></embed></object> '
	}
}	
//================================================================================================