var cidadeSelecionada;
var modulo;
var pagina;
var id_ped;
modulo = 'modulos/painel/layouts/';
msgIncluidoSucesso 	= "Dados 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 abreLay(pag,filtro) 
	{
		var param;
		if (filtro != null)
		{
			param = '&filtro='+filtro;
		}
		pagina = pag;
		include(modulo+'lista.layout.php','pagina='+pag+param,'lista');
	}

	function zeraCamposLay()
	{
		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á layouts cadastrados para este pedido.'
	}

// 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('legenda').value = '';
					
					document.getElementById('aguardeUpload').style.display = 'none';
					abreFotos(document.getElementById('id').value);
				}
				if (obj[0].firstChild.nodeValue == '3') 
				{
					document.getElementById('foto').value = '';
					document.getElementById('legenda').value = '';
					
					document.getElementById('aguardeUpload').style.display = 'none';
					abreFotos(document.getElementById('id').value);
				}
			}
		}
		else { setTimeout('executar(modulo+"bd.insereFoto.php","",addFotoReturn)',500); }
	}
}


function addArq()
{
	var id 		= 	document.getElementById('id');
	var arquivo = 	document.getElementById('arquivo');
		document.getElementById('aguardeUpload').style.display = '';
		document.cad_arq.submit();
		executar(modulo+'bd.insereArquivo.php','',addArqReturn);
}
// verifica se está retornando um XML com mensagem.
function addArqReturn()
{
	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('arquivo').value = '';
					location.href = 'interna.php?comando=painel/layouts';
				}
				if (obj[0].firstChild.nodeValue == '3') 
				{
					document.getElementById('arquivo').value = '';
					document.getElementById('aguardeUpload').style.display = 'none';
					document.getElementById('lista_arq').style.display = '';
					include(modulo+'lista_arquivos.php','','lista_arq');
				}
				if (obj[0].firstChild.nodeValue == '0') 
				{
					alert('Houve um erro durante a inclusão desta imagem.\nPor favor tente novamente mais tarde');	
				}
			}
		}
		else { setTimeout('executar(modulo+"bd.insereArquivo.php","",addArqReturn)',500); }
	}
}

function listArq() {
    document.getElementById('lista_arq').style.display = '';	
   	include(modulo+'lista_arquivos.php','','lista_arq');
}
// função que exibe fotos no div.
function abreFotos(id)
{
	id_ped = 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');
			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_ += "<img title =\"Ampliar\" src='imagens/icones/lupa.gif' width=16 height=16 border=0 style='float:right; margin-top:3px; margin-right:3px; cursor:pointer;' onclick=\"ampliaFoto('"+imagem+"');\">";
				div_ += "<input type='text' value='"+legenda+"' name='novaLegenda"+i+"' id='novaLegenda"+i+"' style='width:120px' title='Editar Legenda'/>"
				div_ += "</div></div>";

	
				td.innerHTML = div_+"<img id='imgf_"+i+"' src='imagem.php?imagem=imagens/layouts/"+imagem+"&tam=90&tipo=1&xy=0' style='cursor:pointer; border:1px solid #fff' onclick=\"abreLeg('"+i+"','"+id+"','"+legenda+"')\" height=90 width=90>";
				j++;
			}
		}
		else
		{ 
		   fotos.innerHTML = 'N&atilde;o h&aacute; layouts cadastrados para este pedido.'; 
		}
		buscarPedidosLay(id_ped);
	}
}

// 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 este layout deste pedido?")) {
		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 deste layout.\nPor favor tente novamente mais tarde.'); return false; }
	}
}

function showFormFoto() {
	var tema = document.getElementById('tema');
	if(tema.value) {
	   document.getElementById('id').value = tema.value;	
	   document.getElementById('form_foto').style.display = '';	
	   abreFotos(tema.value);
	}
	else {
	   document.getElementById('form_foto').style.display = 'none';	
	}
}

function limparCombo(combo,inicio)
{
	var tamanho=combo.options.length;
	for (i=tamanho-1;i>=inicio;i--)
		combo.remove(i) ;
}

function addCombo(valor,texto,combo) {
	var opcao = new Option(texto, valor);
    combo.options[combo.length] = opcao;
}

function showPedidos(id) {
	if (id) {
		document.getElementById('pedido').options[document.getElementById('pedido').selectedIndex].text = 'Aguarde...'; 
		executar(modulo+'bd.getPedidos.php','id='+id,showPedidosRe);
	}
}
function showPedidosRe() {
	if (xhReq.readyState == 4) {
		limparCombo(document.getElementById('pedido'),0);
		addCombo('0','Selecione um Pedido',document.getElementById('pedido'));
		if (xhReq.responseXML) {
			obj = xhReq.responseXML.getElementsByTagName('pedido');
			for (i =0; i < obj.length; i++) {
				id 		= obj[i].getElementsByTagName('id')[0].firstChild.nodeValue;
				nome 	= unescape(obj[i].getElementsByTagName('desc')[0].firstChild.nodeValue);
				addCombo(id,nome,document.getElementById('pedido'));
			}
		}
	}
}

function showForm() {
   document.getElementById('id').value = document.getElementById('pedido').value;	
   if (  document.getElementById('id').value > 0 ) {
   document.getElementById('form_foto').style.display = '';
   document.getElementById('form_arquivo').style.display = '';
   abreFotos(document.getElementById('id').value);
   }
}

function ampliaFoto(img) {
   executar(modulo+"bd.mostraDados.php",'imagem='+img,ampliaFotoRe);
}	

function ampliaFotoRe() {
	if (xhReq.readyState == 4)
	{
		retorno = xhReq.responseXML;
		if (retorno != null)
		{
			obj = retorno.getElementsByTagName('dados');
			var altura;
			var largura;
			var imagem;
			var Xlargura = obj[0].getElementsByTagName("largura")[0].firstChild;
			var Xaltura  = obj[0].getElementsByTagName("altura")[0].firstChild;
			var Ximagem  = obj[0].getElementsByTagName("imagem")[0].firstChild;
			
			altura       = (Xaltura	!= null?unescape(Xaltura.nodeValue):'');
			largura      = (Xlargura!= null?unescape(Xlargura.nodeValue):'');
			imagem       = (Ximagem	!= null?unescape(Ximagem.nodeValue):'');
			largura      = parseInt(largura,10) + 10;
			altura 		 = parseInt(altura,10) + 10;
			var url      = "imagens/layouts/"+imagem;
			//window.open(url,"foto","width='"+largura+"', height='"+altura+"'");
			mostrarImagem(imagem,altura,largura);
		}
		else { alert("Erro"); }
	}
}

function excluirArq(id)
{
	if (confirm("Deseja realmente excluir este arquivo?")) {
		executar(modulo+"bd.deletaArquivo.php",'id='+id,deletaArqRe);
	}
	else { return false; }
}
function deletaArqRe()
{
	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 
					location.href = 'interna.php?comando=painel/layouts';
				}
				else { erro = true; }
			}
			else { erro = true; }
		}
		else { erro = true; }
		if (erro == true) { alert('Ocorreu um erro durante a remoção deste layout.\nPor favor tente novamente mais tarde.'); return false; }
	}
}
function buscarPedidosLay(id) {
   document.getElementById('lista_pedidos_lay').style.display = '';
   include(modulo+'lista_pedidos.php','id='+id,'lista_pedidos_lay');
}

function carregarItensLay(id) {
	var mostra = document.getElementById('lista_itens_busca_lay');
	if(mostra.style.display == 'none') {
		mostra.style.display = '';	
		include(modulo+'lista_item.php','id='+id,'lista_itens_busca_lay');
	}
	else {
	   mostra.style.display = 'none';	
	}
}

