Revised version of the resource page + related plugins
[myslice.git] / plugins / querytable / static / js / querytable.js
1 /**
2  * Description: display a query result in a datatables-powered <table>
3  * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 BGCOLOR_RESET   = 0;
8 BGCOLOR_ADDED   = 1;
9 BGCOLOR_REMOVED = 2;
10
11 (function($){
12
13     var debug=false;
14 //    debug=true
15
16     var QueryTable = Plugin.extend({
17
18         init: function(options, element) {
19             this.classname="querytable";
20             this._super(options, element);
21
22             /* Member variables */
23             // in general we expect 2 queries here
24             // query_uuid refers to a single object (typically a slice)
25             // query_all_uuid refers to a list (typically resources or users)
26             // these can return in any order so we keep track of which has been received yet
27             this.received_all_query = false;
28             this.received_query = false;
29
30             // We need to remember the active filter for datatables filtering
31             this.filters = Array(); 
32
33             // an internal buffer for records that are 'in' and thus need to be checked 
34             this.buffered_records_to_check = [];
35             // an internal buffer for keeping lines and display them in one call to fnAddData
36             this.buffered_lines = [];
37
38             /* Events */
39             // xx somehow non of these triggers at all for now
40             this.elmt().on('show', this, this.on_show);
41             this.elmt().on('shown.bs.tab', this, this.on_show);
42             this.elmt().on('resize', this, this.on_resize);
43
44             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
45             this.object = query.object;
46
47             //// we need 2 different keys
48             // * canonical_key is the primary key as derived from metadata (typically: urn)
49             //   and is used to communicate about a given record with the other plugins
50             // * init_key is a key that both kinds of records 
51             //   (i.e. records returned by both queries) must have (typically: hrn or hostname)
52             //   in general query_all will return well populated records, but query
53             //   returns records with only the fields displayed on startup
54             var keys = manifold.metadata.get_key(this.object);
55             this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
56             // 
57             this.init_key = this.options.init_key;
58             // have init_key default to canonical_key
59             this.init_key = this.init_key || this.canonical_key;
60             // sanity check
61             if ( ! this.init_key ) messages.warning ("QueryTable : cannot find init_key");
62             if ( ! this.canonical_key ) messages.warning ("QueryTable : cannot find canonical_key");
63             if (debug) messages.debug("querytable: canonical_key="+this.canonical_key+" init_key="+this.init_key);
64
65             /* Setup query and record handlers */
66             this.listen_query(options.query_uuid);
67             //this.listen_query(options.query_all_uuid, 'all');
68
69             /* GUI setup and event binding */
70             this.initialize_table();
71         },
72
73         /* PLUGIN EVENTS */
74
75         on_show: function(e) {
76             if (debug) messages.debug("querytable.on_show");
77             var self = e.data;
78             self.table.fnAdjustColumnSizing();
79         },        
80
81         on_resize: function(e) {
82             if (debug) messages.debug("querytable.on_resize");
83             var self = e.data;
84             self.table.fnAdjustColumnSizing();
85         },        
86
87         /* GUI EVENTS */
88
89         /* GUI MANIPULATION */
90
91         initialize_table: function() 
92         {
93             /* Transforms the table into DataTable, and keep a pointer to it */
94             var self = this;
95             var actual_options = {
96                 // Customize the position of Datatables elements (length,filter,button,...)
97                 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
98                 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
99                 sDom: "<'row'<'col-xs-5'f><'col-xs-1'r><'col-xs-6 columns_selector'>>t<'row'<'col-xs-5'l><'col-xs-7'p>>",
100                 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
101                 // hopefully this would come with dataTables v1.10 ?
102                 // in any case, search for 'sPaginationType' all over the code for more comments
103                 sPaginationType: 'bootstrap',
104                 // Handle the null values & the error : Datatables warning Requested unknown parameter
105                 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
106                 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
107                 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
108                 // sScrollX: '100%',       /* Horizontal scrolling */
109                 bProcessing: true,      /* Loading */
110                 fnDrawCallback: function() { self._querytable_draw_callback.call(self); },
111                 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
112                     // This function is called on fnAddData to set the TR id. What about fnUpdate ?
113
114                     // Get the key from the raw data array aData
115                     var key = self.canonical_key;
116
117                     // Get the index of the key in the columns
118                     var cols = self.table.fnSettings().aoColumns;
119                     var index = self.getColIndex(key, cols);
120                     if (index != -1) {
121                         // The key is found in the table, set the TR id after the data
122                         $(nRow).attr('id', self.id_from_key(key, aData[index]));
123                     }
124
125                     // That's the usual return value
126                     return nRow;
127                 }
128                 // XXX use $.proxy here !
129             };
130             // the intention here is that options.datatables_options as coming from the python object take precedence
131             // xxx DISABLED by jordan: was causing errors in datatables.js
132             // xxx turned back on by Thierry - this is the code that takes python-provided options into account
133             // check your datatables_options tag instead 
134             // however, we have to accumulate in aoColumnDefs from here (above) 
135             // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
136             if ( 'aoColumnDefs' in this.options.datatables_options) {
137                 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
138                 delete this.options.datatables_options['aoColumnDefs'];
139             }
140             $.extend(actual_options, this.options.datatables_options );
141             this.table = this.elmt('table').dataTable(actual_options);
142
143             /* Setup the SelectAll button in the dataTable header */
144             /* xxx not sure this is still working */
145             var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
146             oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
147             oSelectAll.button();
148             oSelectAll.css('font-size','11px');
149             oSelectAll.css('float','right');
150             oSelectAll.css('margin-right','15px');
151             oSelectAll.css('margin-bottom','5px');
152             oSelectAll.unbind('click');
153             oSelectAll.click(this._selectAll);
154
155             /* Add a filtering function to the current table 
156              * Note: we use closure to get access to the 'options'
157              */
158             $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
159                 /* No filtering if the table does not match */
160                 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
161                     return true;
162                 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
163             });
164
165             /* Processing hidden_columns */
166             $.each(this.options.hidden_columns, function(i, field) {
167                 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
168                 self.hide_column(field);
169             });
170             $(".dataTables_filter").append("<div style='display:inline-block;height:27px;width:27px;padding-left:6px;padding-top:4px;'><span class='glyphicon glyphicon-search'></span></div>");
171             $(".dataTables_filter input").css("width","100%");
172         }, // initialize_table
173
174         /**
175          * @brief Determine index of key in the table columns 
176          * @param key
177          * @param cols
178          */
179         getColIndex: function(key, cols) {
180             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
181             return (tabIndex.length > 0) ? tabIndex[0] : -1;
182         }, // getColIndex
183
184         // create a checkbox <input> tag
185         // computes 'id' attribute from canonical_key
186         // computes 'init_id' from init_key for initialization phase
187         // no need to used convoluted ids with plugin-uuid or others, since
188         // we search using table.$ which looks only in this table
189         checkbox_html : function (record) {
190             var result="";
191             // Prefix id with plugin_uuid
192             result += "<input";
193             result += " class='querytable-checkbox'";
194          // compute id from canonical_key
195             var id = record[this.canonical_key]
196          // compute init_id form init_key
197             var init_id=record[this.init_key];
198          // set id - for retrieving from an id, or for posting events upon user's clicks
199             result += " id='"+record[this.canonical_key]+"'";
200          // set init_id
201             result += "init_id='" + init_id + "'";
202          // wrap up
203             result += " type='checkbox'";
204             result += " autocomplete='off'";
205             result += "></input>";
206             return result;
207         }, 
208
209
210         new_record: function(record)
211         {
212             // this models a line in dataTables, each element in the line describes a cell
213             line = new Array();
214      
215             // go through table headers to get column names we want
216             // in order (we have temporarily hack some adjustments in names)
217             var cols = this.table.fnSettings().aoColumns;
218             var colnames = cols.map(function(x) {return x.sTitle})
219             var nb_col = cols.length;
220             /* if we've requested checkboxes, then forget about the checkbox column for now */
221             //if (this.options.checkboxes) nb_col -= 1;
222                         // catch up with the last column if checkboxes were requested 
223             if (this.options.checkboxes) {
224                 // Use a key instead of hostname (hard coded...)
225                 line.push(this.checkbox_html(record));
226                 }
227                 
228             /* fill in stuff depending on the column name */
229             for (var j = 1; j < nb_col - 1; j++) { // nb_col includes status
230                 if (typeof colnames[j] == 'undefined') {
231                     line.push('...');
232                 } else if (colnames[j] == 'hostname') {
233                     if (record['type'] == 'resource,link')
234                         //TODO: we need to add source/destination for links
235                         line.push('');
236                     else
237                         line.push(record['hostname']);
238
239                 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
240                     obj = this.object
241                     o = obj.split(':');
242                     if(o.length>1){
243                         obj = o[1];
244                     }else{
245                         obj = o[0];
246                     }
247                     /* XXX TODO: Remove this and have something consistant */
248                     if(obj=='resource'){
249                         //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
250                     }else{
251                         //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
252                     }
253                     line.push(record[this.init_key]);
254                 } else {
255                     if (record[colnames[j]])
256                         line.push(record[colnames[j]]);
257                     else
258                         line.push('');
259                 }
260             }
261             line.push('<span id="' + this.id_from_key('status', record[this.init_key]) + '"></span>'); // STATUS
262     
263             // adding an array in one call is *much* more efficient
264                 // this.table.fnAddData(line);
265                 return line;
266         },
267
268         clear_table: function()
269         {
270             this.table.fnClearTable();
271         },
272
273         redraw_table: function()
274         {
275             this.table.fnDraw();
276         },
277
278         show_column: function(field)
279         {
280             var oSettings = this.table.fnSettings();
281             var cols = oSettings.aoColumns;
282             var index = this.getColIndex(field,cols);
283             if (index != -1)
284                 this.table.fnSetColumnVis(index, true);
285         },
286
287         hide_column: function(field)
288         {
289             var oSettings = this.table.fnSettings();
290             var cols = oSettings.aoColumns;
291             var index = this.getColIndex(field,cols);
292             if (index != -1)
293                 this.table.fnSetColumnVis(index, false);
294         },
295
296         // this is used at init-time, at which point only init_key can make sense
297         // (because the argument record, if it comes from query, might not have canonical_key set
298         set_checkbox_from_record: function (record, checked) {
299         if (checked === undefined) checked = true;
300             var init_id = record[this.init_key];
301         this.set_checkbox_from_record_key(init_id, checked);
302         },
303
304         set_checkbox_from_record_key: function (record_key, checked) {
305         if (checked === undefined) checked = true;
306             if (debug) messages.debug("querytable.set_checkbox_from_record, record_key="+record_key);
307             // using table.$ to search inside elements that are not visible
308             var element = this.table.$('[init_id="'+record_key+'"]');
309             element.attr('checked',checked);
310         },
311
312         // id relates to canonical_key
313         set_checkbox_from_data: function (id, checked) {
314             if (checked === undefined) checked = true;
315             if (debug) messages.debug("querytable.set_checkbox_from_data, id="+id);
316             // using table.$ to search inside elements that are not visible
317             var element = this.table.$("[id='"+id+"']");
318             element.attr('checked',checked);
319         },
320
321         /**
322          * Arguments
323          *
324          * key_value: the key from which we deduce the id
325          * request: STATUS_OKAY, etc.
326          * content: some HTML content
327          */
328         change_status: function(key_value, warnings)
329         {
330             var msg;
331             
332             if ($.isEmptyObject(warnings)) { 
333                 var state = manifold.query_store.get_record_state(this.options.query_uuid, key_value, STATE_SET);
334                 switch(state) {
335                     case STATE_SET_IN:
336                     case STATE_SET_IN_SUCCESS:
337                     case STATE_SET_OUT_FAILURE:
338                     case STATE_SET_IN_PENDING:
339                         // Checkmark sign if no warning for an object in the set
340                         msg = '&#10003;';
341                         break;
342                     default:
343                         // Nothing is the object is not in the set
344                         msg = '';
345                         break;
346                 }
347             } else {
348                 msg = '<ul class="nav nav-pills">';
349                 msg += '<li class="dropdown">'
350                 msg += '<a href="#" data-toggle="dropdown" class="dropdown-toggle nopadding"><b>&#9888</b></a>';
351                 msg += '  <ul class="dropdown-menu dropdown-menu-right" id="menu1">';
352                 $.each(warnings, function(i,warning) {
353                     msg += '<li><a href="#">' + warning + '</a></li>';
354                 });
355                 msg += '  </ul>';
356                 msg += '</li>';
357                 msg += '</ul>';
358             }
359
360             $(document.getElementById(this.id_from_key('status', key_value))).html(msg);
361             $('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
362
363         },
364
365         set_bgcolor: function(key_value, class_name)
366         {
367             var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
368             if (class_name == BGCOLOR_RESET)
369                 elt.removeClass('added removed');
370             else
371                 elt.addClass((class_name == BGCOLOR_ADDED ? 'added' : 'removed'));
372         },
373
374         do_filter: function()
375         {
376             // Let's clear the table and only add lines that are visible
377             var self = this;
378             this.clear_table();
379
380             // XXX Here we have lost checkboxes
381             // set checkbox from record.
382             // only the current plugin known that we have an element in a set
383
384             lines = Array();
385             var record_keys = [];
386             manifold.query_store.iter_visible_records(this.options.query_uuid, function (record_key, record) {
387                 lines.push(self.new_record(record));
388                 record_keys.push(record_key);
389             });
390                 this.table.fnAddData(lines);
391             $.each(record_keys, function(i, record_key) {
392                 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
393                 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
394                 switch(state) {
395                     // XXX The row and checkbox still does not exists !!!!
396                     case STATE_SET_IN:
397                     case STATE_SET_IN_SUCCESS:
398                     case STATE_SET_OUT_FAILURE:
399                         self.set_checkbox_from_record_key(record_key, true);
400                         break;
401                     case STATE_SET_OUT:
402                     case STATE_SET_OUT_SUCCESS:
403                     case STATE_SET_IN_FAILURE:
404                         //self.set_checkbox_from_record_key(record_key, false);
405                         break;
406                     case STATE_SET_IN_PENDING:
407                         self.set_checkbox_from_record_key(record_key, true);
408                         self.set_bgcolor(record_key, BGCOLOR_ADDED);
409                         break;
410                     case STATE_SET_OUT_PENDING:
411                         //self.set_checkbox_from_record_key(record_key, false);
412                         self.set_bgcolor(record_key, BGCOLOR_REMOVED);
413                         break;
414                 }
415                 self.change_status(record_key, warnings); // XXX will retrieve status again
416             });
417         },
418
419         /*************************** QUERY HANDLER ****************************/
420
421         on_filter_added: function(filter)
422         {
423             this.do_filter();
424
425             /*
426             this.filters.push(filter);
427             this.redraw_table();
428             */
429         },
430
431         on_filter_removed: function(filter)
432         {
433             this.do_filter();
434             /*
435             // Remove corresponding filters
436             this.filters = $.grep(this.filters, function(x) {
437                 return x == filter;
438             });
439             this.redraw_table();
440             */
441         },
442         
443         on_filter_clear: function()
444         {
445             this.do_filter();
446         },
447
448         on_field_added: function(field)
449         {
450             this.show_column(field);
451         },
452
453         on_field_removed: function(field)
454         {
455             this.hide_column(field);
456         },
457
458         on_field_clear: function()
459         {
460             alert('QueryTable::clear_fields() not implemented');
461         },
462
463         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
464         /*************************** ALL QUERY HANDLER ****************************/
465
466         on_all_filter_added: function(filter)
467         {
468             this.do_filter();
469         },
470
471         on_all_filter_removed: function(filter)
472         {
473             this.do_filter();
474         },
475         
476         on_all_filter_clear: function()
477         {
478             this.do_filter();
479         },
480
481         on_all_field_added: function(field)
482         {
483             this.show_column(field);
484         },
485
486         on_all_field_removed: function(field)
487         {
488             this.hide_column(field);
489         },
490
491         on_all_field_clear: function()
492         {
493             alert('QueryTable::clear_fields() not implemented');
494         },
495
496
497         /*************************** RECORD HANDLER ***************************/
498
499         on_new_record: function(record)
500         {
501             if (this.received_all_query) {
502                 // if the 'all' query has been dealt with already we may turn on the checkbox
503                 this.set_checkbox_from_record(record, true);
504             } else {
505                 this.buffered_records_to_check.push(record);
506             }
507         },
508
509         on_clear_records: function()
510         {
511         },
512
513         // Could be the default in parent
514         on_query_in_progress: function()
515         {
516             this.spin();
517         },
518
519         on_query_done: function()
520         {
521             this.do_filter();
522 /*
523             this.received_query = true;
524             // unspin once we have received both
525             if (this.received_all_query && this.received_query) this.unspin();
526 */
527         },
528         
529         on_field_state_changed: function(data)
530         {
531             var state = manifold.query_store.get_record_state(this.options.query_uuid, data.value, data.status);
532             switch(data.status) {
533                 case STATE_SET:
534                     switch(state) {
535                         case STATE_SET_IN:
536                         case STATE_SET_IN_SUCCESS:
537                         case STATE_SET_OUT_FAILURE:
538                             this.set_checkbox_from_data(data.value, true);
539                             this.set_bgcolor(data.value, BGCOLOR_RESET);
540                             break;  
541                         case STATE_SET_OUT:
542                         case STATE_SET_OUT_SUCCESS:
543                         case STATE_SET_IN_FAILURE:
544                             this.set_checkbox_from_data(data.value, false);
545                             this.set_bgcolor(data.value, BGCOLOR_RESET);
546                             break;
547                         case STATE_SET_IN_PENDING:
548                             this.set_checkbox_from_data(data.value, true);
549                             this.set_bgcolor(data.value, BGCOLOR_ADDED);
550                             break;  
551                         case STATE_SET_OUT_PENDING:
552                             this.set_checkbox_from_data(data.value, false);
553                             this.set_bgcolor(data.value, BGCOLOR_REMOVED);
554                             break;
555                     }
556                     break;
557
558                 case STATE_WARNINGS:
559                     this.change_status(data.value, state);
560                     break;
561             }
562         },
563
564         /************************** PRIVATE METHODS ***************************/
565
566         /** 
567          * @brief QueryTable filtering function
568          */
569         _querytable_filter: function(oSettings, aData, iDataIndex)
570         {
571             var ret = true;
572             $.each (this.filters, function(index, filter) { 
573                 /* XXX How to manage checkbox ? */
574                 var key = filter[0]; 
575                 var op = filter[1];
576                 var value = filter[2];
577
578                 /* Determine index of key in the table columns */
579                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
580
581                 /* Unknown key: no filtering */
582                 if (typeof(col) == 'undefined')
583                     return;
584
585                 col_value=unfold.get_value(aData[col]);
586                 /* Test whether current filter is compatible with the column */
587                 if (op == '=' || op == '==') {
588                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
589                         ret = false;
590                 }else if (op == 'included') {
591                     $.each(value, function(i,x) {
592                       if(x == col_value){
593                           ret = true;
594                           return false;
595                       }else{
596                           ret = false;
597                       }
598                     });
599                 }else if (op == '!=') {
600                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
601                         ret = false;
602                 } else if(op=='<') {
603                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
604                         ret = false;
605                 } else if(op=='>') {
606                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
607                         ret = false;
608                 } else if(op=='<=' || op=='≤') {
609                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
610                         ret = false;
611                 } else if(op=='>=' || op=='≥') {
612                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
613                         ret = false;
614                 }else{
615                     // How to break out of a loop ?
616                     alert("filter not supported");
617                     return false;
618                 }
619
620             });
621             return ret;
622         },
623
624         _querytable_draw_callback: function()
625         {
626             /* 
627              * Handle clicks on checkboxes: reassociate checkbox click every time
628              * the table is redrawn 
629              */
630             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
631
632             if (!this.table)
633                 return;
634
635             /* Remove pagination if we show only a few results */
636             var wrapper = this.table; //.parent().parent().parent();
637             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
638             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
639             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
640
641             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
642                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
643             } else {
644                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
645             }
646
647             if ( rowsToShow <= minRowsPerPage ) {
648                 $('.querytable_length', wrapper).css('visibility', 'hidden');
649             } else {
650                 $('.querytable_length', wrapper).css('visibility', 'visible');
651             }
652         },
653
654         _check_click: function(e) 
655         {
656             e.stopPropagation();
657
658             var self = e.data;
659             var id=this.id;
660
661             // this.id = key of object to be added... what about multiple keys ?
662             if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
663             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
664             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
665             
666         },
667
668         _selectAll: function() 
669         {
670             // requires jQuery id
671             var uuid=this.id.split("-");
672             var oTable=$("#querytable-"+uuid[1]).dataTable();
673             // Function available in QueryTable 1.9.x
674             // Filter : displayed data only
675             var filterData = oTable._('tr', {"filter":"applied"});   
676             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
677             if(filterData.length<=100){
678                 $.each(filterData, function(index, obj) {
679                     var last=$(obj).last();
680                     var key_value=unfold.get_value(last[0]);
681                     if(typeof($(last[0]).attr('checked'))=="undefined"){
682                         $.publish('selected', 'add/'+key_value);
683                     }
684                 });
685             }
686         },
687
688     });
689
690     $.plugin('QueryTable', QueryTable);
691
692   /* define the 'dom-checkbox' type for sorting in datatables 
693      http://datatables.net/examples/plug-ins/dom_sort.html
694      using trial and error I found that the actual column number
695      was in fact given as a third argument, and not second 
696      as the various online resources had it - go figure */
697     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
698                 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
699                     return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
700                 });
701     };
702
703 })(jQuery);
704