Bug 12556: Remove unused HTML
[koha.git] / koha-tmpl / opac-tmpl / bootstrap / 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"    : window.MSG_DT_FIRST || "First",
11             "last"     : window.MSG_DT_LAST || "Last",
12             "next"     : window.MSG_DT_NEXT || "Next",
13             "previous" : window.MSG_DT_PREVIOUS || "Previous"
14         },
15         "emptyTable"       : window.MSG_DT_EMPTY_TABLE || "No data available in table",
16         "info"             : window.MSG_DT_INFO || "Showing _START_ to _END_ of _TOTAL_ entries",
17         "infoEmpty"        : window.MSG_DT_INFO_EMPTY || "No entries to show",
18         "infoFiltered"     : window.MSG_DT_INFO_FILTERED || "(filtered from _MAX_ total entries)",
19         "lengthMenu"       : window.MSG_DT_LENGTH_MENU || "Show _MENU_ entries",
20         "loadingRecords"   : window.MSG_DT_LOADING_RECORDS || "Loading...",
21         "processing"       : window.MSG_DT_PROCESSING || "Processing...",
22         "search"           : window.MSG_DT_SEARCH || "Search:",
23         "zeroRecords"      : window.MSG_DT_ZERO_RECORDS || "No matching records found",
24         buttons: {
25             "copyTitle"     : window.MSG_DT_COPY_TO_CLIPBOARD || "Copy to clipboard",
26             "copyKeys"      : window.MSG_DT_COPY_KEYS || "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                 _: window.MSG_DT_COPIED_ROWS || "Copied %d rows to clipboard",
29                 1: window.MSG_DT_COPIED_ONE_ROW || "Copied one row to clipboard",
30             }
31         }
32     },
33     "dom": 't',
34     "paginate": false,
35     "buttons": [{
36         fade: 100,
37         className: "dt_button_clear_filter",
38         titleAttr: window.MSG_CLEAR_FILTER,
39         enabled: false,
40         text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + window.MSG_CLEAR_FILTER + '</span>',
41         available: function ( dt ) {
42             // The "clear filter" button is made available if this test returns true
43             if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
44                 return true;
45             }
46         },
47         action: function ( e, dt, node ) {
48             dt.search( "" ).draw("page");
49             node.addClass("disabled");
50         }
51     }],
52     initComplete: function( settings) {
53         var tableId = settings.nTable.id
54         // When the DataTables search function is triggered,
55         // enable or disable the "Clear filter" button based on
56         // the presence of a search string
57         $("#" + tableId ).on( 'search.dt', function ( e, settings ) {
58             if( settings.oPreviousSearch.sSearch == "" ){
59                 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
60             } else {
61                 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
62             }
63         });
64     }
65 };
66
67
68 // Return an array of string containing the values of a particular column
69 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
70     // check that we have a column id
71     if ( typeof iColumn == "undefined" ) return new Array();
72     // by default we only wany unique data
73     if ( typeof bUnique == "undefined" ) bUnique = true;
74     // by default we do want to only look at filtered data
75     if ( typeof bFiltered == "undefined" ) bFiltered = true;
76     // by default we do not wany to include empty values
77     if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
78     // list of rows which we're going to loop through
79     var aiRows;
80     // use only filtered rows
81     if (bFiltered == true) aiRows = oSettings.aiDisplay;
82     // use all rows
83     else aiRows = oSettings.aiDisplayMaster; // all row numbers
84
85     // set up data array
86     var asResultData = new Array();
87     for (var i=0,c=aiRows.length; i<c; i++) {
88         iRow = aiRows[i];
89         var aData = this.fnGetData(iRow);
90         var sValue = aData[iColumn];
91         // ignore empty values?
92         if (bIgnoreEmpty == true && sValue.length == 0) continue;
93         // ignore unique values?
94         else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
95         // else push the value onto the result data array
96         else asResultData.push(sValue);
97     }
98     return asResultData;
99 }
100
101 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
102 // These keys must not launch filtering
103 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
104
105 // Set a filtering delay for global search field
106 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
107     /*
108      * Inputs:      object:oSettings - dataTables settings object - automatically given
109      *              integer:iDelay - delay in milliseconds
110      * Usage:       $('#example').dataTable().fnSetFilteringDelay(250);
111      * Author:      Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
112      * License:     GPL v2 or BSD 3 point style
113      * Contact:     zygimantas.berziunas /AT\ hotmail.com
114      */
115     var
116         _that = this,
117         iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
118
119     this.each( function ( i ) {
120         $.fn.dataTableExt.iApiIndex = i;
121         var
122             $this = this,
123             oTimerId = null,
124             sPreviousSearch = null,
125             anControl = $( 'input', _that.fnSettings().aanFeatures.f );
126
127         anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
128             var $$this = $this;
129             if (blacklist_keys.indexOf(event.keyCode) != -1) {
130                 return this;
131             }else if ( event.keyCode == '13' ) {
132                 $.fn.dataTableExt.iApiIndex = i;
133                 _that.fnFilter( $(this).val() );
134             } else {
135                 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
136                     window.clearTimeout(oTimerId);
137                     sPreviousSearch = anControl.val();
138                     oTimerId = window.setTimeout(function() {
139                         $.fn.dataTableExt.iApiIndex = i;
140                         _that.fnFilter( anControl.val() );
141                     }, iDelay);
142                 }
143             }
144         });
145
146         return this;
147     } );
148     return this;
149 }
150
151 // Add a filtering delay on general search and on all input (with a class 'filter')
152 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
153     var table = this;
154     this.fnSetFilteringDelay(iDelay);
155     var filterTimerId = null;
156     $(table).find("input."+sClass).keyup(function(event) {
157       if (blacklist_keys.indexOf(event.keyCode) != -1) {
158         return this;
159       }else if ( event.keyCode == '13' ) {
160         table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
161       } else {
162         window.clearTimeout(filterTimerId);
163         var input = this;
164         filterTimerId = window.setTimeout(function() {
165           table.fnFilter($(input).val(), $(input).attr('data-column_num'));
166         }, iDelay);
167       }
168     });
169     $(table).find("select."+sClass).on('change', function() {
170         table.fnFilter($(this).val(), $(this).attr('data-column_num'));
171     });
172 }
173
174 // Sorting on html contains
175 // <a href="foo.pl">bar</a> sort on 'bar'
176 function dt_overwrite_html_sorting_localeCompare() {
177     jQuery.fn.dataTableExt.oSort['html-asc']  = function(a,b) {
178         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
179         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
180         if (typeof(a.localeCompare == "function")) {
181            return a.localeCompare(b);
182         } else {
183            return (a > b) ? 1 : ((a < b) ? -1 : 0);
184         }
185     };
186
187     jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
188         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
189         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
190         if(typeof(b.localeCompare == "function")) {
191             return b.localeCompare(a);
192         } else {
193             return (b > a) ? 1 : ((b < a) ? -1 : 0);
194         }
195     };
196
197     jQuery.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
198         var x = a.replace( /<.*?>/g, "" );
199         var y = b.replace( /<.*?>/g, "" );
200         x = parseFloat( x );
201         y = parseFloat( y );
202         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
203     };
204
205     jQuery.fn.dataTableExt.oSort['num-html-desc'] = 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
214 $.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
215     var x = a.replace( /<.*?>/g, "" );
216     var y = b.replace( /<.*?>/g, "" );
217     x = parseFloat( x );
218     y = parseFloat( y );
219     return ((x < y) ? -1 : ((x > y) ?  1 : 0));
220 };
221
222 $.fn.dataTableExt.oSort['num-html-desc'] = 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 (function() {
231
232 /*
233  * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
234  * Author: Jim Palmer (based on chunking idea from Dave Koelle)
235  * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
236  * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
237  */
238 function naturalSort (a, b) {
239     var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
240         sre = /(^[ ]*|[ ]*$)/g,
241         dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
242         hre = /^0x[0-9a-f]+$/i,
243         ore = /^0/,
244         // convert all to strings and trim()
245         x = a.toString().replace(sre, '') || '',
246         y = b.toString().replace(sre, '') || '',
247         // chunk/tokenize
248         xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
249         yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
250         // numeric, hex or date detection
251         xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
252         yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
253     // first try and sort Hex codes or Dates
254     if (yD)
255         if ( xD < yD ) return -1;
256         else if ( xD > yD )  return 1;
257     // natural sorting through split numeric strings and default strings
258     for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
259         // find floats not starting with '0', string or 0 if not defined (Clint Priest)
260         var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
261         var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
262         // handle numeric vs string comparison - number < string - (Kyle Adams)
263         if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
264         // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
265         else if (typeof oFxNcL !== typeof oFyNcL) {
266             oFxNcL += '';
267             oFyNcL += '';
268         }
269         if (oFxNcL < oFyNcL) return -1;
270         if (oFxNcL > oFyNcL) return 1;
271     }
272     return 0;
273 }
274
275 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
276     "natural-asc": function ( a, b ) {
277         return naturalSort(a,b);
278     },
279
280     "natural-desc": function ( a, b ) {
281         return naturalSort(a,b) * -1;
282     }
283 } );
284
285 }());
286
287 /* Plugin to allow sorting on data stored in a span's title attribute
288  *
289  * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
290  *
291  * In DataTables config:
292  *     "aoColumns": [
293  *        { "sType": "title-string" },
294  *      ]
295  * http://datatables.net/plug-ins/sorting#hidden_title_string
296  */
297 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
298     "title-string-pre": function ( a ) {
299         var m = a.match(/title="(.*?)"/);
300         if ( null !== m && m.length ) {
301             return m[1].toLowerCase();
302         }
303         return "";
304     },
305
306     "title-string-asc": function ( a, b ) {
307         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
308     },
309
310     "title-string-desc": function ( a, b ) {
311         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
312     }
313 } );
314
315 /* Plugin to allow sorting on numeric data stored in a span's title attribute
316  *
317  * Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
318  *              [% formatted currency %]
319  *     </span></td>
320  *
321  * In DataTables config:
322  *     "aoColumns": [
323  *        { "sType": "title-numeric" },
324  *      ]
325  * http://datatables.net/plug-ins/sorting#hidden_title
326  */
327 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
328     "title-numeric-pre": function ( a ) {
329         var x = a.match(/title="*(-?[0-9\.]+)/)[1];
330         return parseFloat( x );
331     },
332
333     "title-numeric-asc": function ( a, b ) {
334         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
335     },
336
337     "title-numeric-desc": function ( a, b ) {
338         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
339     }
340 } );
341
342 (function() {
343
344     /* Plugin to allow text sorting to ignore articles
345      *
346      * In DataTables config:
347      *     "aoColumns": [
348      *        { "sType": "anti-the" },
349      *      ]
350      * Based on the plugin found here:
351      * http://datatables.net/plug-ins/sorting#anti_the
352      * Modified to exclude HTML tags from sorting
353      * Extended to accept a string of space-separated articles
354      * from a configuration file (in English, "a," "an," and "the")
355      */
356
357     var config_exclude_articles_from_sort = window.CONFIG_EXCLUDE_ARTICLES_FROM_SORT || "a an the";
358     if (config_exclude_articles_from_sort){
359         var articles = config_exclude_articles_from_sort.split(" ");
360         var rpattern = "";
361         for(i=0;i<articles.length;i++){
362             rpattern += "^" + articles[i] + " ";
363             if(i < articles.length - 1){ rpattern += "|"; }
364         }
365         var re = new RegExp(rpattern, "i");
366     }
367
368     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
369         "anti-the-pre": function ( a ) {
370             var x = String(a).replace( /<[\s\S]*?>/g, "" );
371             var y = x.trim();
372             var z = y.replace(re, "").toLowerCase();
373             return z;
374         },
375
376         "anti-the-asc": function ( a, b ) {
377             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
378         },
379
380         "anti-the-desc": function ( a, b ) {
381             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
382         }
383     });
384
385 }());
386
387 // Remove string between NSB NSB characters
388 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
389     var pattern = new RegExp("\x88.*\x89");
390     a = a.replace(pattern, "");
391     b = b.replace(pattern, "");
392     return (a > b) ? 1 : ((a < b) ? -1 : 0);
393 }
394 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
395     var pattern = new RegExp("\x88.*\x89");
396     a = a.replace(pattern, "");
397     b = b.replace(pattern, "");
398     return (b > a) ? 1 : ((b < a) ? -1 : 0);
399 }
400
401 /* Define two custom functions (asc and desc) for basket callnumber sorting */
402 jQuery.fn.dataTableExt.oSort['callnumbers-asc']  = function(x,y) {
403         var x_array = x.split("<div>");
404         var y_array = y.split("<div>");
405
406         /* Pop the first elements, they are empty strings */
407         x_array.shift();
408         y_array.shift();
409
410         x_array = jQuery.map( x_array, function( a ) {
411             return parse_callnumber( a );
412         });
413         y_array = jQuery.map( y_array, function( a ) {
414             return parse_callnumber( a );
415         });
416
417         x_array.sort();
418         y_array.sort();
419
420         x = x_array.shift();
421         y = y_array.shift();
422
423         if ( !x ) { x = ""; }
424         if ( !y ) { y = ""; }
425
426         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
427 };
428
429 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
430         var x_array = x.split("<div>");
431         var y_array = y.split("<div>");
432
433         /* Pop the first elements, they are empty strings */
434         x_array.shift();
435         y_array.shift();
436
437         x_array = jQuery.map( x_array, function( a ) {
438             return parse_callnumber( a );
439         });
440         y_array = jQuery.map( y_array, function( a ) {
441             return parse_callnumber( a );
442         });
443
444         x_array.sort();
445         y_array.sort();
446
447         x = x_array.pop();
448         y = y_array.pop();
449
450         if ( !x ) { x = ""; }
451         if ( !y ) { y = ""; }
452
453         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
454 };
455
456 function parse_callnumber ( html ) {
457     var array = html.split('<span class="callnumber">');
458     if ( array[1] ) {
459         array = array[1].split('</span>');
460         return array[0];
461     } else {
462         return "";
463     }
464 }
465
466 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
467 function footer_column_sum( api, column_numbers ) {
468     // Remove the formatting to get integer data for summation
469     var intVal = function ( i ) {
470         if ( typeof i === 'number' ) {
471             if ( isNaN(i) ) return 0;
472             return i;
473         } else if ( typeof i === 'string' ) {
474             var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
475             if ( isNaN(value) ) return 0;
476             return value;
477         }
478         return 0;
479     };
480
481
482     for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
483         var column_number = column_numbers[indice];
484
485         var total = 0;
486         var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
487         $(cells).each(function(){
488             total += intVal( $(this).html() );
489         });
490         total /= 100; // Hard-coded decimal precision
491
492         // Update footer
493         $( api.column( column_number ).footer() ).html(total.format_price());
494     };
495 }
496
497 function filterDataTable( table, column, term ){
498     if( column ){
499         table.column( column ).search( term ).draw("page");
500     } else {
501         table.search( term ).draw("page");
502     }
503 }
504
505 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
506     console.warn(message);
507 };
508
509 (function($) {
510
511     $.fn.api = function(options, columns_settings, add_filters) {
512         var settings = null;
513         if(options) {
514             if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
515             options.criteria = options.criteria.toLowerCase();
516             settings = $.extend(true, {}, dataTablesDefaults, {
517                         'deferRender': true,
518                         "paging": true,
519                         'serverSide': true,
520                         'searching': true,
521                         'processing': true,
522                         'language': {
523                             'emptyTable': (options.emptyTable) ? options.emptyTable : "No data available in table"
524                         },
525                         'pagingType': 'full',
526                         'ajax': {
527                             'type': 'GET',
528                             'cache': true,
529                             'dataSrc': 'data',
530                             'beforeSend': function(xhr, settings) {
531                                 this._xhr = xhr;
532                                 if(options.embed) {
533                                     xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
534                                 }
535                                 if(options.header_filter && options.query_parameters) {
536                                     xhr.setRequestHeader('x-koha-query', options.query_parameters);
537                                     delete options.query_parameters;
538                                 }
539                             },
540                             'dataFilter': function(data, type) {
541                                 var json = {data: JSON.parse(data)};
542                                 if(total = this._xhr.getResponseHeader('x-total-count')) {
543                                     json.recordsTotal = total;
544                                     json.recordsFiltered = total;
545                                 }
546                                 return JSON.stringify(json);
547                             },
548                             'data': function( data, settings ) {
549                                 var length = data.length;
550                                 var start  = data.start;
551
552                                 var dataSet = {
553                                     _page: Math.floor(start/length) + 1,
554                                     _per_page: length
555                                 };
556
557                                 var filter = data.search.value;
558                                 var query_parameters = settings.aoColumns
559                                 .filter(function(col) {
560                                     return col.bSearchable && typeof col.data == 'string' && (data.columns[col.idx].search.value != '' || filter != '')
561                                 })
562                                 .map(function(col) {
563                                     var part = {};
564                                     var value = data.columns[col.idx].search.value != '' ? data.columns[col.idx].search.value : filter;
565                                     part[!col.data.includes('.')?'me.'+col.data:col.data] = options.criteria === 'exact'?value:{like: (['contains', 'ends_with'].indexOf(options.criteria) !== -1?'%':'')+value+(['contains', 'starts_with'].indexOf(options.criteria) !== -1?'%':'')};
566                                     return part;
567                                 });
568
569                                 if(query_parameters.length) {
570                                     query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:query_parameters);
571                                     if(options.header_filter) {
572                                         options.query_parameters = query_parameters;
573                                     } else {
574                                         dataSet.q = query_parameters;
575                                         delete options.query_parameters;
576                                     }
577                                 } else {
578                                     delete options.query_parameters;
579                                 }
580
581                                 dataSet._match = options.criteria;
582
583                                 if(options.columns) {
584                                     var order = data.order;
585                                     order.forEach(function (e,i) {
586                                         var order_col      = e.column;
587                                         var order_by       = options.columns[order_col].data;
588                                         var order_dir      = e.dir == 'asc' ? '+' : '-';
589                                         dataSet._order_by = order_dir + (!order_by.includes('.')?'me.'+order_by:order_by);
590                                     });
591                                 }
592
593                                 return dataSet;
594                             }
595                         }
596                     }, options);
597         }
598
599         var counter = 0;
600         var hidden_ids = [];
601         var included_ids = [];
602
603         $(columns_settings).each( function() {
604             var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
605             var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
606             if ( used_id == -1 ) return;
607
608             if ( this['is_hidden'] == "1" ) {
609                 hidden_ids.push( used_id );
610             }
611             if ( this['cannot_be_toggled'] == "0" ) {
612                 included_ids.push( used_id );
613             }
614             counter++;
615         });
616
617         var exportColumns = ":visible:not(.noExport)";
618         if( settings.hasOwnProperty("exportColumns") ){
619             // A custom buttons configuration has been passed from the page
620             exportColumns = settings["exportColumns"];
621         }
622
623         var export_format = {
624             body: function ( data, row, column, node ) {
625                 var newnode = $(node);
626
627                 if ( newnode.find(".noExport").length > 0 ) {
628                     newnode = newnode.clone();
629                     newnode.find(".noExport").remove();
630                 }
631
632                 return newnode.text().replace( /\n/g, ' ' ).trim();
633             }
634         }
635
636         var export_buttons = [
637             {
638                 extend: 'excelHtml5',
639                 text: _("Excel"),
640                 exportOptions: {
641                     columns: exportColumns,
642                     format:  export_format
643                 },
644             },
645             {
646                 extend: 'csvHtml5',
647                 text: _("CSV"),
648                 exportOptions: {
649                     columns: exportColumns,
650                     format:  export_format
651                 },
652             },
653             {
654                 extend: 'copyHtml5',
655                 text: _("Copy"),
656                 exportOptions: {
657                     columns: exportColumns,
658                     format:  export_format
659                 },
660             },
661             {
662                 extend: 'print',
663                 text: _("Print"),
664                 exportOptions: {
665                     columns: exportColumns,
666                     format:  export_format
667                 },
668             }
669         ];
670
671         settings[ "buttons" ] = [
672             {
673                 fade: 100,
674                 className: "dt_button_clear_filter",
675                 titleAttr: _("Clear filter"),
676                 enabled: false,
677                 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + _("Clear filter") + '</span>',
678                 action: function ( e, dt, node, config ) {
679                     dt.search( "" ).draw("page");
680                     node.addClass("disabled");
681                 }
682             }
683         ];
684
685         if( included_ids.length > 0 ){
686             settings[ "buttons" ].push(
687                 {
688                     extend: 'colvis',
689                     fade: 100,
690                     columns: included_ids,
691                     className: "columns_controls",
692                     titleAttr: _("Columns settings"),
693                     text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + _("Columns") + '</span>',
694                     exportOptions: {
695                         columns: exportColumns
696                     }
697                 }
698             );
699         }
700
701         settings[ "buttons" ].push(
702             {
703                 extend: 'collection',
704                 autoClose: true,
705                 fade: 100,
706                 className: "export_controls",
707                 titleAttr: _("Export or print"),
708                 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + _("Export") + '</span>',
709                 buttons: export_buttons
710             }
711         );
712
713         if ( add_filters ) {
714             // Duplicate the table header row for columnFilter
715             thead_row = this.find('thead tr');
716             clone = thead_row.clone().addClass('filters_row');
717             clone.find("th.NoSort").html('');
718             thead_row.before(clone);
719         }
720
721         $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
722
723         return $(this).dataTable(settings);
724     };
725
726 })(jQuery);