var cidadeSelecionada;
var modulo;
var pagina;
modulo = 'modulos/galeria/';
msgIncluidoSucesso 	= "Dados da galeria salvos com sucesso.\n";
msgIncluidoErro 	= "Ocorreu um erro durante a inclusão destas informações.\nPor favor tente novamente mais tarde.";
msgEditarErro = "Ocorreu um erro na leitura desta Informação.\nPor favor tente novamente mais tarde.";
msgStatusErro = "Ocorreu um erro durante a mudança deste status.\nPor favor tente novamente mais tarde."
msgDeleteErro = "Ocorreu um erro durante a exclusão destes dados.\nPor favor tente novamente mais tarde."


 
function exibir_foto(id){
include("frame_galeria.php",'id_foto='+id,'frame_galeria');	
}

function galeria_mini(pag, id_galeria) {
	document.getElementById('frame_galeria_mini').innerHTML = '<div align="center"><br><img src="../imagens/icones/black_preload.gif" width="16" height="16" align="absmiddle"> Aguarde o carregamento dos produtos.<br></div>';
	include("frame_galeria_mini.php",'pagina='+pag+'&id_galeria='+id_galeria,'frame_galeria_mini');
}  

/*
	Função que limpa os campos e adiciona um id temporario.
	Chamada ao clicar em Limpar Campos
*/
	function novo(id_usuario)
	{
		executar(modulo+'bd.novo.php','id='+id_usuario,novoRe);
	}
	function novoRe()
	{
		if (xhReq.readyState == 4)
		{
			resposta = xhReq.responseXML;
			if (resposta)
			{
				obj = resposta.getElementsByTagName('retorno');
				// variaveis do XML
				Xmsg 	= obj[0].getElementsByTagName('mensagem')[0].firstChild;
				Xid		= obj[0].getElementsByTagName('id')[0].firstChild;
				if (Xmsg.nodeValue == '1')
				{
					zeraCampos();
					document.getElementById('id').value = Xid.value;
				}
				else { alert(msgNovoErro); }
			}
			else { alert(msgNovoErro); }
		}
	}

/*
	Função que inclui lista de dados no div 'lista' 
	usar variavel filtro e pegar na lista a filtragem por POST[filtro].
*/
	function abre(pag,filtro) 
	{
		var param;
		if (filtro != null)
		{
			param = '&filtro='+filtro;
		}
		pagina = pag;
		include(modulo+'lista.php','pagina='+pag+param,'lista');
	}
	
/* 
	Função que adiciona item no banco de dados.
*/
	function salvar()
	{
		var titulo 		= document.getElementById('titulo');
		var descricao 	= document.getElementById('descricao');
		var data		= document.getElementById('data');
		var ativo		= document.getElementById('ativo');
		/* valida campos conforme regras de negocio */
		if (titulo.value == '') { alert('Por favor preencha o campo Título'); titulo.focus(); return false; }
		else if (descricao.value == '') { alert('Por favor preencha o campo Descrição'); descricao.focus(); return false; }
		else if (data.value == '') { alert('Por favor preencha o campo Data'); data.focus(); return false; }
		else {
			// envia via ajax o formulario, função de retorno é o salvarReturn
			xhSend(modulo+'bd.salva.php','cad',salvarReturn);
			// função que desabilita todos campos do formulário
			mudaCampos(document.getElementById('cad'),'0');	
			document.getElementById('botao').innerHTML = 'Salvando...';
		}
	}
	function salvarReturn()
	{
		if (xhReq.readyState == 4)
		{
			retorno = xhReq.responseXML;
			// se o retorno for um XML, então começa a agir.
			if (retorno != null)
			{
				obj = retorno.getElementsByTagName('retorno');
				// verifica o campo mensagem do XML, se for 1 é que inseriu OK, caso contrário, é erro.
				if (obj[0].getElementsByTagName("mensagem")[0].firstChild.nodeValue == 1)
				{
					alert(msgIncluidoSucesso);
					// zera os campos do formulário
					zeraCampos();
					// insere a variavel temporario (id temporario no XML) no campo hidden ID.
					document.getElementById('id').value = obj[0].getElementsByTagName("temporario")[0].firstChild.nodeValue;
				}
				else { alert(msgIncluidoErro); }
			}
			else { alert(msgIncluidoErro); }
			mudaCampos(document.getElementById('cad'),'1');
			// da refresh na lista
			abre(pagina);
		}
	}

/*
	Função de editar dados
*/

	function editar(id) 
	{
		/* 	Vai até o arquivo e retorna um XML com os dados do registro
			Passado via POST o id do registro */
		executar(modulo+'bd.get.php','id='+id,editarReturn);
	}
	function editarReturn()
	{
		if (xhReq.readyState == 4)
		{
			resposta = xhReq.responseXML;
			if (resposta)
			{
				obj = resposta.getElementsByTagName('dados');
				if (obj.length >= '1')
				{
					/* Variáveis do Formulário */
					var id 			= document.getElementById('id');
					var titulo 		= document.getElementById('titulo');
					var descricao 	= document.getElementById('descricao');
					var data		= document.getElementById('data');
					var ativo		= document.getElementById('ativo');
					/* Variáveis do XML */
					var Xid			= obj[0].getElementsByTagName('id')[0].firstChild;
					var Xtitulo 	= obj[0].getElementsByTagName('titulo')[0].firstChild;
					var Xdescricao 	= obj[0].getElementsByTagName('descricao')[0].firstChild;
					var Xdata		= obj[0].getElementsByTagName('data')[0].firstChild;
					var Xativo		= obj[0].getElementsByTagName('ativo')[0].firstChild;
					

					titulo.value 	= (Xtitulo 		!= null?unescape(Xtitulo.nodeValue):'');
					descricao.value = (Xdescricao 	!= null?unescape(Xdescricao.nodeValue):'');
					data.value		= (Xdata 		!= null?Xdata.nodeValue.substr(0,10):'');
					ativo.checked	= (Xativo.nodeValue == '1'?true:false);
					id.value		= Xid.nodeValue;
					// lista fotos no div
					abreFotos(id.value);
				}
				else { alert(msgEditarErro); }
			}
			else { alert(msgEditarErro); }
		}
	}

/*
	Função que altera status
*/

	function alteraStatus(id)
	{
		// exibe uma imagem transparente para impedir que o usuário clique duas vezes
		document.getElementById('imgAguarde').style.display = '';
		executar(modulo+'bd.status.php','id='+id,alteraStatusRe);
	}
	function alteraStatusRe()
	{
		if (xhReq.readyState == 4)
		{
			resposta = xhReq.responseXML;
			if (resposta)
			{
				obj = resposta.getElementsByTagName('retorno');
				// pega variaveis do XML
				var Xmsg = obj[0].getElementsByTagName('mensagem')[0].firstChild;

				var Xid = obj[0].getElementsByTagName('id')[0].firstChild;
				var Xstatus = obj[0].getElementsByTagName('novoStatus')[0].firstChild;
				
				// se o retorno for 1 quer dizer que foi Ok
				if (Xmsg.nodeValue == '1') {
					// se o status for 0, quer dizer que passou a ser inativo
					if (Xstatus.nodeValue == '0') { imagem = 'inativo.gif'; }
					else { imagem = 'ativo.gif'; }
					document.getElementById('img'+Xid.nodeValue).src = '../imagens/icones/'+imagem;
				}
				else
				{
					alert(msgStatusErro);	
				}
			}
			else
			{
				alert(msgStatusErro);	
			}
			document.getElementById('imgAguarde').style.display = 'none';
		}
	}
/*
	Função de deletar dados.
*/
	function deletar(id)
	{
		document.getElementById('imgAguarde').style.display = '';
		executar(modulo+'bd.delete.php','id='+id,deletarRe);
	}
	function deletarRe()
	{
		if (xhReq.readyState == 4)
		{
			resposta = xhReq.responseXML;
			if (resposta)
			{
				obj 	= resposta.getElementsByTagName('retorno');
				Xmsg 	= obj[0].getElementsByTagName('mensagem')[0].firstChild;
				if (Xmsg.nodeValue == '1')
				{
					// lista dados apartir da pagina que estava
					abre(pagina);
				}
				else
				{
					alert(msgDeleteErro);
				}
			}
			else
			{
				alert(msgDeleteErro);
			}
			document.getElementById('imgAguarde').style.display = 'none';
		}
	}

/*
	Função que limpa o formulário
*/
	function zeraCampos()
	{
		var titulo 		= document.getElementById('titulo');
		var descricao 	= document.getElementById('descricao');
		var data		= document.getElementById('data');
		var ativo		= document.getElementById('ativo');
		// div com listagem dos thumbs
		var fotos		= document.getElementById('fotos');
		titulo.value 	= '';
		descricao.value = '';
		data.value 		= '';
		ativo.checked	= false;
		document.getElementById('botao').innerHTML = 'Gravar';
		fotos.innerHTML = 'Não há fotos cadastradas para esta Galeria de Fotos'
	}

/*

Fim da manipulação dos estados/cidades

*/


/*

Manipulação de fotos com o DIV fotos

*/

// funcão que adiciona fotos
function addFoto()
{
	var id 		= 	document.getElementById('id');
	var foto 	= 	document.getElementById('foto');
	// se a extensao for jpg, submete o formulario para o iframe
	// e joga para a função addFotoReturn via ajax, que verifica se há a sessão registrada já.
	// se houver, trata
	if (verificaextensao(foto,'Foto','jpg|JPG|jpeg|JPEG') == true)
	{
		document.getElementById('aguardeUpload').style.display = '';
		document.cad.submit();
		executar(modulo+'bd.insereFoto.php','',addFotoReturn);
	}
	else
	{ return false; }		
}
// verifica se está retornando um XML com mensagem.
function addFotoReturn()
{
	if (xhReq.readyState == 4)
	{
		if (xhReq.responseText != '')
		{
			resposta = xhReq.responseXML;
			obj = resposta.getElementsByTagName('retorno');
			if (obj[0].firstChild) 
			{
				if (obj[0].firstChild.nodeValue == '1') 
				{
					document.getElementById('foto').value = '';
					document.getElementById('aguardeUpload').style.display = 'none';
					abreFotos(document.getElementById('id').value);
				}
				else
				{
					alert('Houve um erro durante a inclusão desta imagem.\nPor favor tente novamente mais tarde');	
				}
			}
		}
		else { setTimeout('executar(modulo+"bd.insereFoto.php","",addFotoReturn)',500); }
	}
}

// função que exibe fotos no div.
function abreFotos(id)
{
	executar(modulo+'bd.getFotos.php','id='+id,abreFotosRe);
}

function abreFotosRe()
{
	if (xhReq.readyState == 4)
	{
		var fotos = document.getElementById('fotos')
		resposta = xhReq.responseXML;
		if (resposta && resposta.getElementsByTagName('fotos').length > 0) 
		{
			var j = 0;
			obj = resposta.getElementsByTagName('fotos');
			//alert('tem fotos');
			fotos.innerHTML = "<table id='tbFotos'></table>";
			var tbFotos = document.getElementById('tbFotos');

			for (i = 0; i < obj.length; i++)
			{
				imagem 	= obj[i].getElementsByTagName('imagem')[0].firstChild.nodeValue;
				legenda = (obj[i].getElementsByTagName('legenda')[0].firstChild != null?unescape(obj[i].getElementsByTagName('legenda')[0].firstChild.nodeValue):"");
				id		= obj[i].getElementsByTagName('id')[0].firstChild.nodeValue;
				if (j == 3 || i == 0) 
				{
					numRows = tbFotos.rows.length;
					var row = tbFotos.insertRow(numRows);
					j = 0;
				}
				var td=row.insertCell(j);
				var div_ = "<div id='info_"+i+"' style='margin-left:91px;padding:6px; position:absolute; background-color:#f2f2f2; width:180px; display:none; border:1px solid #3366CC; border-left: 0px; z-index:50;'>";
				div_ += "<div style='float:right; margin-bottom:5px; font-size:10px; cursor:pointer' onclick=\"fecharDivLeg("+i+");\">Fechar [x]</div>";
				div_ += "<div style='float:left; margin-bottom:5px; font-size:10px; cursor:pointer'>Legenda:</div>";
				div_ += "<div style='clear:both'>";
				div_ += "<img title=\"Excluir\" src='../imagens/icones/lixeira.gif' width=16 height=16 border=0 style='float:right; margin-top:3px; cursor:pointer;' onClick=\"deletaFoto('"+id+"');\">";
				div_ += "<img title =\"Salvar\" src='../imagens/icones/salvar.gif' width=16 height=16 border=0 style='float:right; margin-top:3px; margin-right:3px; cursor:pointer;' onClick=\"alteraLegenda('"+id+"',document.getElementById(\'novaLegenda"+i+"\').value,"+i+")\">";
//				div_ += "<input type='text' value='"+legenda+"' name='novaLegenda"+i+"' id='novaLegenda"+i+"' onblur=\"alteraLegenda('"+id+"',this.value,"+i+")\" style='width:130px' title='Editar Legenda'/>"
				div_ += "<input type='text' value='"+legenda+"' name='novaLegenda"+i+"' id='novaLegenda"+i+"' style='width:130px' title='Editar Legenda'/>"
				div_ += "</div></div>";

	
				td.innerHTML = div_+"<img id='imgf_"+i+"' src='../imagem.php?imagem=imagens/galeria/"+imagem+"&tam=90&tipo=1&xy=0' style='cursor:pointer; border:1px solid #fff' onclick=\"abreLeg('"+i+"','"+id+"','"+legenda+"')\">";
				j++;
			}
		}
		else
		{ fotos.innerHTML = 'N&atilde;o h&aacute; fotos cadastradas para esta Galeria de Fotos'; }
	}
}

// exibe div de legenda criado pela leitura das fotos
// abre e coloca uma borda.
function abreLeg(id,id_foto,legenda)
{
	i = 0;
	while (document.getElementById('info_'+i))
	 {
		if (id != i) {
			document.getElementById('info_'+i).style.display = 'none';
			document.getElementById('imgf_'+i).style.border = '1px solid #fff';
		}
		else { 
			document.getElementById('info_'+i).style.display = '';
			document.getElementById('imgf_'+i).style.border = '1px solid #3366CC'; 
		}
		i++;
	 }

}

// fecha o div da legenda e muda a cor da borda
function fecharDivLeg(i)
{
	document.getElementById('info_'+i).style.display = 'none'; 
	document.getElementById('imgf_'+i).style.border = '1px solid #fff'; 
}


// função que altera a legenda da foto.
var campoLegenda;
function alteraLegenda(id,legenda,i)
{
	campoLegenda = document.getElementById("novaLegenda"+i);
	campoLegenda.disabled = true;
	executar(modulo+'bd.troca.legenda.php','id='+id+'&legenda='+escape(legenda),alteraLegendaRe);
}
function alteraLegendaRe()
{
	if (xhReq.readyState == 4)
	{
		resposta = xhReq.responseXML;
		if (resposta != null)
		{
			campoLegenda.disabled = false;
		}
	}
}
// função para deletar foto
function deletaFoto(id_foto)
{
	if (confirm("Deseja realmente excluir esta foto da galeria?")) {
		executar(modulo+"bd.deletaFoto.php",'id='+id_foto,deletaFotoRe);
	}
	else { return false; }
}
function deletaFotoRe()
{
	var erro = false;
	if (xhReq.readyState == 4)
	{
		resposta = xhReq.responseXML;
		if (resposta)
		{
			obj = resposta.getElementsByTagName('retorno');
			if (obj[0].getElementsByTagName('msg')[0].firstChild) {
				if (obj[0].getElementsByTagName('msg')[0].firstChild.nodeValue == '1') {
					// abre as fotos do 
					abreFotos(obj[0].getElementsByTagName('id')[0].firstChild.nodeValue);
				}
				else { erro = true; }
			}
			else { erro = true; }
		}
		else { erro = true; }
		if (erro == true) { alert('Ocorreu um erro durante a remoção desta foto.\nPor favor tente novamente mais tarde.'); return false; }
	}
}
