
	function avancar_analise_etapa4_tabela()
	{
		
		colunasSelecionadas = $("#select_colunas_info").val();
		aColunasSelecionadas = [];
		strColunas = "";
		for(i =0; i < colunasSelecionadas.length; i++)
		{
			for(j =0; j < colunas.length; j++)
			{
				if(colunas[j].nome == colunasSelecionadas[i])
				{
					if(strColunas != "")
					{
						strColunas += ",";
					}
					strColunas += "`"+colunas[j].nome+"`";
					//console.log(colunas[j].nome+" "+colunas[j].tipo_dado);
					aColunasSelecionadas.push({nome: colunas[j].nome, tipo: colunas[j].tipo_dado});
				}
			}
			strColunas.replaceAll("``","`");
		}
		colunas_view_vertical = "";
		colunas_valores_vertical = "";
		coluna_vertical = "";
		colunas_quebrar_parcial_analise_vertical = "";
		colunas_quebrar_media_parcial_analise_vertical = "";
		colunas_total_analise_vertical = "";
		colunas_media_analise_vertical = "";
		colunas_valores_media_parcial = "";
		colunas_valores_soma_parcial = "";
		colunas_sequencia_ordenacao = "";
		if(true)//tipo_analise == "tabela_vertical")
		{
			if($("#select_colunas_info").val() != null)
			{
				//colunas_view_vertical = $("#select_colunas_info").val().toString();
				for(k =0; k < $("#select_colunas_info").val().length; k++)
				{
					if(colunas_view_vertical != ""){colunas_view_vertical += ",";}
					colunas_view_vertical += "`"+$("#select_colunas_info").val()[k]+"`";
				}
				colunas_view_vertical.replaceAll("``","`");
				
			}
			if($("#select_sequenc_colunas_ordenar").val() != null)
			{
				//colunas_view_vertical = $("#select_colunas_info").val().toString();
				for(k =0; k < $("#select_sequenc_colunas_ordenar").val().length; k++)
				{
					if(colunas_sequencia_ordenacao != ""){colunas_sequencia_ordenacao += ",";}
					colunas_sequencia_ordenacao += "`"+$("#select_sequenc_colunas_ordenar").val()[k]+"`";
				}
				colunas_sequencia_ordenacao.replaceAll("``","`");
				
			}
			if($("#select_colunas_valores_vertical").val() != null)
			{
				//colunas_valores_vertical = $("#select_colunas_valores_vertical").val().toString();
				for(k =0; k < $("#select_colunas_valores_vertical").val().length; k++)
				{
					if(colunas_valores_vertical != ""){colunas_valores_vertical += ",";}
					colunas_valores_vertical += "`"+$("#select_colunas_valores_vertical").val()[k]+"`";
				}
				colunas_valores_vertical.replaceAll("``","`");
			}
			coluna_vertical = $("#select_coluna_vertical").val();
			if($("#select_colunas_quebra_parcial_vertical").val() != null)
			{
				//colunas_quebra_parcial_vertical = $("#select_colunas_quebra_parcial_vertical").val().toString();
				for(k =0; k < $("#select_colunas_quebra_parcial_vertical").val().length; k++)
				{
					if(colunas_quebrar_parcial_analise_vertical != ""){colunas_quebrar_parcial_analise_vertical += ",";}
					colunas_quebrar_parcial_analise_vertical += "`"+$("#select_colunas_quebra_parcial_vertical").val()[k]+"`";
				}
				colunas_quebrar_parcial_analise_vertical.replaceAll("``","`");
			}
			if($("#select_colunas_quebra_media_parcial_vertical").val() != null)
			{
				//colunas_quebra_parcial_vertical = $("#select_colunas_quebra_parcial_vertical").val().toString();
				for(k =0; k < $("#select_colunas_quebra_media_parcial_vertical").val().length; k++)
				{
					if(colunas_quebrar_media_parcial_analise_vertical != ""){colunas_quebrar_media_parcial_analise_vertical += ",";}
					colunas_quebrar_media_parcial_analise_vertical += "`"+$("#select_colunas_quebra_media_parcial_vertical").val()[k]+"`";
				}
				colunas_quebrar_media_parcial_analise_vertical.replaceAll("``","`");
			}
			if($("#select_colunas_total_vertical").val() != null)
			{
				//colunas_quebra_parcial_vertical = $("#select_colunas_quebra_parcial_vertical").val().toString();
				for(k =0; k < $("#select_colunas_total_vertical").val().length; k++)
				{
					if(colunas_total_analise_vertical != ""){colunas_total_analise_vertical += ",";}
					colunas_total_analise_vertical += "`"+$("#select_colunas_total_vertical").val()[k]+"`";
				}
				colunas_total_analise_vertical.replaceAll("``","`");
			}
			if($("#select_colunas_media_vertical").val() != null)
			{
				//colunas_quebra_parcial_vertical = $("#select_colunas_quebra_parcial_vertical").val().toString();
				for(k =0; k < $("#select_colunas_media_vertical").val().length; k++)
				{
					if(colunas_media_analise_vertical != ""){colunas_media_analise_vertical += ",";}
					colunas_media_analise_vertical += "`"+$("#select_colunas_media_vertical").val()[k]+"`";
				}
				colunas_media_analise_vertical.replaceAll("``","`");
			}
			if($("#select_colunas_val_soma_parcial").length > 0)
			{
				if($("#select_colunas_val_soma_parcial").val() != null)
				{
					//colunas_quebra_parcial_vertical = $("#select_colunas_quebra_parcial_vertical").val().toString();
					for(k =0; k < $("#select_colunas_val_soma_parcial").val().length; k++)
					{
						if(colunas_valores_soma_parcial != ""){colunas_valores_soma_parcial += ",";}
						colunas_valores_soma_parcial += "`"+$("#select_colunas_val_soma_parcial").val()[k]+"`";
					}
					colunas_valores_soma_parcial.replaceAll("``","`");
				}
				if($("#select_colunas_val_media_parcial").val() != null)
				{
					for(k =0; k < $("#select_colunas_val_media_parcial").val().length; k++)
					{
						if(colunas_valores_media_parcial != ""){colunas_valores_media_parcial += ",";}
						colunas_valores_media_parcial += "`"+$("#select_colunas_val_media_parcial").val()[k]+"`";
					}
					colunas_valores_media_parcial.replaceAll("``","`");
				}
			}
		}
		/*if(coluna_vertical == "" && colunas_valores_vertical == "")
		{
			query = " select "+strColunas+" from ("+$("#query").val()+") a";
			query += " order by "+strColunas
		}
		else if(coluna_vertical != "" && colunas_valores_vertical != "")
		{
			coluna_vertical = "`"+coluna_vertical+"`";
			query = " select "+strColunas+","+coluna_vertical+","+colunas_valores_vertical+" from ("+$("#query").val()+") a ";
			query += " order by "+strColunas
		}
		else if(colunas_valores_vertical != "" )
		{
			query = " select "+strColunas+", "+colunas_valores_vertical+" from ("+$("#query").val()+") a";
			query += " order by "+strColunas
		}
		else
		{
			query = $("#query").val();
		}*/
		
		//marcar colunas usadas
		for(i =0; i < colunas.length; i++)
		{
			if(colunas_valores_vertical.includes(colunas[i].nome.trim()) ||
			   coluna_vertical.includes(colunas[i].nome.trim()) ||
			   colunas_quebrar_parcial_analise_vertical.includes(colunas[i].nome.trim()) ||
			   colunas_quebrar_media_parcial_analise_vertical.includes(colunas[i].nome.trim()) ||
			   colunas_total_analise_vertical.includes(colunas[i].nome.trim()) ||
			   colunas_media_analise_vertical.includes(colunas[i].nome.trim()) ||
			   colunasSelecionadas.includes(colunas[i].nome.trim()) 
			)
			{
				colunas[i].oculto = false;
			}
			$('.linha_cor_dinamica').each(function(){
				//alert($(this).find('[name="col_valor"]').val())
				if($(this).find('[name="col_valor"]').length > 0)
				{
					//alert($(this).find('[name="col_valor"]').val())
					if($(this).find('[name="col_valor"]').val().trim() == colunas[i].nome.trim())
					{
						colunas[i].utilizada_para_calculo = true;
						if(colunas_valores_ocultas_para_calculo != "")
						{
							colunas_valores_ocultas_para_calculo += ",";
						}
						colunas_valores_ocultas_para_calculo += "`"+colunas[i].nome.trim()+"`";
					}
				}
			});
		}
		monta_tabela_agregacao();
		
		$("#etapa2").css("display", "none");
		$("#etapa3").css("display", "none");
		$("#etapa4").css("display", "block");
		
	}
	
	
	function sequenciar_colunas_conforme_escolhidas(colunas)
	{
		aColunasSequencial = [];
		aListaInfoArmazenada = listaInfoArmazenada.split(",");
		for(j =0; j < aListaInfoArmazenada.length; j++)
		{
			for(i =0; i < colunas.length; i++)
			{
				if(colunas[i].nome == aListaInfoArmazenada[j])
				{
					aColunasSequencial.push(colunas[i]);
				}
			}
		}
		aListaValArmazenada = listaInfoValoresArmazenada.split(",");
		for(j =0; j < aListaValArmazenada.length; j++)
		{
			for(i =0; i < colunas.length; i++)
			{
				if(colunas[i].nome == aListaValArmazenada[j])
				{
					aColunasSequencial.push(colunas[i]);
				}
			}
		}
		arrayLen = aColunasSequencial.length;
		for(i =0; i < colunas.length; i++)
		{
			achouNome = false;
			for(j =0; j < arrayLen; j++)
			{
				if(colunas[i].nome == aColunasSequencial[j].nome)
				{
					achouNome = true;
				}
			}
			if(! achouNome)
			{
				aColunasSequencial.push(colunas[i]);
			}
		}
		return aColunasSequencial;
	}
	$(".select2-container--default").click(function(){
		//reprocessar ao abrir os selects
	  atualiza_select_vertical()
	});
	function escolher_tipo_analise()
	{
		
		tipo_analise = "tabela";//$("#select_tipo_analise").val();
		$("#etapa2").css("display", "none");
		$("#etapa3").css("display", "block");
		//$("#etapa3").css("display", "block");
		
		alistaSeqColOrdenarArmazenada = listaSeqColOrdenarArmazenada.split(",");
		for(i =0; i < alistaSeqColOrdenarArmazenada.length; i++)
		{
			if(! $("#select_sequenc_colunas_ordenar").html().replaceAll('"',"").includes(">"+alistaSeqColOrdenarArmazenada[i]+"<"))
			{
				$("#select_sequenc_colunas_ordenar").append($('<option>', {
					value: alistaSeqColOrdenarArmazenada[i],
					text: alistaSeqColOrdenarArmazenada[i],
					"selected": true
				}));
			}
		}
		
		for(i =0; i < colunas.length; i++)
		{
			selected = false;
			if(listaInfoArmazenada.split(",").includes(colunas[i].nome))
			{
				selected = true;
			}
			if(! listaInfoValoresArmazenada.split(",").includes(colunas[i].nome) )
			{
				if(! $("#select_colunas_info").html().replaceAll('"',"").includes(">"+colunas[i].nome+"<"))
				{
					$("#select_colunas_info").append($('<option>', {
						value: colunas[i].nome,
						text: colunas[i].nome,
						"selected": selected
					}));
				}
			}
			
			
			if(! $("#select_sequenc_colunas_ordenar").html().replaceAll('"',"").includes(">"+colunas[i].nome+"<"))
			{
				$("#select_sequenc_colunas_ordenar").append($('<option>', {
					value: colunas[i].nome,
					text: colunas[i].nome,
					"selected": false
				}));
			}
			$("#select_sequenc_colunas_ordenar").select2({ width: '100%' });
			//abaixo codigo para colocar na sequencia de clique
			$("#select_sequenc_colunas_ordenar").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
			
			
			if(colunas[i].tipo_dado == "int" || colunas[i].tipo_dado == "float")
			{
				/*selected = false;
				if(listaQuebraTotFinalArmazenada.includes(colunas[i].nome))
				{
					selected = true;
				}
				$("#select_colunas_total_vertical").append($('<option>', {
					value: colunas[i].nome,
					text: colunas[i].nome,
					"selected": selected
				}));
				selected = false;
				if(listaQuebraMediaFialArmazenada.includes(colunas[i].nome))
				{
					selected = true;
				}
				$("#select_colunas_media_vertical").append($('<option>', {
					value: colunas[i].nome,
					text: colunas[i].nome,
					"selected": selected
				}));*/
			}
			if(listaInfoArmazenada.split(",").includes(colunas[i].nome))
			{
				selected = false;
				if(listaQuebraTotParcialArmazenada.split(",").includes(colunas[i].nome))
				{
					selected = true;
				}
				if(! $("#select_colunas_quebra_parcial_vertical").html().replaceAll('"',"").includes(">"+colunas[i].nome+"<"))
				{
					$("#select_colunas_quebra_parcial_vertical").append($('<option>', {
						value: colunas[i].nome,
						text: colunas[i].nome,
						"selected": selected
					}));
				}
				selected = false;
				if(listaQuebraMediaParcialArmazenada.split(",").includes(colunas[i].nome))
				{
					selected = true;
				}
				if(! $("#select_colunas_quebra_media_parcial_vertical").html().replaceAll('"',"").includes(">"+colunas[i].nome+"<"))
				{
					$("#select_colunas_quebra_media_parcial_vertical").append($('<option>', {
						value: colunas[i].nome,
						text: colunas[i].nome,
						"selected": selected
					}));
				}
					
				
			}
			//var newOption = new Option(colunas[i].nome, colunas[i].nome, false, false);
			//$("#select_colunas_info").append(newOption).trigger('change');
		}
		
		if(true)//tipo_analise == "tabela_vertical")
		{
			
			for(i =0; i < colunas.length; i++)
			{
				//if(colunas[i].tipo_dado != "int" && colunas[i].tipo_dado != "float")
				//{
					selected = false;
					if(listaColunaVerticalInfoArmazenada.split(",").includes(colunas[i].nome))
					{
						selected = true;
					}
					if(! listaInfoValoresArmazenada.split(",").includes(colunas[i].nome) && ! $("#select_coluna_vertical").html().replaceAll('"',"").includes(">"+colunas[i].nome+"<"))
					{
						$("#select_coluna_vertical").append($('<option>', {
							value: colunas[i].nome,
							text: colunas[i].nome,
							"selected": selected
						}));
					}
					
				//}
				
				if(colunas[i].tipo_dado == "int" || colunas[i].tipo_dado == "float")
				{
					selected = false;
					if(listaInfoValoresArmazenada.split(",").includes(colunas[i].nome))
					{
						selected = true;
					}
					if(! $("#select_colunas_valores_vertical").html().replaceAll('"',"").includes(">"+colunas[i].nome+"<"))
					{
						$("#select_colunas_valores_vertical").append($('<option>', {
							value: colunas[i].nome,
							text: colunas[i].nome,
							"selected": selected
						}));
					}
					
				}
			}
			
		}
		///recriar os select2
		crar_select2_com_todas_as_configs();
		atualiza_select_valores_vertical();
		
	}
	/*
	function atualiza_figura_tabelaSimples()
	{
		html='<table class="tabela_view">';
		tabela = $("#select_colunas_info").val();
		$("#tabela_simples_div").append("<thead><tr>");
		if(tabela.length > 0)
		{
			for(i =0; i < tabela.length; i++)
			{
				html+="<td>"+tabela[i]+"</td>";
			}
		}
		html+="</tr></thead>";
		
		html+= "<tbody>";
		htmlBody = "<tr>";
		if(tabela.length > 0)
		{
			for(i =0; i < tabela.length; i++)
			{
				htmlBody+= "<td>-</td>";
			}
		}
		htmlBody += "</tr>";
		htmlBody += htmlBody;
		html+=htmlBody+"</tbody>";
		
		html+='</table>';
		
		$("#tabela_simples_div").html(html);
	}*/
	
	function finalizar_analise_tabela()
	{
		
		
		//Filtros 
		/*lista_filtros = [];
		$('.linha_filtro').each(function(){
			filtro = {tipo: $(this).find('[name="tipo_filtro"]').val(), id: $(this).find('[name="id_filtro"]').val(),
			descricao: $(this).find('[name="descricao_filtro"]').val(), obrigatorio: $(this).find('[name="obrigatorio_filtro"]').val(),
			tabela_buscar: $(this).find('[name="tabela_buscar_filtro"]').val(), coluna_buscar: $(this).find('[name="coluna_buscar_filtro"]').val(),
			codigo: $(this).find('[name="codigo_filtro"]').val(),
			tipo_calculo_data_filtro: $(this).find('[name="tipo_calculo_data_filtro"]').val(),
			valor_calculo_data_filtro: $(this).find('[name="valor_calculo_data_filtro"]').val(),
			tipo_dia_data_filtro: $(this).find('[name="tipo_dia_data_filtro"]').val()
			}
			lista_filtros.push(filtro);
		});*/
		
		query = $("#query").val();
		analise = {nome: $("#nome_analise").val(), query: query, colunas_view_vertical: colunas_view_vertical, 
				colunas_valores_vertical: colunas_valores_vertical, coluna_vertical: coluna_vertical,
				colunas_quebrar_parcial_analise_vertical: colunas_quebrar_parcial_analise_vertical, 
				colunas_quebrar_media_parcial_analise_vertical: colunas_quebrar_media_parcial_analise_vertical,
				colunas_total_analise_vertical: colunas_total_analise_vertical,
				colunas_media_analise_vertical: colunas_media_analise_vertical,
				codigo: $("#codigo_analise").val(),
				lista_filtros : lista_filtros, colunas: colunas, conexao: $("#conexao").val(),
				modelo_dados: $("#modelo_dados").val(),
				"area": $("#area").val(), "exibir_em_analise": $("#exibir_em_analise").val(),
				colunas_valores_soma_parcial: colunas_valores_soma_parcial,
				colunas_valores_media_parcial: colunas_valores_media_parcial,
				colunas_sequencia_ordenacao: colunas_sequencia_ordenacao
			};
		abrir_modal_aviso("<b>Aguarde ...</b>");	
		//console.log(analise);
		$.post("src/controller/Bi_analiseControllerUser.php?mod=salvar_analise", 
			analise, 
			function (retorno)
			{
				fechar_modal_aviso();
				if(! retorno.status)
				{
					alert(retorno.mensagem);
				}
				else
				{
					$("#codigo_analise").val(retorno.codigo);
					if(confirm("Sucesso! Código "+retorno.codigo+". Deseja visualizar a análise?"))
					{
						window.open('Analise_view.php?analise='+retorno.codigo, '_blank');
					}
					$(".modal_fechar").click();
						
					//alert(retorno.mensagem);
				}
			},'json'
		);	
		
	}
	
	function setValoresTotais()
	{
		//alert($("#select_colunas_media_vertical").val());
		if( $("#select_colunas_total_vertical").val() != null)
		{
			listaQuebraTotFinalArmazenada = $("#select_colunas_total_vertical").val();
		}
		else
		{
			listaQuebraTotFinalArmazenada = [];
		}
		if( $("#select_colunas_media_vertical").val() != null)
		{
			listaQuebraMediaFialArmazenada = $("#select_colunas_media_vertical").val();
		}
		else
		{
			listaQuebraMediaFialArmazenada = [];
		}
		///NOVOS
		if( $("#select_colunas_val_soma_parcial").val() != null)
		{
			listacolunas_valores_soma_parcialArmazenada = $("#select_colunas_val_soma_parcial").val();
		}
		else
		{
			listacolunas_valores_soma_parcialArmazenada = [];
		}
		if( $("#select_colunas_val_media_parcial").val() != null)
		{
			listacolunas_valores_media_parcialArmazenada = $("#select_colunas_val_media_parcial").val();
		}
		else
		{
			listacolunas_valores_media_parcialArmazenada = [];
		}
	}
	
	
	function crar_select2_com_todas_as_configs()
	{
		$("#select_colunas_info").select2({ width: '100%' });
		$("#select_colunas_info").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$("#select_colunas_quebra_parcial_vertical").select2({ width: '100%' });
		$("#select_colunas_quebra_parcial_vertical").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$("#select_colunas_quebra_media_parcial_vertical").select2({ width: '100%' });
		$("#select_colunas_quebra_media_parcial_vertical").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$("#select_colunas_total_vertical").select2({ width: '100%' });
		$("#select_colunas_total_vertical").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$("#select_colunas_media_vertical").select2({ width: '100%' });
		$("#select_colunas_media_vertical").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$("#select_coluna_vertical").select2({ width: '100%' });
		$("#select_coluna_vertical").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$("#select_colunas_valores_vertical").select2({ width: '100%' });
		$("#select_colunas_valores_vertical").on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
		
		$(".select2-container--default").click(function(){
			//reprocessar ao abrir os selects
		    atualiza_select_vertical()
		});
		//permite sequenciar as seleções
		criar_sequenciar_colunas();
	}

	function criar_sequenciar_colunas()
	{
		$("ul.select2-selection__rendered").sortable({
		  containment: 'parent',
		  stop: function(event, ui) {
		  // event target would be the <ul> which also contains a list item for searching (which has to be excluded)
		   idDoSelect = $(event.target).parent().parent().parent().prev().attr("id");
		   console.log(idDoSelect);
		   ////return {name: $(this).data('data').text, value: $(this).data('data').id }; 
			var arr = Array.from($(event.target).find('li:not(.select2-search)').map(function () { 
				return $(this).data('data').id ;
			  }))
			   console.log(arr);
			  //recriar com sequencia
			 //$("#"+idDoSelect).val(arr).change();
			 
			 // $("#"+idDoSelect).val(arr);
			 //$("#"+idDoSelect).select2(arr, null, false);
			 //$("#"+idDoSelect).select2("val", arr);
			// $("#"+idDoSelect).trigger('change');
			$("#"+idDoSelect).select2('destroy');
			bkpItens = [];
			$("#"+idDoSelect+" > option").each(function() {
				bkpItens.push({text: this.text, value: this.value, "selected": false});
				$(this).prop("selected", false);
				$(this).remove();
			});	
			aValoresAdicionados = [];
			$("#"+idDoSelect).append($('<option>', {
					value: "",
					text: "",
					"selected": false
				}));
			aValoresAdicionados.push("");	
			for(i =0; i < arr.length; i++)
			{
				$("#"+idDoSelect).append($('<option>', {
					value: arr[i],
					text: arr[i],
					"selected": true
				}));
				aValoresAdicionados.push(arr[i]);
			}
			for(i =0; i < bkpItens.length; i++)
			{
				if(! aValoresAdicionados.includes(bkpItens[i].value))
				{
					$("#"+idDoSelect).append($('<option>', {
						value: bkpItens[i].value,
						text: bkpItens[i].value,
						"selected": false
					}));
						
				}
			}
				
			$("#"+idDoSelect).select2({ width: '100%' });		
			$("#"+idDoSelect).on("select2:select", function (evt) {var element = evt.params.data.element; var $element = $(element); $element.detach(); $(this).append($element); $(this).trigger("change");});
			$(".select2-container--default").click(function(){
				//reprocessar ao abrir os selects
				atualiza_select_vertical()
			});
			criar_sequenciar_colunas();
			
		  }
		  
		});
	}