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