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