Bug 23013: Upgrade DataTables in the staff client
[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 // MSG_DT_* variables comes from datatables.inc
4 // To use it, write:
5 //  $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
6 //      // other settings
7 //  } ) );
8 var dataTablesDefaults = {
9     "oLanguage": {
10         "oPaginate": {
11             "sFirst"    : window.MSG_DT_FIRST || "First",
12             "sLast"     : window.MSG_DT_LAST || "Last",
13             "sNext"     : window.MSG_DT_NEXT || "Next",
14             "sPrevious" : window.MSG_DT_PREVIOUS || "Previous"
15         },
16         "sEmptyTable"       : window.MSG_DT_EMPTY_TABLE || "No data available in table",
17         "sInfo"             : window.MSG_DT_INFO || "Showing _START_ to _END_ of _TOTAL_ entries",
18         "sInfoEmpty"        : window.MSG_DT_INFO_EMPTY || "No entries to show",
19         "sInfoFiltered"     : window.MSG_DT_INFO_FILTERED || "(filtered from _MAX_ total entries)",
20         "sLengthMenu"       : window.MSG_DT_LENGTH_MENU || "Show _MENU_ entries",
21         "sLoadingRecords"   : window.MSG_DT_LOADING_RECORDS || "Loading...",
22         "sProcessing"       : window.MSG_DT_PROCESSING || "Processing...",
23         "sSearch"           : window.MSG_DT_SEARCH || "Search:",
24         "sZeroRecords"      : window.MSG_DT_ZERO_RECORDS || "No matching records found",
25         buttons: {
26             "copyTitle"     : window.MSG_DT_COPY_TITLE || "Copy to clipboard",
27             "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.",
28             "copySuccess": {
29                 _: window.MSG_DT_COPY_SUCCESS_X || "Copied %d rows to clipboard",
30                 1: window.MSG_DT_COPY_SUCCESS_ONE || "Copied one row to clipboard"
31             }
32         }
33     },
34     "dom": '<"top pager"<"table_entries"ilp><"table_controls"fB>>tr<"bottom pager"ip>',
35     "buttons": [{
36         fade: 100,
37         className: "dt_button_clear_filter",
38         titleAttr: MSG_CLEAR_FILTER,
39         enabled: false,
40         text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + 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     "aLengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, window.MSG_DT_ALL || "All"]],
53     "iDisplayLength": 20,
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 /* Plugin to allow sorting on numeric data stored in a span's title attribute
318  *
319  * Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
320  *              [% formatted currency %]
321  *     </span></td>
322  *
323  * In DataTables config:
324  *     "aoColumns": [
325  *        { "sType": "title-numeric" },
326  *      ]
327  * http://datatables.net/plug-ins/sorting#hidden_title
328  */
329 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
330     "title-numeric-pre": function ( a ) {
331         var x = a.match(/title="*(-?[0-9\.]+)/)[1];
332         return parseFloat( x );
333     },
334
335     "title-numeric-asc": function ( a, b ) {
336         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
337     },
338
339     "title-numeric-desc": function ( a, b ) {
340         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
341     }
342 } );
343
344 (function() {
345
346     /* Plugin to allow text sorting to ignore articles
347      *
348      * In DataTables config:
349      *     "aoColumns": [
350      *        { "sType": "anti-the" },
351      *      ]
352      * Based on the plugin found here:
353      * http://datatables.net/plug-ins/sorting#anti_the
354      * Modified to exclude HTML tags from sorting
355      * Extended to accept a string of space-separated articles
356      * from a configuration file (in English, "a," "an," and "the")
357      */
358
359     if(CONFIG_EXCLUDE_ARTICLES_FROM_SORT){
360         var articles = CONFIG_EXCLUDE_ARTICLES_FROM_SORT.split(" ");
361         var rpattern = "";
362         for(i=0;i<articles.length;i++){
363             rpattern += "^" + articles[i] + " ";
364             if(i < articles.length - 1){ rpattern += "|"; }
365         }
366         var re = new RegExp(rpattern, "i");
367     }
368
369     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
370         "anti-the-pre": function ( a ) {
371             var x = String(a).replace( /<[\s\S]*?>/g, "" );
372             var y = x.trim();
373             var z = y.replace(re, "").toLowerCase();
374             return z;
375         },
376
377         "anti-the-asc": function ( a, b ) {
378             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
379         },
380
381         "anti-the-desc": function ( a, b ) {
382             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
383         }
384     });
385
386 }());
387
388 // Remove string between NSB NSB characters
389 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
390     var pattern = new RegExp("\x88.*\x89");
391     a = a.replace(pattern, "");
392     b = b.replace(pattern, "");
393     return (a > b) ? 1 : ((a < b) ? -1 : 0);
394 }
395 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
396     var pattern = new RegExp("\x88.*\x89");
397     a = a.replace(pattern, "");
398     b = b.replace(pattern, "");
399     return (b > a) ? 1 : ((b < a) ? -1 : 0);
400 }
401
402 /* Define two custom functions (asc and desc) for basket callnumber sorting */
403 jQuery.fn.dataTableExt.oSort['callnumbers-asc']  = function(x,y) {
404         var x_array = x.split("<div>");
405         var y_array = y.split("<div>");
406
407         /* Pop the first elements, they are empty strings */
408         x_array.shift();
409         y_array.shift();
410
411         x_array = jQuery.map( x_array, function( a ) {
412             return parse_callnumber( a );
413         });
414         y_array = jQuery.map( y_array, function( a ) {
415             return parse_callnumber( a );
416         });
417
418         x_array.sort();
419         y_array.sort();
420
421         x = x_array.shift();
422         y = y_array.shift();
423
424         if ( !x ) { x = ""; }
425         if ( !y ) { y = ""; }
426
427         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
428 };
429
430 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
431         var x_array = x.split("<div>");
432         var y_array = y.split("<div>");
433
434         /* Pop the first elements, they are empty strings */
435         x_array.shift();
436         y_array.shift();
437
438         x_array = jQuery.map( x_array, function( a ) {
439             return parse_callnumber( a );
440         });
441         y_array = jQuery.map( y_array, function( a ) {
442             return parse_callnumber( a );
443         });
444
445         x_array.sort();
446         y_array.sort();
447
448         x = x_array.pop();
449         y = y_array.pop();
450
451         if ( !x ) { x = ""; }
452         if ( !y ) { y = ""; }
453
454         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
455 };
456
457 function parse_callnumber ( html ) {
458     var array = html.split('<span class="callnumber">');
459     if ( array[1] ) {
460         array = array[1].split('</span>');
461         return array[0];
462     } else {
463         return "";
464     }
465 }
466
467 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
468 function footer_column_sum( api, column_numbers ) {
469     // Remove the formatting to get integer data for summation
470     var intVal = function ( i ) {
471         if ( typeof i === 'number' ) {
472             if ( isNaN(i) ) return 0;
473             return i;
474         } else if ( typeof i === 'string' ) {
475             var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
476             if ( isNaN(value) ) return 0;
477             return value;
478         }
479         return 0;
480     };
481
482
483     for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
484         var column_number = column_numbers[indice];
485
486         var total = 0;
487         var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
488         $(cells).each(function(){
489             total += intVal( $(this).html() );
490         });
491         total /= 100; // Hard-coded decimal precision
492
493         // Update footer
494         $( api.column( column_number ).footer() ).html(total.format_price());
495     };
496 }
497
498 function filterDataTable( table, column, term ){
499     if( column ){
500         table.column( column ).search( term ).draw("page");
501     } else {
502         table.search( term ).draw("page");
503     }
504 }