PageSourceSearch

https://www.cooperstowncred.com/wp-content/plugins/data-tables-gen…/Core/assets/js/core.js?ver=1.15.3

js cooperstowncred.com collected 2026-10-02 05:10:05 UTC 119,634 bytes, 3,084 lines download raw bytes

1if (typeof SDT_DATA == 'undefined') {
2  var SDT_DATA = {};
3}
4var g_stbServerSideProcessing = false;
5var g_stbServerSideProcessingIsActive = false;
6
7(function (vendor, $, window) {
8  var appName = 'Tables';
9  var dataTableInstances = [];
10  var ruleJSInstances = [];
11  var extraConfig = {};
12
13  if (!(appName in vendor)) {
14    vendor[appName] = {};
15
16    vendor[appName].getAppName = function () {
17      return appName;
18    };
19
20    vendor[appName].setExtraConfig = function (param, value) {
21      extraConfig[param] = value;
22    };
23
24    vendor[appName].getParameterByName = function (name) {
25      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
26
27      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
28        results = regex.exec(location.search);
29
30      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
31    };
32
33    vendor[appName].replaceParameterByName = function (url, paramName, paramValue) {
34      var pattern = new RegExp('\\b(' + paramName + '=).*?(&|$)');
35      if (url.search(pattern) >= 0) {
36        return url.replace(pattern, '$1' + paramValue + '$2');
37      }
38      return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
39    };
40
41    vendor[appName].getAllTableInstances = function () {
42      return dataTableInstances;
43    };
44
45    vendor[appName].removeAllTableInstances = function () {
46      dataTableInstances = [];
47    };
48
49    vendor[appName].setTableInstance = function (instance) {
50      dataTableInstances.push(instance);
51    };
52
53    vendor[appName].getTableInstanceById = function (id) {
54      var allTables = this.getAllTableInstances();
55
56      for (var i = 0; i < allTables.length; i++) {
57        if (allTables[i].table_id == id) {
58          return allTables[i];
59        }
60      }
61      return false;
62    };
63
64    vendor[appName].getTableInstanceByViewId = function (viewId) {
65      var allTables = this.getAllTableInstances();
66
67      for (var i = 0; i < allTables.length; i++) {
68        if (allTables[i].table_view_id == viewId) {
69          return allTables[i];
70        }
71      }
72      return false;
73    };
74
75    vendor[appName].removeTableInstanceByViewId = function (viewId) {
76      var allTables = this.getAllTableInstances();
77
78      for (var i = 0; i < allTables.length; i++) {
79        if (allTables[i].table_view_id == viewId) {
80          allTables.splice(i, 1);
81          return true;
82        }
83      }
84      return false;
85    };
86
87    vendor[appName].getAllRuleJSInstances = function () {
88      return ruleJSInstances;
89    };
90
91    vendor[appName].setRuleJSInstance = function (table) {
92      var rootElem = table.closest('.supsystic-tables-wrap'),
93        viewId = table.data('view-id');
94
95      ruleJSInstances[viewId] = new ruleJS(rootElem.attr('id'));
96      ruleJSInstances[viewId].instanceTable = table;
97      return ruleJSInstances[viewId];
98    };
99
100    vendor[appName].getRuleJSInstance = function (table) {
101      var allRuleJS = this.getAllRuleJSInstances(),
102        viewId = table.data('view-id');
103
104      if (!allRuleJS[viewId]) {
105        this.setRuleJSInstance(table);
106      }
107      return allRuleJS[viewId];
108    };
109
110    vendor[appName].request = function (route, data) {
111      if (!jQuery.isPlainObject(route) || !('module' in route) || !('action' in route)) {
112        throw new Error('Request route is not specified.');
113      }
114      if (!jQuery.isPlainObject(data)) {
115        data = {};
116      }
117      if ('action' in data) {
118        throw new Error('Reserved field "action" used.');
119      }
120      data.action = 'supsystic-tables';
121
122      var url = window.ajaxurl ? window.ajaxurl : ajax_obj.ajaxurl,
123        deferred = jQuery.Deferred();
124
125      jQuery
126        .post(
127          url,
128          jQuery.extend(
129            {},
130            {
131              route: route,
132            },
133            data
134          )
135        )
136        .done(function (response, textStatus, jqXHR) {
137          if (response.success) {
138            deferred.resolve(response, textStatus, jqXHR);
139          } else {
140            if (data._maxIter) {
141              retryAjax(deferred, url, route, data, 1, data._maxIter);
142            } else {
143              var message = typeof response.message !== 'undefined' ? response.message : 'There are errors during the request.';
144
145              deferred.reject(message, textStatus, jqXHR);
146            }
147          }
148        })
149        .fail(function (jqXHR, textStatus, errorThrown) {
150          if (data._maxIter) {
151            retryAjax(deferred, url, route, data, 1, data._maxIter);
152          } else {
153            deferred.reject(errorThrown, textStatus, jqXHR);
154          }
155        });
156
157      function retryAjax(def, url, route, data, curIter, maxIter) {
158        jQuery
159          .post(
160            url,
161            jQuery.extend(
162              {},
163              {
164                route: route,
165              },
166              data
167            )
168          )
169          .done(function (response, textStatus, jqXHR) {
170            if (response.success) {
171              def.resolve(response, textStatus, jqXHR);
172            } else {
173              var message = typeof response.message !== 'undefined' ? response.message : 'There are errors during the request.';
174
175              retryErrorHandler(def, url, route, data, curIter, maxIter, message, textStatus, jqXHR);
176            }
177          })
178          .fail(function (jqXHR, textStatus, errorThrown) {
179            retryErrorHandler(def, url, route, data, curIter, maxIter, errorThrown, textStatus, jqXHR);
180          });
181      }
182
183      function retryErrorHandler(def, url, route, data, curIter, maxIter, errorThrown, textStatus, jqXHR) {
184        curIter++;
185        if (curIter < maxIter) {
186          retryAjax(def, url, route, data, curIter, maxIter);
187        } else {
188          def.reject(errorThrown, textStatus, jqXHR);
189        }
190      }
191
192      return deferred.promise();
193    };
194
195    vendor[appName].setTableMobileWidth = function (isMobile) {
196      jQuery('div .supsystic-tables-wrap').each(function () {
197        isMobile = typeof isMobile == 'undefined' ? true : isMobile;
198        var ssDiv = jQuery(this),
199          widthAttr = ssDiv.data('table-width-' + (isMobile ? 'mobile' : 'fixed'));
200        if (typeof widthAttr != 'undefined') {
201          ssDiv.css('display', widthAttr == 'auto' ? 'inline-block' : '').css('width', widthAttr);
202        }
203      });
204    };
205
206    vendor[appName].initTablesOnPage = function (id) {
207      this._initTablesOnPage(id);
208    };
209
210    vendor[appName]._initTablesOnPage = function (id) {
211      var tables = jQuery(typeof id != 'undefined' ? '#supsystic-table-' + id + ':not(.dataTable)' : '.supsystic-table');
212      if (tables.length == 0) return;
213      if (typeof this._initTablesOnPageWoo === 'function') this._initTablesOnPageWoo(id);
214
215      var self = this,
216        firstTableId = '',
217        firstTableViewId = '',
218        firstTable = '',
219        firstTableWrapper = '',
220        firstTableFirstRow = '';
221
222      if (jQuery(window).width() <= 991) {
223        self.setTableMobileWidth();
224      }
225
226      tables.each(function () {
227        self.initializeTable(this, self.showTable, function (table) {
228          // This is used when table is hidden in tabs and can't calculate itself width to adjust on small screens
229          if (table.is(':visible')) {
230            // Fix bug in FF and IE which not supporting max-width 100% for images in td
231            self._calculateImages(table);
232          } else {
233            table.data(
234              'isVisible',
235              setInterval(function () {
236                if (table.is(':visible')) {
237                  clearInterval(table.data('isVisible'));
238                  self._calculateImages(table);
239                }
240              }, 250)
241            );
242          }
243          // Align all tables on page by the columns width depending on the columns width of first table on page
244          if (table.data('align-by-first-table')) {
245            firstTableId = firstTableId || jQuery('.supsystic-table:first').data('id');
246            firstTable = firstTable || jQuery('#supsystic-table-' + firstTableId);
247            firstTableViewId = firstTable.data('view-id');
248            firstTableWrapper = firstTableWrapper || firstTable.parents('#supsystic-table-' + firstTableViewId);
249            firstTableFirstRow = firstTable.data('head') ? firstTable.find('thead tr:first-child th') : firstTable.find('tbody tr:first-child td');
250
251            if (firstTableViewId != table.data('view-id')) {
252              var currentTableWrapper = table.parents('#supsystic-table-' + table.data('view-id'));
253
254              currentTableWrapper.css({
255                width: firstTableWrapper.get(0).style.width,
256              });
257              table.css({
258                width: firstTable.get(0).style.width,
259              });
260              currentTableWrapper.find('.supsystic-table').each(function () {
261                var curTable = jQuery(this),
262                  curTableFirstRow = curTable.data('head') ? curTable.find('thead tr:first-child th') : curTable.find('tbody tr:first-child td');
263
264                jQuery.each(curTableFirstRow, function (index, element) {
265                  if (firstTableFirstRow[index]) {
266                    jQuery(this).width(jQuery(firstTableFirstRow[index]).get(0).style.width);
267                  }
268                });
269              });
270            }
271          }
272          //if row has merged cells no need place header there
273          if (table.data('merged') && table.hasClass('ColWithMergeCellsAlign')) {
274            var mergedData = table.data('merged');
275            jQuery.each(mergedData, function (index, value) {
276              var rowNumWithMergeCell = value.row;
277              var numForEq = Number(rowNumWithMergeCell) - 1;
278              table
279                .find('tbody tr:eq(' + numForEq + ')')
280                .closest('tr')
281                .addClass('haveMergedCell');
282            });
283            self.setCellAttributes(table.parents('.supsystic-tables-wrap:first').find('.DTFC_LeftWrapper, DTFC_RightWrapper, .dataTables_scrollHead, .dataTables_scrollFoot').find('th, td'));
284          }
285          if (typeof self.getTableInstanceById(table.data('id')).fnAdjustColumnSizing == 'function') {
286            table.trigger('responsive-resize.dt');
287            setTimeout(function () {
288              table.trigger('responsive-resize.dt');
289              self.getTableInstanceById(table.data('id')).fnAdjustColumnSizing(false);
290            }, 500);
291          }
292          self.initShortcodesInTable(table);
293        });
294        //self.initShortcodesInTable(jQuery(this));
295      });
296    };
297
298    vendor[appName].initShortcodesInTable = function (table) {
299      var tableViewId = table.data('view-id');
300      //google-maps-easy
301      if (typeof gmpAllMapsInfo !== 'undefined' && gmpAllMapsInfo && gmpAllMapsInfo.length) {
302        for (var i = 0; i < gmpAllMapsInfo.length; i++) {
303          var mapData = gmpAllMapsInfo[i],
304            map = jQuery('#' + mapData.view_html_id);
305          if (map.length && map.closest('#supsystic-table-' + tableViewId).length) {
306            var mapViewId = mapData.view_id;
307            setTimeout(
308              function (mapData, mapViewId) {
309                g_gmpAllMaps = jQuery.grep(g_gmpAllMaps, function (value) {
310                  if (value.getViewId() == mapViewId) {
311                    if (mapData.heatmap && mapData.heatmap.coords) {
312                      var coord = [],
313                        oldCoord = mapData.heatmap.coords;
314                      for (var c = 0; c < oldCoord.length; c++) {
315                        var data = oldCoord[c];
316                        coord.push(typeof data == 'object' ? data.join(',') : data);
317                      }
318                      mapData.heatmap.coords = coord;
319                    }
320                    if (value._mapParams.simple_slider_id) {
321                      jQuery('#' + value._mapParams.simple_slider_id).html(value._mapParams.original_slider_html);
322                    }
323                  }
324                  return value.getViewId() != mapViewId;
325                });
326                gmpInitMapOnPage(mapData);
327              },
328              50,
329              mapData,
330              mapViewId
331            );
332          }
333        }
334        jQuery(document).trigger('gmpAmiVarInited');
335      }
336      //ultimate-maps
337      if (typeof umsAllMapsInfo !== 'undefined' && umsAllMapsInfo && umsAllMapsInfo.length) {
338        for (var i = 0; i < umsAllMapsInfo.length; i++) {
339          var mapData = umsAllMapsInfo[i],
340            map = jQuery('#' + mapData.view_html_id);
341          if (map.length && map.closest('#supsystic-table-' + tableViewId).length) {
342            var mapViewId = mapData.view_id;
343            setTimeout(
344              function (mapData, mapViewId) {
345                g_umsAllMaps = jQuery.grep(g_umsAllMaps, function (value) {
346                  if (value.getViewId() == mapViewId) {
347                    value._mapObj.remove();
348                  }
349                  return value.getViewId() != mapViewId;
350                });
351                umsInitMapOnPage(mapData);
352              },
353              600,
354              mapData,
355              mapViewId
356            );
357          }
358        }
359        jQuery(document).trigger('umsAmiVarInited');
360      }
361    };
362
363    vendor[appName]._getOriginalImageSizes = function (img) {
364      var tempImage = new Image(),
365        width,
366        height;
367      if ('naturalWidth' in tempImage && 'naturalHeight' in tempImage) {
368        width = img.naturalWidth;
369        height = img.naturalHeight;
370      } else {
371        tempImage.src = img.src;
372        width = tempImage.width;
373        height = tempImage.height;
374      }
375      return {
376        width: width,
377        height: height,
378      };
379    };
380
381    vendor[appName]._calculateImages = function ($table) {
382      var self = this,
383        $images = $table.find('img');
384      if ($images.length > 0 && /firefox|trident|msie/i.test(navigator.userAgent)) {
385        $images.hide();
386        jQuery.each($images, function (index, el) {
387          var $img = jQuery(this),
388            originalSizes = self._getOriginalImageSizes(this);
389          if ($img.closest('td, th').width() < originalSizes.width) {
390            $img.css('width', '100%');
391          }
392        });
393        $images.show();
394      }
395    };
396
397    vendor[appName].createSpinner = function (elem) {
398      elem = typeof elem != 'undefined' ? elem : false;
399
400      if (elem) {
401        var icon = elem.attr('disabled', true).find('.fa');
402
403        if (icon) {
404          icon.data('icon', icon.attr('class'));
405          icon.attr('class', 'fa fa-spinner fa-spin');
406        }
407      } else {
408        return jQuery('<i/>', {
409          class: 'fa fa-spinner fa-spin',
410        });
411      }
412    };
413
414    vendor[appName].deleteSpinner = function (elem) {
415      var icon = elem.attr('disabled', false).find('.fa');
416
417      if (icon) {
418        icon.attr('class', icon.data('icon'));
419        icon.data('icon', '');
420      }
421    };
422
423    vendor[appName].getResponsiveColumnSettings = function ($table) {
424      var defaults = {
425          desktop: { minWidth: 1025, maxWidth: '', visible: '*', toggle: '' },
426          tablet: { minWidth: 768, maxWidth: 1024, visible: '1-5', toggle: '*' },
427          mobile: { minWidth: 0, maxWidth: 767, visible: '1-2', toggle: '*' },
428        },
429        source = $table.data('responsive-column-settings') || {},
430        settings = {},
431        names = ['desktop', 'tablet', 'mobile'];
432
433      jQuery.each(names, function (index, name) {
434        var current = source && source[name] ? source[name] : {};
435        settings[name] = jQuery.extend({}, defaults[name], current);
436        settings[name].minWidth = parseInt(settings[name].minWidth, 10);
437        settings[name].maxWidth = settings[name].maxWidth === '' || typeof settings[name].maxWidth == 'undefined' ? '' : parseInt(settings[name].maxWidth, 10);
438        settings[name].minWidth = isNaN(settings[name].minWidth) ? defaults[name].minWidth : settings[name].minWidth;
439        settings[name].maxWidth = settings[name].maxWidth === '' || isNaN(settings[name].maxWidth) ? '' : settings[name].maxWidth;
440        settings[name].visible = typeof settings[name].visible == 'undefined' ? defaults[name].visible : String(settings[name].visible);
441        settings[name].toggle = typeof settings[name].toggle == 'undefined' ? defaults[name].toggle : String(settings[name].toggle);
442      });
443
444      return settings;
445    };
446
447    vendor[appName].parseResponsiveColumnList = function (value, columnCount) {
448      var result = { all: false, columns: {} };
449
450      value = typeof value == 'undefined' ? '' : String(value).replace(/\s+/g, '');
451      if (!value.length) {
452        return result;
453      }
454      if (value === '*') {
455        result.all = true;
456        return result;
457      }
458
459      jQuery.each(value.split(','), function (index, part) {
460        var range, start, end, i;
461
462        if (!part.length) {
463          return;
464        }
465        if (part === '*') {
466          result.all = true;
467          return false;
468        }
469
470        range = part.split('-');
471        start = parseInt(range[0], 10);
472        end = range.length > 1 ? parseInt(range[1], 10) : start;
473        if (isNaN(start) || isNaN(end)) {
474          return;
475        }
476        if (end < start) {
477          i = start;
478          start = end;
479          end = i;
480        }
481        start = Math.max(1, start);
482        end = Math.min(columnCount, end);
483        if (start > columnCount || end < 1) {
484          return;
485        }
486        for (i = start; i <= end; i++) {
487          result.columns[i - 1] = true;
488        }
489      });
490
491      return result;
492    };
493
494    vendor[appName].responsiveColumnListContains = function (list, columnIndex) {
495      return !!(list && (list.all || list.columns[columnIndex]));
496    };
497
498    vendor[appName].getResponsiveColumnPreviewProfile = function ($table) {
499      var names = ['desktop', 'tablet', 'mobile'],
500        previewContainer = $table.closest('#table-preview'),
501        profile = $table.attr('data-responsive-column-preview-profile') || previewContainer.attr('data-responsive-column-profile');
502
503      profile = typeof profile == 'undefined' ? '' : String(profile);
504      return toeInArray(profile, names) != -1 ? profile : '';
505    };
506
507    vendor[appName].getActiveResponsiveColumnProfile = function ($table) {
508      var settings = this.getResponsiveColumnSettings($table),
509        previewProfile = this.getResponsiveColumnPreviewProfile($table),
510        width = window.innerWidth || jQuery(window).width(),
511        names = ['desktop', 'tablet', 'mobile'],
512        fallback = 'desktop';
513
514      if (previewProfile) {
515        return previewProfile;
516      }
517
518      for (var i = 0; i < names.length; i++) {
519        var name = names[i],
520          min = settings[name].minWidth,
521          max = settings[name].maxWidth === '' ? Infinity : settings[name].maxWidth;
522
523        if (width >= min && width <= max) {
524          return name;
525        }
526      }
527
528      if (width <= settings.mobile.maxWidth) {
529        fallback = 'mobile';
530      } else if (settings.tablet.maxWidth !== '' && width <= settings.tablet.maxWidth) {
531        fallback = 'tablet';
532      }
533
534      return fallback;
535    };
536
537    vendor[appName].isResponsiveColumnVisibleForProfile = function ($table, profile, columnIndex, columnCount) {
538      var settings = this.getResponsiveColumnSettings($table),
539        list = this.parseResponsiveColumnList(settings[profile].visible, columnCount);
540
541      return this.responsiveColumnListContains(list, columnIndex);
542    };
543
544    vendor[appName].isResponsiveColumnToggleForProfile = function ($table, profile, columnIndex, columnCount) {
545      var settings = this.getResponsiveColumnSettings($table),
546        visible = this.parseResponsiveColumnList(settings[profile].visible, columnCount),
547        toggle = this.parseResponsiveColumnList(settings[profile].toggle, columnCount);
548
549      if (this.responsiveColumnListContains(visible, columnIndex)) {
550        return false;
551      }
552      if (!jQuery.trim(settings[profile].toggle).length) {
553        return true;
554      }
555      if (toggle.all) {
556        return true;
557      }
558
559      return this.responsiveColumnListContains(toggle, columnIndex);
560    };
561
562    vendor[appName].getResponsiveColumnBreakpoints = function ($table) {
563      var settings = this.getResponsiveColumnSettings($table),
564        previewProfile = this.getResponsiveColumnPreviewProfile($table);
565
566      if (previewProfile) {
567        return [{ name: previewProfile, width: Infinity }];
568      }
569
570      return [
571        { name: 'desktop', width: settings.desktop.maxWidth === '' ? Infinity : settings.desktop.maxWidth },
572        { name: 'tablet', width: settings.tablet.maxWidth === '' ? 1024 : settings.tablet.maxWidth },
573        { name: 'mobile', width: settings.mobile.maxWidth === '' ? 767 : settings.mobile.maxWidth },
574      ];
575    };
576
577    vendor[appName].applyResponsiveColumnClasses = function ($table) {
578      var self = this,
579        profiles = ['desktop', 'tablet', 'mobile'],
580        headers = $table.find('thead tr:not(.stbColumnsSearchWra
580pper):first th'),
581        columnCount = headers.length;
582
583      headers.each(function (columnIndex) {
584        var header = jQuery(this),
585          classes = [];
586
587        header.removeClass('desktop tablet mobile none all');
588        jQuery.each(profiles, function (index, profile) {
589          if (self.isResponsiveColumnVisibleForProfile($table, profile, columnIndex, columnCount)) {
590            classes.push(profile);
591          }
592        });
593        header.addClass(classes.length ? classes.join(' ') : 'none');
594      });
595    };
596
597    vendor[appName].buildResponsiveDetailsRenderer = function (modeWithSettings) {
598      var self = this;
599
600      return function (api, rowIdx, columns) {
601        var $table = jQuery(api.table().node()),
602          profile = self.getActiveResponsiveColumnProfile($table),
603          columnCount = columns.length,
604          $subTable = jQuery('<table/>');
605
606        jQuery.each(columns, function (i, col) {
607          if (modeWithSettings) {
608            if (!self.isResponsiveColumnToggleForProfile($table, profile, col.columnIndex, columnCount)) {
609              return;
610            }
611          } else if (!col.hidden) {
612            return;
613          }
614
615          var $cell = jQuery(api.cell(col.rowIndex, col.columnIndex).node()).clone(),
616            markup = '<tr data-dt-row="' + col.rowIndex + '" data-dt-column="' + col.columnIndex + '">';
617          if ($table.data('head') == 'on') {
618            var tableHeadTr = jQuery(api.table().header()).find('tr:not(.stbColumnsSearchWra
618pper)').eq(0);
619            var $headerCell = tableHeadTr.find('th').eq(col.columnIndex).clone();
620            $headerCell.find('.stbColumnSearchField').remove();
621            var $headerContent = $headerCell.html();
622            markup += '<td>';
623            if ($headerContent) {
624              markup += $headerContent;
625            }
626            markup += '</td>';
627          }
628          markup += '</tr>';
629          $cell.after(jQuery('<td>').addClass('collapsed-cell-holder').attr('data-cell-row', col.rowIndex).attr('data-cell-column', col.columnIndex).hide());
630          $subTable.append(jQuery(markup).append($cell.addClass('collapsed').show()));
631        });
632        return $subTable.is(':empty') ? false : $subTable;
633      };
634    };
635
636    vendor[appName].syncResponsiveColumnSearch = function ($table, columns) {
637      $table.find('th input.search-column').each(function () {
638        var th = jQuery(this).parents('th:first'),
639          i = th.index();
640        if (columns.length > i) {
641          th.css('display', columns[i] ? '' : 'none');
642        }
643      });
644    };
645
646    vendor[appName].getCellMaxHeight = function ($table) {
647      var height = parseInt($table.data('cell-max-height'), 10);
648
649      return isNaN(height) || height <= 0 ? 0 : height;
650    };
651
652    vendor[appName].getCellMaxWidth = function ($table) {
653      var width = parseInt($table.data('cell-max-width'), 10);
654
655      return isNaN(width) || width <= 0 ? 0 : width;
656    };
657
658    vendor[appName].getCellMaxWidthRules = function ($table, columnCount) {
659      var self = this,
660        source = $table.data('cell-max-width-rules') || [],
661        rules = [];
662
663      if (!jQuery.isArray(source) && typeof source == 'object') {
664        source = jQuery.map(source, function (rule) {
665          return rule;
666        });
667      }
668      if (!jQuery.isArray(source)) {
669        return rules;
670      }
671
672      jQuery.each(source, function (index, rule) {
673        var columns = rule && typeof rule.columns != 'undefined' ? jQuery.trim(String(rule.columns)) : '',
674          maxWidth = rule && typeof rule.maxWidth != 'undefined' ? parseInt(rule.maxWidth, 10) : 0,
675          list;
676
677        if (!columns.length || isNaN(maxWidth) || maxWidth <= 0) {
678          return;
679        }
680
681        list = self.parseResponsiveColumnList(columns, columnCount);
682        if (list.all || !jQuery.isEmptyObject(list.columns)) {
683          rules.push({
684            columns: list,
685            maxWidth: maxWidth,
686          });
687        }
688      });
689
690      return rules;
691    };
692
693    vendor[appName].applyCellDimensions = function ($table) {
694      var self = this,
695        height = this.getCellMaxHeight($table),
696        globalWidth = this.getCellMaxWidth($table),
697        firstRowCells = $table.children('tbody').children('tr:not(.child):first').children('td'),
698        columnCount = firstRowCells.length || $table.find('thead tr:not(.stbColumnsSearchWra
698pper):first th').length,
699        widthRules = this.getCellMaxWidthRules($table, columnCount);
700
701      if (!height && !globalWidth && !widthRules.length) {
702        return;
703      }
704
705      var getInnerStyles = function (height, width) {
706        return {
707          maxHeight: height ? height + 'px' : '',
708          maxWidth: width ? width + 'px' : '',
709        };
710      },
711        unwrapCell = function ($cell, $inner) {
712          $cell.removeClass('stb-cell-dimension-cell');
713          if ($inner.length) {
714            $inner.contents().unwrap();
715          }
716        };
717
718      $table
719        .children('tbody')
720        .children('tr:not(.child)')
721        .children('td')
722        .not('.collapsed-cell-holder, .dataTables_empty')
723        .each(function () {
724          var $cell = jQuery(this),
725            columnIndex = $cell.index(),
726            width = globalWidth,
727            $inner = $cell.children('.stb-cell-dimension-inner:first, .stb-cell-max-height-inner:first');
728
729          jQuery.each(widthRules, function (index, rule) {
730            if (self.responsiveColumnListContains(rule.columns, columnIndex)) {
731              width = rule.maxWidth;
732            }
733          });
734
735          if (!height && !width) {
736            unwrapCell($cell, $inner);
737            return;
738          }
739
740          $cell.addClass('stb-cell-dimension-cell');
741          if ($inner.length) {
742            $inner.addClass('stb-cell-dimension-inner').css(getInnerStyles(height, width));
743          } else {
744            $inner = jQuery('<div/>').addClass('stb-cell-dimension-inner').css(getInnerStyles(height, width));
745            $cell.contents().appendTo($inner);
746            $cell.append($inner);
747          }
748
749          if ((!height || $inner.get(0).scrollHeight <= height + 1) && (!width || $inner.get(0).scrollWidth <= width + 1)) {
750            unwrapCell($cell, $inner);
751          }
752        });
753    };
754
755    vendor[appName].queueCellDimensions = function ($table) {
756      var self = this,
757        timers = $table.data('stb-cell-dimension-timers') || [],
758        delays = [0, 50, 250];
759
760      jQuery.each(timers, function (index, timer) {
761        clearTimeout(timer);
762      });
763
764      timers = [];
765
766      jQuery.each(delays, function (index, delay) {
767        var timer = setTimeout(function () {
768          self.applyCellDimensions($table);
769          if (index === delays.length - 1) {
770            $table.removeData('stb-cell-dimension-timers');
771          }
772        }, delay);
773
774        timers.push(timer);
775      });
776
777      $table.data('stb-cell-dimension-timers', timers);
778    };
779
780    vendor[appName].initializeTable = function (table, callback, finalCallback, reinit, addInstance) {
781      if (typeof jQuery.fn.dataTable.moment == 'undefined' && typeof moment !== 'undefined') {
782        jQuery.fn.dataTable.moment = function (format, locale, reverseEmpties) {
783          var types = jQuery.fn.dataTable.ext.type;
784          // Add type detection
785          types.detect.unshift(function (d) {
786            if (d) {
787              // Strip HTML tags and newline characters if possible
788              if (d.replace) {
789                d = d.replace(/(<.*?>)|(\r?\n|\r)/g, '');
790              }
791
792              // Strip out surrounding white space
793              d = jQuery.trim(d);
794            }
795            // Null and empty values are acceptable
796            if (d === '' || d === null) {
797              return 'moment-' + format;
798            }
799            return moment(d, format, locale, true).isValid() ? 'moment-' + format : null;
800          });
801          // Add sorting method - use an integer for the sorting
802          types.order['moment-' + format + '-pre'] = function (d) {
803            if (d) {
804              // Strip HTML tags and newline characters if possible
805              if (d.replace) {
806                d = d.replace(/(<.*?>)|(\r?\n|\r)/g, '');
807              }
808
809              // Strip out surrounding white space
810              d = jQuery.trim(d);
811            }
812
813            return !moment(d, format, locale, true).isValid() ? (reverseEmpties ? -Infinity : Infinity) : parseInt(moment(d, format, locale, true).format('x'), 10);
814          };
815        };
816      }
817
818      if (typeof jQuery.fn.dataTable.ext.order.intl == 'undefined' && typeof window.Intl !== 'undefined') {
819        jQuery.fn.dataTable.ext.order.intl = function (locales, options) {
820          if (window.Intl) {
821            var collator = new Intl.Collator(locales, options);
822            var types = jQuery.fn.dataTable.ext.type;
823
824            delete types.order['string-pre'];
825            types.order['string-asc'] = collator.compare;
826            types.order['string-desc'] = function (a, b) {
827              return collator.compare(a, b) * -1;
828            };
829          }
830        };
831      }
832
833      if (typeof naturalSort == 'undefined') {
834        function naturalSort(a, b, html) {
835          var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?%?$|^0x[0-9a-f]+$|[0-9]+)/gi,
836            sre = /(^[ ]*|[ ]*$)/g,
837            dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
838            hre = /^0x[0-9a-f]+$/i,
839            ore = /^0/,
840            htmre = /(<([^>]+)>)/gi,
841            // convert all to strings and trim()
842            x = a.toString().replace(sre, '') || '',
843            y = b.toString().replace(sre, '') || '';
844          // remove html from strings if desired
845          if (!html) {
846            x = x.replace(htmre, '');
847            y = y.replace(htmre, '');
848          }
849          // chunk/tokenize
850          var xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
851            yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
852            // numeric, hex or date detection
853            xD = parseInt(x.match(hre), 10) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
854            yD = parseInt(y.match(hre), 10) || (xD && y.match(dre) && Date.parse(y)) || null;
855
856          // first try and sort Hex codes or Dates
857          if (yD) {
858            if (xD < yD) {
859              return -1;
860            } else if (xD > yD) {
861              return 1;
862            }
863          }
864
865          // natural sorting through split numeric strings and default strings
866          for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
867            // find floats not starting with '0', string or 0 if not defined (Clint Priest)
868
869            /*supsystic*/
870            //var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc], 10) || xN[cLoc] || 0;
871            //var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc], 10) || yN[cLoc] || 0;
872            var oFxNcL = parseFloat(xN[cLoc], 10) || xN[cLoc] || undefined;
873            var oFyNcL = parseFloat(yN[cLoc], 10) || yN[cLoc] || undefined;
874            /*****/
875
876            // handle numeric vs string comparison - number < string - (Kyle Adams)
877            if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
878              return isNaN(oFxNcL) ? 1 : -1;
879            }
880            // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
881            else if (typeof oFxNcL !== typeof oFyNcL) {
882              oFxNcL += '';
883              oFyNcL += '';
884            }
885            if (oFxNcL < oFyNcL) {
886              return -1;
887            }
888            if (oFxNcL > oFyNcL) {
889              return 1;
890            }
891          }
892          return 0;
893        }
894      }
895
896      if (typeof jQuery.fn.dataTableExt.oApi.fnFakeRowspan == 'undefined') {
897        jQuery.fn.dataTableExt.oApi.fnFakeRowspan = function (oSettings) {
898          if (oSettings) {
899            var cells;
900            jQuery.each(oSettings.aoData, function (index, rowData) {
901              vendor[appName].setCellAttributes(rowData.anCells);
902            });
903            if (oSettings.aoHeader.length) {
904              cells = [];
905              jQuery.each(oSettings.aoHeader, function (index, rowData) {
906                jQuery.each(rowData, function (index, cellData) {
907                  cells.push(cellData.cell);
908                });
909              });
910              vendor[appName].setCellAttributes(cells);
911            }
912            if (oSettings.aoFooter.length) {
913              cells = [];
914              jQuery.each(oSettings.aoFooter, function (index, rowData) {
915                jQuery.each(rowData, function (index, cellData) {
916                  cells.push(cellData.cell);
917                });
918              });
919              vendor[appName].setCellAttributes(cells);
920            }
921          }
922          return this;
923        };
924      }
925
926      if (typeof jQuery.fn.dataTableExt.oApi.fnResetFakeRowspan == 'undefined') {
927        jQuery.fn.dataTableExt.oApi.fnResetFakeRowspan = function (oSettings) {
928          if (oSettings) {
929            var displayRows = oSettings.aiDisplay,
930              mergedData = jQuery(oSettings.nTable).data('merged');
931            if (!mergedData || mergedData.length == 0 || displayRows.length == 0) return this;
932
933            var rows = oSettings.aoData,
934              table = jQuery(oSettings.nTable),
935              autoHiding = table.attr('data-auto-hiding'),
936              rowNums = {},
937              first = table.attr('data-auto-index') == 'new' ? 1 : 0;
938            autoHiding = typeof autoHiding != 'undefined' && autoHiding.length > 0 ? autoHiding.split(',').map(Number) : [];
939
940            jQuery.each(displayRows, function (index, rowNum) {
941              var cells = rows[rowNum].anCells;
942              rowNums[cells[first].getAttribute('data-y')] = rowNum;
943              for (var i = 0; i < cells.length; i++) {
944                if (cells[i].getAttribute('data-hide') == 'true' && (autoHiding.length <= i || autoHiding[i] == 1)) {
945                  jQuery(cells[i]).css('display', '');
946                }
947                cells[i].setAttribute('rowspan', 1);
948                cells[i].setAttribute('colspan', 1);
949              }
950            });
951            jQuery.each(mergedData, function (index, value) {
952              var firstRow = Number(value.row) + 1,
953                lastRow = firstRow + Number(value.rowspan) - 1,
954                colspan = Number(value.colspan),
955                firstCol = Number(value.col) + first,
956                lastCol = firstCol + colspan - 1,
957                rowspan = 0;
958              for (var r = firstRow; r <= lastRow; r++) {
959                if (r in rowNums) {
960                  if (rowspan == 0) {
961                    firstRow = r;
962                  }
963                  for (var c = firstCol + (firstRow == r ? 1 : 0); c <= lastCol; c++) {
964                    var cell = rows[rowNums[r]].anCells[c];
965                    if (typeof cell !== 'undefined' && typeof cell.style !== 'undefined' && typeof cell.style.display !== 'undefined') {
966                      cell.style.display = 'none';
967                    }
968                    if (autoHiding[c] === 0) {
969                      colspan--;
970                    }
971                  }
972                  rowspan++;
973                }
974              }
975              if (rowspan > 0) {
976                var mergedCell = rows[rowNums[firstRow]].anCells[firstCol];
977                if (rowspan > 1) {
978                  mergedCell.setAttribute('rowspan', rowspan);
979                }
980                if (colspan > 1) {
981                  mergedCell.setAttribute('colspan', colspan);
982                }
983              }
984            });
985          }
986          return this;
987        };
988      }
989
990      if (typeof jQuery.fn.dataTableExt.oSort !== 'undefined') {
991        jQuery.extend(jQuery.fn.dataTableExt.oSort, {
992          'natural-asc': function (a, b) {
993            return naturalSort(a, b, true);
994          },
995          'natural-desc': function (a, b) {
996            return naturalSort(a, b, true) * -1;
997          },
998          'natural-nohtml-asc': function (a, b) {
999            return naturalSort(a, b, false);
1000          },
1001          'natural-nohtml-desc': function (a, b) {
1002            return naturalSort(a, b, false) * -1;
1003          },
1004          'natural-ci-asc': function (a, b) {
1005            a = a.toString().toLowerCase();
1006            b = b.toString().toLowerCase();
1007
1008            return naturalSort(a, b, true);
1009          },
1010          'natural-ci-desc': function (a, b) {
1011            a = a.toString().toLowerCase();
1012            b = b.toString().toLowerCase();
1013
1014            return naturalSort(a, b, true) * -1;
1015          },
1016          'natural-nohtml-ci-asc': function (a, b) {
1017            a = a.toString().toLowerCase();
1018            b = b.toString().toLowerCase();
1019
1020            return naturalSort(a, b, false);
1021          },
1022          'natural-nohtml-ci-desc': function (a, b) {
1023            a = a.toString().toLowerCase();
1024            b = b.toString().toLowerCase();
1025
1026            return naturalSort(a, b, false) * -1;
1027          },
1028        });
1029      }
1030
1031      reinit = typeof reinit != 'undefined' ? reinit : {};
1032      addInstance = typeof addInstance != 'undefined' ? addInstance : true;
1033
1034      var self = this,
1035        $table = table instanceof $ ? table : jQuery(table),
1036        features = $table.data('features'),
1037        config = {},
1038        responsiveMode = $table.data('responsive-mode'),
1039        searchingSettings = $table.data('searching-settings'),
1040        tableInstance = {},
1041        buildProcessingLoaderHtml = function ($currentTable) {
1042          var iconName = $currentTable.data('loader-icon-name') || 'default',
1043            iconItems = parseInt($currentTable.data('loader-icon-items'), 10),
1044            processingColor = $currentTable.data('processing-color') || $currentTable.data('loader-color') || '#000000',
1045            processingBg = $currentTable.data('processing-bg') || '#ffffff',
1046            itemsHtml = '',
1047            i = 0;
1048
1049          iconItems = isNaN(iconItems) || iconItems < 0 ? 0 : iconItems;
1050          if (iconName === 'default') {
1051            return '<div class="stb-processing-loader-wrap" style="background-color:' + processingBg + ';"><div class="supsystic-table-loader spinner" style="background-color:' + processingColor + ';"></div></div>';
1052          }
1053
1054          for (i = 0; i < iconItems; i++) {
1055            itemsHtml += '<div></div>';
1056          }
1057
1058          return '<div class="stb-processing-loader-wrap" style="background-color:' + processingBg + ';"><div class="supsystic-table-loader la-' + iconName + ' la-2x" style="color:' + processingColor + ';">' + itemsHtml + '</div></div>';
1059        },
1060        setupProcessingLoader = function ($currentTable, instance) {
1061          var $processing = $currentTable.closest('.dataTables_wrapper').find('.dataTables_processing');
1062
1063          if (!$processing.length) {
1064            return;
1065          }
1066
1067          $processing.html(buildProcessingLoaderHtml($currentTable));
1068
1069          if (instance && typeof instance.on === 'function') {
1070            instance.on('processing.dt', function () {
1071              $processing.html(buildProcessingLoaderHtml($currentTable));
1072            });
1073          }
1074        },
1075        cssEscapeIdentifier = function (value) {
1076          if (window.CSS && typeof window.CSS.escape === 'function') {
1077            return window.CSS.escape(String(value));
1078          }
1079
1080          return String(value).replace(/^[0-9-]|[^a-zA-Z0-9_-]/g, function (character) {
1081            return '\\' + character.charCodeAt(0).toString(16) + ' ';
1082          });
1083        },
1084        cssEscapeString = function (value) {
1085          return String(value)
1086            .replace(/\\/g, '\\\\')
1087            .replace(/"/g, '\\"')
1088            .replace(/\r/g, '\\D ')
1089            .replace(/\n/g, '\\A ')
1090            .replace(/\f/g, '\\C ');
1091        },
1092        appendResponsiveLabelStyles = function ($currentTable) {
1093          var tableId = $currentTable.attr('id'),
1094            labelStyles = '',
1095            styleNode;
1096
1097          if (!tableId) {
1098            return;
1099          }
1100
1101          $currentTable.find('thead th').each(function (index) {
1102            labelStyles += '#' + cssEscapeIdentifier(tableId) + '.oneColumnWithLabels td:nth-of-type(' + (index + 1) + '):before { content: "' + cssEscapeString(jQuery(this).text()) + '"; }';
1103          });
1104
1105          if (!labelStyles) {
1106            return;
1107          }
1108
1109          styleNode = document.createElement('style');
1110          styleNode.type = 'text/css';
1111          styleNode.setAttribute('data-supsystic-responsive-labels', tableId);
1112          styleNode.textContent = labelStyles;
1113          $currentTable.before(styleNode);
1114        },
1115        defaultFeatures = {
1116          autoWidth: false,
1117          info: false,
1118          ordering: false,
1119          paging: false,
1120          responsive: false,
1121          searching: false,
1122          stateSave: false,
1123          bJQueryUI: true,
1124          api: true,
1125          retrieve: true,
1126          processing: true,
1127          initComplete: callback,
1128          headerCallback: function (thead, data, start, end, display) {
1129            jQuery(thead)
1130              .closest('thead')
1131              .find('th')
1132              .each(function () {
1133                self.setStylesToCell(this);
1134              });
1135          },
1136          footerCallback: function (tfoot, data, start, end, display) {
1137            jQuery(tfoot)
1138              .closest('tfoot')
1139              .find('th')
1140              .each(function () {
1141                self.setStylesToCell(this);
1142              });
1143          },
1144          // order param disable the default table sorting.
1145          // it should be here because of Woocommerce addon:
1146          // it has no hidden header for tables without header
1147          // and in triggers an error during initializing.
1148          // order param should be disabled later during sorting activation
1149          order: [],
1150        };
1151
1152      g_stbServerSideProcessing = $table.data('server-side-processing') && $table.data('server-side-processing') == 'on';
1153
1154      // Fix for searching by merged cells
1155      $table.find('tbody td[data-colspan], tbody td[data-rowspan]').each(function (index, item) {
1156        var cell = jQuery(item),
1157          cellData = cell.html();
1158
1159        // prevent of copy cell data if it contains tags with id attribute - it must be unique on page
1160        if (!cellData.toString().match(/<.*?id=['|"].*?['|"].*?>/g)) {
1161          var cellOrValue = cell.data('original-value'),
1162            cellFormula = cell.data('formula'),
1163            cellOrder = cell.data('order'),
1164            table = cell.parents('table:first'),
1165            colIndex = cell.index(),
1166            rowIndex = cell.parents('tr:first').index(),
1167            colspan = cell.data('colspan'),
1168            rowspan = cell.data('rowspan');
1169
1170          for (var i = rowIndex + 1; i <= rowIndex + rowspan; i++) {
1171            for (var j = colIndex + 1; j <= colIndex + colspan; j++) {
1172              var hiddenCell = table.find('tbody tr:nth-child(' + i + ') td:nth-child(' + j + ')');
1173
1174              if (hiddenCell.data('hide') && !$table.data('merged')) {
1175                hiddenCell.html(cellData);
1176                hiddenCell.data('original-value', cellOrValue);
1177                hiddenCell.attr('data-original-value', cellOrValue);
1178                hiddenCell.data('order', cellOrder);
1179                hiddenCell.attr('data-order', cellOrder);
1180                if (cellFormula) {
1181                  hiddenCell.data('formula', cellFormula);
1182                  hiddenCell.attr('data-formula', cellFormula);
1183                }
1184              }
1185            }
1186          }
1187        }
1188      });
1189
1190      // Set features
1191      jQuery.each(features, function () {
1192        var featureName = this.replace(/[-_]([a-z])/g, function (g) {
1193          return g[1].toUpperCase();
1194        });
1195        config[featureName] = true;
1196      });
1197      if ($table.data('search-value') && !config['searching']) {
1198        config['searching'] = true;
1199      }
1200      if (!config['searching'] && typeof this.setTableAddSearching === 'function') {
1201        config['searching'] = this.setTableAddSearching($table);
1202      }
1203      if (toeInArray('searching', features) != -1 && searchingSettings) {
1204        if (searchingSettings.searchByHiddenField !== 'on') {
1205          var hiddenSearchTargets = [];
1206          $table.find('thead tr:first th.invisibleCell').each(function () {
1207            hiddenSearchTargets.push(jQuery(this).index());
1208          });
1209          if (hiddenSearchTargets.length) {
1210            config.columnDefs = config.columnDefs || [];
1211            config.columnDefs.push({
1212              targets: hiddenSearchTargets,
1213              searchable: false,
1214            });
1215          }
1216        }
1217        if (searchingSettings.minChars > 0 || searchingSettings.resultOnly || searchingSettings.strictMatching) {
1218          jQuery.fn.dataTable.ext.search.push(function (settings, data) {
1219            var $searchInput = jQuery(settings.nTableWrapper).find('.dataTables_filter input'),
1220              searchValue = $searchInput.val();
1221
1222            if (searchingSettings.resultOnly && searchValue.length === 0) {
1223              if (searchingSettings.showTable) {
1224                return false;
1225              }
1226              return false;
1227            }
1228            if (searchingSettings.strictMatching) {
1229              searchValue = jQuery.fn.dataTable.util.escapeRegex(searchValue);
1230              var regExp = new RegExp('^' + searchValue, 'i');
1231
1232              for (var i = 0; i < data.length; i++) {
1233                var words = data[i].replace(/\s\s+/g, ' ').split(' ');
1234
1235                for (var j = 0; j < words.length; j++) {
1236                  if (words[j].match(regExp)) {
1237                    return true;
1238                  }
1239                }
1240              }
1241              return false;
1242            } else {
1243              return data.join(' ').toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
1244            }
1245          });
1246          $table.on('init.dt', function (event, settings) {
1247            if (!settings) {
1248              return;
1249            }
1250
1251            var $tableWrapper = jQuery(settings.nTableWrapper),
1252              $tableSearchInput = $tableWrapper.find('.dataTables_filter input'),
1253              $customInput = $tableSearchInput.clone();
1254
1255            $tableSearchInput.replaceWith($customInput);
1256
1257            $customInput.on('input change', function () {
1258              if (!searchingSettings.showTable) {
1259                if (searchingSettings.resultOnly && searchingSettings.minChars && (this.value.length < searchingSettings.minChars || !this.value.length)) {
1260                  $table.hide();
1261                  $table.parent().find('.dataTables_paginate').hide();
1262                } else {
1263                  $table.show();
1264                  $table.parent().find('.dataTables_paginate').show();
1265                }
1266              }
1267              if (searchingSettings.minChars && this.value.length < searchingSettings.minChars && this.value.length !== 0) {
1268                event.preventDefault();
1269                return false;
1270              }
1271              $table.api().draw();
1272            });
1273
1274            if (searchingSettings.resultOnly && !searchingSettings.showTable) {
1275              $table.hide();
1276              $table.parent().find('.dataTables_paginate').hide();
1277            }
1278          });
1279        }
1280        if (searchingSettings.columnSearch) {
1281          var inputTop = searchingSettings.columnSearchPosition && searchingSettings.columnSearchPosition == 'top',
1282   
1282         tPosition = inputTop ? 'thead' : 'tfoot',
1283            labelsSettingEnabled = searchingSettings.columnSearchShowLabel && searchingSettings.columnSearchShowLabel == 'on',
1284            showColumnLabel = labelsSettingEnabled,
1285            hasHeader = !!$table.data('head'),
1286            inlineTopSearch = inputTop && hasHeader,
1287            escapeHtml = function (text) {
1288              return String(text)
1289                .replace(/&/g, '&amp;')
1290                .replace(/</g, '&lt;')
1291                .replace(/>/g, '&gt;')
1292                .replace(/"/g, '&quot;')
1293                .replace(/'/g, '&#039;');
1294            };
1295          if (inputTop && hasHeader) {
1296            showColumnLabel = false;
1297          }
1298          if (!$table.find('.stbColumnsSearchWrapper').length) {
1299            var headerRow = $table.find('thead tr:first').find('th');
1300            if (headerRow.length) {
1301              if (inlineTopSearch) {
1302                for (var i = 0; i < headerRow.length; i++) {
1303                  var inlineCell = jQuery(headerRow[i]);
1304                  if (inlineCell.find('.stbColumnSearchField.stbColumnsSearchWra
1304pper').length) {
1305                    continue;
1306                  }
1307
1308                  var inlineTitle = jQuery.trim(
1309                      inlineCell
1310                        .clone()
1311                        .find('.stbColumnSearchField')
1312                        .remove()
1313                        .end()
1314                        .text()
1315                    ).replace(/\s+/g, ' '),
1316                    escapedInlineTitle = escapeHtml(inlineTitle),
1317                    inlinePlaceholder = inlineTitle && (!hasHeader || labelsSettingEnabled) ? ' placeholder="' + escapedInlineTitle + '"' : '';
1318
1319                  inlineCell.append(
1320                    '<div class="stbColumnSearchField stbColumnsSearchWrapper">' +
1321                      '<input class="search-column" type="text" data-column-num="' +
1322                      i +
1323                      '"' +
1324                      inlinePlaceholder +
1325                      '/>' +
1326                    '</div>'
1327                  );
1328                }
1329              } else {
1330                var searchRow = '<tr class="stbColumnsSearchWrapper">',
1331                  func = inputTop ? 'prepend' : 'append';
1332                for (var i = 0; i < headerRow.length; i++) {
1333                  var cellItem = jQuery(headerRow[i]),
1334                    cellClass = '',
1335                    cellStyle = '';
1336                  if (!g_stbServerSideProcessing) {
1337                    cellStyle = cellItem.is(':visible') ? '' : 'style="display: none;"';
1338                  }
1339                  if (cellItem.hasClass('invisibleCell')) {
1340                    cellClass = ' class="invisibleCell"';
1341                  }
1342                  var columnTitle = jQuery.trim(cellItem.text()).replace(/\s+/g, ' '),
1343                    escapedColumnTitle = escapeHtml(columnTitle),
1344                    columnLabel = showColumnLabel && columnTitle ? '<span class="stbColumnSearchLabel">' + escapedColumnTitle + '</span>' : '',
1345                    inputPlaceholder = columnTitle && (!hasHeader || labelsSettingEnabled) ? ' placeholder="' + escapedColumnTitle + '"' : '';
1346
1347                  searchRow +=
1348                    '<th ' +
1349                    cellClass +
1350                    cellStyle +
1351                    '><div class="stbColumnSearchField">' +
1352                    columnLabel +
1353                    '<input class="search-column" type="text" data-column-num="' +
1354                    i +
1355                    '"' +
1356                    inputPlaceholder +
1357                    '/></div></th>';
1358                }
1359                searchRow += '</tr>';
1360                if ($table.find(tPosition).length == 0) {
1361                  $table.append(jQuery('<' + tPosition + '>'));
1362                }
1363                $table.find(tPosition)[func](searchRow);
1364              }
1365            }
1366          }
1367          if ($table.data('auto-index') && $table.data('auto-index') !== 'off') {
1368            if (inlineTopSearch) {
1369              $table.find('thead tr:first th:first-child .stbColumnSearchField').css({
1370                visibility: 'hidden',
1371              });
1372            } else {
1373              jQuery('.stbColumnsSearchWrapper th:first-child .stbColumnSearchField').css({
1374                visibility: 'hidden',
1375              });
1376            }
1377          }
1378        }
1379      }
1380      if (toeInArray('ordering', features) != -1) {
1381        var sortingEnable = ['_all'],
1382          sortingDisable = [],
1383          aaSorting = [],
1384          multipleSorting = $table.data('multiple-sorting'),
1385          disableSorting = $table.data('disable-sorting'),
1386          isSortingDisabledForColumn = function (columnIndex, disabledTargets) {
1387            if (!disabledTargets || !disabledTargets.length) {
1388              return false;
1389            }
1390
1391            if ($.inArray('_all', disabledTargets) !== -1) {
1392              return true;
1393            }
1394
1395            return $.inArray(parseInt(columnIndex, 10), $.map(disabledTargets, function (target) {
1396              var parsedTarget = parseInt(target, 10);
1397
1398              return isNaN(parsedTarget) ? null : parsedTarget;
1399            })) !== -1;
1400          };
1401
1402        if (!$table.data('head')) {
1403          sortingDisable = ['_all'];
1404        }
1405        if (disableSorting && disableSorting.length) {
1406          sortingDisable = disableSorting;
1407        }
1408        if (multipleSorting && multipleSorting.length) {
1409          aaSorting = $.grep(multipleSorting, function (sortItem) {
1410            return sortItem && sortItem.length && !isSortingDisabledForColumn(sortItem[0], sortingDisable);
1411          });
1412        } else {
1413          var columnsCount = $table.find('tr:first th').length,
1414            sortColumn = $table.data('sort-column') || 0,
1415            sortOrder = $table.data('sort-order') || 'asc',
1416            columnNumber = sortColumn - 1;
1417
1418          if (columnNumber >= 0 && columnNumber < columnsCount && !isSortingDisabledForColumn(columnNumber, sortingDisable)) {
1419            aaSorting.push([columnNumber, sortOrder]);
1420          }
1421        }
1422        if (sortingDisable.length) {
1423          if (typeof config.columnDefs == 'undefined' || jQuery.isEmptyObject(config.columnDefs)) {
1424            config.columnDefs = [];
1425          }
1426          config.columnDefs.push({
1427            targets: sortingDisable,
1428            sortable: false,
1429            orderable: false,
1430            bSortable: false,
1431          });
1432        }
1433        config.aaSorting = aaSorting;
1434        delete defaultFeatures.order;
1435      }
1436      if ($table.data('pagination-length')) {
1437        var paginationLength = String($table.data('pagination-length'));
1438
1439        config.aLengthMenu = [];
1440        config.aLengthMenu.push(paginationLength.replace('All', -1).split(',').map(Number));
1441        config.aLengthMenu.push(paginationLength.split(','));
1442      }
1443      if ($table.data('auto-index') && $table.data('auto-index') !== 'off') {
1444        $table.on('draw.dt', function () {
1445          var isFirst = true,
1446            index = 1;
1447          $table
1448            .api()
1449            .column(0)
1450            .nodes()
1451            .each(function (cell, i) {
1452              var style = window.getComputedStyle(cell);
1453              if (isFirst) {
1454                index = i + 1;
1455                isFirst = false;
1456              }
1457              if (style.display !== 'none' && !cell.classList.contains('invisibleCell')) {
1458                cell.innerHTML = index;
1459                index++;
1460              }
1461            });
1462        });
1463      }
1464
1465      // Set responsive mode
1466      if (responsiveMode == 0) {
1467        // Responsive Mode: Standart Responsive Mode
1468        appendResponsiveLabelStyles($table);
1469
1470        jQuery(window).on('load resize orientationchange', $table, function (event) {
1471          event.preventDefault();
1472          clearTimeout($table.data('resizeTimer'));
1473
1474          $table.data(
1475            'resizeTimer',
1476            setTimeout(function () {
1477              $table.removeClass('oneColumn oneColumnWithLabels');
1478              $table.css('width', '100%');
1479              var tableWidth = $table.width(),
1480                wrapperWidth = $table.closest('.supsystic-tables-wrap').width();
1481              if (tableWidth > wrapperWidth || jQuery(window).width() <= 475) {
1482                $table.addClass('oneColumn');
1483
1484                if ($table.data('head') == 'on') {
1485                  $table.addClass('oneColumnWithLabels');
1486                }
1487              }
1488            }, 150)
1489          );
1490          if (g_stbServerSideProcessing) {
1491            $table.find('td').each(function () {
1492              jQuery(this).css({
1493                width: '',
1494                'min-width': '',
1495              });
1496            });
1497          }
1498        });
1499      } else if (responsiveMode === 1) {
1500        // Responsive Mode: Automatic Column Hiding
1501        config.responsive = {
1502          details: {
1503            renderer: self.buildResponsiveDetailsRenderer(false),
1504          },
1505        };
1506        $table.on('responsive-resize.dt', function (event, api, columns) {
1507          if (typeof api == 'undefined' || typeof columns == 'undefined') {
1508            var tbl = jQuery(this),
1509              instance = vendor[appName].getTableInstanceById(tbl.data('id'));
1510
1511            if (instance) {
1512              api = typeof api != 'undefined' ? api : instance.api();
1513              columns = typeof columns != 'undefined' ? columns : instance.api().columns();
1514            }
1515          }
1516          var autoHiding = [],
1517            searchColumn = $table.find('.stbColumnsSearchWrapper input.search-column');
1518          for (var i = 0, len = columns.length; i < len; i++) {
1519            autoHiding[i] = columns[i] ? 1 : 0;
1520          }
1521          self.syncResponsiveColumnSearch($table, columns);
1522          if (typeof columns[0] == 'boolean') {
1523            $table.attr('data-auto-hiding', autoHiding.join());
1524          }
1525          if ($table.width() > $table.parent().width()) {
1526            $table.css('width', '100%');
1527            $table.css('max-width', '100%');
1528            api.responsive.recalc();
1529            return;
1530          }
1531          for (var i = 0, len = columns.length; i < len; i++) {
1532            if (columns[i]) {
1533              $table.find('tr > td.collapsed-cell-holder[data-cell-column="' + i + '"]').each(function (index, el) {
1534                var $this = jQuery(this);
1535                var $cell = jQuery(api.cell($this.data('cell-row'), $this.data('cell-column')).node());
1536
1537                if ($cell.hasClass('collapsed')) {
1538                  $cell.removeClass('collapsed');
1539                  $this.replaceWith($cell);
1540                }
1541              });
1542            }
1543          }
1544          if ($table.data('merged')) {
1545            // if has merged cells remove them, with autohidding they not working
1546            $table.find('td[data-hide]').show();
1547            $table.find('td[data-rowspan]').attr({
1548              'data-rowspan': 1,
1549              rowspan: 1,
1550              'data-colspan': 1,
1551              colspan: 1,
1552            });
1553          }
1554        });
1555      } else if (responsiveMode === 4) {
1556        // Responsive Mode: Column Hiding with Settings
1557        self.applyResponsiveColumnClasses($table);
1558        config.responsive = {
1559          auto: false,
1560          breakpoints: self.getResponsiveColumnBreakpoints($table),
1561          details: {
1562            renderer: self.buildResponsiveDetailsRenderer(true),
1563          },
1564        };
1565        $table.on('responsive-resize.dt', function (event, api, columns) {
1566          if (typeof api == 'undefined' || typeof columns == 'undefined') {
1567            var tbl = jQuery(this),
1568              instance = vendor[appName].getTableInstanceById(tbl.data('id'));
1569
1570            if (instance) {
1571              api = typeof api != 'undefined' ? api : instance.api();
1572              columns = typeof columns != 'undefined' ? columns : instance.api().columns();
1573            }
1574          }
1575          if (typeof columns == 'undefined') {
1576            return;
1577          }
1578          var autoHiding = [];
1579          for (var i = 0, len = columns.length; i < len; i++) {
1580            autoHiding[i] = columns[i] ? 1 : 0;
1581          }
1582          self.syncResponsiveColumnSearch($table, columns);
1583          if (typeof columns[0] == 'boolean') {
1584            $table.attr('data-auto-hiding', autoHiding.join());
1585          }
1586          for (var i = 0, len = columns.length; i < len; i++) {
1587            if (columns[i]) {
1588              $table.find('tr > td.collapsed-cell-holder[data-cell-column="' + i + '"]').each(function (index, el) {
1589                var $this = jQuery(this);
1590                var $cell = jQuery(api.cell($this.data('cell-row'), $this.data('cell-column')).node());
1591
1592                if ($cell.hasClass('collapsed')) {
1593                  $cell.removeClass('collapsed');
1594                  $this.replaceWith($cell);
1595                }
1596              });
1597            }
1598          }
1599        });
1600      } else if (responsiveMode === 2) {
1601        // Responsive Mode: Horizontal Scroll
1602        config.scrollX = true;
1603        config.bAutoWidth = false;
1604        var firstRow = $table.find('tbody tr:first-child td');
1605        if (firstRow.length) {
1606          var cntCols = firstRow.length;
1607          $table.find('thead tr:first-child th').each(function (i, th) {
1608            if (cntCols > i && jQuery(th).css('width')) {
1609              firstRow.eq(i).css('width', jQuery(th).css('width'));
1610            }
1611          });
1612        }
1613      }
1614      if (responsiveMode === 2 || responsiveMode === 3) {
1615        // Responsive Mode: 2 - Horizontal Scroll, 3 - Disable Responsivity
1616        var fixedHead = $table.data('head') && $table.data('fixed-head'),
1617          fixedFoot = $table.data('foot') && $table.data('fixed-foot'),
1618          fixedLeft = $table.data('fixed-left'),
1619          fixedRight = $table.data('fixed-right');
1620
1621        // TODO: correct the code to set fixed header and fixed footer in the standard way
1622        // TODO: https://datatables.net/extensions/fixedheader/#Features
1623        //config.fixedHeader = {
1624        //	header: false,
1625        //	footer: false
1626        //};
1627        //if (fixedHead) {
1628        //	config.fixedHeader.header = true;
1629        //}
1630        //if (fixedFoot) {
1631        //	config.fixedHeader.footer = true;
1632        //}
1633        if (fixedHead || fixedFoot) {
1634          config.scrollY = $table.data('fixed-height');
1635          config.scrollCollapse = true;
1636        }
1637        if ($table.data('fixed-cols')) {
1638          config.fixedColumns = {
1639            leftColumns: fixedLeft ? parseInt(fixedLeft) : 0,
1640            rightColumns: fixedRight ? parseInt(fixedRight) : 0,
1641          };
1642          config.scrollX = true;
1643        }
1644      }
1645
1646      //$table.find('.invisibleCell').siblings('td').addClass('invisibleCell');
1647
1648      // Add translation
1649      var langData = typeof g_stbTblLangData != 'undefined' ? JSON.parse(g_stbTblLangData) : $table.data('translation'),
1650        translation = langData || {},
1651        override = $table.data('override');
1652
1653      if (typeof translation != 'object') {
1654        translation = {}; // for just to be sure that it is object
1655      }
1656      jQuery.each(override, function (key, value) {
1657        if (value.length) {
1658          if (key == 'previous' || key == 'next') {
1659            if (typeof translation['paginate'] === 'undefined') {
1660              translation['paginate'] = {};
1661            }
1662            translation['paginate'][key] = value;
1663          }
1664          translation[key] = value;
1665          // We need to support old DT format, cuz some languages use it
1666          translation['s' + key.charAt(0).toUpperCase() + key.substr(1)] = value;
1667        }
1668      });
1669      config.language = translation;
1670      config.language.processing = '';
1671      config.language.sProcessing = '';
1672
1673      var ajaxSource = {},
1674        loadedRows = [],
1675        loadedCells = [],
1676        loadedDomRows = [];
1677
1678      if (!g_stbServerSideProcessing) {
1679        $table.find('tbody tr').each(function () {
1680          loadedDomRows.push(this.attributes);
1681        });
1682      }
1683
1684      if (g_stbServerSideProcessing) {
1685        var currentApp = this;
1686        var nonce = typeof DTGS_NONCE !== 'undefined' ? DTGS_NONCE : DTGS_NONCE_FRONTEND;
1687        var route = {
1688            action: 'getPageRows',
1689            module: 'tables',
1690            nonce: nonce,
1691          },
1692          headerRowsCount = $table.data('head') == 'on' ? $table.data('head-rows-count') : 0,
1693          footerRowsCount = $table.data('foot') == 'on' ? $table.data('foot-custom-rows-count') : 0;
1694        ajaxSource = {
1695          processing: true,
1696          serverSide: true,
1697          ajax: {
1698            url: window.ajaxurl ? window.ajaxurl : ajax_obj.ajaxurl,
1699            type: 'POST',
1700            beforeSend: function () {
1701              g_stbServerSideProcessingIsActive = true;
1702            },
1703            data: function (d) {
1704              var currentSearchParams = jQuery.extend(true, {}, searchingSettings || {}),
1705                input;
1706
1707              if (typeof currentApp.getServerSideSearchParams === 'function') {
1708                currentSearchParams = currentApp.getServerSideSearchParams($table, currentSearchParams) || currentSearchParams;
1709              }
1710
1711              input = jQuery('#' + cssEscapeIdentifier($table.attr('id') + '_filter') + '.dataTables_filter').find('input');
1712
1713              return jQuery.extend(true, d, {
1714                action: 'supsystic-tables',
1715                route: route,
1716                id: $table.data('id'),
1717                searchParams: currentSearchParams,
1718                searchValue: input.length ? input.val() : '',
1719                header: headerRowsCount,
1720                footer: footerRowsCount,
1721              });
1722            },
1723            dataFilter: function (data) {
1724              var json = jQuery.parseJSON(data),
1725                rowsHtml = json.rows || '',
1726                tbodyMatch = rowsHtml.match(/<tbody[\s\S]*<\/tbody>/i),
1727                rowsSource = tbodyMatch ? jQuery('<table>' + tbodyMatch[0] + '</table>') : jQuery('<div>' + rowsHtml + '</div>'),
1728                rows = rowsSource.find('tbody tr'),
1729                aData = [];
1730
1731              if (!rows.length) {
1732                rows = rowsSource.find('tr');
1733              }
1734
1735              loadedRows = [];
1736              loadedCells = [];
1737              for (var i = 0; i < rows.length; i++) {
1738                var row = rows[i];
1739                loadedRows.push(row.attributes);
1740                var cells = jQuery(row).find('td'),
1741                  attrs = [],
1742                  vals = [];
1743                for (var j = 0; j < cells.length; j++) {
1744                  var cell = cells[j];
1745                  attrs.push(cell.attributes);
1746                  vals.push(cell.innerHTML);
1747                }
1748                loadedCells.push(attrs);
1749                aData.push(vals);
1750              }
1751              json.rows = '';
1752              json.data = aData;
1753              g_stbServerSideProcessingIsActive = false;
1754              return JSON.stringify(json);
1755            },
1756          },
1757        };
1758        if (typeof config.aoColumnDefs == 'undefined' || jQuery.isEmptyObject(config.aoColumnDefs)) {
1759          config.aoColumnDefs = [];
1760        }
1761        config.aoColumnDefs.push({
1762          targets: '_all',
1763          cellType: 'td',
1764          createdCell: function (td, cellData, rowData, row, col) {
1765            if (typeof loadedCells[row][col] != 'undefined') {
1766              var rowspan = 1,
1767                colspan = 1;
1768              jQuery(loadedCells[row][col]).each(function () {
1769                if (this.name == 'data-rowspan' && this.value > 1) {
1770                  rowspan = this.value;
1771                }
1772                if (this.name == 'data-colspan' && this.value > 1) {
1773                  colspan = this.value;
1774                }
1775              });
1776              if (rowspan > 1 || colspan > 1) {
1777                var stopRow = row + parseInt(rowspan),
1778                  stopCol = col + parseInt(colspan),
1779                  startRow = colspan > 1 ? row : row + 1,
1780                  hide;
1781                if (stopRow >= loadedCells.length) {
1782                  stopRow = loadedCells.length;
1783                }
1784                if (stopCol >= loadedCells[row].length) {
1785                  stopCol = loadedCells[row].length;
1786                }
1787
1788                for (i = startRow; i < stopRow; i++) {
1789                  if (i > row) {
1790                    hide = document.createAttribute('data-hide');
1791                    hide.value = 'true';
1792                    loadedCells[i][col].setNamedItem(hide);
1793                  }
1794                  for (j = col + 1; j < stopCol; j++) {
1795                    hide = document.createAttribute('data-hide');
1796                    hide.value = 'true';
1797                    loadedCells[i][j].setNamedItem(hide);
1798                  }
1799                }
1800              }
1801              jQuery(loadedCells[row][col]).each(function () {
1802                //if(this.name != 'data-formula') {
1803                jQuery(td).attr(this.name, this.value);
1804                //}
1805              });
1806            }
1807          },
1808        });
1809      }
1810      var sourceCreatedRow = typeof config.createdRow === 'function' ? config.createdRow : null,
1811        ajaxCreatedRow = typeof ajaxSource.createdRow === 'function' ? ajaxSource.createdRow : null;
1812      config.createdRow = function (row, data, dataIndex) {
1813        var rowAttrs = typeof loadedRows[dataIndex] != 'undefined' ? loadedRows[dataIndex] : loadedDomRows[dataIndex];
1814
1815        if (sourceCreatedRow) {
1816          sourceCreatedRow.call(this, row, data, dataIndex);
1817        }
1818        if (ajaxCreatedRow) {
1819          ajaxCreatedRow.call(this, row, data, dataIndex);
1820        }
1821        if (typeof rowAttrs != 'undefined') {
1822          jQuery(rowAttrs).each(function () {
1823            jQuery(row).attr(this.name, this.value);
1824          });
1825        }
1826      };
1827      if (ajaxSource.createdRow) {
1828        delete ajaxSource.createdRow;
1829      }
1830      window.table = $table;
1831      $table.trigger('beforeInitializeTable', $table);
1832      var dateFormat = $table.data('date-format');
1833      // if (typeof $table.dataTable.moment !== "undefined") {
1834      $table.dataTable.moment(dateFormat);
1835      // }
1836      // if (typeof jQuery.fn.dataTable.ext.order.intl !== "undefined") {
1837      jQuery.fn.dataTable.ext.order.intl();
1838      // }
1839      tableInstance = $table.dataTable(jQuery.extend({}
1839, defaultFeatures, config, extraConfig, ajaxSource, reinit));
1840      tableInstance.table_id = $table.data('id');
1841      tableInstance.table_view_id = $table.data('view-id');
1842      if (!g_stbServerSideProcessing && loadedDomRows.length) {
1843        var restoreDomRowAttributes = function () {
1844          var api = tableInstance.api ? tableInstance.api() : null;
1845
1846          if (!api || typeof api.rows !== 'function') {
1847            return;
1848          }
1849
1850          api.rows({ page: 'current', search: 'applied', order: 'current' }).every(function (rowIdx) {
1851            var row = this.node(),
1852              rowAttrs = typeof loadedDomRows[rowIdx] != 'undefined' ? loadedDomRows[rowIdx] : null;
1853
1854            if (!row || !rowAttrs) {
1855              return;
1856            }
1857
1858            jQuery(rowAttrs).each(function () {
1859              jQuery(row).attr(this.name, this.value);
1860            });
1861          });
1862        };
1863
1864        restoreDomRowAttributes();
1865        $table.off('draw.dt.stbRowAttrs').on('draw.dt.stbRowAttrs', restoreDomRowAttributes);
1866      }
1867      setupProcessingLoader($table, tableInstance);
1868      if (typeof tableInstance.fnFakeRowspan !== 'undefined') {
1869        tableInstance.fnFakeRowspan();
1870      }
1871      self._checkOnClickPopups($table);
1872      window.table = $table;
1873      if ($table.data('remove-rows')) {
1874        jQuery(function () {
1875          jQuery.contextMenu({
1876            selector: '.dataTable td',
1877            animation: {
1878              duration: 250,
1879              show: 'fadeIn',
1880              hide: 'fadeOut',
1881            },
1882            callback: function (key, options) {
1883              var m = 'clicked: ' + key;
1884            },
1885            items: {
1886              remove_row: {
1887                name: 'Remove row',
1888                callback: function (itemKey, opt, e) {
1889                  contextMenuAction(this, 'remove_row');
1890                },
1891              },
1892              add_row_before: {
1893                name: 'Add row before',
1894                callback: function (itemKey, opt, e) {
1895                  contextMenuAction(this, 'add_row', 'before');
1896                },
1897              },
1898              add_row_after: {
1899                name: 'Add row after',
1900                callback: function (itemKey, opt, e) {
1901                  contextMenuAction(this, 'add_row', 'after');
1902                },
1903              },
1904              sep1: '---------',
1905              quit: {
1906                name: 'Quit',
1907              },
1908            },
1909          });
1910
1911          function contextMenuAction(e, action, second) {
1912            var coltext = e.text();
1913            var colvindex = e.parent().children().index(e);
1914            var colindex = jQuery('table.dataTable thead tr th:eq(' + colvindex + ')').data('column-index');
1915
1916            /* Global var for counter */
1917            var giCount = 1;
1918            switch (action) {
1919              case 'remove_row':
1920                $table.fnDeleteRow(e.parent('tr'));
1921                $table.fnUpdate();
1922                break;
1923              case 'add_row':
1924                var tr = e.parent('tr').clone(true, true);
1925                tr.find('td').html('').addClass('menu-injected').addClass('editable').addClass('justCloned');
1926                tr.find('td').data('original-value', '').attr('data-original-value', '');
1927                var order = tr.find('td').data('order');
1928                if (second == 'before') {
1929                  order = order - 1;
1930                  tr.find('td').data('order', order).attr('data-order', order);
1931                } else {
1932                  order = order + 1;
1933                  tr.find('td').data('order', order).attr('data-order', order);
1934                }
1935                tr.find('td').data('cell-type', 'text').attr('data-cell-type', 'text');
1936                tr.find('td').data('cell-format-type', '').attr('data-cell-format-type', '');
1937                $table.append(tr);
1938                $table.fnAddData(tr, true);
1939                tr.find('td.justCloned').data('y', '9999').attr('data-y', '9999').removeClass('justCloned');
1940                // $table.fnUpdate();
1941                // $table.trigger('draw.dt');
1942                break;
1943            }
1944          }
1945        });
1946      }
1947
1948      if (g_stbServerSideProcessing) {
1949        jQuery('.dataTables_processing').css('z-index', '10');
1950      } else {
1951        self.setColumnSearch($table);
1952      }
1953      $table.on('draw.dt', function () {
1954        var searching = $table.data('searching-settings');
1955        if (searching && 'columnSearch' in searching && searching.columnSearch == 'on') {
1956          self.setColumnSearch($table);
1957        }
1958        if (!g_stbServerSideProcessing && $table.data('merged')) {
1959          tableInstance.fnResetFakeRowspan();
1960        }
1961        self.initShortcodesInTable($table);
1962      });
1963      if (responsiveMode === 1 || responsiveMode === 4) {
1964        $table.on('responsive-resize.dt', function (event, api, columns) {
1965          if (!g_stbServerSideProcessing && $table.data('merged')) {
1966            tableInstance.fnResetFakeRowspan();
1967          }
1968        });
1969      }
1970      if (typeof $table.data('fixed-cols') !== 'undefined') {
1971        tableInstance.api().fixedColumns().update();
1972      }
1973      if (addInstance) {
1974        this.setTableInstance(tableInstance);
1975      }
1976      return typeof finalCallback == 'function' ? finalCallback(tableInstance) : tableInstance;
1977    };
1978
1979    /** Callback for displaying table after initializing
1980     * @param {object} settings - DataTables settings object
1981     * @param {object} json - JSON data retrieved from the server if the ajax option was set. Otherwise undefined.
1982     */
1983    vendor[appName].showTable = function (settings, json) {
1984      var self = vendor[appName], // it is callback so "this" does not equal vendor[appName] object
1985        $table = this instanceof $ ? this : settings, // for compatibility with old pro versions
1986        $tableWrap = $table.closest('.supsystic-tables-wrap'),
1987        tableSelector = '#supsystic-table-' + $table.data('view-id') + ' #supsystic-table-' + $table.data('id'),
1988        afterTableLoadedScriptString = $table.attr('data-after-table-loaded-script'),
1989        _ruleJS = self.setRuleJSInstance($table),
1990        responsiveMode = $table.data('responsive-mode'),
1991        fixedHeader = $table.data('fixed-head') == 'on',
1992        fixedFooter = $table.data('fixed-foot') == 'on',
1993        fixedColumns = $table.data('fixed-right') > 0 || $table.data('fixed-left') > 0,
1994        viewId = $table.data('view-id');
1995
1996      // Apply custom CSS styles, which have been set through the table editor
1997      $table.find('th, td').each(function () {
1998        self.setStylesToCell(this);
1999      });
2000      $table.bind('column-visibility.dt draw.dt', function (e) {
2001        jQuery(this)
2002          .find('th, td')
2003          .each(function () {
2004            self.setStylesToCell(this);
2005          });
2006      });
2007
2008      // Remove sorting visual elements from the tags if there is no header on table
2009      if (!$table.data('head')) {
2010        $table.find('th').removeClass('sorting sorting_asc sorting_desc sorting_disabled');
2011      }
2012
2013      // Calculate formulas
2014      _ruleJS.init();
2015
2016      // Set formats
2017      self.formatDataAtTable($table, true);
2018
2019      // On SSP each page/search draw replaces the tbody with freshly ajax-loaded
2020      // rows, so formulas (e.g. HYPERLINK) and cell formats (date/number/currency)
2021      // must be recalculated/reapplied for those rows too, not just on the initial draw.
2022      if (g_stbServerSideProcessing) {
2023        $table.on('draw.dt', function () {
2024          self.getRuleJSInstance($table).init();
2025          self.formatDataAtTable($table, true);
2026        });
2027      }
2028
2029      // Apply shortcode param "search"
2030      if ($table.data('search-value')) {
2031        $table.api().search($table.data('search-value')).draw();
2032      }
2033
2034      // Show comments on tap
2035      if ('ontouchstart' in window || navigator.msMaxTouchPoints) {
2036        $table.parents('.supsystic-tables-wrap:first').find('td, th').on('click', self.applyMobileTableComments);
2037      }
2038
2039      // Prepare Contact Form by Supsystic buttons
2040      $table.parents('.supsystic-tables-wrap:first').find('th, td').each(self._contactFormBtnCellClb);
2041
2042      // Page change callback
2043      $table.on('page.dt', function () {
2044        if (g_stbServerSideProcessing) {
2045          g_stbServerSideProcessingIsActive = true;
2046        }
2047        var table = jQuery(this),
2048          tableSelector = '#supsystic-table-' + table.data('view-id') + ' #supsystic-table-' + table.data('id');
2049        self.applyTableEventClb(self.pageEvent, 50, tableSelector);
2050        if ($table.data('pagination-scroll') == 'on') {
2051          jQuery('html, body').animate(
2052            {
2053              scrollTop: table.closest('.dataTables_wrapper').offset().top,
2054            },
2055            100
2056          );
2057        }
2058        if (typeof self.setImgLightbox == 'function') {
2059          self.setImgLightbox($table);
2060        }
2061      });
2062
2063      // Frontend fields
2064      if (typeof self.createEditableFields == 'function') {
2065        // for compatibility with old pro versions
2066        var $editableFields = $tableWrap.find('.editable'),
2067          $editfileFields = $tableWrap.find('.editfile'),
2068          $selectableFields = $tableWrap.find('.selectable'),
2069          $tableId = $table.data('id'),
2070          useEditableFields = typeof useEdit != 'undefined' && typeof useEdit[$tableId] != 'undefined' ? useEdit[$tableId] : false;
2071
2072        if (useEditableFields || (SDT_DATA.isAdmin && SDT_DATA.isPro)) {
2073          if (typeof self.setFrontendFields == 'function') {
2074            self.setFrontendFields($table);
2075          } else if (typeof self.setAllFields == 'function') {
2076            self.setAllFields($table, $editableFields, $selectableFields);
2077          } else {
2078            self.createEditableFields($table, $editableFields);
2079            self.createEditableFileFields($table, $editfileFields);
2080          }
2081          $table.on('init.dt', function () {
2082            $table.on('responsive-resize.dt responsive-display.dt draw.dt', function () {
2083              $editableFields.off('click.sup'); // for compatibility with old pro versions
2084              $editfileFields.off('click.sup');
2085              self.updateAfterRedraw($table);
2086            });
2087          });
2088        }
2089      }
2090      if (typeof self.setImgLightbox == 'function') {
2091        self.setImgLightbox($table);
2092      }
2093
2094      // apply page.dt event by change table pagination via select
2095      var paginationSelect = $tableWrap.find('.dataTables_length select');
2096      if (paginationSelect.length) {
2097        paginationSelect.on('change', function () {
2098          $table.trigger('page.dt');
2099        });
2100      }
2101
2102      self.applyTableEventClb(self.fixHeaderOfHiddenColumns, 50, tableSelector);
2103
2104      $table.trigger('beforeShowTable', $table);
2105
2106      // Show table
2107      $tableWrap.prev('.supsystic-table-loader').hide();
2108      $tableWrap.css('visibility', 'visible');
2109
2110      self.fixSortingForMultipleHeader($table);
2111
2112      if (responsiveMode === 2 || fixedHeader || fixedFooter) {
2113        // Responsive Mode: Horizontal Scroll
2114        jQuery(window).on('load resize orientationchange', $table, function (event) {
2115          var tBody = $tableWrap.find('.dataTables_scrollBody'),
2116            tBodyTable = tBody.find('.supsystic-table');
2117
2118          if (tBody.width() > tBodyTable.width() || $tableWrap.width() > tBodyTable.width()) {
2119            tBody.width(tBodyTable.width());
2120            $tableWrap.find('.dataTables_scrollHead, .dataTables_scrollFoot, .dataTables_scrollBody').width(tBodyTable.width() + 1);
2121            /*
2122                        var scrollTables = $tableWrap.find('.dataTables_scrollHead, .dataTables_scrollFoot');
2123                        scrollTables.width(tBodyTable.width() + 1);
2124                        scrollTables.find('table').width(tBodyTable.width() + 1);*/
2125          }
2126          if (tBody.isHorizontallyScrollable()) {
2127            tBody.css({
2128              'border-bottom': 'none',
2129            });
2130          } else {
2131            tBody.removeStyle('border-bottom');
2132          }
2133          var table = self.getTableInstanceById($table.data('id'));
2134          if (typeof table.fnAdjustColumnSizing == 'function') {
2135            setTimeout(function () {
2136              table.fnAdjustColumnSizing(false);
2137            }, 350);
2138          }
2139        });
2140
2141        // need resize twice to get better frontend view
2142        var tBody = $tableWrap.find('.dataTables_scrollBody'),
2143          tBodyTable = tBody.find('.supsystic-table');
2144
2145        if (tBodyTable.is(':visible')) {
2146          setTimeout(function () {
2147            jQuery(window).trigger('load');
2148          }, 200);
2149        }
2150        var $tHeadTable = $tableWrap.find('.dataTables_scrollHead .supsystic-table');
2151        if ($tHeadTable.length) {
2152          self.formatDataAtTable($tHeadTable, true);
2153        }
2154        var $tFootTable = $tableWrap.find('.dataTables_scrollFoot .supsystic-table');
2155        if ($tFootTable.length) {
2156          self.formatDataAtTable($tFootTable, true);
2157        }
2158      }
2159      // Correct width of fixed header / footer
2160      if (fixedHeader || fixedFooter) {
2161        $table.api().fixedHeader.adjust();
2162
2163        var i = 1;
2164        setTimeout(function () {
2165          var flag = fixedHeader,
2166            el = fixedHeader ? $tableWrap.find('.dataTables_scrollHead table thead tr:first-child th') : $tableWrap.find('.dataTables_scrollFoot table tfoot tr:first-child th');
2167
2168          el.each(function () {
2169            var thWidth = $tableWrap.find('.dataTables_scrollBody table tbody tr:first-child td:nth-child(' + i + ')');
2170
2171            jQuery(this).css({
2172              width: thWidth.outerWidth(),
2173              'min-width': thWidth.outerWidth(),
2174              'box-sizing': 'border-box',
2175            });
2176            if (fixedFooter && flag) {
2177              var footerEl = $tableWrap.find('.dataTables_scrollFoot table tfoot tr:first-child th:nth-child(' + i + ')');
2178              footerEl.css({
2179                width: thWidth.outerWidth(),
2180                'min-width': thWidth.outerWidth(),
2181                'box-sizing': 'border-box',
2182              });
2183            }
2184            i++;
2185          });
2186        }, 200);
2187      }
2188
2189      // Correct width of fixed columns
2190      if (fixedColumns) {
2191        $table.api().fixedColumns().relayout();
2192
2193        //var tableCaption = jQuery('.dataTables_scrollHead caption');
2194        //
2195        //if(tableCaption.length) {
2196        //self._fixTableCaption(tableCaption.height(), viewId, 10);
2197        //}
2198      }
2199      /* Fix for Horizontal scroll responsive mode if table has different width for one column in header and body */
2200      if (!fixedHeader && !fixedFooter && responsiveMode === 2 && toeInArray('auto_width', $table.data('features')) == -1) {
2201        $tableWrap.find('.dataTables_scrollBody table thead tr:first-child th').each(function () {
2202          var tableWidth = $table.width(),
2203            tableWrapWidth = $tableWrap.width();
2204
2205          if (tableWrapWidth > tableWidth) {
2206            $tableWrap.find('.dataTables_scrollHeadInner, .dataTables_scrollBody, .dataTables_scrollFootInner').addClass('fit-content');
2207          }
2208        });
2209      }
2210
2211      // Load user custom scripts
2212      if (afterTableLoadedScriptString !== undefined) {
2213        afterTableLoadedScriptString = afterTableLoadedScriptString.substring(1, afterTableLoadedScriptString.length - 1);
2214
2215        var afterTableLoadedScript = b64DecodeUnicode(afterTableLoadedScriptString).replace(/"/g, "'"),
2216          executeScript = new Function(afterTableLoadedScript);
2217
2218        if (typeof executeScript === 'function') {
2219          setTimeout(function () {
2220            executeScript();
2221          }, 1000);
2222        }
2223      }
2224
2225      if (g_stbServerSideProcessing) {
2226        $table
2227          .on('draw.dt', function (e) {
2228            var searching = $table.data('searching-settings');
2229            if (searching && 'columnSearch' in searching && searching.columnSearch == 'on') {
2230              self.setColumnSearch($table);
2231            }
2232            self.getTableInstanceByViewId(viewId).fnFakeRowspan();
2233            if (responsiveMode === 0 || responsiveMode === 2) {
2234              jQuery(window).trigger('load');
2235            }
2236          })
2237          .trigger('draw.dt');
2238      }
2239
2240      $table.off('draw.dt.stbCellDimensions').on('draw.dt.stbCellDimensions', function () {
2241        self.queueCellDimensions($table);
2242      });
2243      self.queueCellDimensions($table);
2244
2245      var tblEditLink = 'g_stbTblEditLink_' + $table.data('id'),
2246        showTblEditLink = eval('typeof ' + tblEditLink) !== 'undefined' ? jQuery(window.atob(eval(tblEditLink))) : false;
2247
2248      if (showTblEditLink && jQuery(tableSelector).closest('.supsystic-tables-wrap').find('.tblEditLink').length === 0) {
2249        jQuery(tableSelector).closest('.supsystic-tables-wrap').append(showTblEditLink);
2250      }
2251
2252      function b64DecodeUnicode(str) {
2253        return decodeURIComponent(
2254          Array.prototype.map
2255            .call(atob(str), function (c) {
2256              return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
2257            })
2258            .join('')
2259        );
2260      }
2261    };
2262
2263    vendor[appName].applyTableEventClb = function (clb, timeout) {
2264      // Callback for applying events' actions and other functions to tables with server side processing (SSP)
2265      timeout = timeout ? timeout : 0;
2266      var self = this,
2267        args = Array.from(arguments);
2268
2269      if (g_stbServerSideProcessing && g_stbServerSideProcessingIsActive) {
2270        setTimeout(function () {
2271          self.applyTableEventClb.apply(self, args);
2272        }, 50);
2273      } else {
2274        if (typeof clb == 'function') {
2275          args = args.slice(2);
2276          setTimeout(function () {
2277            clb.apply(self, args);
2278          }, timeout);
2279        }
2280      }
2281    };
2282
2283    vendor[appName].pageEvent = function (tableSelector) {
2284      var table = jQuery(tableSelector),
2285        tableWrapper = table.parents('.supsystic-tables-wrap:first');
2286
2287      this.getRuleJSInstance(table).init();
2288      this.formatDataAtTable(table, true);
2289      this.fixHeaderOfHiddenColumns(table);
2290      if ('ontouchstart' in window || navigator.msMaxTouchPoints) {
2291        tableWrapper.find('td, th').on('click', this.applyMobileTableComments);
2292      }
2293      tableWrapper.find('td, th').each(this._contactFormBtnCellClb);
2294      this.initShortcodesInTable(table);
2295    };
2296
2297    vendor[appName].fixHeaderOfHiddenColumns = function ($table) {
2298      $table = $table instanceof $ ? $table : jQuery($table);
2299
2300      var tableWrapper = $table.parents('.supsystic-tables-wrap:first');
2301
2302      if (!$table.data('head')) {
2303        tableWrapper.find('thead').each(function () {
2304          var thead = jQuery(this);
2305          thead.find('th').each(function (iter, item) {
2306            var th = jQuery(this),
2307              itemIndex = iter + 1,
2308              columnAllTd = thead.parents('table:first').find('tbody td:nth-child(' + itemIndex + ')'),
2309              columnInvTd = columnAllTd.filter('.invisibleCell'),
2310              hidden = columnAllTd.length > 0 && columnAllTd.length == columnInvTd.length;
2311            if (hidden) {
2312              // Fix of correct displaying of tables with hidden rows / columns for tables without headers
2313              th.addClass('invisibleCell');
2314            }
2315          });
2316        });
2317      }
2318    };
2319
2320    vendor[appName].applyMobileTableComments = function (e) {
2321      var $elem = jQuery(this),
2322        title = $elem.attr('title');
2323
2324      if (title) {
2325        var tableViewId = $elem.parents('table.supsystic-table:first').data('view-id'),
2326          cellId = $elem.data('cell-id'),
2327          comment = jQuery('.stbMobileComment[data-table="' + tableViewId + '"][data-cell="' + cellId + '"]');
2328
2329        if (!comment.length) {
2330          comment = jQuery('<div class="stbMobileComment" style="display:none;"/>');
2331          comment.text(title).data('table', tableViewId).attr('data-table', tableViewId).data('cell', cellId).attr('data-cell', cellId).appendTo('body');
2332        }
2333        comment
2334          .css({
2335            top: e.pageY - 70 + 'px',
2336            left: e.pageX + 20 + 'px',
2337          })
2338          .fadeIn('slow');
2339
2340        setTimeout(function () {
2341          comment.fadeOut('slow');
2342        }, 2500);
2343      }
2344    };
2345
2346    vendor[appName]._contactFormBtnCellClb = function (e) {
2347      var cell = jQuery(this),
2348        y = cell.data('y'),
2349        pair,
2350        valueCell;
2351      if (cell.html().indexOf('cfsPreFill') != -1) {
2352        var cellHtml = cell.html().replace(/href=["|']([^"]*?)["|']/g, function (a, b) {
2353          if (b.indexOf('cfsPreFill') != -1) {
2354            var newB = b.split('&amp;');
2355            if (newB.length) {
2356              for (var i = 0; i < newB.length; i++) {
2357                pair = newB[i].split('=');
2358                if (pair.length && pair[1].match(/[A-Za-z]/)) {
2359                  valueCell = cell.parents('tr:first').find('[data-cell-id="' + pair[1] + y + '"]');
2360                  if (valueCell.length) {
2361                    pair[1] = jQuery.trim(valueCell.html());
2362                  }
2363                }
2364                newB[i] = pair.join('=');
2365              }
2366              newB = newB.join('&amp;');
2367              a = a.replace(b, newB);
2368            }
2369            return a;
2370          }
2371        });
2372        cell.html(cellHtml);
2373      }
2374    };
2375
2376    vendor[appName].setColumnSearch = function (table) {
2377      if (typeof this.setTableAddFilters === 'function') this.setTableAddFilters(table);
2378
2379      var self = this,
2380        searchingSettings = table.data('searching-settings'),
2381        inputs = table.parents('.dataTables_wrapper:first').find('.stbColumnsSearchWrapper .search-column');
2382      if (inputs.length == 0) {
2383        return;
2384      }
2385
2386      inputs.off('mousedown.dtg click.dtg touchstart.dtg').on('mousedown.dtg click.dtg touchstart.dtg', function (e) {
2387        e.stopPropagation();
2388      });
2389
2390      inputs.off('change.dtg blur.dtg').on('change.dtg blur.dtg', function () {
2391        var input = jQuery(this),
2392          position = input.parents('th:first').index(),
2393          value = this.value,
2394          column = table.api().column(position);
2395        if (typeof self.resetTableAddFilters === 'function') self.resetTableAddFilters(table);
2396        if (column.search() !== value) {
2397          column.search(value.replace(/;/g, '|'), true, false).draw();
2398          setTimeout(function () {
2399            column.draw();
2400          }, 50);
2401        }
2402      });
2403    };
2404
2405    vendor[appName].setCopyEvents = function (obj, events) {
2406      jQuery.each(events, function (event, handlers) {
2407        jQuery.each(handlers, function (j, handler) {
2408          jQuery(obj).unbind(event).bind(event, handler);
2409        });
2410      });
2411    };
2412
2413    // Callback for executing script after table is initialized
2414    vendor[appName].executeScript = function (table) {
2415      var $table = table instanceof $ ? table : jQuery(table),
2416        $tableWrap = $table.closest('.supsystic-tables-wrap');
2417
2418      this.getRuleJSInstance($table).init();
2419      $tableWrap.prev('.supsystic-table-loader').hide();
2420      $tableWrap.css('visibility', 'visible');
2421    };
2422
2423    vendor[appName].fixSortingForMultipleHeader = function (table) {
2424      if (table.data('head-rows-count') > 1 && table.data('sort-order')) {
2425        var thead = table.find('thead tr').get().reverse();
2426
2427        // Fix of sorting for table with multiple header (when header has more than 1 row)
2428        if (table.data('head')) {
2429          jQuery.each(table.find('thead tr:last-child th'), function (index, element) {
2430            var th = jQuery(element),
2431              nthChild = index + 1;
2432
2433            if (th.data('hide')) {
2434              jQuery(thead).each(function () {
2435                var item = jQuery(this).find('th:nth-child(' + nthChild + ')');
2436
2437                if (!item.data('hide')) {
2438                  item.addClass('sorting');
2439                  item.click(function () {
2440                    th.trigger('click');
2441                    if (th.hasClass('sorting')) {
2442                      item.removeClass('sorting_asc');
2443                      item.removeClass('sorting_desc');
2444                      item.addClass('sorting');
2445                    } else if (th.hasClass('sorting_asc')) {
2446                      item.removeClass('sorting');
2447                      item.removeClass('sorting_desc');
2448                      item.addClass('sorting_asc');
2449                    } else if (th.hasClass('sorting_desc')) {
2450                      item.removeClass('sorting');
2451                      item.removeClass('sorting_asc');
2452                      item.addClass('sorting_desc');
2453                    }
2454                  });
2455                  return false; // stop .each() function
2456                }
2457              });
2458            }
2459          });
2460        }
2461      }
2462    };
2463
2464    vendor[appName].formatDataAtTable = function (table, correctSorting) {
2465      correctSorting = correctSorting ? correctSorting : false;
2466
2467      var self = this,
2468        numberFormat = table.data('number-format'),
2469        generalCurrencyFormat = table.data('currency-format'),
2470        generalPercentFormat = table.data('percent-format'),
2471        generalDateFormat = table.data('date-format'),
2472        generalTimeFormat = table.data('time-format');
2473
2474      table.find('th, td').each(function (index, el) {
2475        var $this = jQuery(this);
2476
2477        if ((table.data('auto-index') != 'off' && $this.is(':first-child')) || ((table.data('responsive-mode') == 1 || table.data('responsive-mode') == 4) && table.hasClass('collapsed') && $this.hasClass('child')) || $this.find('.search-column').length || $this.hasClass('tooltipCell') || $this.data('hide')) {
2478          // Break current .each iteration
2479          return;
2480        }
2481
2482        var languageData = numeral.languageData(),
2483          format = $this.data('cell-format'),
2484          formatType = $this.data('cell-format-type'),
2485          $dimensionInner = $this.children('.stb-cell-dimension-inner:first, .stb-cell-max-height-inner:first'),
2486          preparedFormat,
2487          delimiters,
2488          value = jQuery.trim($dimensionInner.length ? $dimensionInner.html() : $this.html()),
2489          noFormat = false;
2490
2491        // function checkIfDate(parts) {
2492        //   var newDate = new Date(parts[0], parts[1]-1, parts[2]);
2493        //   if (newDate.getTime() === newDate.getTime()) {
2494        //     $this.attr('data-cell-format-type', 'date');
2495        //     $this.data('cell-format-type', 'date');
2496        //     formatType = $this.data('cell-format-type');
2497        //     console.log(parts);
2498        //   }
2499        // }
2500        // var parts = value.split('.');
2501        // if (parts.length > 0) {
2502        //   checkIfDate(parts);
2503        // }
2504        // var parts = value.split('-');
2505        // if (parts.length > 0) {
2506        //   checkIfDate(parts);
2507        // }
2508        // var parts = value.split('/');
2509        // if (parts.length > 0) {
2510        //   checkIfDate(parts);
2511        // }
2512
2513        // Fix data params for cells which use formulas, which depen
2513ded on cells with shortcodes inside
2514        if (correctSorting && toeInArray(formatType, ['date', 'time_duration']) == -1) {
2515          var dataTableInstance = typeof table.api == 'function' ? table : self.getTableInstanceById(table.data('id'));
2516
2517          if ($this.data('original-value') != value) {
2518            $this.data('original-value', value);
2519            $this.attr('data-original-value', value);
2520          }
2521          if ($this.data('data-order') != value) {
2522            $this.data('order');
2523            $this.attr('data-order', value);
2524            if (dataTableInstance) {
2525              dataTableInstance.api().cell($this).invalidate();
2526            }
2527          }
2528        }
2529        if (value) {
2530          if ($this.data('cell-reformat')) {
2531            switch (formatType) {
2532              case 'date':
2533                var newDate = moment(value, format);
2534                if (newDate.isValid()) {
2535                  value = newDate.format(generalDateFormat);
2536
2537                  $this.data('cell-format', generalDateFormat);
2538                  $this.attr('data-cell-format', generalDateFormat);
2539
2540                  $this.data('original-value', value);
2541                  $this.attr('data-original-value', value);
2542
2543                  $this.data('order', value);
2544                  $this.attr('data-order', value);
2545
2546                  if (!g_stbServerSideProcessing) {
2547                    $this.data('cell-reformat', false);
2548                    $this.attr('data-cell-reformat', 0);
2549                  }
2550                }
2551                break;
2552              case 'time_duration':
2553                var newTime = moment(value, format),
2554                  isValid = false;
2555                // console.log(newTime);
2556
2557                if (newTime.isValid()) {
2558                  value = newTime.format(generalTimeFormat);
2559                  isValid = true;
2560                } else {
2561                  newTime = moment.duration(value);
2562                  if (newTime._milliseconds || value == 0) {
2563                    value = newTime.format(generalTimeFormat);
2564                    isValid = true;
2565                  }
2566                }
2567                if (isValid) {
2568                  $this.data('cell-format', generalTimeFormat);
2569                  $this.attr('data-cell-format', generalTimeFormat);
2570
2571                  $this.data('original-value', value);
2572                  $this.attr('data-original-value', value);
2573
2574                  $this.data('order', value);
2575                  $this.attr('data-order', value);
2576
2577                  if (!g_stbServerSideProcessing) {
2578                    $this.data('cell-reformat', false);
2579                    $this.attr('data-cell-reformat', 0);
2580                  }
2581                }
2582                break;
2583              default:
2584                break;
2585            }
2586          } else if (self.isNumber(value) && !isNaN(value)) {
2587            numberFormat = numberFormat ? numberFormat.toString() : '';
2588
2589            switch (formatType) {
2590              case 'percent':
2591                format = format ? format : generalPercentFormat;
2592
2593                if (format) {
2594                  format = format.toString();
2595
2596                  var clearFormat = format.indexOf('%') > -1 ? format.replace('%', '') : format;
2597
2598                  value = value.indexOf('%') > -1 ? $this.data('original-value') : value;
2599                  delimiters = (clearFormat.match(/[^\d]/g) || [',', '.']).reverse();
2600                  languageData.delimiters = {
2601                    decimal: delimiters[0],
2602                    thousands: delimiters[1],
2603                  };
2604
2605                  // We need to use dafault delimiters for format string
2606                  preparedFormat = format.replace(clearFormat, clearFormat.replace(delimiters[0], '.').replace(delimiters[1], ','));
2607                } else {
2608                  noFormat = true;
2609                }
2610                break;
2611              case 'currency':
2612                format = format ? format : generalCurrencyFormat;
2613
2614                if (format) {
2615                  format = format.toString();
2616
2617                  var formatWithoutCurrency = format.match(/\d.?\d*.?\d*/)[0],
2618                    currencySymbol = format.replace(formatWithoutCurrency, '') || '$'; // We need to set currency symbol in any case for normal work of numeraljs
2619
2620                  delimiters = (formatWithoutCurrency.match(/[^\d]/g) || [',', '.']).reverse();
2621
2622                  languageData.delimiters = {
2623                    decimal: delimiters[0],
2624                    thousands: delimiters[1],
2625                  };
2626                  languageData.currency.symbol = currencySymbol;
2627                  // We need to use dafault delimiters for format string
2628                  preparedFormat = format.replace(formatWithoutCurrency, formatWithoutCurrency.replace(delimiters[0], '.').replace(delimiters[1], ',')).replace(currencySymbol, '$');
2629                } else {
2630                  noFormat = true;
2631                }
2632                break;
2633              case 'date':
2634              case 'time_duration':
2635                noFormat = true;
2636                break;
2637              default:
2638                if (numberFormat) {
2639                  format = numberFormat;
2640                  delimiters = (format.match(/[^\d]/g) || [',', '.']).reverse();
2641                  languageData.delimiters = {
2642                    decimal: delimiters[0],
2643                    thousands: delimiters[1],
2644                  };
2645
2646                  // We need to use dafault delimiters for format string
2647                  preparedFormat = format.replace(format, format.replace(delimiters[0], '.').replace(delimiters[1], ','));
2648                  break;
2649                } else {
2650                  noFormat = true;
2651                }
2652                break;
2653            }
2654            if (noFormat) {
2655              noFormat = false;
2656            } else {
2657              numeral.language('en', languageData);
2658              value = numeral(value).format(preparedFormat);
2659            }
2660          }
2661        }
2662        if ($dimensionInner.length) {
2663          $dimensionInner.html(value);
2664        } else {
2665          $this.html(value);
2666        }
2667      });
2668    };
2669
2670    vendor[appName].isNumber = function (value) {
2671      if (value) {
2672        if (value.toString().match(/^-{0,1}\d+\.{0,1}\d*$/)) {
2673          return true;
2674        }
2675      }
2676      return false;
2677    };
2678
2679    vendor[appName].prepareFormulaToParse = function (value) {
2680      value = value
2681        .replace(/&apos;|&#0*39;|&#x0*27;/gi, "'")
2682        .replace(/&quot;|&#0*34;|&#x0*22;/gi, '"');
2683
2684      var formulaStringPattern = /"(?:[^"]|"")*"|'(?:[^']|'')*'/g,
2685        stringsInFormula = value.match(formulaStringPattern);
2686
2687      if (stringsInFormula && stringsInFormula.length) {
2688        var clearValue = value.replace(formulaStringPattern, '%STR%'),
2689          index = 0;
2690
2691        clearValue = clearValue.toUpperCase();
2692        value = clearValue.replace(/%STR%/g, function (match) {
2693          var val = match;
2694
2695          if (index < stringsInFormula.length) {
2696            val = stringsInFormula[index];
2697            index++;
2698          }
2699          return val;
2700        });
2701      } else {
2702        value = value.toUpperCase();
2703      }
2704      return value;
2705    };
2706
2707    vendor[appName].Base64 = {
2708      _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
2709      encode: function (input) {
2710        var self = vendor[appName].Base64,
2711          output = '',
2712          i = 0,
2713          chr1,
2714          chr2,
2715          chr3,
2716          enc1,
2717          enc2,
2718          enc3,
2719          enc4;
2720
2721        input = self._utf8_encode(input);
2722
2723        while (i < input.length) {
2724          chr1 = input.charCodeAt(i++);
2725          chr2 = input.charCodeAt(i++);
2726          chr3 = input.charCodeAt(i++);
2727
2728          enc1 = chr1 >> 2;
2729          enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
2730          enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
2731          enc4 = chr3 & 63;
2732
2733          if (isNaN(chr2)) {
2734            enc3 = enc4 = 64;
2735          } else if (isNaN(chr3)) {
2736            enc4 = 64;
2737          }
2738          output = output + self._keyStr.charAt(enc1) + self._keyStr.charAt(enc2) + self._keyStr.charAt(enc3) + self._keyStr.charAt(enc4);
2739        }
2740
2741        return output;
2742      },
2743      // private method for UTF-8 encoding
2744      _utf8_encode: function (string) {
2745        string = string.replace(/\r\n/g, '\n');
2746        var utftext = '';
2747
2748        for (var n = 0; n < string.length; n++) {
2749          var c = string.charCodeAt(n);
2750
2751          if (c < 128) {
2752            utftext += String.fromCharCode(c);
2753          } else if (c > 127 && c < 2048) {
2754            utftext += String.fromCharCode((c >> 6) | 192);
2755            utftext += String.fromCharCode((c & 63) | 128);
2756          } else {
2757            utftext += String.fromCharCode((c >> 12) | 224);
2758            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
2759            utftext += String.fromCharCode((c & 63) | 128);
2760          }
2761        }
2762
2763        return utftext;
2764      },
2765    };
2766
2767    vendor[appName].getClassesRegexp = function () {
2768      return {
2769        color: /color\-([0-9a-f]{6})/,
2770        background: /bg\-([0-9a-f]{6})/,
2771        fontFamily: /ffamily\-([a-z_]+)/i,
2772        fontSize: /fsize\-([0-9]+)/,
2773      };
2774    };
2775
2776    vendor[appName].setStylesToCell = function (cell) {
2777      var $cell = cell instanceof jQuery ? cell : jQuery(cell),
2778        viewId = $cell.parents('.supsystic-table:first').data('view-id'),
2779        classes = this.getClassesRegexp(),
2780        cellClassNames = $cell.get(0).className,
2781        color = classes.color.exec(cellClassNames),
2782        background = classes.background.exec(cellClassNames),
2783        fontFamily = classes.fontFamily.exec(cellClassNames),
2784        fontSize = classes.fontSize.exec(cellClassNames);
2785
2786      if (null !== color) {
2787        $cell.css({
2788          color: '#' + color[1],
2789        });
2790      }
2791      if (null !== background) {
2792        $cell.css({
2793          backgroundColor: '#' + background[1],
2794        });
2795      }
2796      if (null !== fontFamily) {
2797        var family = fontFamily[1].replace(/_/g, ' '),
2798          familyName = fontFamily[1].replace(/_/g, '+'),
2799          familyString = '@import url("//fonts.googleapis.com/css?family=' 
2799+ familyName + '");';
2800
2801        if (g_stbStandartFontsList && toeInArray(family, g_stbStandartFontsList) == -1 && g_stbAllFontsList && toeInArray(family, g_stbAllFontsList) != -1) {
2802          var style = this.getFrontendCellStylesElem(viewId);
2803
2804          if (style.text().indexOf(familyString) == -1) {
2805            style.text(familyString + '\n' + style.text());
2806          }
2807        }
2808        $cell.css({
2809          fontFamily: family,
2810        });
2811      }
2812      if (null !== fontSize) {
2813        var lineHeight = +fontSize[1] + 6;
2814        $cell.css({
2815          fontSize: fontSize[1] + 'px',
2816          lineHeight: lineHeight + 'px',
2817        });
2818      }
2819    };
2820
2821    vendor[appName].getAdminCellStylesElem = function () {
2822      var $style = jQuery('#supsystic-tables-style');
2823
2824      if (!$style.length) {
2825        $style = jQuery('<style/>', {
2826          id: 'supsystic-tables-style',
2827        });
2828        jQuery('head').append($style);
2829      }
2830      return $style;
2831    };
2832
2833    vendor[appName].getFrontendCellStylesElem = function (viewId) {
2834      var $style = jQuery('#supsystic-table-' + viewId + '-css');
2835
2836      if (!$style.length) {
2837        $style = jQuery('<style/>', {
2838          id: 'supsystic-table-' + viewId + '-css',
2839        });
2840        jQuery('head').append($style);
2841      }
2842      return $style;
2843    };
2844
2845    vendor[appName]._fixTableCaption = function (captionHeight, viewId, counter) {
2846      if (counter < 0) return false;
2847
2848      // Fix for displaying of caption for tables with fixed columns
2849      var self = this,
2850        tableViewHtmlId = '#supsystic-table-' + viewId,
2851        fixedColumnsWrapper = jQuery(tableViewHtmlId + ' .DTFC_LeftWrapper, ' + tableViewHtmlId + ' .DTFC_RightWrapper');
2852
2853      if (fixedColumnsWrapper.length) {
2854        fixedColumnsWrapper.find('caption').css({
2855          display: 'none',
2856        });
2857        fixedColumnsWrapper.css({
2858          top: captionHeight + 'px',
2859        });
2860      } else {
2861        counter--;
2862        setTimeout(function () {
2863          self._fixTableCaption(captionHeight, viewId, counter);
2864        }, 50);
2865      }
2866    };
2867
2868    vendor[appName]._getChunksArray = function (arr, len) {
2869      var chunks = [],
2870        i = 0,
2871        n = arr.length;
2872
2873      while (i < n) {
2874        chunks.push(arr.slice(i, (i += len)));
2875      }
2876
2877      return chunks;
2878    };
2879
2880    vendor[appName]._checkOnClickPopups = function ($table) {
2881      // Integration with our PopUp plugin
2882      // Only after table was inited - we can do this, and only in that way it will work
2883      if (typeof _ppsBindOnElementClickPopups !== 'undefined' && $table && $table.size()) {
2884        var $bindedLinks = $table.find('[href*="#ppsShowPopUp_"].ppsClickBinded');
2885        if ($bindedLinks && $bindedLinks.size()) {
2886          $bindedLinks.removeClass('ppsClickBinded').unbind('click');
2887        }
2888        _ppsBindOnElementClickPopups();
2889      }
2890    };
2891
2892    vendor[appName].setCellAttributes = function (cells) {
2893      var colspan, rowspan;
2894      for (var i = 0; i < cells.length; i++) {
2895        if (cells[i].getAttribute('data-hide')) {
2896          cells[i].style.display = 'none';
2897        }
2898        if ((colspan = cells[i].getAttribute('data-colspan'))) {
2899          if (colspan > 1) {
2900            cells[i].setAttribute('colspan', colspan);
2901            jQuery(cells[i]).attr('colspan', colspan);
2902          }
2903        }
2904        if ((rowspan = cells[i].getAttribute('data-rowspan'))) {
2905          if (rowspan > 1) {
2906            cells[i].setAttribute('rowspan', rowspan);
2907          }
2908        }
2909      }
2910    };
2911  }
2912})((window.supsystic = window.supsystic || {}), window.jQuery, window);
2913
2914// For compatibility to old PRO versions
2915function classesRegexp() {
2916  return window.supsystic.Tables.getClassesRegexp();
2917}
2918
2919function getAdminCellStylesElem() {
2920  return window.supsystic.Tables.getAdminCellStylesElem();
2921}
2922
2923/**
2924 * We will not use just jQUery.inArray because it is work incorrect for objects
2925 * @return mixed - key that was found element or -1 if not
2926 */
2927function toeInArray(needle, haystack) {
2928  if (typeof haystack == 'object') {
2929    for (var k in haystack) {
2930      if (haystack[k] == needle) return k;
2931    }
2932  } else if (typeof haystack == 'array') {
2933    return jQuery.inArray(needle, haystack);
2934  }
2935  return -1;
2936}
2937
2938(function ($) {
2939  /**
2940   * Detects whether element can be scrolled vertically.
2941   * @this jQuery
2942   * @return {boolean}
2943   */
2944  jQuery.fn.isVerticallyScrollable = function () {
2945    if (this.scrollTop()) {
2946      // Element is already scrolled, so it is scrollable
2947      return true;
2948    } else {
2949      // Test by actually scrolling
2950      this.scrollTop(1);
2951
2952      if (this.scrollTop()) {
2953        // Scroll back
2954        this.scrollTop(0);
2955        return true;
2956      }
2957    }
2958    return false;
2959  };
2960
2961  /**
2962   * Detects whether element can be scrolled horizontally.
2963   * @this jQuery
2964   * @return {boolean}
2965   */
2966  jQuery.fn.isHorizontallyScrollable = function () {
2967    if (this.scrollLeft()) {
2968      // Element is already scrolled, so it is scrollable
2969      return true;
2970    } else {
2971      // Test by actually scrolling
2972      this.scrollLeft(1);
2973
2974      if (this.scrollLeft()) {
2975        // Scroll back
2976        this.scrollLeft(0);
2977        return true;
2978      }
2979    }
2980    return false;
2981  };
2982
2983  jQuery.extend(jQuery.expr.pseudos || jQuery.expr[':'], {
2984    'vertically-scrollable': function (a, i, m) {
2985      return jQuery(a).isVerticallyScrollable();
2986    },
2987    'horizontally-scrollable': function (a, i, m) {
2988      return jQuery(a).isHorizontallyScrollable();
2989    },
2990  });
2991
2992  jQuery.fn.removeStyle = function (style) {
2993    var search = new RegExp(style + '[^;]+;?', 'g');
2994
2995    return this.each(function () {
2996      jQuery(this).attr('style', function (i, style) {
2997        return style && style.replace(search, '');
2998      });
2999    });
vendor: 2,953 bytes, lines 3000-3084
3000  };
3001
3002  if (!Array.from) {
3003    // Fix of compatibility with IE browser to use ES6 feature
3004    Array.from = (function () {
3005      var toStr = Object.prototype.toString;
3006      var isCallable = function (fn) {
3007        return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
3008      };
3009      var toInteger = function (value) {
3010        var number = Number(value);
3011        if (isNaN(number)) {
3012          return 0;
3013        }
3014        if (number === 0 || !isFinite(number)) {
3015          return number;
3016        }
3017        return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
3018      };
3019      var maxSafeInteger = Math.pow(2, 53) - 1;
3020      var toLength = function (value) {
3021        var len = toInteger(value);
3022        return Math.min(Math.max(len, 0), maxSafeInteger);
3023      };
3024
3025      // The length property of the from method is 1.
3026      return function from(arrayLike /*, mapFn, thisArg */) {
3027        // 1. Let C be the this value.
3028        var C = this;
3029
3030        // 2. Let items be ToObject(arrayLike).
3031        var items = Object(arrayLike);
3032
3033        // 3. ReturnIfAbrupt(items).
3034        if (arrayLike == null) {
3035          throw new TypeError('Array.from requires an array-like object - not null or undefined');
3036        }
3037
3038        // 4. If mapfn is undefined, then let mapping be false.
3039        var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
3040        var T;
3041        if (typeof mapFn !== 'undefined') {
3042          // 5. else
3043          // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
3044          if (!isCallable(mapFn)) {
3045            throw new TypeError('Array.from: when provided, the second argument must be a function');
3046          }
3047
3048          // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
3049          if (arguments.length > 2) {
3050            T = arguments[2];
3051          }
3052        }
3053
3054        // 10. Let lenValue be Get(items, "length").
3055        // 11. Let len be ToLength(lenValue).
3056        var len = toLength(items.length);
3057
3058        // 13. If IsConstructor(C) is true, then
3059        // 13. a. Let A be the result of calling the [[Construct]] internal method
3060        // of C with an argument list containing the single item len.
3061        // 14. a. Else, Let A be ArrayCreate(len).
3062        var A = isCallable(C) ? Object(new C(len)) : new Array(len);
3063
3064        // 16. Let k be 0.
3065        var k = 0;
3066        // 17. Repeat, while k < len… (also steps a - h)
3067        var kValue;
3068        while (k < len) {
3069          kValue = items[k];
3070          if (mapFn) {
3071            A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
3072          } else {
3073            A[k] = kValue;
3074          }
3075          k += 1;
3076        }
3077        // 18. Let putStatus be Put(A, "length", len, true).
3078        A.length = len;
3079        // 20. Return A.
3080        return A;
3081      };
3082    })();
3083  }
3084})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.