Bug 21819: (QA follow-up) Replace onchange() in touched code
[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"ilpfB>tr<"bottom pager"ip>',
35     "buttons": [],
36     "aLengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, window.MSG_DT_ALL || "All"]],
37     "iDisplayLength": 20
38 };
39
40
41 // Return an array of string containing the values of a particular column
42 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
43     // check that we have a column id
44     if ( typeof iColumn == "undefined" ) return new Array();
45     // by default we only wany unique data
46     if ( typeof bUnique == "undefined" ) bUnique = true;
47     // by default we do want to only look at filtered data
48     if ( typeof bFiltered == "undefined" ) bFiltered = true;
49     // by default we do not wany to include empty values
50     if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
51     // list of rows which we're going to loop through
52     var aiRows;
53     // use only filtered rows
54     if (bFiltered == true) aiRows = oSettings.aiDisplay;
55     // use all rows
56     else aiRows = oSettings.aiDisplayMaster; // all row numbers
57
58     // set up data array
59     var asResultData = new Array();
60     for (var i=0,c=aiRows.length; i<c; i++) {
61         iRow = aiRows[i];
62         var aData = this.fnGetData(iRow);
63         var sValue = aData[iColumn];
64         // ignore empty values?
65         if (bIgnoreEmpty == true && sValue.length == 0) continue;
66         // ignore unique values?
67         else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
68         // else push the value onto the result data array
69         else asResultData.push(sValue);
70     }
71     return asResultData;
72 }
73
74 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
75 // These keys must not launch filtering
76 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
77
78 // Set a filtering delay for global search field
79 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
80     /*
81      * Inputs:      object:oSettings - dataTables settings object - automatically given
82      *              integer:iDelay - delay in milliseconds
83      * Usage:       $('#example').dataTable().fnSetFilteringDelay(250);
84      * Author:      Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
85      * License:     GPL v2 or BSD 3 point style
86      * Contact:     zygimantas.berziunas /AT\ hotmail.com
87      */
88     var
89         _that = this,
90         iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
91
92     this.each( function ( i ) {
93         $.fn.dataTableExt.iApiIndex = i;
94         var
95             $this = this,
96             oTimerId = null,
97             sPreviousSearch = null,
98             anControl = $( 'input', _that.fnSettings().aanFeatures.f );
99
100         anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
101             var $$this = $this;
102             if (blacklist_keys.indexOf(event.keyCode) != -1) {
103                 return this;
104             }else if ( event.keyCode == '13' ) {
105                 $.fn.dataTableExt.iApiIndex = i;
106                 _that.fnFilter( $(this).val() );
107             } else {
108                 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
109                     window.clearTimeout(oTimerId);
110                     sPreviousSearch = anControl.val();
111                     oTimerId = window.setTimeout(function() {
112                         $.fn.dataTableExt.iApiIndex = i;
113                         _that.fnFilter( anControl.val() );
114                     }, iDelay);
115                 }
116             }
117         });
118
119         return this;
120     } );
121     return this;
122 }
123
124 // Add a filtering delay on general search and on all input (with a class 'filter')
125 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
126     var table = this;
127     this.fnSetFilteringDelay(iDelay);
128     var filterTimerId = null;
129     $(table).find("input."+sClass).keyup(function(event) {
130       if (blacklist_keys.indexOf(event.keyCode) != -1) {
131         return this;
132       }else if ( event.keyCode == '13' ) {
133         table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
134       } else {
135         window.clearTimeout(filterTimerId);
136         var input = this;
137         filterTimerId = window.setTimeout(function() {
138           table.fnFilter($(input).val(), $(input).attr('data-column_num'));
139         }, iDelay);
140       }
141     });
142     $(table).find("select."+sClass).on('change', function() {
143         table.fnFilter($(this).val(), $(this).attr('data-column_num'));
144     });
145 }
146
147 // Sorting on html contains
148 // <a href="foo.pl">bar</a> sort on 'bar'
149 function dt_overwrite_html_sorting_localeCompare() {
150     jQuery.fn.dataTableExt.oSort['html-asc']  = function(a,b) {
151         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
152         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
153         if (typeof(a.localeCompare == "function")) {
154            return a.localeCompare(b);
155         } else {
156            return (a > b) ? 1 : ((a < b) ? -1 : 0);
157         }
158     };
159
160     jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
161         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
162         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
163         if(typeof(b.localeCompare == "function")) {
164             return b.localeCompare(a);
165         } else {
166             return (b > a) ? 1 : ((b < a) ? -1 : 0);
167         }
168     };
169
170     jQuery.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
171         var x = a.replace( /<.*?>/g, "" );
172         var y = b.replace( /<.*?>/g, "" );
173         x = parseFloat( x );
174         y = parseFloat( y );
175         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
176     };
177
178     jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
179         var x = a.replace( /<.*?>/g, "" );
180         var y = b.replace( /<.*?>/g, "" );
181         x = parseFloat( x );
182         y = parseFloat( y );
183         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
184     };
185 }
186
187 $.fn.dataTableExt.oPagination.four_button = {
188     /*
189      * Function: oPagination.four_button.fnInit
190      * Purpose:  Initalise dom elements required for pagination with a list of the pages
191      * Returns:  -
192      * Inputs:   object:oSettings - dataTables settings object
193      *           node:nPaging - the DIV which contains this pagination control
194      *           function:fnCallbackDraw - draw function which must be called on update
195      */
196     "fnInit": function ( oSettings, nPaging, fnCallbackDraw )
197     {
198         nFirst = document.createElement( 'span' );
199         nPrevious = document.createElement( 'span' );
200         nNext = document.createElement( 'span' );
201         nLast = document.createElement( 'span' );
202
203         nFirst.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sFirst ) );
204         nPrevious.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sPrevious ) );
205         nNext.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sNext ) );
206         nLast.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sLast ) );
207
208         nFirst.className = "paginate_button first";
209         nPrevious.className = "paginate_button previous";
210         nNext.className="paginate_button next";
211         nLast.className = "paginate_button last";
212
213         nPaging.appendChild( nFirst );
214         nPaging.appendChild( nPrevious );
215         nPaging.appendChild( nNext );
216         nPaging.appendChild( nLast );
217
218         $(nFirst).click( function () {
219             oSettings.oApi._fnPageChange( oSettings, "first" );
220             fnCallbackDraw( oSettings );
221         } );
222
223         $(nPrevious).click( function() {
224             oSettings.oApi._fnPageChange( oSettings, "previous" );
225             fnCallbackDraw( oSettings );
226         } );
227
228         $(nNext).click( function() {
229             oSettings.oApi._fnPageChange( oSettings, "next" );
230             fnCallbackDraw( oSettings );
231         } );
232
233         $(nLast).click( function() {
234             oSettings.oApi._fnPageChange( oSettings, "last" );
235             fnCallbackDraw( oSettings );
236         } );
237
238         /* Disallow text selection */
239         $(nFirst).bind( 'selectstart', function () { return false; } );
240         $(nPrevious).bind( 'selectstart', function () { return false; } );
241         $(nNext).bind( 'selectstart', function () { return false; } );
242         $(nLast).bind( 'selectstart', function () { return false; } );
243     },
244
245     /*
246      * Function: oPagination.four_button.fnUpdate
247      * Purpose:  Update the list of page buttons shows
248      * Returns:  -
249      * Inputs:   object:oSettings - dataTables settings object
250      *           function:fnCallbackDraw - draw function which must be called on update
251      */
252     "fnUpdate": function ( oSettings, fnCallbackDraw )
253     {
254         if ( !oSettings.aanFeatures.p )
255         {
256             return;
257         }
258
259         /* Loop over each instance of the pager */
260         var an = oSettings.aanFeatures.p;
261         for ( var i=0, iLen=an.length ; i<iLen ; i++ )
262         {
263             var buttons = an[i].getElementsByTagName('span');
264             if ( oSettings._iDisplayStart === 0 )
265             {
266                 buttons[0].className = "paginate_disabled_first";
267                 buttons[1].className = "paginate_disabled_previous";
268             }
269             else
270             {
271                 buttons[0].className = "paginate_enabled_first";
272                 buttons[1].className = "paginate_enabled_previous";
273             }
274
275             if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() )
276             {
277                 buttons[2].className = "paginate_disabled_next";
278                 buttons[3].className = "paginate_disabled_last";
279             }
280             else
281             {
282                 buttons[2].className = "paginate_enabled_next";
283                 buttons[3].className = "paginate_enabled_last";
284             }
285         }
286     }
287 };
288
289 $.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
290     var x = a.replace( /<.*?>/g, "" );
291     var y = b.replace( /<.*?>/g, "" );
292     x = parseFloat( x );
293     y = parseFloat( y );
294     return ((x < y) ? -1 : ((x > y) ?  1 : 0));
295 };
296
297 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
298     var x = a.replace( /<.*?>/g, "" );
299     var y = b.replace( /<.*?>/g, "" );
300     x = parseFloat( x );
301     y = parseFloat( y );
302     return ((x < y) ?  1 : ((x > y) ? -1 : 0));
303 };
304
305 (function() {
306
307 /*
308  * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
309  * Author: Jim Palmer (based on chunking idea from Dave Koelle)
310  * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
311  * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
312  */
313 function naturalSort (a, b) {
314     var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
315         sre = /(^[ ]*|[ ]*$)/g,
316         dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
317         hre = /^0x[0-9a-f]+$/i,
318         ore = /^0/,
319         // convert all to strings and trim()
320         x = a.toString().replace(sre, '') || '',
321         y = b.toString().replace(sre, '') || '',
322         // chunk/tokenize
323         xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
324         yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
325         // numeric, hex or date detection
326         xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
327         yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
328     // first try and sort Hex codes or Dates
329     if (yD)
330         if ( xD < yD ) return -1;
331         else if ( xD > yD )  return 1;
332     // natural sorting through split numeric strings and default strings
333     for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
334         // find floats not starting with '0', string or 0 if not defined (Clint Priest)
335         var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
336         var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
337         // handle numeric vs string comparison - number < string - (Kyle Adams)
338         if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
339         // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
340         else if (typeof oFxNcL !== typeof oFyNcL) {
341             oFxNcL += '';
342             oFyNcL += '';
343         }
344         if (oFxNcL < oFyNcL) return -1;
345         if (oFxNcL > oFyNcL) return 1;
346     }
347     return 0;
348 }
349
350 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
351     "natural-asc": function ( a, b ) {
352         return naturalSort(a,b);
353     },
354
355     "natural-desc": function ( a, b ) {
356         return naturalSort(a,b) * -1;
357     }
358 } );
359
360 }());
361
362 /* Plugin to allow sorting on data stored in a span's title attribute
363  *
364  * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
365  *
366  * In DataTables config:
367  *     "aoColumns": [
368  *        { "sType": "title-string" },
369  *      ]
370  * http://datatables.net/plug-ins/sorting#hidden_title_string
371  */
372 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
373     "title-string-pre": function ( a ) {
374         var m = a.match(/title="(.*?)"/);
375         if ( null !== m && m.length ) {
376             return m[1].toLowerCase();
377         }
378         return "";
379     },
380
381     "title-string-asc": function ( a, b ) {
382         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
383     },
384
385     "title-string-desc": function ( a, b ) {
386         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
387     }
388 } );
389
390 /* Plugin to allow sorting on numeric data stored in a span's title attribute
391  *
392  * Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
393  *              [% formatted currency %]
394  *     </span></td>
395  *
396  * In DataTables config:
397  *     "aoColumns": [
398  *        { "sType": "title-numeric" },
399  *      ]
400  * http://datatables.net/plug-ins/sorting#hidden_title
401  */
402 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
403     "title-numeric-pre": function ( a ) {
404         var x = a.match(/title="*(-?[0-9\.]+)/)[1];
405         return parseFloat( x );
406     },
407
408     "title-numeric-asc": function ( a, b ) {
409         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
410     },
411
412     "title-numeric-desc": function ( a, b ) {
413         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
414     }
415 } );
416
417 (function() {
418
419     /* Plugin to allow text sorting to ignore articles
420      *
421      * In DataTables config:
422      *     "aoColumns": [
423      *        { "sType": "anti-the" },
424      *      ]
425      * Based on the plugin found here:
426      * http://datatables.net/plug-ins/sorting#anti_the
427      * Modified to exclude HTML tags from sorting
428      * Extended to accept a string of space-separated articles
429      * from a configuration file (in English, "a," "an," and "the")
430      */
431
432     if(CONFIG_EXCLUDE_ARTICLES_FROM_SORT){
433         var articles = CONFIG_EXCLUDE_ARTICLES_FROM_SORT.split(" ");
434         var rpattern = "";
435         for(i=0;i<articles.length;i++){
436             rpattern += "^" + articles[i] + " ";
437             if(i < articles.length - 1){ rpattern += "|"; }
438         }
439         var re = new RegExp(rpattern, "i");
440     }
441
442     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
443         "anti-the-pre": function ( a ) {
444             var x = String(a).replace( /<[\s\S]*?>/g, "" );
445             var y = x.trim();
446             var z = y.replace(re, "").toLowerCase();
447             return z;
448         },
449
450         "anti-the-asc": function ( a, b ) {
451             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
452         },
453
454         "anti-the-desc": function ( a, b ) {
455             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
456         }
457     });
458
459 }());
460
461 // Remove string between NSB NSB characters
462 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
463     var pattern = new RegExp("\x88.*\x89");
464     a = a.replace(pattern, "");
465     b = b.replace(pattern, "");
466     return (a > b) ? 1 : ((a < b) ? -1 : 0);
467 }
468 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
469     var pattern = new RegExp("\x88.*\x89");
470     a = a.replace(pattern, "");
471     b = b.replace(pattern, "");
472     return (b > a) ? 1 : ((b < a) ? -1 : 0);
473 }
474
475 /* Define two custom functions (asc and desc) for basket callnumber sorting */
476 jQuery.fn.dataTableExt.oSort['callnumbers-asc']  = function(x,y) {
477         var x_array = x.split("<div>");
478         var y_array = y.split("<div>");
479
480         /* Pop the first elements, they are empty strings */
481         x_array.shift();
482         y_array.shift();
483
484         x_array = jQuery.map( x_array, function( a ) {
485             return parse_callnumber( a );
486         });
487         y_array = jQuery.map( y_array, function( a ) {
488             return parse_callnumber( a );
489         });
490
491         x_array.sort();
492         y_array.sort();
493
494         x = x_array.shift();
495         y = y_array.shift();
496
497         if ( !x ) { x = ""; }
498         if ( !y ) { y = ""; }
499
500         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
501 };
502
503 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
504         var x_array = x.split("<div>");
505         var y_array = y.split("<div>");
506
507         /* Pop the first elements, they are empty strings */
508         x_array.shift();
509         y_array.shift();
510
511         x_array = jQuery.map( x_array, function( a ) {
512             return parse_callnumber( a );
513         });
514         y_array = jQuery.map( y_array, function( a ) {
515             return parse_callnumber( a );
516         });
517
518         x_array.sort();
519         y_array.sort();
520
521         x = x_array.pop();
522         y = y_array.pop();
523
524         if ( !x ) { x = ""; }
525         if ( !y ) { y = ""; }
526
527         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
528 };
529
530 function parse_callnumber ( html ) {
531     var array = html.split('<span class="callnumber">');
532     if ( array[1] ) {
533         array = array[1].split('</span>');
534         return array[0];
535     } else {
536         return "";
537     }
538 }
539
540 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
541 function footer_column_sum( api, column_numbers ) {
542     // Remove the formatting to get integer data for summation
543     var intVal = function ( i ) {
544         if ( typeof i === 'number' ) {
545             if ( isNaN(i) ) return 0;
546             return i;
547         } else if ( typeof i === 'string' ) {
548             var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
549             if ( isNaN(value) ) return 0;
550             return value;
551         }
552         return 0;
553     };
554
555
556     for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
557         var column_number = column_numbers[indice];
558
559         var total = 0;
560         var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
561         $(cells).each(function(){
562             total += intVal( $(this).html() );
563         });
564         total /= 100; // Hard-coded decimal precision
565
566         // Update footer
567         $( api.column( column_number ).footer() ).html(total.format_price());
568     };
569 }