
			
			
			
			
			function popoverOpening(popId,id) {
				$(".ps-popover").hide();
				$(popId).show();
				if($(id).length >0) {
					if(!$(id).is("[data-done]")) {
						$(id).attr("src",$(id).attr("data-src")).attr("data-done","true");
					}	
				}
            }
            
            function montaHTML(table) {
                var dt = table.data("datatable");
                var columns = dt.columns({"filter": "applied"}).data();
                var rows = dt.rows({"filter": "applied"}).data();
                var line_count = columns[0].length;
                var ths = $("thead th", table); //Pega titulos da tabela
    
                return getHeaders(ths) + getTableBody(table); 
            }

            function getHeaders(ths){
                var thstext = '';
            ths.each(function() {
                var th = $(this);
    
                if ((th.is(":visible") || th.is("[data-printexcel]")) && !th.is("[printexcel = 'false']")) {
                   var txt;
                   if (th.find("select").length > 0) {
                       txt = th.find(".thText").text();
                   } else {
                       txt = $.trim(th.html().replace(/(<[^>]*>)|\n|\r/g, ""));
                   }
                }	
                thstext = thstext + '<th>' + txt + '</th>';	
            });
            return thstext;
    }


    function getTableBody(table){
       var tbodytext = '<tbody>';


       var cols = new Array(); 
       $('th',table).each(function(index){
            if($(this).hasClass('typeNumber')){
                cols.push(index)
            }
       })
        
       table.data("datatable").rows({"filter": "applied"}).data().each(function (value, index) { 
       var linhatxt = "<tr>" ;
        $(value).each(function (ind, val){
            var texto;
             // verifica se e uma tag hmtl se for pega o primeiro elemento dela, se nao pela o valor direto   
             val[0] == "<" ? texto = $(val)[0].innerHTML : texto = val;

             if(cols.indexOf(ind) > -1){
                 texto = "'" + texto;
             }
             linhatxt += "<td>" + texto + "</td>"
       });
       linhatxt += "</tr>"
       tbodytext += linhatxt; 
       });
        tbodytext +=  '</tbody>';
        return tbodytext;
    }
			
			function datatableInit(_this) {
				var table = $(_this);
					
					var datePatterndatePattern = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
					var dateColumns = new Array();
					var otherColumns = new Array();
					$("tbody > tr:first > td", table).each(function(d, j) {
						var val = $.trim($(j).text().replace(/(<[^>]*>)|\n|\r/g, ""));
						if (val && datePatterndatePattern.test(val)) {
							dateColumns.push($(this).index());
						} else {
							otherColumns.push($(this).index());
						}
					});
					
					var disabledColumns = new Array();
					$("thead > tr:first > th", table).each(function(d, j) {
						if($(this).hasClass("no-order")) disabledColumns.push($(this).index())
					});
					
					var popoverColumns = new Array();
					$("tbody > tr:first > td", _this).each(function(d, j) {
						if ($(this).html().indexOf("popover") != -1) {
							popoverColumns.push($(this).index());
						} 
					});
		
					var toShow = table.attr("data-show");
					if(!toShow && toShow != "false") toShow = 5;
					else if(toShow != "false") toShow = parseInt(toShow);
					else toShow = false;
					
					var lines = table.find("tr").size();
					var aLengthMenu = new Array();
					var show = 10;
					
					if (toShow && toShow != "") {
						var i = toShow;
						aLengthMenu.push(i);
						while (i < lines) {
							i *= 2;
							aLengthMenu.push(i);
						}
					}
					
					if((lines-1) <= toShow) toShow= false;
					
					var orderColumn = $(_this).attr("data-order-column")? $(_this).attr("data-order-column"): 0;
					var orderType = $(_this).attr("data-order-type")? $(_this).attr("data-order-type") : "asc";
					
					var doOrder = $(_this).is('[data-no-order]')?false:true;
					
					var zeroResults = 'Nenhum registro encontrado';
					if($(_this).attr('zero-results') != undefined && $(_this).attr('zero-results') != ''){
						zeroResults = $(_this).attr('zero-results');
					}
					
					try {
						table.dataTable({
							"autoWidth": false,
							columnDefs: [{
									targets: dateColumns,
									type: 'date-eu'
								}, // plugin para a correção de data 
								{
									targets: disabledColumns,
									orderable: false
								}
								,
								{
									targets: popoverColumns,
									data: function ( source, type, val ) {
										if (type === 'sort') {
										  
										  return source[popoverColumns[0]].substring(source[popoverColumns[0]].indexOf("</ul>") + 5);
										}
										return source[popoverColumns[0]];
									}
								}
							],
							"bSort": doOrder,
							"bStateSave": false,
							"stateSaveParams": function(oSettings, oData) { 
								save_dt_view(oSettings, oData); 
							},
							"stateLoadParams": function(oSettings) { 
								return load_dt_view(oSettings); 
							},
							"order": [
								[orderColumn, orderType]
							],
							"searching": true,
							"paging": toShow,
							"info": toShow,
							"pagingType": "full_numbers",
							"fnDrawCallback": function( oSettings ) {
								GIWLib.Init($(_this));
							},
							"iDisplayLength": toShow ? toShow : lines,
							// Texto que aparecem na tela
							"language": {
								// "lengthMenu": "Mostrando _MENU_ linhas por página",
								"info": "Total _TOTAL_ | Página _PAGE_ de _PAGES_",
								"zeroRecords": zeroResults,
								"infoEmpty": "", //"Nenhum registro encontrado", 
								"infoFiltered": "(filtrado de um total de _MAX_ registros)",
								"sSearch": "Buscar:",
								"oPaginate": {
									"sPrevious": "«",
									"sNext": "»",
									"sFirst": "« Primeira",
									"sLast": "Última »"
								}
							},
							"dom": doSearch(table,toShow)
						});
					} catch(e) {
					
					}
					
					var dt = $(_this).DataTable();
					$(_this).data("datatable", dt);
					createFilters($(_this));
					updateFilters($(_this));
					dt.columns.adjust();
			}
			$(function() {
				
	
				$("form").submit(function(){
					localStorage.clear();
					reset_dt_view();
				});
		
				//Plugin para normalizar células com conteúdo HTML durante a busca.
				jQuery.fn.DataTable.ext.type.search.html = function(data) {
					return !data ?
						'' :
						typeof data === 'string' ?
						data.replace(/(<[^>]*>)|\n|\r/g, "") :
						data;
				};
				//Plugin para ordenar datas corretamente.
				jQuery.extend(jQuery.fn.dataTableExt.oSort, {
					"date-eu-pre": function(date) {
						try {
							date = $.trim(date.replace(/(<[^>]*>)|\n|\r/g, ""));
							var eu_date, year;
							if (date == '') {
								return 0;
							}
							if (date.indexOf('.') > 0) {
								/*date a, format dd.mn.(yyyy) ; (year is optional)*/
								eu_date = date.split('.');
							} else {
								/*date a, format dd/mn/(yyyy) ; (year is optional)*/
								eu_date = date.split('/');
							}
							/*year (optional)*/
							if (eu_date[2]) {
								year = eu_date[2];
							} else {
								year = 0;
							}
							/*month*/
							var month = eu_date[1];
							if (month.length == 1) {
								month = 0 + month;
							}
							/*day*/
							var day = eu_date[0];
							if (day.length == 1) {
								day = 0 + day;
							}
							return (year + month + day) * 1;
						} catch (e) {
							return 0;
						}
					},
					"date-eu-asc": function(a, b) {
						return ((a < b) ? -1 : ((a > b) ? 1 : 0));
					},
					"date-eu-desc": function(a, b) {
						return ((a < b) ? 1 : ((a > b) ? -1 : 0));
					}
				});
				
				$(".giw-datatable").each(function() {
					datatableInit($(this));
				});
				
				$("a.downloadxlsDT").click(function(e) {
				      var htmls = "";
                  var uri = 'data:application/vnd.ms-excel;base64,';
                  var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
                  var base64 = function(s) {
                      return window.btoa(unescape(encodeURIComponent(s)))
                  };

                  var format = function(s, c) {
                      return s.replace(/{(\w+)}/g, function(m, p) {
                          return c[p];
                      })
                  };

                  var t = $(this).closest(".giw-datatable-holder").find(".giw-datatable");
                  var clone = t.clone(true);
                  $(clone).find('.iptHolder').remove();

                 //htmls = $(clone).html();
                   htmls = montaHTML(t);

                  var ctx = {
                      worksheet : 'Worksheet',
                      table : htmls
                  }


                  var link = document.createElement("a");
                  link.download = "download.xls";
                  link.href = uri + base64(format(template, ctx));
                  link.click();	
				})
				
				$("body").on("click", ".ps-popover-close", function(e) {
					e.preventDefault();
					var t = $(this)
					  , p = t.parent()
					  , callback = "undefined" != typeof p.data("onpopoverhide") ? p.data("onpopoverhide") : !1;
					p.fadeOut(200, function() {
						callback && eval(callback)
					})
				}),
		
				$("body").on("click",".ps-giwpopover-toggle", function(e) {
						var t = $(this)
						  , d = t.data("popover")
						  , dw = $(d).outerWidth()
						  , ref = t.offset()
						  , tw = t.outerWidth()
						  , th = t.outerHeight()
						  , config = {}
						  , isHelper = t.is(".ps-lbl-helper");
						if (maxW = $(".ps-container:eq(0)").outerWidth() - (ref.left + tw - 7),
						"undefined" != typeof d)
							if (psLib.IsMobile ? ($(d).addClass("ps-popover-top"),
							config = {
								margin: "7px 0",
								width: "100%"
							}) : maxW < 100 ? (maxW = 271,
							dw > maxW && (dw = maxW),
							$(d).addClass("ps-popover-left"),
							config = {
								"margin-left": tw + 7 + "px",
								"margin-top": "-" + (th + 7) + "px",
								"max-width": maxW + "px"
							},
							isHelper || (config = {
								top: ref.top + th / 2 - 21 + "px",
								left: ref.left - dw - 6 + "px"
							})) : (maxW > 271 && (maxW = 271),
							$(d).removeClass("ps-popover-left"),
							config = {
								"margin-left": tw + 7 + "px",
								"margin-top": "-" + (th + 6) + "px",
								"max-width": maxW + "px"
							},
							isHelper || (config = {
								top: ref.top + th / 2 - 21 + "px",
								left: ref.left + tw + 3 + "px"
							})),
							t.parent("td").each(function() {
								$(this).css("position", "relative"),
								$(d).removeClass("ps-popover-left").addClass("ps-popover-bottom"),
								config = {
									"margin-top": "9px",
									width: "100%"
								}
							}),
							$(d).css(config),
							!t.is(".ps-popover-toggle-over") && "click" == e.type || t.is(".ps-popover-toggle-over") && "mouseenter" == e.type) {
								var callback = "undefined" != typeof $(d).data("onpopovershow") ? $(d).data("onpopovershow") : !1;
								$(d).fadeIn(200, function() {
									callback && eval(callback)
								})
							} else if (t.is(".ps-popover-toggle-over") && "mouseleave" == e.type) {
								var callback = "undefined" != typeof $(d).data("onpopoverhide") ? $(d).data("onpopoverhide") : !1;
								$(d).fadeOut(200, function() {
									callback && eval(callback)
								})
							}
				})
			});
			
			function doSearch(table,showPagination) {
				if ($(table).is('[data-search]')) {
					if(showPagination) {
						return "<'top'f>rt<'bottom'ip><'clear'>"
					} else {
						return "<'top'f>rt<'clear'>"
					}
				} else {
					if(showPagination) {
						return "<'top'>rt<'bottom'ip><'clear'>"
					} else {
						return "<'top'>rt<'clear'>"
					}
					
				}
			};
			
			function createFilters(table) {
				if(table.is("[data-filtering = 'true']")) {
					$("thead th", table).each(function(thIndex, th) {
						if($(this).is("[data-filtering = 'false']")) {
							var txt = $(this).find(".thText").text();
							var div = $("<div class='iptHolder'></div>");
							if(thIndex == 0) $(div).addClass("first");
							var msgInd = $(this).is("[data-filteringmsg]") ? $(this).attr("data-filteringmsg") : "Filtro Indisponível";
							var input = $("<input type='text' disabled class='ps-frm-entry iptFilterDt notFiltering' value='Filtro Indisponível' placeholder='"+msgInd+"' ></input>");
							$(input).appendTo(div);
							$(div).appendTo($(this));
							$(div).click(function(e) {
								e.stopPropagation();
							});
						} else {
							if($(this).is("[filtercombo]")) {
								var div = $("<div class='iptHolder'></div>");
								var div2 = $("<div class='ps-frm-select'></div>");
								if(thIndex == 0) $(div).addClass("first");
								var defaultOptionLabel = $(this).is('[data-defaultOptionLabel]') ? $(this).data('defaultoptionlabel') : 'Filtrar';
								var input = $("<select data-gtm-type='select' class='selFilterDt'><option value=''>" + defaultOptionLabel + "</option></select>");
								$(input).appendTo(div2);
								$(div2).appendTo(div);
								$(div).appendTo($(this));
							} else if($(this).is("[filtercheck]")) {
								var div = $("<div class='ps-alignCenter iptHolder filterCheck'></div>");
								if(thIndex == 0) $(div).addClass("first");
								var input = $('<input type="checkbox" name="tableCheckAll" value="" class="check-datatable ps-frm-checkbox" id="ps-frm-chk-tablecheck" /><label class="ps-frm-checkbox" for="ps-frm-chk-tablecheck"></label>');
								$(input).appendTo(div);
								$(div).appendTo($(this));
								$(input).change(function() {
									var idx = $(this).closest("th").index();
									if($(this).is(":checked")) {
										$(this).closest("table").find("tr").each(function() {
											$("td",this).each(function(i){
												if ( i == idx) {
													if($(this).find(":checkbox").length > 0) {
														if($(this).find(":checkbox").is("[disabled]")) {
														} else {
															$(this).find(":checkbox").prop("checked","true");
														}
													}
												}
											});
										});
									} else {
										$(this).closest("table").find("tr").each(function() {
											$("td",this).each(function(i){
												if ( i == idx) {
													if($(this).find(":checkbox").length > 0) {
														if($(this).find(":checkbox").is("[disabled]")) {
														} else {
															$(this).find(":checkbox").removeAttr("checked");
														}
													}
												}
											});
										});
									}
								});
								
								$(div).click(function(e) {
									e.stopPropagation();
								});
							} else {
								var txt = $(this).is("[data-filtermsg]") ? $(this).data("filtermsg") : "Filtrar " + $(this).find(".thText").text();
								var div = $("<div class='iptHolder'></div>");
								if(thIndex == 0) $(div).addClass("first");
								var input = $("<input type='text' class='ps-frm-entry iptFilterDt' placeholder='"+ txt +"'></input>");
								$(input).appendTo(div);
								$(div).appendTo($(this));
							}
						}
					});
				}
			}
			
			function updateFilters(table) {
				var dt = $(table).data("datatable");
				if(table.is("[data-filtering = 'true']")) {
					if(dt) {
						$("thead th", table).each(function(index, inputFilterContainer) {
							$(this).click(function(){
								dataLayer.push({'event':'table-order','column-index':index});
							});
							if($(this).find(".selFilterDt").length > 0) {
								var selIpt = $(this).find(".selFilterDt");
								var oldSelectValue = selIpt.val();
								var oldValueExists = false;
								var contentsFiltered = arrayUnique(dt.columns(index, {"filter": "applied"}).nodes()[0]).sort(); 
								var contents = arrayUnique(dt.columns(index, {}).nodes()[0]).sort();
								if (contents) {
									for (var i = 0; i < contents.length; i++) {
										var text = $(contents[i]).html().replace(/(<[^>]*>)|\n|\r/g, "");
										var value;
										if($(contents[i]).attr("code") != null && $(contents[i]).attr("code") != undefined){
											value = $(contents[i]).attr("code");
										}else{
											value = text;
										}
										
										if(contentsFiltered.length == 1){
											if(text == $(contentsFiltered[0]).html().replace(/(<[^>]*>)|\n|\r/g, "")){
												$("<option value='" + value + "' selected>" + text + "</option>").appendTo(selIpt);
											}else{
												$("<option value='" + value + "'>" + text + "</option>").appendTo(selIpt);
											}
										}else{
											$("<option value='" + value + "'>" + text + "</option>").appendTo(selIpt);
										}
										
										if (value == oldSelectValue) {
											oldValueExists = true;
										}
									}
									if (oldValueExists) {
										selIpt.val(oldSelectValue);
									}
								}
								
								selIpt.change(function() {
									if (selIpt.val() != "") {
										dt.column(index).search("^" + $(":selected", selIpt).text().replaceAll("+", "\\+") + "$", true).draw();
									} else {
										dt.column(index).search("").draw();
									}
								});
								
								selIpt.click(function(e) {
									e.stopPropagation();
								});
							} else if($(this).find(".iptFilterDt").length > 0) {
								var ipt = $(this).find(".iptFilterDt");
								var jsonStorage = JSON.parse(sessionStorage.getItem('DataTables_'+window.location.pathname));
								//dt.column(index).search("").draw();
								if(jsonStorage) {
									ipt.val(jsonStorage.aoSearchCols[index].sSearch);
								}
								ipt.keyup(function(){
									window.setTimeout(function(){
										updateSums();
									},100);
									if (ipt.val() != "") {
										dt.column(index).search(ipt.val()).draw();
									} else {
										dt.column(index).search("").draw();
									}
									dataLayer.push({'event':'table-filter','column-index':index,'filter-value':ipt.val()});
								});
								
								ipt.click(function(e) {
									e.stopPropagation();
								});
							}
						});
					}
				}
			}
			
			function arrayUnique(a) {
				var b = new Array();
				var c = new Array();
				for (var x = 0; x < a.length; x++) {
					if (b[$(a[x]).text()] == undefined) {
						b[$(a[x]).text()] = a[x];
						c.push(a[x]);
					}
				}
				return c;
			};

			//State Controller
			function save_dt_view (oSettings, oData) {
			  //sessionStorage.setItem( 'DataTables_'+window.location.pathname, JSON.stringify(oData) );
			}
			function load_dt_view (oSettings) {
			  //return JSON.parse( sessionStorage.getItem('DataTables_'+window.location.pathname) );
			}
			function reset_dt_view() {
			  //sessionStorage.removeItem('DataTables_'+window.location.pathname);
			}

	
		
	