Bug 31203: (follow-up) Remove stray debug statement
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / datatables.js
1 // These default options are for translation but can be used
2 // for any other datatables settings
3 // To use it, write:
4 //  $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
5 //      // other settings
6 //  } ) );
7 var dataTablesDefaults = {
8     "language": {
9         "paginate": {
10             "first"    : __('First'),
11             "last"     : __('Last'),
12             "next"     : __('Next'),
13             "previous" : __('Previous'),
14         },
15         "emptyTable"       : __('No data available in table'),
16         "info"             : __('Showing _START_ to _END_ of _TOTAL_ entries'),
17         "infoEmpty"        : __('No entries to show'),
18         "infoFiltered"     : __('(filtered from _MAX_ total entries)'),
19         "lengthMenu"       : __('Show _MENU_ entries'),
20         "loadingRecords"   : __('Loading...'),
21         "processing"       : __('Processing...'),
22         "search"           : __('Search:'),
23         "zeroRecords"      : __('No matching records found'),
24         buttons: {
25             "copyTitle"     : __('Copy to clipboard'),
26             "copyKeys"      : __('Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.'),
27             "copySuccess": {
28                 _: __('Copied %d rows to clipboard'),
29                 1: __('Copied one row to clipboard'),
30             }
31         }
32     },
33     "dom": '<"top pager"<"table_entries"ilp><"table_controls"fB>>tr<"bottom pager"ip>',
34     "buttons": [{
35         fade: 100,
36         className: "dt_button_clear_filter",
37         titleAttr: __('Clear filter'),
38         enabled: false,
39         text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __('Clear filter') + '</span>',
40         available: function ( dt ) {
41             // The "clear filter" button is made available if this test returns true
42             if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
43                 return true;
44             }
45         },
46         action: function ( e, dt, node ) {
47             dt.search( "" ).draw("page");
48             node.addClass("disabled");
49         }
50     }],
51     "lengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, __('All')]],
52     "pageLength": 20,
53     "fixedHeader": true,
54     initComplete: function( settings) {
55         var tableId = settings.nTable.id
56         // When the DataTables search function is triggered,
57         // enable or disable the "Clear filter" button based on
58         // the presence of a search string
59         $("#" + tableId ).on( 'search.dt', function ( e, settings ) {
60             if( settings.oPreviousSearch.sSearch == "" ){
61                 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
62             } else {
63                 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
64             }
65         });
66     }
67 };
68
69
70 // Return an array of string containing the values of a particular column
71 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
72     // check that we have a column id
73     if ( typeof iColumn == "undefined" ) return new Array();
74     // by default we only wany unique data
75     if ( typeof bUnique == "undefined" ) bUnique = true;
76     // by default we do want to only look at filtered data
77     if ( typeof bFiltered == "undefined" ) bFiltered = true;
78     // by default we do not wany to include empty values
79     if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
80     // list of rows which we're going to loop through
81     var aiRows;
82     // use only filtered rows
83     if (bFiltered == true) aiRows = oSettings.aiDisplay;
84     // use all rows
85     else aiRows = oSettings.aiDisplayMaster; // all row numbers
86
87     // set up data array
88     var asResultData = new Array();
89     for (var i=0,c=aiRows.length; i<c; i++) {
90         iRow = aiRows[i];
91         var aData = this.fnGetData(iRow);
92         var sValue = aData[iColumn];
93         // ignore empty values?
94         if (bIgnoreEmpty == true && sValue.length == 0) continue;
95         // ignore unique values?
96         else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
97         // else push the value onto the result data array
98         else asResultData.push(sValue);
99     }
100     return asResultData;
101 }
102
103 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
104 // These keys must not launch filtering
105 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
106
107 // Set a filtering delay for global search field
108 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
109     /*
110      * Inputs:      object:oSettings - dataTables settings object - automatically given
111      *              integer:iDelay - delay in milliseconds
112      * Usage:       $('#example').dataTable().fnSetFilteringDelay(250);
113      * Author:      Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
114      * License:     GPL v2 or BSD 3 point style
115      * Contact:     zygimantas.berziunas /AT\ hotmail.com
116      */
117     var
118         _that = this,
119         iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
120
121     this.each( function ( i ) {
122         $.fn.dataTableExt.iApiIndex = i;
123         var
124             $this = this,
125             oTimerId = null,
126             sPreviousSearch = null,
127             anControl = $( 'input', _that.fnSettings().aanFeatures.f );
128
129         anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
130             var $$this = $this;
131             if (blacklist_keys.indexOf(event.keyCode) != -1) {
132                 return this;
133             }else if ( event.keyCode == '13' ) {
134                 $.fn.dataTableExt.iApiIndex = i;
135                 _that.fnFilter( $(this).val() );
136             } else {
137                 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
138                     window.clearTimeout(oTimerId);
139                     sPreviousSearch = anControl.val();
140                     oTimerId = window.setTimeout(function() {
141                         $.fn.dataTableExt.iApiIndex = i;
142                         _that.fnFilter( anControl.val() );
143                     }, iDelay);
144                 }
145             }
146         });
147
148         return this;
149     } );
150     return this;
151 }
152
153 // Add a filtering delay on general search and on all input (with a class 'filter')
154 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
155     var table = this;
156     this.fnSetFilteringDelay(iDelay);
157     var filterTimerId = null;
158     $(table).find("input."+sClass).keyup(function(event) {
159       if (blacklist_keys.indexOf(event.keyCode) != -1) {
160         return this;
161       }else if ( event.keyCode == '13' ) {
162         table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
163       } else {
164         window.clearTimeout(filterTimerId);
165         var input = this;
166         filterTimerId = window.setTimeout(function() {
167           table.fnFilter($(input).val(), $(input).attr('data-column_num'));
168         }, iDelay);
169       }
170     });
171     $(table).find("select."+sClass).on('change', function() {
172         table.fnFilter($(this).val(), $(this).attr('data-column_num'));
173     });
174 }
175
176 // Sorting on html contains
177 // <a href="foo.pl">bar</a> sort on 'bar'
178 function dt_overwrite_html_sorting_localeCompare() {
179     jQuery.fn.dataTableExt.oSort['html-asc']  = function(a,b) {
180         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
181         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
182         if (typeof(a.localeCompare == "function")) {
183            return a.localeCompare(b);
184         } else {
185            return (a > b) ? 1 : ((a < b) ? -1 : 0);
186         }
187     };
188
189     jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
190         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
191         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
192         if(typeof(b.localeCompare == "function")) {
193             return b.localeCompare(a);
194         } else {
195             return (b > a) ? 1 : ((b < a) ? -1 : 0);
196         }
197     };
198
199     jQuery.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
200         var x = a.replace( /<.*?>/g, "" );
201         var y = b.replace( /<.*?>/g, "" );
202         x = parseFloat( x );
203         y = parseFloat( y );
204         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
205     };
206
207     jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
208         var x = a.replace( /<.*?>/g, "" );
209         var y = b.replace( /<.*?>/g, "" );
210         x = parseFloat( x );
211         y = parseFloat( y );
212         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
213     };
214 }
215
216 $.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
217     var x = a.replace( /<.*?>/g, "" );
218     var y = b.replace( /<.*?>/g, "" );
219     x = parseFloat( x );
220     y = parseFloat( y );
221     return ((x < y) ? -1 : ((x > y) ?  1 : 0));
222 };
223
224 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
225     var x = a.replace( /<.*?>/g, "" );
226     var y = b.replace( /<.*?>/g, "" );
227     x = parseFloat( x );
228     y = parseFloat( y );
229     return ((x < y) ?  1 : ((x > y) ? -1 : 0));
230 };
231
232 (function() {
233
234 /*
235  * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
236  * Author: Jim Palmer (based on chunking idea from Dave Koelle)
237  * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
238  * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
239  */
240 function naturalSort (a, b) {
241     var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
242         sre = /(^[ ]*|[ ]*$)/g,
243         dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
244         hre = /^0x[0-9a-f]+$/i,
245         ore = /^0/,
246         // convert all to strings and trim()
247         x = a.toString().replace(sre, '') || '',
248         y = b.toString().replace(sre, '') || '',
249         // chunk/tokenize
250         xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
251         yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
252         // numeric, hex or date detection
253         xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
254         yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
255     // first try and sort Hex codes or Dates
256     if (yD)
257         if ( xD < yD ) return -1;
258         else if ( xD > yD )  return 1;
259     // natural sorting through split numeric strings and default strings
260     for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
261         // find floats not starting with '0', string or 0 if not defined (Clint Priest)
262         var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
263         var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
264         // handle numeric vs string comparison - number < string - (Kyle Adams)
265         if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
266         // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
267         else if (typeof oFxNcL !== typeof oFyNcL) {
268             oFxNcL += '';
269             oFyNcL += '';
270         }
271         if (oFxNcL < oFyNcL) return -1;
272         if (oFxNcL > oFyNcL) return 1;
273     }
274     return 0;
275 }
276
277 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
278     "natural-asc": function ( a, b ) {
279         return naturalSort(a,b);
280     },
281
282     "natural-desc": function ( a, b ) {
283         return naturalSort(a,b) * -1;
284     }
285 } );
286
287 }());
288
289 /* Plugin to allow sorting on data stored in a span's title attribute
290  *
291  * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
292  *
293  * In DataTables config:
294  *     "aoColumns": [
295  *        { "sType": "title-string" },
296  *      ]
297  * http://datatables.net/plug-ins/sorting#hidden_title_string
298  */
299 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
300     "title-string-pre": function ( a ) {
301         var m = a.match(/title="(.*?)"/);
302         if ( null !== m && m.length ) {
303             return m[1].toLowerCase();
304         }
305         return "";
306     },
307
308     "title-string-asc": function ( a, b ) {
309         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
310     },
311
312     "title-string-desc": function ( a, b ) {
313         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
314     }
315 } );
316
317 (function() {
318
319     /* Plugin to allow text sorting to ignore articles
320      *
321      * In DataTables config:
322      *     "aoColumns": [
323      *        { "sType": "anti-the" },
324      *      ]
325      * Based on the plugin found here:
326      * http://datatables.net/plug-ins/sorting#anti_the
327      * Modified to exclude HTML tags from sorting
328      * Extended to accept a string of space-separated articles
329      * from a configuration file (in English, "a," "an," and "the")
330      */
331
332     var config_exclude_articles_from_sort = __('a an the');
333     if (config_exclude_articles_from_sort){
334         var articles = config_exclude_articles_from_sort.split(" ");
335         var rpattern = "";
336         for(i=0;i<articles.length;i++){
337             rpattern += "^" + articles[i] + " ";
338             if(i < articles.length - 1){ rpattern += "|"; }
339         }
340         var re = new RegExp(rpattern, "i");
341     }
342
343     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
344         "anti-the-pre": function ( a ) {
345             var x = String(a).replace( /<[\s\S]*?>/g, "" );
346             var y = x.trim();
347             var z = y.replace(re, "").toLowerCase();
348             return z;
349         },
350
351         "anti-the-asc": function ( a, b ) {
352             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
353         },
354
355         "anti-the-desc": function ( a, b ) {
356             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
357         }
358     });
359
360 }());
361
362 // Remove string between NSB NSB characters
363 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
364     var pattern = new RegExp("\x88.*\x89");
365     a = a.replace(pattern, "");
366     b = b.replace(pattern, "");
367     return (a > b) ? 1 : ((a < b) ? -1 : 0);
368 }
369 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
370     var pattern = new RegExp("\x88.*\x89");
371     a = a.replace(pattern, "");
372     b = b.replace(pattern, "");
373     return (b > a) ? 1 : ((b < a) ? -1 : 0);
374 }
375
376 /* Define two custom functions (asc and desc) for basket callnumber sorting */
377 jQuery.fn.dataTableExt.oSort['callnumbers-asc']  = function(x,y) {
378         var x_array = x.split("<div>");
379         var y_array = y.split("<div>");
380
381         /* Pop the first elements, they are empty strings */
382         x_array.shift();
383         y_array.shift();
384
385         x_array = jQuery.map( x_array, function( a ) {
386             return parse_callnumber( a );
387         });
388         y_array = jQuery.map( y_array, function( a ) {
389             return parse_callnumber( a );
390         });
391
392         x_array.sort();
393         y_array.sort();
394
395         x = x_array.shift();
396         y = y_array.shift();
397
398         if ( !x ) { x = ""; }
399         if ( !y ) { y = ""; }
400
401         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
402 };
403
404 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
405         var x_array = x.split("<div>");
406         var y_array = y.split("<div>");
407
408         /* Pop the first elements, they are empty strings */
409         x_array.shift();
410         y_array.shift();
411
412         x_array = jQuery.map( x_array, function( a ) {
413             return parse_callnumber( a );
414         });
415         y_array = jQuery.map( y_array, function( a ) {
416             return parse_callnumber( a );
417         });
418
419         x_array.sort();
420         y_array.sort();
421
422         x = x_array.pop();
423         y = y_array.pop();
424
425         if ( !x ) { x = ""; }
426         if ( !y ) { y = ""; }
427
428         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
429 };
430
431 function parse_callnumber ( html ) {
432     var array = html.split('<span class="callnumber">');
433     if ( array[1] ) {
434         array = array[1].split('</span>');
435         return array[0];
436     } else {
437         return "";
438     }
439 }
440
441 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
442 function footer_column_sum( api, column_numbers ) {
443     // Remove the formatting to get integer data for summation
444     var intVal = function ( i ) {
445         if ( typeof i === 'number' ) {
446             if ( isNaN(i) ) return 0;
447             return i;
448         } else if ( typeof i === 'string' ) {
449             var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
450             if ( isNaN(value) ) return 0;
451             return value;
452         }
453         return 0;
454     };
455
456
457     for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
458         var column_number = column_numbers[indice];
459
460         var total = 0;
461         var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
462         var budgets_totaled = [];
463         $(cells).each(function(){ budgets_totaled.push( $(this).data('self_id') ); });
464         $(cells).each(function(){
465             if( $(this).data('parent_id') && $.inArray( $(this).data('parent_id'), budgets_totaled) > -1 ){
466                 return;
467             } else {
468                 total += intVal( $(this).html() );
469             }
470
471         });
472         total /= 100; // Hard-coded decimal precision
473
474         // Update footer
475         $( api.column( column_number ).footer() ).html(total.format_price());
476     };
477 }
478
479 function filterDataTable( table, column, term ){
480     if( column ){
481         table.column( column ).search( term ).draw("page");
482     } else {
483         table.search( term ).draw("page");
484     }
485 }
486
487 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
488     if ( settings && settings.jqXHR ) {
489         console.log("Got %s (%s)".format(settings.jqXHR.status, settings.jqXHR.statusText));
490         alert(__("Something went wrong when loading the table.\n%s: %s").format(settings.jqXHR.status, settings.jqXHR.statusText));
491     } else {
492         alert(__("Something went wrong when loading the table."));
493     }
494     console.log(message);
495 };
496
497 (function($) {
498
499     /**
500     * Create a new dataTables instance that uses the Koha RESTful API's as a data source
501     * @param  {Object}  options         Please see the dataTables documentation for further details
502     *                                   We extend the options set with the `criteria` key which allows
503     *                                   the developer to select the match type to be applied during searches
504     *                                   Valid keys are: `contains`, `starts_with`, `ends_with` and `exact`
505     * @param  {Object}  table_settings The arrayref as returned by TableSettings.GetTableSettings function available
506     *                                   from the columns_settings template toolkit include
507     * @param  {Boolean} add_filters     Add a filters row as the top row of the table
508     * @param  {Object}  default_filters Add a set of default search filters to apply at table initialisation
509     * @return {Object}                  The dataTables instance
510     */
511     $.fn.kohaTable = function(options, table_settings, add_filters, default_filters) {
512         var settings = null;
513
514         if ( add_filters ) {
515             $(this).find('thead tr').clone(true).appendTo( $(this).find('thead') );
516         }
517
518         if(options) {
519             if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
520             options.criteria = options.criteria.toLowerCase();
521
522             // Don't redefine the default initComplete
523             if ( options.initComplete ) {
524                 let our_initComplete = options.initComplete;
525                 options.initComplete = function(settings, json){
526                     our_initComplete(settings, json);
527                     dataTablesDefaults.initComplete(settings, json)
528                 };
529             }
530
531             settings = $.extend(true, {}, dataTablesDefaults, {
532                         'deferRender': true,
533                         "paging": true,
534                         'serverSide': true,
535                         'searching': true,
536                         'pagingType': 'full_numbers',
537                         'processing': true,
538                         'language': {
539                             'emptyTable': (options.emptyTable) ? options.emptyTable : __("No data available in table")
540                         },
541                         'ajax': {
542                             'type': 'GET',
543                             'cache': true,
544                             'dataSrc': 'data',
545                             'beforeSend': function(xhr, settings) {
546                                 this._xhr = xhr;
547                                 if(options.embed) {
548                                     xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
549                                 }
550                                 if(options.header_filter && options.query_parameters) {
551                                     xhr.setRequestHeader('x-koha-query', options.query_parameters);
552                                     delete options.query_parameters;
553                                 }
554                             },
555                             'dataFilter': function(data, type) {
556                                 var json = {data: JSON.parse(data)};
557                                 if (total = this._xhr.getResponseHeader('x-total-count')) {
558                                     json.recordsTotal = total;
559                                     json.recordsFiltered = total;
560                                 }
561                                 if (total = this._xhr.getResponseHeader('x-base-total-count')) {
562                                     json.recordsTotal = total;
563                                 }
564                                 if (draw = this._xhr.getResponseHeader('x-koha-request-id')) {
565                                     json.draw = draw;
566                                 }
567
568                                 return JSON.stringify(json);
569                             },
570                             'data': function( data, settings ) {
571                                 var length = data.length;
572                                 var start  = data.start;
573
574                                 var dataSet = {
575                                     _page: Math.floor(start/length) + 1,
576                                     _per_page: length
577                                 };
578
579                                 function build_query(col, value){
580
581                                     var parts = [];
582                                     var attributes = col.data.split(':');
583                                     for (var i=0;i<attributes.length;i++){
584                                         var part = {};
585                                         var attr = attributes[i];
586                                         let criteria = options.criteria;
587                                         if ( value.match(/^\^(.*)\$$/) ) {
588                                             value = value.replace(/^\^/, '').replace(/\$$/, '');
589                                             criteria = "exact";
590                                         } else {
591                                            // escape SQL LIKE special characters % and _
592                                            value = value.replace(/(\%|\\)/g, "\\$1");
593                                         }
594                                         part[!attr.includes('.')?'me.'+attr:attr] = criteria === 'exact'
595                                             ? value
596                                             : {like: (['contains', 'ends_with'].indexOf(criteria) !== -1?'%':'') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1?'%':'')};
597                                         parts.push(part);
598                                     }
599                                     return parts;
600                                 }
601
602                                 var filter = data.search.value;
603                                 // Build query for each column filter
604                                 var and_query_parameters = settings.aoColumns
605                                 .filter(function(col) {
606                                     return col.bSearchable && typeof col.data == 'string' && data.columns[col.idx].search.value != ''
607                                 })
608                                 .map(function(col) {
609                                     var value = data.columns[col.idx].search.value;
610                                     return build_query(col, value)
611                                 })
612                                 .map(function r(e){
613                                     return ($.isArray(e) ? $.map(e, r) : e);
614                                 });
615
616                                 // Build query for the global search filter
617                                 var or_query_parameters = settings.aoColumns
618                                 .filter(function(col) {
619                                     return col.bSearchable && filter != ''
620                                 })
621                                 .map(function(col) {
622                                     var value = filter;
623                                     return build_query(col, value)
624                                 })
625                                 .map(function r(e){
626                                     return ($.isArray(e) ? $.map(e, r) : e);
627                                 });
628
629                                 if ( default_filters ) {
630                                     let additional_filters = {};
631                                     for ( f in default_filters ) {
632                                         let k; let v;
633                                         if ( typeof(default_filters[f]) === 'function' ) {
634                                             let val = default_filters[f]();
635                                             if ( val != undefined && val != "" ) {
636                                                 k = f; v = val;
637                                             }
638                                         } else {
639                                             k = f; v = default_filters[f];
640                                         }
641
642                                         // Pass to -or if you want a separate OR clause
643                                         // It's not the usual DBIC notation!
644                                         if ( f == '-or' ) {
645                                             if (v) or_query_parameters.push(v)
646                                         } else if ( f == '-and' ) {
647                                             if (v) and_query_parameters.push(v)
648                                         } else if ( v ) {
649                                             additional_filters[k] = v;
650                                         }
651                                     }
652                                     if ( Object.keys(additional_filters).length ) {
653                                         and_query_parameters.push(additional_filters);
654                                     }
655                                 }
656                                 query_parameters = and_query_parameters;
657                                 if ( or_query_parameters.length) {
658                                     query_parameters.push(or_query_parameters);
659                                 }
660
661                                 if(query_parameters.length) {
662                                     query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:{"-and": query_parameters});
663                                     if(options.header_filter) {
664                                         options.query_parameters = query_parameters;
665                                     } else {
666                                         dataSet.q = query_parameters;
667                                         delete options.query_parameters;
668                                     }
669                                 } else {
670                                     delete options.query_parameters;
671                                 }
672
673                                 dataSet._match = options.criteria;
674
675                                 if ( data["draw"] !== undefined ) {
676                                     settings.ajax.headers = { 'x-koha-request-id': data.draw }
677                                 }
678
679                                 if(options.columns) {
680                                     var order = data.order;
681                                     var orderArray = new Array();
682                                     order.forEach(function (e,i) {
683                                         var order_col      = e.column;
684                                         var order_by       = options.columns[order_col].data;
685                                         order_by           = order_by.split(':');
686                                         var order_dir      = e.dir == 'asc' ? '+' : '-';
687                                         Array.prototype.push.apply(orderArray,order_by.map(x => order_dir + (!x.includes('.')?'me.'+x:x)));
688                                     });
689                                     dataSet._order_by = orderArray.filter((v, i, a) => a.indexOf(v) === i).join(',');
690                                 }
691
692                                 return dataSet;
693                             }
694                         }
695                     }, options);
696         }
697
698         var counter = 0;
699         var hidden_ids = [];
700         var included_ids = [];
701
702
703         if ( table_settings ) {
704             var columns_settings = table_settings['columns'];
705             $(columns_settings).each( function() {
706                 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
707                 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
708                 if ( used_id == -1 ) return;
709
710                 if ( this['is_hidden'] == "1" ) {
711                     hidden_ids.push( used_id );
712                 }
713                 if ( this['cannot_be_toggled'] == "0" ) {
714                     included_ids.push( used_id );
715                 }
716                 counter++;
717             });
718         }
719
720         var exportColumns = ":visible:not(.noExport)";
721         if( settings.hasOwnProperty("exportColumns") ){
722             // A custom buttons configuration has been passed from the page
723             exportColumns = settings["exportColumns"];
724         }
725
726         var export_format = {
727             body: function ( data, row, column, node ) {
728                 var newnode = $(node);
729
730                 if ( newnode.find(".noExport").length > 0 ) {
731                     newnode = newnode.clone();
732                     newnode.find(".noExport").remove();
733                 }
734
735                 return newnode.text().replace( /\n/g, ' ' ).trim();
736             }
737         }
738
739         var export_buttons = [
740             {
741                 extend: 'excelHtml5',
742                 text: __("Excel"),
743                 exportOptions: {
744                     columns: exportColumns,
745                     format:  export_format
746                 },
747             },
748             {
749                 extend: 'csvHtml5',
750                 text: __("CSV"),
751                 exportOptions: {
752                     columns: exportColumns,
753                     format:  export_format
754                 },
755             },
756             {
757                 extend: 'copyHtml5',
758                 text: __("Copy"),
759                 exportOptions: {
760                     columns: exportColumns,
761                     format:  export_format
762                 },
763             },
764             {
765                 extend: 'print',
766                 text: __("Print"),
767                 exportOptions: {
768                     columns: exportColumns,
769                     format:  export_format
770                 },
771             }
772         ];
773
774         settings[ "buttons" ] = [
775             {
776                 fade: 100,
777                 className: "dt_button_clear_filter",
778                 titleAttr: __("Clear filter"),
779                 enabled: false,
780                 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
781                 action: function ( e, dt, node, config ) {
782                     dt.search( "" ).draw("page");
783                     node.addClass("disabled");
784                 }
785             }
786         ];
787
788         if( included_ids.length > 0 ){
789             settings[ "buttons" ].push(
790                 {
791                     extend: 'colvis',
792                     fade: 100,
793                     columns: included_ids,
794                     className: "columns_controls",
795                     titleAttr: __("Columns settings"),
796                     text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
797                     exportOptions: {
798                         columns: exportColumns
799                     }
800                 }
801             );
802         }
803
804         settings[ "buttons" ].push(
805             {
806                 extend: 'collection',
807                 autoClose: true,
808                 fade: 100,
809                 className: "export_controls",
810                 titleAttr: __("Export or print"),
811                 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
812                 buttons: export_buttons
813             }
814         );
815
816         if ( table_settings && CAN_user_parameters_manage_column_config ) {
817             settings[ "buttons" ].push(
818                 {
819                     className: "dt_button_configure_table",
820                     titleAttr: __("Table settings"),
821                     text: '<i class="fa fa-lg fa-wrench"></i> <span class="dt-button-text">' + __("Configure") + '</span>',
822                     action: function() {
823                         window.location = '/cgi-bin/koha/admin/columns_settings.pl?module=' + table_settings['module'] + '&page=' + table_settings['page'] + '&table=' + table_settings['table'];
824                     },
825                 }
826             );
827         }
828
829         $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
830
831         if ( add_filters ) {
832             settings['orderCellsTop'] = true;
833         }
834
835         if ( table_settings ) {
836             if ( table_settings.hasOwnProperty('default_display_length') && table_settings['default_display_length'] != null ) {
837                 settings["pageLength"] = table_settings['default_display_length'];
838             }
839             if ( table_settings.hasOwnProperty('default_sort_order') && table_settings['default_sort_order'] != null ) {
840                 settings["order"] = [[ table_settings['default_sort_order'], 'asc' ]];
841             }
842         }
843
844         var table = $(this).dataTable(settings);
845
846
847         if ( add_filters ) {
848             var table_dt = table.DataTable();
849             $(this).find('thead tr:eq(1) th').each( function (i) {
850                 var is_searchable = table_dt.settings()[0].aoColumns[i].bSearchable;
851                 if ( is_searchable ) {
852                     let input_type = 'input';
853                     if ( $(this).data('filter') ) {
854                         input_type = 'select'
855                         let filter_type = $(this).data('filter');
856                         var existing_search = table_dt.column(i).search();
857                         let select = $('<select><option value=""></option></select');
858
859                         // FIXME eval here is bad and dangerous, how do we workaround that?
860                         $(eval(filter_type)).each(function(){
861                             let o = $('<option value="%s">%s</option>'.format(this._id, this._str));
862                             if ( existing_search == this._id ) {
863                                 o.prop("selected", "selected");
864                             }
865                             o.appendTo(select);
866                         });
867                         $(this).html( select );
868                     } else {
869                         var title = $(this).text();
870                         var existing_search = table_dt.column(i).search();
871                         if ( existing_search ) {
872                             $(this).html( '<input type="text" value="%s" style="width: 100%" />'.format(existing_search) );
873                         } else {
874                             var search_title = _("%s search").format(title);
875                             $(this).html( '<input type="text" placeholder="%s" style="width: 100%" />'.format(search_title) );
876                         }
877                     }
878
879                     $( input_type, this ).on( 'keyup change', function () {
880                         if ( table_dt.column(i).search() !== this.value ) {
881                             if ( input_type == "input" ) {
882                                 table_dt
883                                     .column(i)
884                                     .search( this.value )
885                                     .draw();
886                             } else {
887                                 table_dt
888                                     .column(i)
889                                     .search( this.value.length ? '^'+this.value+'$' : '', true, false )
890                                     .draw();
891                             }
892                         }
893                     } );
894                 } else {
895                     $(this).html('');
896                 }
897             } );
898         }
899
900         table.DataTable().on("column-visibility.dt", function(){
901             if( typeof columnsInit == 'function' ){
902                 // This function can be created separately and used to trigger
903                 // an event after the DataTable has loaded AND column visibility
904                 // has been updated according to the table's configuration
905                 columnsInit();
906             }
907         }).columns( hidden_ids ).visible( false );
908
909         return table;
910     };
911
912 })(jQuery);