//table = null;
tempNamespace = {};
function iniciar_tabulator(seletor, table_seletor)
{
	tamanhoTabela = $(window).height() - ($(table_seletor).last().offset().top) - 80
	if(tamanhoTabela < 200)
	{
		tamanhoTabela = 200
	}
		
		//define some sample data
	$(table_seletor).css("display","none");
	var aCabecalho = new Array();
	var idCab = 1;
	//$(document).ready(function() { 
		$(table_seletor+" thead tr td").each(function(i){
		   largura = 150
		   if($(this).text() == "Editar" || $(this).text() == "Excluir" || $(this).text() == "")
		   {
				largura = 80
		   }
		   else if($(this).text() == "Código" )
		   {
				largura = 90
		   }
		   aCabecalho.push({title:$(this).text(), field:("fild"+idCab), width:largura, formatter:"html"});
		   idCab += 1;
		   //alert($(this).text())
		});
	//});
	var tabledata = [];
	tempNamespace[seletor.replace("#","")] = new Tabulator(seletor, {
			height:tamanhoTabela, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
			data:tabledata, //assign data to table
			layout:"fitColumns", //fit columns to width of table (optional)
			columns:aCabecalho,
			rowClick:function(e, row){ //trigger an alert message when the row is clicked
				//alert("Row " + row.getData().id + " Clicked!!!!");
			},
		});
	$(".tabulator-col").css({ border: 0, margin: 0, background: "white"});
	$(".tabulator-header").css({ border: 0, margin: 0, background: "white", 'border-bottom': 'solid 1px #d9d9d9', padding: '4px'});
	$(".tabulator").css({ border: 0, margin: 0, background: "white"})	;
}		

function monta_conteudo_tabulator(seletor, table_seletor)
{
	//define some sample data
	$(table_seletor).css("display","none");
	tempNamespace[seletor.replace("#","")].clearData()
	var tabledata = new Array();
	/*
	var idConteudo = 1;
	$(document).ready(function() { 
		$("#listtable tbody tr td").each(function(i){
				
		   tabledata.push({id:idConteudo, name:$(this).text(), age:"12", col:"red", dob:""});
		   idConteudo += 1;
		   //alert($(this).text())
		});
	});*/
	//alert($(table_seletor).attr('id'))
	var table_rows = document.getElementById($(table_seletor).attr('id'))//document.getElementById('listtable');
	var rowLength = table_rows.rows.length;
	
	for(var i=1; i < rowLength; i+=1){
	  var row = table_rows.rows[i];
	  //your code goes here, looping over every row.
	  //cells are accessed as easy
	  var cellLength = row.cells.length;
	  var colunas = new Array();
	  
	 var idCab = 1;
	  var objcolunas = { id:i+1}
	  for(var y=0; y<cellLength; y+=1){
		var cell = row.cells[y];
		var fild = ("fild"+idCab)
		objcolunas[fild] = row.cells[y].innerHTML
		
		//do something with every cell here
		idCab += 1;
	  }
	  
	  //colunas.push(objcolunas)
	  tabledata.push(JSON.parse(JSON.stringify(objcolunas)));
	  //tabledata.push(objcolunas)
	}
	tempNamespace[seletor.replace("#","")].addData(tabledata);
	
	//carga de tabela

	$(seletor+" .cargaTabela").mouseover(function() {
		//alert("sss")
		//var $target = $(e.currentTarget);
		//$(e.currentTarget).css("position","fixed");
		
		var link = $(seletor);
		var offset = link.offset();
		var top = offset.top;
		var left = offset.left;
		var bottom = top + link.outerHeight();
		var right = left + link.outerWidth();
		
		$( this ).children().css("position","fixed");
		
		//se tiver no final exibe mais para cima
		linha_em_relacao_ao_conteudo = bottom -  ( $( this ).offset().top ) 
		if(linha_em_relacao_ao_conteudo > 70)
		{	
			$( this ).children().css("top", ($( this ).offset().top - $(seletor).offset().top)+"px" );
		}
		else
		{
			$( this ).children().css("top", ($( this ).offset().top - $(seletor).offset().top - 55)+"px" );
		}
		
		$( this ).children().css("left", ($( this ).offset().left - $(seletor).offset().left +10)+"px" );
		//$( this ).children().css("left", 0+"px" );
		//$( "*" ).css("z-index","9");
		$(seletor+ " .cargaTabela" ).children().css("z-index","9999 ");
			//$(this).parent().css("z-index","9999 ");
	})
	
	layout_table();
	//$(".tabulator-cell").css({padding: '4px'});
	$(".tabulator-tableHolder").on( 'scroll', function(){
			layout_table();
			//$(".tabulator-cell").css({ padding: '4px'});
	});
	$(".tabulator-col").on( 'click', function(){
			layout_table();
	});
	

}

function layout_table()
{
	$(".tabulator-cell").css({ border: 0, margin: 0, background: "white"});
	$(".tabulator-row").css({ width: "100%", background: "white",'border-bottom': 'solid 1px #d9d9d9', display: "table", padding: '4px'});
	$(".tabulator-table").css({width: "auto", 'min-width': "100%", background: "white"});
}
var WindowsSize=function(){
    if($('.tabulator').length > 0)
	{
		tamanhoTabela = $(window).height() - ($(".tabulator").last().offset().top) - 80
		if(tamanhoTabela < 200)
		{
			tamanhoTabela = 200
		}
		$(".tabulator").css("height", tamanhoTabela + "px");
	}	
 };
$(document).ready(WindowsSize); 
$(window).resize(WindowsSize); 


//grid editavel
//link_item = "src/controller/Item_pedidoController.php?mod=form";
//campo_chave= "codigo";
//seletor_contendo_colunas_item = "colunas_grid_editavel_item_pedido";
//input_manter_qtd_linhas = "qtd_linhasItem_pedido";
//inicia_grid_editavel("div_grid_editavelitem_pedido", '#listtableitem_pedido', lista_item, link_item, campo_chave, seletor_contendo_colunas_item, input_manter_qtd_linhas );
tempNamespaceContadorLinhaGrid = {};
function inicia_grid_editavel(seletor, table, lista_item, link_item, campo_chave, seletor_contendo_colunas_item, input_manter_qtd_linhas, name_contador, lista_campos_nao_obrigatorios)
{
	//monta cabeçalho fixo
	if($(table).length > 0)
	{	
		document.getElementById($(table).attr("id")).addEventListener("scroll", function(){
		   var translate = "translate(0,"+this.scrollTop+"px)";
		   this.querySelector("thead").style.transform = translate;
		});
		//alert($("#listtable_item").last().offset().top + " "+$(window).height())
		tamanhoTabela = $(window).height() - ($(table).last().offset().top) - 150
		if(tamanhoTabela < 200)
		{
			tamanhoTabela = 200
		}
		$(table).css("height", tamanhoTabela + "px");
		$(seletor).css("width", ($("form").width() - 70)+"px");
		
	}	
	var WindowsSize=function(){
		if($(table).length > 0)
		{
			tamanhoTabela = $(window).height() - ($(".table_grid_editavel").last().offset().top) - 150
			if(tamanhoTabela < 200)
			{
				tamanhoTabela = 200
			}
			$(seletor).css("width", ($("form").width() - 70)+"px");
		}	
	 };
	$(document).ready(WindowsSize); 
	$(window).resize(WindowsSize); 
	var codigo_item = "";
	//percorre colunas da tabela bd de item e preenche a tabela html
	
	for(i = 0; i < lista_item.length; i++)
	{
		//alert(lista[i])
		//codigo_item = JSON.parse(JSON.stringify(lista_item[i]))
		$.post(link_item+"&"+campo_chave+"="+lista_item[i],{campo_chave: lista_item[i]}, function (e){
			//alert(e.find("name[campo_chave]").val())
			$("#"+seletor_contendo_colunas_item).html(e);
			tempNamespaceContadorLinhaGrid[name_contador] += 1;
			$("#"+input_manter_qtd_linhas).val(tempNamespaceContadorLinhaGrid[name_contador]);
			htmlItem = "<tr id='linha_grid_"+tempNamespaceContadorLinhaGrid[name_contador]+"'>";
			//htmlItem += '<td><span class=\"form_obrigatorio_grid_editavel\" >&nbsp;</span><a href="javaScript:void(0)" class="cor_verde" onclick="excluirDados(\''+link_item+'?mod=excluir&amp;'+campo_chave+'='+JSON.parse(JSON.stringify(codigo_item))+'\'); $(\'#linha_grid_'+tempNamespaceContadorLinhaGrid[name_contador]+'\').remove();"><i class="fa fa-trash" aria-hidden="true"></i></a></td>';
			htmlItem += '<td><span class=\"form_obrigatorio_grid_editavel\" >&nbsp;</span><a href="javaScript:void(0)" class="cor_verde" onclick="excluir_linha_com_dados(\''+table+'\', '+tempNamespaceContadorLinhaGrid[name_contador]+'); $(this).remove();"><i class="fa fa-trash" aria-hidden="true"></i></a></td>';
			$("#"+seletor_contendo_colunas_item+" .filtroForm").each(function(i){
				html_conteudo = $(this).html();
				if(html_conteudo.includes('datalist'))
				{
					html_conteudo = html_conteudo.replace("filtroForm", "filtroForm_grid_editavel").replace("buscarListaValor", "buscarListaValorGridEditavel");
					//html_conteudo = html_conteudo.replace("buscarListaValorGridEditavel('", "buscarListaValorGridEditavel('"+tempNamespaceContadorLinhaGrid[name_contador])
					//html_conteudo = html_conteudo.replace('list="','list="'+tempNamespaceContadorLinhaGrid[name_contador]);
					//html_conteudo = html_conteudo.replace("', 'datalist", "', '"+tempNamespaceContadorLinhaGrid[name_contador]+"datalist");
					html_conteudo = html_conteudo.replace('valuepost="','valuepost="'+tempNamespaceContadorLinhaGrid[name_contador]);
					//html_conteudo = html_conteudo.replace('id="datalist', 'id="'+tempNamespaceContadorLinhaGrid[name_contador]+'datalist');
					html_conteudo = html_conteudo.split('datalist').join("datalist"+tempNamespaceContadorLinhaGrid[name_contador])//.replace("datalist","datalist"+tempNamespaceContadorLinhaGrid[name_contador]);
					html_conteudo = html_conteudo.replace('class="datalist'+tempNamespaceContadorLinhaGrid[name_contador],'class="datalist');
				}
				if(html_conteudo.includes('form_obrigatorio'))
				{
					html_conteudo = "<span class=\"form_obrigatorio_grid_editavel\" >*</span>" + html_conteudo
				}
				else
				{
					html_conteudo = "<span class=\"form_obrigatorio_grid_editavel\" >&nbsp;</span>" + html_conteudo
				}
				html_conteudo = html_conteudo.replace("<label>", "<label style='display: none;'>");
				html_conteudo = html_conteudo.replace("<br>", "");
				if($(this).parent().attr("class") != "filtroForm" && $(this).parent().attr("class") != "filtroForm_grid_editavel" && ! html_conteudo.includes('datalist')) 
				{
						htmlItem += "<td>"+html_conteudo.replace('name="', 'name="'+name_contador+tempNamespaceContadorLinhaGrid[name_contador]+'').replace('id="', 'id="'+tempNamespaceContadorLinhaGrid[name_contador]+'') +"</td>";
				}
				else if($(this).parent().attr("class") != "filtroForm" && $(this).parent().attr("class") != "filtroForm_grid_editavel" )
				{
					htmlItem += "<td>"+html_conteudo.replace('name="', 'name="'+name_contador+tempNamespaceContadorLinhaGrid[name_contador]+'') +"</td>";
				}	
					
			});
			htmlItem += "</tr>";
			$(table).append(htmlItem);
			//$('#'+item+'formdatalistpedido').css('display','none');
			//$("#resultadoItem_pedido").find('input[name="'+item+'pedido"]').prop('required',false);
			//$('#'+item+'formdatalistpedido').prop('required',false);
			for(inaoobrig = 0; inaoobrig < lista_campos_nao_obrigatorios.length; inaoobrig++)
			{
				$(table).find('input[name="'+tempNamespaceContadorLinhaGrid[name_contador]+lista_campos_nao_obrigatorios[inaoobrig]+'"]').prop('required',false);
				$('#formdatalist'+tempNamespaceContadorLinhaGrid[name_contador]+lista_campos_nao_obrigatorios[inaoobrig]).prop('required',false);
			}	
			iniciaValorForm();
			$(".select2").remove();
			$('select.noSelect2').select2('destroy');
			$("select").removeClass("select2-hidden-accessible");
			$("select").css("padding", "5px");
			$(table).parent().css("min-width", ($("tr:first > td", table).length*110)+"px");
			$("td").css("width", "auto");
			//inicia_select2();
		})	
	}
	
	
}

function add_item_grid_editavel(link_item, seletor_contendo_colunas_item, input_manter_qtd_linhas, table, name_contador, lista_campos_nao_obrigatorios) 
{
		$.post(link_item, function (e){
			$("#"+seletor_contendo_colunas_item).html(e);
			tempNamespaceContadorLinhaGrid[name_contador] += 1;
			$("#"+input_manter_qtd_linhas).val(tempNamespaceContadorLinhaGrid[name_contador]);
			htmlItem = "<tr id='linha_grid_"+tempNamespaceContadorLinhaGrid[name_contador]+"'>";
			htmlItem += '<td><span class=\"form_obrigatorio_grid_editavel\" >&nbsp;</span><a href="javaScript:void(0)" class="cor_verde" onclick="$(\'#linha_grid_'+tempNamespaceContadorLinhaGrid[name_contador]+'\').remove();"><i class="fa fa-trash" aria-hidden="true"></i></a></td>';
			$("#"+seletor_contendo_colunas_item+" .filtroForm").each(function(i){
				html_conteudo = $(this).html();
				if(html_conteudo.includes('datalist'))
				{
					html_conteudo = html_conteudo.replace("filtroForm", "filtroForm_grid_editavel").replace("buscarListaValor", "buscarListaValorGridEditavel");
					//html_conteudo = html_conteudo.replace("buscarListaValorGridEditavel('", "buscarListaValorGridEditavel('"+tempNamespaceContadorLinhaGrid[name_contador])
					//html_conteudo = html_conteudo.replace('list="','list="'+tempNamespaceContadorLinhaGrid[name_contador]);
					//html_conteudo = html_conteudo.replace("', 'datalist", "', '"+tempNamespaceContadorLinhaGrid[name_contador]+"datalist");
					html_conteudo = html_conteudo.replace('valuepost="','valuepost="'+tempNamespaceContadorLinhaGrid[name_contador]);
					//html_conteudo = html_conteudo.replace('id="datalist', 'id="'+tempNamespaceContadorLinhaGrid[name_contador]+'datalist');
					html_conteudo = html_conteudo.split('datalist').join("datalist"+tempNamespaceContadorLinhaGrid[name_contador])//.replace("datalist","datalist"+tempNamespaceContadorLinhaGrid[name_contador]);
					html_conteudo = html_conteudo.replace('class="datalist'+tempNamespaceContadorLinhaGrid[name_contador],'class="datalist');
				}
				if(html_conteudo.includes('form_obrigatorio'))
				{
					html_conteudo = "<span class=\"form_obrigatorio_grid_editavel\" >*</span>" + html_conteudo
				}
				else
				{
					html_conteudo = "<span class=\"form_obrigatorio_grid_editavel\" >&nbsp;</span>" + html_conteudo
				}
				html_conteudo = html_conteudo.replace("<label>", "<label style='display: none;'>");
				html_conteudo = html_conteudo.replace("<br>", "");
				if($(this).parent().attr("class") != "filtroForm" && $(this).parent().attr("class") != "filtroForm_grid_editavel" && ! html_conteudo.includes('datalist')) 
				{
						htmlItem += "<td>"+html_conteudo.replace('name="', 'name="'+name_contador+tempNamespaceContadorLinhaGrid[name_contador]+'').replace('id="', 'id="'+tempNamespaceContadorLinhaGrid[name_contador]+'') +"</td>";
				}
				else if($(this).parent().attr("class") != "filtroForm" && $(this).parent().attr("class") != "filtroForm_grid_editavel" )
				{
					htmlItem += "<td>"+html_conteudo.replace('name="', 'name="'+name_contador+tempNamespaceContadorLinhaGrid[name_contador]+'') +"</td>";
				}
			   //alert($(this).html())
			});
			 //htmlItem = htmlItem.replaceAll("<select", "<select noSelect2='true'");
			
			 htmlItem += "</tr>";
			$(table).append(htmlItem);
			//$('#'+item+'formdatalistpedido').css('display','none');
			//$("#resultadoItem_pedido").find('input[name="'+item+'pedido"]').prop('required',false);
			//$('#'+item+'formdatalistpedido').prop('required',false);
			for(inaoobrig = 0; inaoobrig < lista_campos_nao_obrigatorios.length; inaoobrig++)
			{
				$(table).find('input[name="'+tempNamespaceContadorLinhaGrid[name_contador]+lista_campos_nao_obrigatorios[inaoobrig]+'"]').prop('required',false);
				$('#formdatalist'+tempNamespaceContadorLinhaGrid[name_contador]+lista_campos_nao_obrigatorios[inaoobrig]).prop('required',false);
			}
			 $(".select2").remove();
			$('select.noSelect2').select2('destroy');
			$("select").removeClass("select2-hidden-accessible");
			$("select").css("padding", "5px");
			$(table).parent().css("min-width", ($("tr:first > td", table).length*110)+"px");
			$("td").css("width", "auto");
			//inicia_select2();
		})	
		
		
		
		
}

function excluir_linha_com_dados(table, linha)
{
	$(table+' #linha_grid_'+linha+'').css('background', 'red'); 
	$(table+' #linha_grid_'+linha+' *').attr('readonly', true);
	//$('#linha_grid_'+linha+' *').val("excluir_"+$('#linha_grid_'+linha+' *').val(""));
	$(table+' #linha_grid_'+linha+' *').each(function(i){
		$(this).val("excluir_"+$(this).val());
	});
	habilitarComponente("#btnSalvar");
	habilitarComponente("#btnCancelar");
	habilitarComponente(".btnSalvar");
	habilitarComponente(".btnCancelar");
}

/*
 var tabledata = [
 	{id:1, name:"Oli Bob", age:"12", col:"red", dob:""},
 	{id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"},
 	{id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"},
 	{id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"},
 	{id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"},
 ];
	 //create Tabulator on DOM element with id "example-table"
	var table = new Tabulator("#example-table", {
		height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
		data:tabledata, //assign data to table
		layout:"fitColumns", //fit columns to width of table (optional)
		columns:[ //Define Table Columns
			{title:"Name", field:"name", width:150},
			{title:"Age", field:"age", hozAlign:"left", formatter:"progress"},
			{title:"Favourite Color", field:"col"},
			{title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
		],
		rowClick:function(e, row){ //trigger an alert message when the row is clicked
			alert("Row " + row.getData().id + " Clicked!!!!");
		},
	});*/