function MarcaAbaSelecionada(Aba){
	for(var i=1;i<=document.getElementById('Abas').getElementsByTagName('div').length;i++){
		// Testa de for uma aba de opção, tem uma no final de complemento
		//  Muda o classe da Aba selecionada para 'DivOp'
		if(document.getElementById('Aba'+i)) document.getElementById('Aba'+i).className = 'Aba';
		// Muda o classe da Aba anterior para 'DivOpSelectRight'
		if(i+1 == Aba.id.substr(5,1)) document.getElementById('DivOp'+i).className = 'AbaSelectRight';
	}
	Aba.className = 'AbaSelect';
}

function Win(imagem){
	width = 450;
	height = 360;
	var top = (screen.availHeight - height)/2;
	var left = (screen.width - width)/2;
	window.open('','','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width='+width+',height='+height+',left='+left+',top='+top+'');
}
var browser = navigator.appName;
function AjustaTamanhoDivPrincipal(){
	document.getElementById('Menu').style.width = 180;
	document.getElementById('Menu').style.height = (document.body.clientHeight) - 185;
	document.getElementById('Principal').style.height = (document.body.clientHeight) - 170;
	document.getElementById('Principal').style['max-height'] = (document.body.clientHeight) - 200;
	
	// Corrige um erro no layout para o Internet Explorer
    if(browser == "Microsoft Internet Explorer") document.getElementById('Principal').style.width = 0;
	document.getElementById('Principal').style.width = (document.body.clientWidth) - 230;
}

function MenuOver(Menu){
	if(Menu.className != 'MenuSelected'){
		Menu.className = 'MenuOver';
	}
}
function MenuOut_(Menu){
	if(Menu.className != 'MenuSelected'){
		Menu.className = 'Menu';
	}
}
function SubMenuOver(Menu){
	Menu.className = 'SubMenuOpOver';
}
function SubMenuOut_(Menu){
	Menu.className = 'SubMenuOp';
}
function AbrirMenu(Menu){
	var SubMenu = 'SubMenu'+Menu;
	var Menu = 'Menu'+Menu;
	if(document.getElementById(SubMenu).style.visibility == '' || document.getElementById(SubMenu).style.visibility == 'hidden'){
		var altura = document.getElementById(SubMenu).offsetHeight;
		document.getElementById(SubMenu).style.height = 0;
		document.getElementById(SubMenu).style.position = 'relative';
		document.getElementById(SubMenu).style.visibility = 'visible';
		for(var i=0;i<=altura;i++) window.setTimeout('document.getElementById("'+SubMenu+'").style.height = '+i,i*3);
		//document.getElementById(SubMenu).className = 'SubMenuSelected';
		document.getElementById(Menu).className = 'MenuSelected';
	}else{
		var altura = document.getElementById(SubMenu).offsetHeight;
		for(var i=altura;i>=0;i--) window.setTimeout('document.getElementById("'+SubMenu+'").style.height = '+i,(altura-i)*3);
		window.setTimeout('document.getElementById("'+SubMenu+'").style.position = "absolute";document.getElementById("'+SubMenu+'").style.visibility = "hidden";document.getElementById("'+SubMenu+'").style.height ='+altura,altura*3);
		//document.getElementById(SubMenu).style.visibility = 'hidden';
		//document.getElementById(SubMenu).className = 'SubMenu';
		document.getElementById(Menu).className = 'MenuOver';
	}
}

function AtualizaCaminho(Menu,Programa,Aba){
	DivMenu = document.getElementById('CaminhoMenu');
	DivPrograma = document.getElementById('CaminhoPrograma');
	DivAba = document.getElementById('CaminhoAba');
	if(Menu){
		DivMenu.innerHTML = '/ ' + Menu;
		DivPrograma.innerHTML = '';
		DivAba.innerHTML = '';
	}
	
	if(Programa){
		DivPrograma.innerHTML = '/ ' + Programa;
		DivAba.innerHTML = '';
	}
	
	if(Aba) DivAba.innerHTML = '/ ' + Aba;
}

function PrincipalLimpa(){
	document.getElementById('Principal').innerHTML = '<br><br><br><br><center>Aguarde, carregando dados ...<br><br><img src="img/loading.gif" width="107" height="13" border="0"></center>';
}

function ConfirmarExcluir(Url){
	if (confirm('Confirmar exclusão.\nDeseja excluir este dado definitivamente?\nSe outras informações dependerem desta, não será possível finalzar a exclusão.\nSe não for possível excluí-la, exclua primeiro as suas dependências e depois esta.')){
		//alert(Url);
		SelecionaAba('',Url);
	}
}

// Máscara para Telefone
function MaskTel(campo){
    var valor = campo.value;
    var tamanho = valor.length;
    if ((tamanho==1) && (valor!='(')){
		campo.value = '('+valor;
    }else if (tamanho==3){
    	campo.value = valor+') ';
    }else if (tamanho==9){
    	campo.value = valor+'-';
    }
}

// Máscara para CPF
function MaskCPF(campo){
    var valor = campo.value;
    var tamanho = valor.length;
    if ((tamanho==3) || (tamanho==7)){
		campo.value = valor+'.';
    }else if(tamanho==11){
    	campo.value = valor+'-';
    }
}

// Máscara para CEP
function MaskCEP(campo){
    var valor = campo.value;
    var tamanho = valor.length;
    if (tamanho==5){
		campo.value = valor+'-';
    }
}

// Máscara para Data
function MaskData(campo){
    var valor = campo.value;
    var tamanho = valor.length;
    if ((tamanho==2) || (tamanho==5)){
		campo.value = valor+'/';
    }
}

// Máscara para Valor
function MaskValor(campo){
    var valor = campo.value;
    var tamanho = valor.length;
    campo.value = valor.replace(".","");
    if ((tamanho>=3)){
    	valor = valor.replace(".","");
    	var inteiro = valor.substr(0,valor.length-2);
    	var centavos = valor.substr(valor.length-2,valor.length);
    	valor = inteiro+'.'+centavos;
		campo.value = valor;
    }
}

// MouseOver e MousOut nas céulas dos grids
function Row0Over(cel){
	if(cel.style.backgroundColor != '#0a246a') cel.style.backgroundColor='#DDEEFF';
}
function Row0Out(cel){
	if(cel.style.backgroundColor != '#0a246a') cel.style.backgroundColor='#FFFFFF';
}
function Row1Over(cel){
	if(cel.style.backgroundColor != '#0a246a') cel.style.backgroundColor='#DDEEFF';
}
function Row1Out(cel){
	if(cel.style.backgroundColor != '#0a246a') cel.style.backgroundColor='#FCFAF6';
}


/**
 * Ajax - XMLRequest
 */
// 'Logado' Usada para o javascript verificar se o usuário está ou não logado
var Logado = false;
function createRequestObject(){
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer") ro = new ActiveXObject("Microsoft.XMLHTTP");
    else ro = new XMLHttpRequest();
    return ro;
}
var http = createRequestObject();

function SelecionaProgramaGrupoFamiliarUrbano(grupo_id){
  	//var httpG = createRequestObject();
	PrincipalLimpa();
	//SelecionaPrograma('32&grupo_id='+grupo_id);
	httpP.open('get', '../../../sistema/funcoes_ajax.php?op=seleciona_programa&programa_codigo=32&grupo_id='+grupo_id);
    httpP.onreadystatechange = function (){
		if(httpP.readyState == 4){
			dados = httpP.responseText.split('.x.');
			if(dados[0]){
				document.getElementById('Abas').innerHTML = dados[0];
			}
			document.getElementById('Principal').innerHTML = dados[1];
			window.setTimeout("AjustaTamanhoDivPrincipal();",10);
		}
	}
    httpP.send(null);
    /**/
}

function SelecionaProgramaGrupoFamiliar(grupo_id){
  	//var httpG = createRequestObject();
	PrincipalLimpa();
	//SelecionaPrograma('2&grupo_id='+grupo_id);
	httpP.open('get', '../../../sistema/funcoes_ajax.php?op=seleciona_programa&programa_codigo=2&grupo_id='+grupo_id);
    httpP.onreadystatechange = function (){
		if(httpP.readyState == 4){
			dados = httpP.responseText.split('.x.');
			if(dados[0]){
				document.getElementById('Abas').innerHTML = dados[0];
			}
			document.getElementById('Principal').innerHTML = dados[1];
			window.setTimeout("AjustaTamanhoDivPrincipal();",10);
		}
	}
    httpP.send(null);
    /**/
}
function SelecionaAbaIframe(Aba,Url){
  	if(Aba) MarcaAbaSelecionada(Aba);
  	document.getElementById('Principal').innerHTML = Url;
}

var httpP = createRequestObject();
function SelecionaPrograma(ProgramaCodigo){
	PrincipalLimpa();
	httpP.open('get', '../../../sistema/funcoes_ajax.php?op=seleciona_programa&programa_codigo='+ProgramaCodigo);
    httpP.onreadystatechange = function (){
		if(httpP.readyState == 4){
			dados = httpP.responseText.split('.x.');
			if(dados[0]){
				document.getElementById('Abas').innerHTML = dados[0];
			}
			document.getElementById('Principal').innerHTML = dados[1];
			window.setTimeout("AjustaTamanhoDivPrincipal();",10);
		}
	}
    httpP.send(null);
}

function SelecionaAba(Aba,Programa){
  	var httpA = createRequestObject();
	PrincipalLimpa();
	httpA.open('get', 'funcoes_ajax.php?op=seleciona_aba&programa_codigo='+Programa);
    httpA.onreadystatechange = function (){
		if(httpA.readyState == 4){
			dados = httpA.responseText.split('.x.');
			if(dados[0]){
				document.getElementById('Abas').innerHTML = dados[0];
			}
			document.getElementById('Principal').innerHTML = dados[1];
			window.setTimeout("AjustaTamanhoDivPrincipal();",10);
		}
	}
    httpA.send(null);
    if(Aba){
	    document.getElementById('CaminhoAba').innerHTML = '/ '+Aba.innerHTML;
	    // Varre todas as divs q estão dentro da div id="DivOp"
		for(var i=1;i<=document.getElementById('Abas').getElementsByTagName('div').length;i++){
			// Testa de for uma aba de opção, tem uma no final de complemento
			//  Muda o classe da Aba selecionada para 'DivOp'
			if(document.getElementById('Aba'+i)) document.getElementById('Aba'+i).className = 'Aba';
			// Muda o classe da Aba anterior para 'DivOpSelectRight'
			if(i+1 == Aba.id.substr(5,1)) document.getElementById('DivOp'+i).className = 'AbaSelectRight';
		}
		Aba.className = 'AbaSelect';
    }
}

// Por causa de conflitos dos XMLHTPRequests entre as requisições
// foi separada uma função de retorno para cada solicitação.
function SelecionaProgramaAbaRetorno(){
  	//alert('Aba Selecionada');
	if(http.readyState == 4){
		dados = http.responseText.split('.x.');
		if(dados[0]){
			document.getElementById('Abas').innerHTML = dados[0];
			if(dados[2]){
				document.getElementById('CaminhoMenu').innerHTML = '/ '+dados[2];
			}else{
				document.getElementById('CaminhoMenu').innerHTML = '';
				document.getElementById('CaminhoPrograma').innerHTML = '';
				document.getElementById('CaminhoAba').innerHTML = '';
			}
			if(dados[3]){
				document.getElementById('CaminhoPrograma').innerHTML = '/ '+dados[3];
			}else{
				document.getElementById('CaminhoPrograma').innerHTML = '';
				document.getElementById('CaminhoAba').innerHTML = '';
			}
			if(dados[4]){
				document.getElementById('CaminhoAba').innerHTML = '/ '+dados[4];
			}else{
				document.getElementById('CaminhoAba').innerHTML = '';
			}
		}
		document.getElementById('Principal').innerHTML = dados[1];
		window.setTimeout("AjustaTamanhoDivPrincipal();",10);
	}
}



function Index(){
  	var httpI = createRequestObject();
	PrincipalLimpa();
	httpI.open('get', 'funcoes_ajax.php');
    httpI.onreadystatechange = function (){
		if(httpI.readyState == 4){
			dados = httpI.responseText.split('.x.');
			document.getElementById('CaminhoMenu').innerHTML = '';
			document.getElementById('CaminhoPrograma').innerHTML = '';
			document.getElementById('CaminhoAba').innerHTML = '';
			if(!dados[0]) dados[0] = '...';
			document.getElementById('Usuario').innerHTML = dados[0];
			if(dados[1]) document.getElementById('Menu').innerHTML = dados[1];
			if(dados[2]) document.getElementById('Abas').innerHTML = dados[2];
			if(dados[3]) document.getElementById('Principal').innerHTML = dados[3];
		}
	}
    httpI.send(null);
}

var httpLog = createRequestObject();
function Login(form){
	if(form.LoginUsuario.value == ''){
		document.getElementById('LoginInf').className = 'Erro';
		document.getElementById('LoginInf').innerHTML = 'Por favor, informe o seu <b>Login</b>.';
		form.LoginUsuario.focus();
		setTimeout("document.getElementById('LoginInf').innerHTML = '';document.getElementById('LoginInf').className=''",2000);
		return false;
	}
	if(form.LoginSenha.value == ''){
		document.getElementById('LoginInf').className = 'Erro';
		document.getElementById('LoginInf').innerHTML = 'Por favor, informe a sua <b>Senha</b>.';
		form.LoginSenha.focus();
		setTimeout("document.getElementById('LoginInf').innerHTML = '';;document.getElementById('LoginInf').className=''",2000);
		return false;
	}
	document.getElementById('LoginInf').innerHTML = 'Criptografando, autenticando ...';
	httpLog.open('post', 'funcoes_ajax.php?op=login');
	httpLog.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    httpLog.onreadystatechange = function (){
		if(httpLog.readyState == 4){
			if(httpLog.responseText){
				document.getElementById('LoginInf').className = 'Erro';
				document.getElementById('LoginInf').innerHTML = httpLog.responseText;
				form.LoginSenha.value = '';
				form.LoginSenha.focus();
				setTimeout("document.getElementById('LoginInf').innerHTML = '';document.getElementById('LoginInf').className=''",2000);
			}else{
				Index();
			}
		}
	}
	httpLog.send('LoginUsuario='+form.LoginUsuario.value+'&LoginSenha='+form.LoginSenha.value);
    //return false;
}
function Logout(){
	httpLog.open('get', './funcoes_ajax.php?op=logout');
    httpLog.onreadystatechange = function (){
		if(httpLog.readyState == 4) Index();
	}
	httpLog.send(null);
}
function ProcuraNomeUsuario(login,DivIdRetorno){
	http.open('post', 'funcoes_ajax.php?op=procuranomeusuario&login='+login);
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.onreadystatechange = function (){
		if(http.readyState == 4){
			document.getElementById(DivIdRetorno).innerHTML = http.responseText;
		}
	}
	http.send('login='+login.value);
}

function Ajax(metodo,url,DivRetorno){
	PrincipalLimpa();
	http.open(metodo, url);
    http.onreadystatechange = function(){
		if(http.readyState == 4){
			document.getElementById(DivRetorno).innerHTML = http.responseText;
		}
	}
    http.send(null);
}

function SubmitForm(Campos,Url){
	http.open('post', 'funcoes_ajax.php?op=seleciona_programa&programa_codigo='+Url);
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.onreadystatechange = SelecionaProgramaAbaRetorno;
	http.send(Campos);
}

/**
 * Verficação de formulários
 */
function SubmitFormUsuario(Form,Url){
	if(Form.login.value == ''){
		alert("Por favor, informe o Login do usuário.");
		Form.login.focus();
		return false;
	}
	if(Form.Unome.value == ''){
		alert("Por favor, informe o Nome do usuário.");
		Form.Unome.focus();
		return false;
	}
	if(Form.enviarsenha.value){
		if(Form.senha.value == ''){
			alert("Por favor, preencha a Senha");
			Form.senha.focus();
			return false;
		}
		if(Form.senhaC.value == ''){
			alert("Por favor, preencha a Confirmação da Senha");
			Form.senhaC.focus();
			return false;
		}
		if(Form.senha.value != Form.senhaC.value){
			Form.senha.value = '';
			Form.senhaC.value = '';
			alert("A Senha e Confirmação de Senha devem ser iguais.");
			Form.senha.focus();
			return false;
		}
	}
	http.open('post', 'funcoes_ajax.php?op=seleciona_programa&programa_codigo='+Url);
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.onreadystatechange = SelecionaProgramaAbaRetorno;
    var perfis = Form.perfis.value.split(',');
    var perfis_selecionados = '';
    var marcado = '';
    for(i=0;i<perfis.length;i++){
    	if(Form['Perfil'+perfis[i]].checked) marcado = '1';
    	else marcado = '';
    	perfis_selecionados += '&perfil'+perfis[i]+'='+marcado;
    }
	http.send('login='+Form.login.value+'&nome='+Form.Unome.value+'&enviarsenha='+Form.enviarsenha.value+'&senha='+Form.senha.value+'&perfis='+Form.perfis.value+''+perfis_selecionados);
	return false;
}
function AlterarSenhaMostrar(){
	document.getElementById('AlterarSenha').style.position = 'relative';
	document.getElementById('AlterarSenha').style.visibility = 'visible';
	document.getElementById('LinkAlterarSenha').style.position = 'absolute';
	document.getElementById('LinkAlterarSenha').style.visibility = 'hidden';
	document.Usuario.enviarsenha.value = '1';
}
function AlterarSenhaEsconder(){
	document.getElementById('AlterarSenha').style.position = 'absolute';
	document.getElementById('AlterarSenha').style.visibility = 'hidden';
	document.getElementById('LinkAlterarSenha').style.position = 'relative';
	document.getElementById('LinkAlterarSenha').style.visibility = 'visible';
	document.Usuario.enviarsenha.value = '';
}


function SubmitFormProgramas(Form,Url){
	if(Form.titulo.value == ''){
		alert("Por favor, informe um Título para o programa.");
		Form.titulo.focus();
		return false;
	}
	if(Form.descri.value == ''){
		alert("Por favor, informe o nome do arquivo do programa.");
		Form.descri.focus();
		return false;
	}
	if(Form.menu_codigo.value == ''){
		alert("Por favor, selecione o menu a qual este programa pertencerá.");
		Form.menu_codigo.focus();
		return false;
	}
	http.open('post', 'funcoes_ajax.php?op=seleciona_programa&programa_codigo='+Url);
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.onreadystatechange = SelecionaProgramaAbaRetorno;
	var perfis = Form.perfis.value.split(',');
    var perfis_selecionados = '';
    var marcado = '';
    for(i=0;i<perfis.length;i++){
    	if(Form['Perfil'+perfis[i]].checked) marcado = '1';
    	else marcado = '';
    	perfis_selecionados += '&perfil'+perfis[i]+'='+marcado;
    }
    http.send('codigo_programa='+Form.codigo_programa.value+'&menu_codigo='+Form.menu_codigo.value+'&titulo='+Form.titulo.value+'&descri='+Form.descri.value+'&perfis='+Form.perfis.value+''+perfis_selecionados);
	return false;
}


function SubmitFormMenus(Form,Url){
	if(Form.descri.value == ''){
		alert("Por favor, informe um Título para o menu.");
		Form.descri.focus();
		return false;
	}
	http.open('post', 'funcoes_ajax.php?op=seleciona_programa&programa_codigo='+Url);
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.onreadystatechange = SelecionaProgramaAbaRetorno;
    http.send('codigo_menu='+Form.codigo_menu.value+'&descri='+Form.descri.value);
	return false;
}

function SubmitFormPerfis(Form,Url){
	if(Form.descri.value == ''){
		alert("Por favor, informe o Título do Perfil.");
		Form.descri.focus();
		return false;
	}
	http.open('post', 'funcoes_ajax.php?op=seleciona_programa&programa_codigo='+Url);
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.onreadystatechange = SelecionaProgramaAbaRetorno;
    http.send('codigo_perfil='+Form.codigo_perfil.value+'&descri='+Form.descri.value);
	return false;
}

/*
var fotos = createRequestObject();
// Seleciona Foto Principal
function SelecionaFoto(cod_foto){
   if (cod_foto){
	   fotos.open('get', 'funcoes_ajax.php?op=SelecionaFoto&cod_foto='+cod_foto); 
	   fotos.onreadystatechange = SelecionaFotoR; 
	   fotos.send(null);
   }
}
function SelecionaFotoR() {
   if(fotos.readyState == 4){
   		var retorno = fotos.responseText;
   		
   		// Separa a string pelo separador ".x.", entre a foto e a legenda
   		dados = retorno.split('.x.');
		
   		document.getElementById('FotoAmpliada').innerHTML = dados[0];
   		document.getElementById('FotoDescricao').innerHTML = dados[1];
   }
}
*/
