fixed hazelnut checkbox management
[myslice.git] / plugins / hazelnut / hazelnut.js
1 /**
2  * Description: display a query result in a datatables-powered <table>
3  * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 /*
8  * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
9  * Expression) that maps it to the dollar sign so it can't be overwritten by
10  * another library in the scope of its execution.
11  */
12
13 // TEMP
14 var ELEMENT_KEY = 'resource_hrn';
15
16 (function($){
17
18     var debug=false;
19     debug=true
20
21     // routing calls
22     $.fn.Hazelnut = function( method ) {
23         if ( methods[method] ) {
24             return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
25         } else if ( typeof method === 'object' || ! method ) {
26             return methods.init.apply( this, arguments );
27         } else {
28             $.error( 'Method ' +  method + ' does not exist on jQuery.Hazelnut' );
29         }    
30     };
31
32     /***************************************************************************
33      * Public methods
34      ***************************************************************************/
35
36     var methods = {
37
38         /**
39          * @brief Plugin initialization
40          * @param options : an associative array of setting values
41          * @return : a jQuery collection of objects on which the plugin is
42          *     applied, which allows to maintain chainability of calls
43          */
44         init : function ( options ) {
45
46             /* Default settings */
47             var options = $.extend( {
48                 'checkboxes': false
49             }, options);
50
51             return this.each(function() {
52
53                 var $this = $(this);
54
55                 /* An object that will hold private variables and methods */
56                 var hazelnut = new Hazelnut (options);
57                 $this.data('Hazelnut', hazelnut);
58
59                 /* Events */
60                 $this.on('show.Datatables', methods.show);
61
62                 // This is the new plugin API meant to replace the weird publish_subscribe mechanism
63                 $this.set_query_handler(options.query_uuid, hazelnut.query_handler);
64                 $this.set_record_handler(options.query_uuid, hazelnut.record_handler); 
65                 $this.set_record_handler(options.query_all_uuid, hazelnut.record_handler_all); 
66
67 //                /* Subscriptions */
68 //                var query_channel   = '/query/' + options.query_uuid + '/changed';
69 //                var update_channel  = '/update-set/' + options.query_uuid;
70 //                var results_channel = '/results/' + options.query_uuid + '/changed';
71 //
72 //                // xxx not tested yet
73 //                $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
74 //                // xxx not tested yet
75 //                $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
76 //                // expected to work
77 //                $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
78 //                if (debug)
79 //                    messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
80
81             }); // this.each
82         }, // init
83
84         /**
85          * @brief Plugin destruction
86          * @return : a jQuery collection of objects on which the plugin is
87          *     applied, which allows to maintain chainability of calls
88          */
89         destroy : function( ) {
90
91             return this.each(function() {
92                 var $this = $(this);
93                 var hazelnut = $this.data('Hazelnut');
94
95                 // Unbind all events using namespacing
96                 $(window).unbind('Hazelnut');
97
98                 // Remove associated data
99                 hazelnut.remove();
100                 $this.removeData('Hazelnut');
101             });
102         }, // destroy
103
104         show : function( ) {
105             var $this=$(this);
106             // xxx wtf. why [1] ? would expect 0...
107             if (debug)
108                 messages.debug("Hitting suspicious line in hazelnut.show");
109             var oTable = $($('.dataTable', $this)[1]).dataTable();
110             oTable.fnAdjustColumnSizing()
111         
112             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
113             $(this).each(function(i,elt) {
114                 if (jQuery(elt).hasClass('dataTables')) {
115                     var myDiv=jQuery('#hazelnut-' + this.id).parent();
116                     if(myDiv.height()==0) {
117                         var oTable=$('#hazelnut-' + this.id).dataTable();            
118                         oTable.fnDraw();
119                     }
120                 }
121             });
122         } // show
123
124     }; // var methods;
125
126     /***************************************************************************
127      * Hazelnut object
128      ***************************************************************************/
129
130     function Hazelnut(options) 
131     {
132         /* member variables */
133         this.options = options;
134
135         // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
136         //this.current_query = null;
137         this.current_query=manifold.find_query(this.options.query_uuid);
138         //  if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
139         this.query_update = null;
140         this.current_resources = Array();
141
142         // query status
143         this.received_all = false;
144         this.received_set = false;
145         this.in_set_buffer = Array();
146
147         var object = this;
148
149         /* Transforms the table into DataTable, and keep a pointer to it */
150         actual_options = {
151             // Customize the position of Datatables elements (length,filter,button,...)
152             // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
153             sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
154             sPaginationType: 'bootstrap',
155             // Handle the null values & the error : Datatables warning Requested unknown parameter
156             // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
157             aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
158             // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
159             // sScrollX: '100%',       /* Horizontal scrolling */
160             bProcessing: true,      /* Loading */
161             fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
162         };
163         // the intention here is that options.datatables_options as coming from the python object take precedence
164         //  XXX DISABLED by jordan: was causing errors in datatables.js     $.extend(actual_options, options.datatables_options );
165         this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
166
167         /* Setup the SelectAll button in the dataTable header */
168         /* xxx not sure this is still working */
169         var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
170         oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
171         oSelectAll.button();
172         oSelectAll.css('font-size','11px');
173         oSelectAll.css('float','right');
174         oSelectAll.css('margin-right','15px');
175         oSelectAll.css('margin-bottom','5px');
176         oSelectAll.unbind('click');
177         oSelectAll.click(selectAll);
178
179         /* Add a filtering function to the current table 
180          * Note: we use closure to get access to the 'options'
181          */
182         $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
183             /* No filtering if the table does not match */
184             if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
185                 return true;
186             return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
187         });
188
189         /* methods */
190
191 // DEPRECATED //        this.set_query = function(query) {
192 // DEPRECATED //            messages.info('hazelnut.set_query');
193 // DEPRECATED //            var options = this.options;
194 // DEPRECATED //            /* Compare current and advertised query to get added and removed fields */
195 // DEPRECATED //            previous_query = this.current_query;
196 // DEPRECATED //            /* Save the query as the current query */
197 // DEPRECATED //            this.current_query = query;
198 // DEPRECATED //            if (debug)
199 // DEPRECATED //                messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
200 // DEPRECATED //
201 // DEPRECATED //            /* We check all necessary fields : in column editor I presume XXX */
202 // DEPRECATED //            // XXX ID naming has no plugin_uuid
203 // DEPRECATED //            if (typeof(query.fields) != 'undefined') {        
204 // DEPRECATED //                $.each (query.fields, function(index, value) { 
205 // DEPRECATED //                    if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
206 // DEPRECATED //                        $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
207 // DEPRECATED //                });
208 // DEPRECATED //            }
209 // DEPRECATED //
210 // DEPRECATED //            /* Process updates in filters / current_query must be updated before this call for filtering ! */
211 // DEPRECATED //            this.table.fnDraw();
212 // DEPRECATED //
213 // DEPRECATED //            /*
214 // DEPRECATED //             * Process updates in fields
215 // DEPRECATED //             */
216 // DEPRECATED //            if (typeof(query.fields) != 'undefined') {     
217 // DEPRECATED //                /* DataTable Settings */
218 // DEPRECATED //                var oSettings = this.table.dataTable().fnSettings();
219 // DEPRECATED //                var cols = oSettings.aoColumns;
220 // DEPRECATED //                var colnames = cols.map(function(x) {return x.sTitle});
221 // DEPRECATED //                colnames = $.grep(colnames, function(value) {return value != "+/-";});
222 // DEPRECATED //
223 // DEPRECATED //                if (previous_query == null) {
224 // DEPRECATED //                    var added_fields = query.fields;
225 // DEPRECATED //                    var removed_fields = colnames;            
226 // DEPRECATED //                    removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
227 // DEPRECATED //                } else {
228 // DEPRECATED //                    var tmp = previous_query.diff_fields(query);
229 // DEPRECATED //                    var added_fields = tmp.added;
230 // DEPRECATED //                    var removed_fields = tmp.removed;
231 // DEPRECATED //                }
232 // DEPRECATED //
233 // DEPRECATED //                /* Hide/unhide columns to match added/removed fields */
234 // DEPRECATED //                var object = this;
235 // DEPRECATED //                $.each(added_fields, function (index, field) {            
236 // DEPRECATED //                    var index = object.getColIndex(field,cols);
237 // DEPRECATED //                    if(index != -1)
238 // DEPRECATED //                        object.table.fnSetColumnVis(index, true);
239 // DEPRECATED //                });
240 // DEPRECATED //                $.each(removed_fields, function (index, field) {
241 // DEPRECATED //                    var index = object.getColIndex(field,cols);
242 // DEPRECATED //                    if(index != -1)
243 // DEPRECATED //                        object.table.fnSetColumnVis(index, false);
244 // DEPRECATED //                });            
245 // DEPRECATED //            }
246 // DEPRECATED //        }
247
248 // DEPRECATED //        this.set_resources = function(resources, instance) {
249 // DEPRECATED //            if (debug)
250 // DEPRECATED //                messages.debug("entering hazelnut.set_resources");
251 // DEPRECATED //            var options = this.options;
252 // DEPRECATED //            var previous_resources = this.current_resources;
253 // DEPRECATED //            this.current_resources = resources;
254 // DEPRECATED //    
255 // DEPRECATED //            /* We uncheck all checkboxes ... */
256 // DEPRECATED //            $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
257 // DEPRECATED //            /* ... and check the ones specified in the resource list */
258 // DEPRECATED //            $.each(this.current_resources, function(index, urn) {
259 // DEPRECATED //                $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
260 // DEPRECATED //            });
261 // DEPRECATED //            
262 // DEPRECATED //        }
263
264         /**
265          * @brief Determine index of key in the table columns 
266          * @param key
267          * @param cols
268          */
269         this.getColIndex = function(key, cols) {
270             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
271             return (tabIndex.length > 0) ? tabIndex[0] : -1;
272         }
273     
274 // DEPRECATED //        /**
275 // DEPRECATED //         * @brief
276 // DEPRECATED //         * XXX will be removed/replaced
277 // DEPRECATED //         */
278 // DEPRECATED //        this.selected_changed = function(e, change) {
279 // DEPRECATED //        if (debug) messages.debug("entering hazelnut.selected_changed");
280 // DEPRECATED //            var actions = change.split("/");
281 // DEPRECATED //            if (actions.length > 1) {
282 // DEPRECATED //                var oNodes = this.table.fnGetNodes();
283 // DEPRECATED //                var myNode = $.grep(oNodes, function(value) {
284 // DEPRECATED //                    if (value.id == actions[1]) { return value; }
285 // DEPRECATED //                });                
286 // DEPRECATED //                if( myNode.length>0 ) {
287 // DEPRECATED //                    if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
288 // DEPRECATED //                        checked='';
289 // DEPRECATED //                    else
290 // DEPRECATED //                        checked="checked='checked' ";
291 // DEPRECATED //                    var newValue = this.checkbox(actions[1], 'node', checked, false);
292 // DEPRECATED //                    var columnPos = this.table.fnSettings().aoColumns.length - 1;
293 // DEPRECATED //                    this.table.fnUpdate(newValue, myNode[0], columnPos);
294 // DEPRECATED //                    this.table.fnDraw();
295 // DEPRECATED //                }
296 // DEPRECATED //            }
297 // DEPRECATED //        }
298     
299         this.update_plugin = function(e, rows) {
300             // e.data is what we passed in second argument to subscribe
301             // so here it is the jquery object attached to the plugin <div>
302             var $plugindiv=e.data;
303             if (debug)
304                 messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
305             // clear the spinning wheel: look up an ancestor that has the need-spin class
306             // do this before we might return
307             $plugindiv.closest('.need-spin').spin(false);
308
309             var options = this.options;
310             var hazelnut = this;
311     
312             /* if we get no result, or an error, try to make that clear, and exit */
313             if (rows.length==0) {
314                 if (debug) 
315                     messages.debug("Empty result on hazelnut " + this.options.domid);
316                 var placeholder=$(this.table).find("td.dataTables_empty");
317                 console.log("placeholder "+placeholder);
318                 if (placeholder.length==1) 
319                     placeholder.html(unfold.warning("Empty result"));
320                 else
321                     this.table.html(unfold.warning("Empty result"));
322                     return;
323             } else if (typeof(rows[0].error) != 'undefined') {
324                 // we now should have another means to report errors that this inline/embedded hack
325                 if (debug) 
326                     messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
327                 this.table.html(unfold.error(rows[0].error));
328                 return;
329             }
330
331             /* 
332              * fill the dataTables object
333              * we cannot set html content directly here, need to use fnAddData
334              */
335             var lines = new Array();
336     
337             this.current_resources = Array();
338     
339             $.each(rows, function(index, row) {
340                 // this models a line in dataTables, each element in the line describes a cell
341                 line = new Array();
342      
343                 // go through table headers to get column names we want
344                 // in order (we have temporarily hack some adjustments in names)
345                 var cols = object.table.fnSettings().aoColumns;
346                 var colnames = cols.map(function(x) {return x.sTitle})
347                 var nb_col = cols.length;
348                 /* if we've requested checkboxes, then forget about the checkbox column for now */
349                 if (options.checkboxes) nb_col -= 1;
350
351                 /* fill in stuff depending on the column name */
352                 for (var j = 0; j < nb_col; j++) {
353                     if (typeof colnames[j] == 'undefined') {
354                         line.push('...');
355                     } else if (colnames[j] == 'hostname') {
356                         if (row['type'] == 'resource,link')
357                             //TODO: we need to add source/destination for links
358                             line.push('');
359                         else
360                             line.push(row['hostname']);
361                     } else {
362                         if (row[colnames[j]])
363                             line.push(row[colnames[j]]);
364                         else
365                             line.push('');
366                     }
367                 }
368     
369                 /* catch up with the last column if checkboxes were requested */
370                 if (options.checkboxes) {
371                     var checked = '';
372                     // xxx problem is, we don't get this 'sliver' thing set apparently
373                     if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
374                         checked = 'checked ';
375                         hazelnut.current_resources.push(row[ELEMENT_KEY]);
376                     }
377                     // Use a key instead of hostname (hard coded...)
378                     line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
379                 }
380     
381                 lines.push(line);
382     
383             });
384     
385             this.table.fnClearTable();
386             if (debug)
387                 messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
388             this.table.fnAddData(lines);
389         
390         };
391
392         this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str)
393         {
394             var result="";
395             if (header === null)
396                 header = '';
397             // Prefix id with plugin_uuid
398             result += "<input";
399             result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
400             result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header).replace(/\\/g, '')  + "'";
401             result += " name='" + unfold.get_value(field) + "'";
402             result += " type='checkbox'";
403             result += selected_str;
404             result += disabled_str;
405             result += " autocomplete='off'";
406             result += " value='" + unfold.get_value(header) + "'";
407             result += "></input>";
408             return result;
409         };
410
411         ////////////////////////////////////////////////////////////////////////
412         // New plugin API (in tests)
413
414         // TODO : signal empty/non empty table
415
416         this.new_record = function(record)
417         {
418             // this models a line in dataTables, each element in the line describes a cell
419             line = new Array();
420      
421             // go through table headers to get column names we want
422             // in order (we have temporarily hack some adjustments in names)
423             var cols = object.table.fnSettings().aoColumns;
424             var colnames = cols.map(function(x) {return x.sTitle})
425             var nb_col = cols.length;
426             /* if we've requested checkboxes, then forget about the checkbox column for now */
427             if (options.checkboxes) nb_col -= 1;
428
429             /* fill in stuff depending on the column name */
430             for (var j = 0; j < nb_col; j++) {
431                 if (typeof colnames[j] == 'undefined') {
432                     line.push('...');
433                 } else if (colnames[j] == 'hostname') {
434                     if (record['type'] == 'resource,link')
435                         //TODO: we need to add source/destination for links
436                         line.push('');
437                     else
438                         line.push(record['hostname']);
439                 } else {
440                     if (record[colnames[j]])
441                         line.push(record[colnames[j]]);
442                     else
443                         line.push('');
444                 }
445             }
446     
447             /* catch up with the last column if checkboxes were requested */
448             if (options.checkboxes) {
449                 var checked = '';
450                 // xxx problem is, we don't get this 'sliver' thing set apparently
451                 if (typeof(record['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
452                     checked = 'checked ';
453                     hazelnut.current_resources.push(record[ELEMENT_KEY]);
454                 }
455                 // Use a key instead of hostname (hard coded...)
456                 line.push(object.checkbox(options.plugin_uuid, record[ELEMENT_KEY], record['type'], checked, false));
457             }
458     
459             // XXX Is adding an array of lines more efficient ?
460             this.table.fnAddData(line);
461
462         };
463
464         this.set_checkbox = function(record)
465         {
466             // XXX urn should be replaced by the key
467             // XXX we should enforce that both queries have the same key !!
468             checkbox_id = "#hazelnut-checkbox-" + object.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
469             $(checkbox_id, object.table.fnGetNodes()).attr('checked', true);
470         }
471
472         this.record_handler = function(e, event_type, record)
473         {
474             // elements in set
475             switch(event_type) {
476                 case NEW_RECORD:
477                     /* NOTE in fact we are doing a join here */
478                     if (object.received_all)
479                         // update checkbox for record
480                         object.set_checkbox(record);
481                     else
482                         // store for later update of checkboxes
483                         object.in_set_buffer.push(record);
484                     break;
485                 case CLEAR_RECORDS:
486                     // nothing to do here
487                     break;
488                 case IN_PROGRESS:
489                     manifold.spin($(this));
490                     break;
491                 case DONE:
492                     if (object.received_all)
493                         manifold.spin($(this), false);
494                     object.received_set = true;
495                     break;
496             }
497         };
498
499         this.record_handler_all = function(e, event_type, record)
500         {
501             // all elements
502             switch(event_type) {
503                 case NEW_RECORD:
504                     // Add the record to the table
505                     object.new_record(record);
506                     break;
507                 case CLEAR_RECORDS:
508                     object.table.fnClearTable();
509                     break;
510                 case IN_PROGRESS:
511                     manifold.spin($(this));
512                     break;
513                 case DONE:
514                     if (object.received_set) {
515                         /* XXX needed ? XXX We uncheck all checkboxes ... */
516                         $("[id^='datatables-checkbox-" + object.options.plugin_uuid +"']").attr('checked', false);
517
518                         /* ... and check the ones specified in the resource list */
519                         $.each(object.in_set_buffer, function(i, record) {
520                             object.set_checkbox(record);
521                         });
522
523                         manifold.spin($(this), false);
524                     }
525                     object.received_all = true;
526                     break;
527             }
528         };
529
530         this.query_handler = function(e, event_type, query)
531         {
532             // This replaces the complex set_query function
533             // The plugin does not need to remember the query anymore
534             switch(event_type) {
535                 // Filters
536                 case FILTER_ADDED:
537                 case FILTER_REMOVED:
538                 case CLEAR_FILTERS:
539                     // XXX Here we might need to maintain the list of filters !
540                     /* Process updates in filters / current_query must be updated before this call for filtering ! */
541                     object.table.fnDraw();
542                     break;
543
544                 // Fields
545                 /* Hide/unhide columns to match added/removed fields */
546                 case FIELD_ADDED:
547                     var object = this;
548                     $.each(added_fields, function (index, field) {            
549                         var index = object.getColIndex(field,cols);
550                         if(index != -1)
551                             object.table.fnSetColumnVis(index, true);
552                     });
553                     break;
554                 case FIELD_REMOVED:
555                     var object = this;
556                     $.each(removed_fields, function (index, field) {
557                         var index = object.getColIndex(field,cols);
558                         if(index != -1)
559                             object.table.fnSetColumnVis(index, false);
560                     });            
561                     break;
562                 case CLEAR_FIELDS:
563                     alert('Hazelnut::clear_fields() not implemented');
564                     break;
565             } // switch
566
567
568         }
569     } // constructor
570
571     /***************************************************************************
572      * Private methods
573      * xxx I'm not sure why this should not be methods in the Hazelnut class above
574      ***************************************************************************/
575
576     /** 
577      * @brief Hazelnut filtering function
578      */
579     function hazelnut_filter (oSettings, aData, iDataIndex) {
580         var cur_query = this.current_query;
581         if (!cur_query) return true;
582         var ret = true;
583
584         /* We have an array of filters : a filter is an array (key op val) 
585          * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
586          *     can we exploit the data property somewhere ?
587          * field values (unless formatting) : aData
588          *     formatting should leave original data available in a hidden field
589          *
590          * The current line should validate all filters
591          */
592         $.each (cur_query.filters, function(index, filter) { 
593             /* XXX How to manage checkbox ? */
594             var key = filter[0]; 
595             var op = filter[1];
596             var value = filter[2];
597
598             /* Determine index of key in the table columns */
599             var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
600
601             /* Unknown key: no filtering */
602             if (typeof(col) == 'undefined')
603                 return;
604
605             col_value=unfold.get_value(aData[col]);
606             /* Test whether current filter is compatible with the column */
607             if (op == '=' || op == '==') {
608                 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
609                     ret = false;
610             }else if (op == '!=') {
611                 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
612                     ret = false;
613             } else if(op=='<') {
614                 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
615                     ret = false;
616             } else if(op=='>') {
617                 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
618                     ret = false;
619             } else if(op=='<=' || op=='≤') {
620                 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
621                     ret = false;
622             } else if(op=='>=' || op=='≥') {
623                 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
624                     ret = false;
625             }else{
626                 // How to break out of a loop ?
627                 alert("filter not supported");
628                 return false;
629             }
630
631         });
632         return ret;
633     }
634
635     function hazelnut_draw_callback() {
636         var options = this.options;
637         /* 
638          * Handle clicks on checkboxes: reassociate checkbox click every time
639          * the table is redrawn 
640          */
641         $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
642         $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
643
644         if (!this.table)
645             return;
646
647         /* Remove pagination if we show only a few results */
648         var wrapper = this.table; //.parent().parent().parent();
649         var rowsPerPage = this.table.fnSettings()._iDisplayLength;
650         var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
651         var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
652
653         if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
654             $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
655         } else {
656             $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
657         }
658
659         if ( rowsToShow <= minRowsPerPage ) {
660             $('.hazelnut_length', wrapper).css('visibility', 'hidden');
661         } else {
662             $('.hazelnut_length', wrapper).css('visibility', 'visible');
663         }
664     }
665
666     function check_click (e) {
667
668         var object = e.data.instance;
669
670         /* The key of the object to be added */
671         // XXX What about multiple keys ?
672         var value = this.value; 
673
674         // NEW PLUGIN API
675         manifold.raise_event(object.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, value);
676         
677         // OLD PLUGIN API BELOW
678
679         if (this.checked) {
680             object.current_resources.push(value);
681         } else {
682             tmp = $.grep(object.current_resources, function(x) { return x != value; });
683             object.current_resources = tmp;
684         }
685
686         /* inform slice that our selected resources have changed */
687         $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
688
689     }
690
691     function selectAll() {
692         // requires jQuery id
693         var uuid=this.id.split("-");
694         var oTable=$("#hazelnut-"+uuid[1]).dataTable();
695         // Function available in Hazelnut 1.9.x
696         // Filter : displayed data only
697         var filterData = oTable._('tr', {"filter":"applied"});   
698         /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
699         if(filterData.length<=100){
700             $.each(filterData, function(index, obj) {
701                 var last=$(obj).last();
702                 var key_value=unfold.get_value(last[0]);
703                 if(typeof($(last[0]).attr('checked'))=="undefined"){
704                     $.publish('selected', 'add/'+key_value);
705                 }
706             });
707         }
708     }
709     
710 })( jQuery );