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