a21e5246fc53a0874e3bdff17412e27dfc744482
[myslice.git] / plugins / univbrisfvf / static / js / univbrisfvf.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 (function($){
8
9     var debug=false;
10     debug=true
11
12     var UnivbrisFvf = Plugin.extend({
13
14         init: function(options, element) {
15             //alert("foam init called");
16             this.classname="univbrisfvf";
17             this._super(options, element);
18                 
19             //alert(this.options.hidden_columns);
20             /* Member variables */
21             // in general we expect 2 queries here
22             // query_uuid refers to a single object (typically a slice)
23             // query_all_uuid refers to a list (typically resources or users)
24             // these can return in any order so we keep track of which has been received yet
25             //this.received_all_query = false;
26             //this.received_query = false;
27
28             // We need to remember the active filter for datatables filtering
29             this.filters = Array(); 
30
31             // an internal buffer for records that are 'in' and thus need to be checked 
32             this.buffered_records_to_check = [];
33             // an internal buffer for keeping lines and display them in one call to fnAddData
34             this.buffered_lines = [];
35
36             /* Events */
37             // xx somehow non of these triggers at all for now
38             //this.elmt().on('show', this, this.on_show);
39             //this.elmt().on('shown.bs.tab', this, this.on_show);
40             //this.elmt().on('resize', this, this.on_resize);
41
42             //var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
43             //this.object = query.object;
44
45             //// we need 2 different keys
46             // * canonical_key is the primary key as derived from metadata (typically: urn)
47             //   and is used to communicate about a given record with the other plugins
48             // * init_key is a key that both kinds of records 
49             //   (i.e. records returned by both queries) must have (typically: hrn or hostname)
50             //   in general query_all will return well populated records, but query
51             //   returns records with only the fields displayed on startup
52             var keys = manifold.metadata.get_key(this.object);
53             this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
54             // 
55             this.init_key = this.options.init_key;
56             // have init_key default to canonical_key
57             this.init_key = this.init_key || this.canonical_key;
58             // sanity check
59             if ( ! this.init_key ) messages.warning ("UnivbrisFvf : cannot find init_key");
60             if ( ! this.canonical_key ) messages.warning ("UnivbrisFvf : cannot find canonical_key");
61             if (debug) messages.debug("UnivbrisFvf: canonical_key="+this.canonical_key+" init_key="+this.init_key);
62
63             /* Setup query and record handlers */
64             //this.listen_query(options.query_uuid);
65             //this.listen_query(options.query_all_uuid, 'all');
66
67             /* GUI setup and event binding */
68             //this.initialize_table();
69             //alert("init fvf");
70             jQuery("#uob_fv_table_form").hide();
71         
72             $('<button id="cancel_addflowspaceform" type="button" style="height: 25px; width: 200px" onclick="fnCancel()">Cancel</button>').appendTo('#fvf_table_button');
73
74             $('<button id="addflowspaceform" type="button" style="height: 25px; width: 200px" onclick="fnAddflowspace()">Add flowspace</button>').appendTo('#fvf_table_button');
75                 
76             this._querytable_draw_callback();
77         },
78
79         /* PLUGIN EVENTS */
80
81         on_show: function(e) {
82             if (debug) messages.debug("univbrisfvf.on_show");
83             var self = e.data;
84             self.table.fnAdjustColumnSizing();
85         },        
86
87         on_resize: function(e) {
88             if (debug) messages.debug("univbrisfvf.on_resize");
89             var self = e.data;
90             self.table.fnAdjustColumnSizing();
91         },        
92
93         /* GUI EVENTS */
94
95         /* GUI MANIPULATION */
96
97         initialize_table: function() 
98         {
99             /* Transforms the table into DataTable, and keep a pointer to it */
100             var self = this;
101             var actual_options = {
102                 // Customize the position of Datatables elements (length,filter,button,...)
103                 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
104                 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
105                 //sDom: "<'row'<'col-xs-2'l><'col-xs-9'r><'col-xs-2'f>>t<'row'<'col-xs-5'i><'col-xs-5'p>><'next'>",
106                 sDom: "<'row'<'col-xs-9'r>t<'buttons'>",
107                 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
108                 // hopefully this would come with dataTables v1.10 ?
109                 // in any case, search for 'sPaginationType' all over the code for more comments
110                 sPaginationType: 'bootstrap',
111                 // Handle the null values & the error : Datatables warning Requested unknown parameter
112                 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
113                 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
114                 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
115                 // sScrollX: '100%',       /* Horizontal scrolling */
116                 bProcessing: false,      /* Loading */
117                 fnDrawCallback: function() { self._querytable_draw_callback.call(self);}
118                 //fnFooterCallback: function() {self._univbrisfvf_footer_callback.call(self,nFoot, aData, iStart, iEnd, aiDisplay)};}
119                 // XXX use $.proxy here !
120             };
121             // the intention here is that options.datatables_options as coming from the python object take precedence
122             // xxx DISABLED by jordan: was causing errors in datatables.js
123             // xxx turned back on by Thierry - this is the code that takes python-provided options into account
124             // check your datatables_options tag instead 
125             // however, we have to accumulate in aoColumnDefs from here (above) 
126             // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
127             if ( 'aoColumnDefs' in this.options.datatables_options) {
128                 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
129                 delete this.options.datatables_options['aoColumnDefs'];
130             }
131             $.extend(actual_options, this.options.datatables_options );
132             this.table = $("#univbris_flowspace_form__table").dataTable(actual_options);
133
134             //alert(this.table);
135
136             /* Setup the SelectAll button in the dataTable header */
137             /* xxx not sure this is still working */
138             var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
139             oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
140             oSelectAll.button();
141             oSelectAll.css('font-size','11px');
142             oSelectAll.css('float','right');
143             oSelectAll.css('margin-right','15px');
144             oSelectAll.css('margin-bottom','5px');
145             oSelectAll.unbind('click');
146             oSelectAll.click(this._selectAll);
147
148             /* Add a filtering function to the current table 
149              * Note: we use closure to get access to the 'options'
150              */
151             $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
152                 /* No filtering if the table does not match */
153                 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
154                     return true;
155                 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
156             });
157
158            //alert(this.options.hidden_columns);
159
160             /* Processing hidden_columns */
161             $.each(this.options.hidden_columns, function(i, field) {
162                 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
163                 //alert (field);
164                 self.hide_column(field);
165                 //self.hide_column(field);
166             });
167
168         }, // initialize_table
169
170
171         fnCancel:function(e){
172                 //var sData=$("#uob_fv_table_form").find("input").serialize();
173                 //alert("add flowspace:" + sData);
174                 jQuery("#uob_fv_table_form").hide();
175                 jQuery( "#univbris_flowspace_selection" ).show();
176         },
177
178         fnAddflowspace:function(e){
179                 if(fvf_add==1){
180                         pk_flowspace_index=1+pk_flowspace_index;
181                         jQuery("#uob_fv_table_form").hide();
182                         var sData=$("#uob_fv_table_form").find("input").serialize();
183                         var form =serializeAnything("#uob_fv_table_form");
184                         this.table = $("#univbris_flowspace_selection__table").dataTable();
185                         flowspace=sData;
186                 
187                         var string = "<p id='"+form+"'> <a onclick=\'fnPopTable(\""+form+"\");'>"+$("#flowspace_name").val()+"</a></p>";        
188                         this.table.fnAddData([string, '<a class="edit">Edit</a>', '<a class="delete" href="">Delete</a>']);
189                         jQuery( "#univbris_flowspace_selection" ).show();
190                 }
191                 else{
192                         jQuery("#uob_fv_table_form").hide();
193                         var sData=$("#uob_fv_table_form").find("input").serialize();
194                         var form =serializeAnything("#uob_fv_table_form");
195                         this.table = $("#univbris_flowspace_selection__table").dataTable();
196                         flowspace=sData;
197                         
198                         var string = "<p id='"+form+"'> <a onclick=\'fnPopTable(\""+form+"\");'>"+$("#flowspace_name").val()+"</a></p>";
199                         this.table.fnDeleteRow(fvf_nrow);       
200                         this.table.fnAddData([string, '<a class="edit">Edit</a>', '<a class="delete" href="">Delete</a>']);
201                         jQuery( "#univbris_flowspace_selection" ).show();
202                 
203                 }
204         },
205
206
207         fnModflowspace:function(e){
208                 //alert("modify");
209
210                 jQuery("#uob_fv_table_form").hide();
211                 var sData=$("#uob_fv_table_form").find("input").serialize();
212                 var form =serializeAnything("#uob_fv_table_form");
213                 this.table = $("#univbris_flowspace_selection__table").dataTable();
214                 flowspace=sData;
215                 alert(form+"\n"+sData);
216                 
217                 var string = "<p id='"+form+"'> <a onclick=\'fnPopTable(\""+form+"\");'>"+$("#flowspace_name").val()+"</a></p>";
218                 this.table.fnDeleteRow(fvf_nrow);       
219                 this.table.fnAddData([string, '<a class="edit">Edit</a>', '<a class="delete" href="">Delete</a>']);
220                 jQuery( "#univbris_flowspace_selection" ).show();
221         },
222
223         /**
224          * @brief Determine index of key in the table columns 
225          * @param key
226          * @param cols
227          */
228         getColIndex: function(key, cols) {
229             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
230             return (tabIndex.length > 0) ? tabIndex[0] : -1;
231         }, // getColIndex
232
233         // create a checkbox <input> tag
234         // computes 'id' attribute from canonical_key
235         // computes 'init_id' from init_key for initialization phase
236         // no need to used convoluted ids with plugin-uuid or others, since
237         // we search using table.$ which looks only in this table
238         checkbox_html : function (record) {
239             var result="";
240             // Prefix id with plugin_uuid
241             result += "<input";
242             result += " class='univbrisfvf-checkbox'";
243          // compute id from canonical_key
244             var id = record[this.canonical_key]
245          // compute init_id form init_key
246             var init_id=record[this.init_key];
247          // set id - for retrieving from an id, or for posting events upon user's clicks
248             result += " id='"+record[this.canonical_key]+"'";
249          // set init_id
250             result += "init_id='" + init_id + "'";
251          // wrap up
252             result += " type='checkbox'";
253             result += " autocomplete='off'";
254             result += "></input>";
255             return result;
256         }, 
257
258          fake_checkbox_html : function (record) {
259             //alert("fake fun called");
260             var result="";
261             // Prefix id with plugin_uuid
262             result += "<input";
263             //result += " class='univbrisfvf-checkbox'";
264          // set id - for retrieving from an id, or for posting events upon user's clicks
265             result += " id='"+ record +"'";
266             result += " name='"+ record +"'";
267          // set init_id
268             result += " init_id='" + record + "'";
269          // wrap up
270             result += " type='checkbox'";
271             result += " autocomplete='off'";
272             result += "></input>";
273             ///alert(result);
274             return result;
275         }, 
276
277
278         new_record: function(record)
279         {
280            
281          // this models a line in dataTables, each element in the line describes a cell
282             line = new Array();
283      
284             // go through table headers to get column names we want
285             // in order (we have temporarily hack some adjustments in names)
286             var cols = this.table.fnSettings().aoColumns;
287             var colnames = cols.map(function(x) {return x.sTitle})
288             var nb_col = cols.length;
289             /* if we've requested checkboxes, then forget about the checkbox column for now */
290             if (this.options.checkboxes) nb_col -= 1;
291             
292             //alert(colnames);
293             /*replace production*/
294             /* fill in stuff depending on the column name */
295              var cols = this.table.fnSettings().aoColumns;
296             //alert("col "+cols);
297             var colnames = cols.map(function(x) {return x.sTitle})
298             var nb_col = cols.length;
299                         //alert("nb_col: "+ nb_col);
300             /* if we've requested checkboxes, then forget about the checkbox column for now */
301             if (this.options.checkboxes) nb_col -= 1;
302                         //alert("nb_col: "+ nb_col);
303             //alert(colnames);
304             /*replace production*/
305             /* fill in stuff depending on the column name */
306             for (var j = 0; j < nb_col; j++) {
307                 if (typeof colnames[j] == 'undefined') {
308                     line.push('...');
309                 } else if (colnames[j] == 'Flowspace Selector') {
310                     //alert("added");
311                     line.push("first");
312                 }
313                 
314
315                 /*if (typeof colnames[j] == 'undefined') {
316                     line.push('...');
317                 } else if (colnames[j] == 'hostname') {
318                     if (record['type'] == 'resource,link')
319                         //TODO: we need to add source/destination for links
320                         line.push('');
321                     else
322                         line.push(record['hostname']);
323
324                 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
325                     line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
326                 } else {
327                     if (record[colnames[j]])
328                         line.push(record[colnames[j]]);
329                     else
330                         line.push('');
331                 }*/
332             }
333     
334             // catch up with the last column if checkboxes were requested 
335             if (this.options.checkboxes) {
336                 // Use a key instead of hostname (hard coded...)
337                 line.push(this.checkbox_html(record));
338                 }
339     
340             // adding an array in one call is *much* more efficient
341                 // this.table.fnAddData(line);
342                 this.buffered_lines.push(line);
343                 this.table.fnAddData(this.buffered_lines);
344                 //this.table.redraw();
345                 //this._querytable_draw_callback();
346         },
347
348         clear_table: function()
349         {
350             this.table.fnClearTable();
351         },
352
353         redraw_table: function()
354         {
355             this.table.fnDraw();
356         },
357
358         show_column: function(field)
359         {
360             var oSettings = this.table.fnSettings();
361             var cols = oSettings.aoColumns;
362             var index = this.getColIndex(field,cols);
363             if (index != -1)
364                 this.table.fnSetColumnVis(index, true);
365         },
366
367         hide_column: function(field)
368         {
369             var oSettings = this.table.fnSettings();
370             var cols = oSettings.aoColumns;
371             var index = this.getColIndex(field,cols);
372             //index=-1;
373             //alert(field + ": index: " + index );
374             if (index != -1)
375                 //alert(field + ": hidden with index: " + index );
376                 this.table.fnSetColumnVis(index, false);
377         },
378
379         // this is used at init-time, at which point only init_key can make sense
380         // (because the argument record, if it comes from query, might not have canonical_key set
381         set_checkbox_from_record: function (record, checked) {
382             if (checked === undefined) checked = true;
383             var init_id = record[this.init_key];
384             if (debug) messages.debug("univbrisfvf.set_checkbox_from_record, init_id="+init_id);
385             // using table.$ to search inside elements that are not visible
386             var element = this.table.$('[init_id="'+init_id+'"]');
387             element.attr('checked',checked);
388         },
389
390         // id relates to canonical_key
391         set_checkbox_from_data: function (id, checked) {
392             if (checked === undefined) checked = true;
393             if (debug) messages.debug("univbrisfvf.set_checkbox_from_data, id="+id);
394             // using table.$ to search inside elements that are not visible
395             var element = this.table.$("[id='"+id+"']");
396             element.attr('checked',checked);
397         },
398
399         /*************************** QUERY HANDLER ****************************/
400
401         on_filter_added: function(filter)
402         {
403             this.filters.push(filter);
404             this.redraw_table();
405         },
406
407         on_filter_removed: function(filter)
408         {
409             // Remove corresponding filters
410             this.filters = $.grep(this.filters, function(x) {
411                 return x != filter;
412             });
413             this.redraw_table();
414         },
415         
416         on_filter_clear: function()
417         {
418             // XXX
419             this.redraw_table();
420         },
421
422         on_field_added: function(field)
423         {
424             this.show_column(field);
425         },
426
427         on_field_removed: function(field)
428         {
429             this.hide_column(field);
430         },
431
432         on_field_clear: function()
433         {
434             alert('UnivbrisFvf::clear_fields() not implemented');
435         },
436
437         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
438         /*************************** ALL QUERY HANDLER ****************************/
439
440         on_all_filter_added: function(filter)
441         {
442             // XXX
443             this.redraw_table();
444         },
445
446         on_all_filter_removed: function(filter)
447         {
448             // XXX
449             this.redraw_table();
450         },
451         
452         on_all_filter_clear: function()
453         {
454             // XXX
455             this.redraw_table();
456         },
457
458         on_all_field_added: function(field)
459         {
460             this.show_column(field);
461         },
462
463         on_all_field_removed: function(field)
464         {
465             this.hide_column(field);
466         },
467
468         on_all_field_clear: function()
469         {
470             alert('UnivbrisFvf::clear_fields() not implemented');
471         },
472
473
474         /*************************** RECORD HANDLER ***************************/
475
476         on_new_record: function(record)
477         {
478             if (this.received_all_query) {
479                 // if the 'all' query has been dealt with already we may turn on the checkbox
480                 this.set_checkbox_from_record(record, true);
481             } else {
482                 this.buffered_records_to_check.push(record);
483             }
484         },
485
486         on_clear_records: function()
487         {
488         },
489
490         // Could be the default in parent
491         on_query_in_progress: function()
492         {
493             this.spin();
494         },
495
496         on_query_done: function()
497         {
498             this.received_query = true;
499             // unspin once we have received both
500             if (this.received_all_query && this.received_query) this.unspin();
501         },
502         
503         on_field_state_changed: function(data)
504         {
505             switch(data.request) {
506                 case FIELD_REQUEST_ADD:
507                 case FIELD_REQUEST_ADD_RESET:
508                     this.set_checkbox_from_data(data.value, true);
509                     break;
510                 case FIELD_REQUEST_REMOVE:
511                 case FIELD_REQUEST_REMOVE_RESET:
512                     this.set_checkbox_from_data(data.value, false);
513                     break;
514                 default:
515                     break;
516             }
517         },
518
519         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
520         // all
521         on_all_field_state_changed: function(data)
522         {
523             switch(data.request) {
524                 case FIELD_REQUEST_ADD:
525                 case FIELD_REQUEST_ADD_RESET:
526                     this.set_checkboxfrom_data(data.value, true);
527                     break;
528                 case FIELD_REQUEST_REMOVE:
529                 case FIELD_REQUEST_REMOVE_RESET:
530                     this.set_checkbox_from_data(data.value, false);
531                     break;
532                 default:
533                     break;
534             }
535         },
536
537         on_all_new_record: function(record)
538         {
539             this.new_record(record);
540         },
541
542         on_all_clear_records: function()
543         {
544             this.clear_table();
545
546         },
547
548         on_all_query_in_progress: function()
549         {
550             // XXX parent
551             this.spin();
552         }, // on_all_query_in_progress
553
554         on_all_query_done: function()
555         {
556             if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
557             this.table.fnAddData (this.buffered_lines);
558             this.buffered_lines=[];
559             
560             var self = this;
561             // if we've already received the slice query, we have not been able to set 
562             // checkboxes on the fly at that time (dom not yet created)
563             $.each(this.buffered_records_to_check, function(i, record) {
564                 if (debug) messages.debug ("querytable delayed turning on checkbox " + i + " record= " + record);
565                 self.set_checkbox_from_record(record, true);
566             });
567             this.buffered_records_to_check = [];
568
569             this.received_all_query = true;
570             // unspin once we have received both
571             if (this.received_all_query && this.received_query) this.unspin();
572
573         }, // on_all_query_done
574
575         /************************** PRIVATE METHODS ***************************/
576
577         /** 
578          * @brief QueryTable filtering function
579          */
580         _querytable_filter: function(oSettings, aData, iDataIndex)
581         {
582             var ret = true;
583             $.each (this.filters, function(index, filter) { 
584                 /* XXX How to manage checkbox ? */
585                 var key = filter[0]; 
586                 var op = filter[1];
587                 var value = filter[2];
588
589                 /* Determine index of key in the table columns */
590                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
591
592                 /* Unknown key: no filtering */
593                 if (typeof(col) == 'undefined')
594                     return;
595
596                 col_value=unfold.get_value(aData[col]);
597                 /* Test whether current filter is compatible with the column */
598                 if (op == '=' || op == '==') {
599                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
600                         ret = false;
601                 }else if (op == '!=') {
602                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
603                         ret = false;
604                 } else if(op=='<') {
605                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
606                         ret = false;
607                 } else if(op=='>') {
608                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
609                         ret = false;
610                 } else if(op=='<=' || op=='≤') {
611                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
612                         ret = false;
613                 } else if(op=='>=' || op=='≥') {
614                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
615                         ret = false;
616                 }else{
617                     // How to break out of a loop ?
618                     alert("filter not supported");
619                     return false;
620                 }
621
622             });
623             return ret;
624         },
625
626         _querytable_draw_callback: function()
627         {
628             /* 
629              * Handle clicks on checkboxes: reassociate checkbox click every time
630              * the table is redrawn    
631              */
632             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
633             //alert("fvf_add: "+fvf_add);
634             if(fvf_add==1){
635                 $("#addflowspaceform").unbind('click').click(this, this.fnAddflowspace);
636             }
637             else{
638                 $("[id='addflowspaceform'").unbind('click').click(this, this.fnModflowspace);
639             }
640             $("#cancel_addflowspaceform").unbind('click').click(this,this.fnCancel);
641
642             if (!this.table)
643                 return;
644
645             /* Remove pagination if we show only a few results */
646             var wrapper = this.table; //.parent().parent().parent();
647             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
648             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
649             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
650
651             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
652                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
653             } else {
654                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
655             }
656
657             if ( rowsToShow <= minRowsPerPage ) {
658                 $('.querytable_length', wrapper).css('visibility', 'hidden');
659             } else {
660                 $('.querytable_length', wrapper).css('visibility', 'visible');
661             }
662
663         },
664
665
666
667         _check_click: function(e) 
668         {
669             e.stopPropagation();
670
671             var self = e.data;
672             var id=this.id;
673
674             // this.id = key of object to be added... what about multiple keys ?
675             if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
676             //manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
677             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
678             
679         },
680
681         _selectAll: function() 
682         {
683             // requires jQuery id
684             var uuid=this.id.split("-");
685             var oTable=$("#querytable-"+uuid[1]).dataTable();
686             // Function available in QueryTable 1.9.x
687             // Filter : displayed data only
688             var filterData = oTable._('tr', {"filter":"applied"});   
689             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
690             if(filterData.length<=100){
691                 $.each(filterData, function(index, obj) {
692                     var last=$(obj).last();
693                     var key_value=unfold.get_value(last[0]);
694                     if(typeof($(last[0]).attr('checked'))=="undefined"){
695                         $.publish('selected', 'add/'+key_value);
696                     }
697                 });
698             }
699         },
700
701     });
702
703     $.plugin('UnivbrisFvf', UnivbrisFvf);
704
705   /* define the 'dom-checkbox' type for sorting in datatables 
706      http://datatables.net/examples/plug-ins/dom_sort.html
707      using trial and error I found that the actual column number
708      was in fact given as a third argument, and not second 
709      as the various online resources had it - go figure */
710     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
711         return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
712             return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
713         } );
714
715 };
716
717 })(jQuery);
718
719
720
721 function fnPopTable(e){
722                 //alert("e: "+e);
723                 //this.table = $("#univbris_flowspace_selection__table").dataTable();
724                 //alert(this.table);
725                 /**var rows = $("#univbris_flowspace_selection__table").dataTable().fnGetNodes();
726                 for(var i=0;i<rows.length;i++)
727                 {
728                         alert($(rows[i]).find("td:eq(0)").html()); 
729                 }
730                 **/
731
732
733                 //var anSelected = fnGetSelected( this.table );
734                 //var iRow = oTable.fnGetPosition( anSelected[0] );
735                 //alert(iRow);
736
737                 //var rowIndex = this.table.fnGetPosition( $(this).closest('tr')[0]);
738                 //alert(rowIndex);
739                 $("[id='addflowspaceform']").hide();
740                 $("#uob_fv_table_form :input").prop("disabled", false);
741                 $("#uob_fv_table_form").deserialize(e);
742                 $("[name='flowspace_name']").prop("disabled", true)
743                 $("#uob_fv_table_form :input").prop("disabled", true);
744                 $("[id='cancel_addflowspaceform']").prop("disabled", false);
745                 $("[id='cancel_addflowspaceform']").text('close');
746                 //$("[id='addflowspaceform'").hide();
747                 jQuery("#univbris_flowspace_selection").hide();
748                 jQuery("#uob_fv_table_form").show();
749 };
750
751
752
753 function fnGetSelected( oTableLocal )
754 {
755         var aReturn = new Array();
756         var aTrs = oTableLocal.fnGetNodes();
757         
758         for ( var i=0 ; i<aTrs.length ; i++ )
759         {
760                 if ( $(aTrs[i]).hasClass('row_selected') )
761                 {
762                         aReturn.push( aTrs[i] );
763                 }
764         }
765         return aReturn;
766 }
767
768 function serializeAnything (form){
769         var toReturn    = [];
770         var els         = $(form).find(':input').get();
771
772         $.each(els, function() {                        
773                 if (this.name && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
774                                 var val = $(this).val();
775                                 toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
776                         }
777                 });
778
779                 return toReturn.join("&").replace(/%20/g, "+");
780
781 }
782
783
784 (function ($) {
785     $.fn.extend({
786         deserialize : function (d, config) {
787             var data = d,
788                 currentDom,
789                 $current = null,
790                 $currentSavedValue = null,
791                 $self = this,
792                 i = 0,
793                 keyValPairString = [],
794                 keyValPairObject = {},
795                 tmp = null,
796                 defaults = null;
797
798             if (d === undefined || !$self.is('form')) {
799                 return $self;
800             }
801
802             defaults = {
803                 overwrite : true
804             };
805
806             config = $.extend(defaults, config);
807
808             if (d.constructor === String) {
809
810
811                 d = decodeURIComponent(d.replace(/\+/g, " "));
812
813                 keyValPairString = d.split('&');
814
815                 for (i = 0; i < keyValPairString.length; i++) {
816                     tmp = keyValPairString[i].split('=');
817                     keyValPairObject[tmp[0]] = tmp[1];
818
819                 }
820             }
821
822             $('input, select, textarea', $self).each(function (i) {
823
824                 $current = $(this);
825                 currentDom = $current.get(0);
826                 $currentSavedValue = keyValPairObject[$current.attr('name')];
827
828                 if (currentDom.disabled === true) {
829                     //current.val($currentSavedValue);
830                     return true;
831                 }
832
833                 if ($current.is('textarea')) {
834                     if ($currentSavedValue === undefined) {
835                         $current.val('');
836                     } else {
837                         $current.val($currentSavedValue);
838                     }
839                     return true;
840                 }
841
842                 if ($current.is('select')) {
843                     if ($currentSavedValue === undefined) {
844                         return true;
845                     } else {
846                         currentDom.selectedIndex = $currentSavedValue;
847                     }
848                     return true;
849                 }
850
851                 if ($current.is('input:radio')) {
852                     if ($currentSavedValue !== undefined) {
853
854                         $current.each(function () {
855                             if ($(this).val() === $currentSavedValue) {
856                                 $(this).get(0).checked = true;
857                             }
858                         });
859                     }
860
861                     return true;
862                 }
863
864                 if ($current.is('input:checkbox')) {
865                     currentDom.checked = ($current.val() === $currentSavedValue);
866                     return true;
867                 }
868
869                 if ($current.is('input:text, input:hidden')) {
870                     if ($currentSavedValue === undefined) {
871                         $current.val('');
872                     } else {
873                         $current.val($currentSavedValue);
874                         return true;
875                     }
876
877                 }
878
879             });
880
881             return $self;
882         }
883
884     });
885
886
887 }(jQuery));
888
889