Revised version of the resource page + related plugins
[myslice.git] / manifoldapi / static / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
21 Object.toType = (function toType(global) {
22   return function(obj) {
23     if (obj === global) {
24       return "global";
25     }
26     return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
27   }
28 })(this);
29
30 /* ------------------------------------------------------------ */
31
32 // Constants that should be somehow moved to a plugin.js file
33 var FILTER_ADDED   = 1;
34 var FILTER_REMOVED = 2;
35 var CLEAR_FILTERS  = 3;
36 var FIELD_ADDED    = 4;
37 var FIELD_REMOVED  = 5;
38 var CLEAR_FIELDS   = 6;
39 var NEW_RECORD     = 7;
40 var CLEAR_RECORDS  = 8;
41
42 /**
43  * event: FIELD_STATE_CHANGED
44  *
45  * Parameters:
46  *   dict :
47  *      .request    : ???? used to be FIELD_REQUEST_ADD / FIELD_REQUEST_REMOVE
48  *      .key        : ??? the key fields of the record
49  *      .value      : the key of the record who has received an update
50  *      .status     : the new state of the record
51  *        TODO rename to state, and use values from STATE_SET            
52  */
53 var FIELD_STATE_CHANGED = 9;
54
55 var IN_PROGRESS    = 101;
56 var DONE           = 102;
57
58 /* Update requests related to subqueries */
59
60 /**
61  * event: SET_ADD
62  *
63  * Parameters:
64  *    string : The key of the element being added
65  */
66 var SET_ADD        = 201;
67
68 /**
69  * event: SET_REMOVED
70  *
71  * Parameters:
72  *    string : The key of the element being removed
73  */
74 var SET_REMOVED    = 202;
75
76
77 // request
78 var FIELD_REQUEST_CHANGE  = 301;
79 var FIELD_REQUEST_ADD     = 302;
80 var FIELD_REQUEST_REMOVE  = 303;
81 var FIELD_REQUEST_ADD_RESET = 304;
82 var FIELD_REQUEST_REMOVE_RESET = 305;
83 // status (XXX Should be deprecated)
84 var FIELD_REQUEST_PENDING = 401;
85 var FIELD_REQUEST_SUCCESS = 402;
86 var FIELD_REQUEST_FAILURE = 403;
87 var STATUS_OKAY           = 404;
88 var STATUS_SET_WARNING    = 405;
89 var STATUS_ADD_WARNING    = 406;
90 var STATUS_REMOVE_WARNING = 407;
91 var STATUS_RESET          = 408;
92
93 /* Requests for query cycle */
94 var RUN_UPDATE     = 601;
95
96 /* MANIFOLD types */
97 var TYPE_VALUE  = 1;
98 var TYPE_RECORD = 2;
99 var TYPE_LIST_OF_VALUES = 3;
100 var TYPE_LIST_OF_RECORDS = 4;
101
102 /******************************************************************************
103  * QUERY STATUS (for manifold events)
104  ******************************************************************************/
105
106 var STATUS_NONE               = 500; // Query has not been started yet
107 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
108 var STATUS_GET_RECEIVED       = 502; // Success
109 var STATUS_GET_ERROR          = 503; // Error
110 var STATUS_UPDATE_PENDING     = 504;
111 var STATUS_UPDATE_IN_PROGRESS = 505;
112 var STATUS_UPDATE_RECEIVED    = 506;
113 var STATUS_UPDATE_ERROR       = 507;
114
115 /******************************************************************************
116  * QUERY STATE (for query_store)
117  ******************************************************************************/
118
119 // XXX Rendundant with query status ?
120
121 var QUERY_STATE_INIT        = 0;
122 var QUERY_STATE_INPROGRESS  = 1;
123 var QUERY_STATE_DONE        = 2;
124
125 /******************************************************************************
126  * RECORD STATES (for query_store)
127  ******************************************************************************/
128
129 var STATE_SET       = 0;
130 var STATE_WARNINGS  = 1;
131 var STATE_VISIBLE   = 2;
132
133 // STATE_SET : enum
134 var STATE_SET_IN            = 0;
135 var STATE_SET_OUT           = 1;
136 var STATE_SET_IN_PENDING    = 2;
137 var STATE_SET_OUT_PENDING   = 3;
138 var STATE_SET_IN_SUCCESS    = 4;
139 var STATE_SET_OUT_SUCCESS   = 5;
140 var STATE_SET_IN_FAILURE    = 6;
141 var STATE_SET_OUT_FAILURE   = 7;
142
143 // STATE_WARNINGS : dict
144
145 // STATE_VISIBLE : boolean
146
147 /******************************************************************************
148  * CONSTRAINTS
149  ******************************************************************************/
150
151 var CONSTRAINT_RESERVABLE_LEASE     = 0;
152
153 // A structure for storing queries
154
155 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled, domain_query_ext) {
156
157     /* Constructor */
158     if (typeof query == "undefined")
159         throw "Must pass a query in QueryExt constructor";
160     this.query                 = query;
161     this.parent_query_ext      = (typeof parent_query_ext      == "undefined") ? null  : parent_query_ext;
162     this.main_query_ext        = (typeof main_query_ext        == "undefined") ? null  : main_query_ext;
163     this.update_query_ext      = (typeof update_query_ext      == "undefined") ? null  : update_query_ext;
164     this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null  : update_query_orig_ext;
165     this.disabled              = (typeof disabled              == "undefined") ? false : disabled;
166
167     // A domain query is a query that is issued to retrieve all possible values for a set
168     // eg. all resources that can be attached to a slice
169     // It is null unless we are a subquery for which a domain query has been issued
170     this.domain_query_ext      = (typeof domain_query_ext      == "undefined") ? null  : domain_query_ext;
171
172     // Set members to buffer until the domain query is completed
173     // A list of keys
174     this.set_members = [];
175
176     // The set query is the query for which the domain query has been issued.
177     // It is null unless the query is a domain query
178     this.set_query_ext         = (typeof set_query_ext         == "undefined") ? null  : domain_query_ext;
179     
180     this.query_state = QUERY_STATE_INIT;
181
182     // Results from a query consists in a dict that maps keys to records
183     this.records = new Hashtable();
184
185     // Status is a dict that maps keys to record status
186     this.state = new Hashtable();
187
188     // Filters that impact visibility in the local interface
189     this.filters = [];
190
191     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
192 }
193
194 function QueryStore() {
195
196     this.main_queries     = {};
197     this.analyzed_queries = {};
198
199     /* Insertion */
200
201     this.insert = function(query) {
202         // We expect only main_queries are inserted
203         
204         /* If the query has not been analyzed, then we analyze it */
205         if (query.analyzed_query == null) {
206             query.analyze_subqueries();
207         }
208
209         /* We prepare the update query corresponding to the main query and store both */
210         /* Note: they have the same UUID */
211
212         // XXX query.change_action() should become deprecated
213         update_query = query.clone();
214         update_query.action = 'update';
215         update_query.analyzed_query.action = 'update';
216         update_query.params = {};
217         update_query_ext = new QueryExt(update_query);
218
219         /* We remember the original query to be able to reset it */
220         update_query_orig_ext = new QueryExt(update_query.clone());
221
222
223         /* We store the main query */
224         query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
225         manifold.query_store.main_queries[query.query_uuid] = query_ext;
226         /* Note: the update query does not have an entry! */
227
228
229         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
230         // XXX unless we have no subqueries ???
231         // we will complete with params when records are received... this has to be done by the manager
232         // SET_ADD, SET_REMOVE will change the status of the elements of the set
233         // UPDATE will change also, etc.
234         // XXX We need a proper structure to store this information...
235
236         // We also need to insert all queries and subqueries from the analyzed_query
237         // XXX We need the root of all subqueries
238         query.iter_subqueries(function(sq, data, parent_query) {
239             var parent_query_ext;
240             if (parent_query) {
241                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
242             } else {
243                 parent_query_ext = null;
244             }
245             // XXX parent_query_ext == false
246             // XXX main.subqueries = {} # Normal, we need analyzed_query
247             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
248
249             if (parent_query) {
250                 /* Let's issue a query for the subquery domain. This query will not need any update etc.
251                    eg. for resources in a slice, we also query all resources */
252                 var all_fields = manifold.metadata.get_field_names(sq.object);
253                 var domain_query = new ManifoldQuery('get', sq.object, 'now', [], {}, all_fields); 
254                 //var domain_query = new ManifoldQuery('get', sq.object); 
255
256                 console.log("Created domain query", domain_query);
257                 var domain_query_ext = new QueryExt(domain_query);
258
259                 domain_query_ext.set_query_ext = sq_ext;
260                 sq_ext.domain_query_ext = domain_query_ext;
261
262                 // One of these two is useless ?
263                 manifold.query_store.main_queries[domain_query.query_uuid] = domain_query_ext;
264                 manifold.query_store.analyzed_queries[domain_query.query_uuid] = domain_query_ext;
265
266                 // XXX This query is run before the plugins are initialized and listening
267                 manifold.run_query(domain_query);
268             }
269
270             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
271         });
272
273         // XXX We have spurious update queries...
274     }
275
276     /* Searching */
277
278     this.find_query_ext = function(query_uuid)
279     {
280         return this.main_queries[query_uuid];
281     }
282
283     this.find_query = function(query_uuid) 
284     {
285         return this.find_query_ext(query_uuid).query;
286     }
287
288     this.find_analyzed_query_ext = function(query_uuid)
289     {
290         return this.analyzed_queries[query_uuid];
291     }
292
293     this.find_analyzed_query = function(query_uuid) 
294     {
295         return this.find_analyzed_query_ext(query_uuid).query;
296     }
297
298     this.state_dict_create = function(default_set)
299     {
300         default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
301         var state_dict = {};
302         // We cannot use constants in literal definition, so...
303         state_dict[STATE_WARNINGS] = {};
304         state_dict[STATE_SET] = default_set;
305         state_dict[STATE_VISIBLE] = true;
306         return state_dict;
307     }
308
309     // RECORDS
310
311     this.set_records = function(query_uuid, records, default_set)
312     {
313         default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
314
315         var self = this;
316         var query_ext = this.find_analyzed_query_ext(query_uuid);
317         var record_key = manifold.metadata.get_key(query_ext.query.object);
318         $.each(records, function(i, record) {
319             var key = manifold.metadata.get_key(query_ext.query.object);
320             // ["start_time", "resource", "end_time"]
321             // ["urn"]
322             
323             var record_key_value = manifold.record_get_value(record, record_key);
324             query_ext.records.put(record_key_value, record);
325
326             if (!(query_ext.state.get(record_key_value)))
327                 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
328         });
329     }
330
331     this.get_records = function(query_uuid)
332     {
333         var query_ext = this.find_analyzed_query_ext(query_uuid);
334         return query_ext.records.values();
335     }
336
337     this.get_record = function(query_uuid, record_key)
338     {
339         var query_ext = this.find_analyzed_query_ext(query_uuid);
340         return query_ext.records.get(record_key);
341     }
342
343     this.add_record = function(query_uuid, record, new_state)
344     {
345         var query_ext = this.find_analyzed_query_ext(query_uuid);
346         
347         var key = manifold.metadata.get_key(query_ext.query.object);
348         var record_key = manifold.record_get_value(record, key);
349
350         var record_entry = query_ext.records.get(record_key);
351         if (!record_entry)
352             query_ext.records.put(record_key, record);
353
354         manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
355     }
356
357     this.remove_record = function(query_uuid, record, new_state)
358     {
359         var query_ext = this.find_analyzed_query_ext(query_uuid);
360         
361         var key = manifold.metadata.get_key(query_ext.query.object);
362         var record_key = manifold.record_get_value(record, key);
363
364         manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
365     }
366
367     this.iter_records = function(query_uuid, callback)
368     {
369         var query_ext = this.find_analyzed_query_ext(query_uuid);
370         query_ext.records.each(callback);
371         //callback = function(record_key, record)
372     }
373
374     this.iter_visible_records = function(query_uuid, callback)
375     {
376         var query_ext = this.find_analyzed_query_ext(query_uuid);
377         query_ext.records.each(function(record_key, record) {
378             if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
379                 callback(record_key, record);
380         });
381         //callback = function(record_key, record)
382
383     }
384
385     // STATE
386
387     this.set_record_state = function(query_uuid, result_key, state, value)
388     {
389         var query_ext = this.find_analyzed_query_ext(query_uuid);
390         var state_dict = query_ext.state.get(result_key);
391         if (!state_dict)
392             state_dict = this.state_dict_create();
393
394         state_dict[state] = value;
395
396         query_ext.state.put(result_key, state_dict);
397     }
398
399     this.get_record_state = function(query_uuid, result_key, state)
400     {
401         var query_ext = this.find_analyzed_query_ext(query_uuid);
402         var state_dict = query_ext.state.get(result_key);
403         if (!state_dict)
404             return null;
405         return state_dict[state];
406     }
407
408     // FILTERS
409
410     this.add_filter = function(query_uuid, filter)
411     {
412         var query_ext = this.find_analyzed_query_ext(query_uuid);
413         // XXX When we update a filter
414         query_ext.filters.push(filter);
415
416         this.apply_filters(query_uuid);
417
418     }
419
420     this.update_filter = function(query_uuid, filter)
421     {
422         // XXX
423
424         this.apply_filters(query_uuid);
425     }
426
427     this.remove_filter = function(query_uuid, filter)
428     {
429         var query_ext = this.find_analyzed_query_ext(query_uuid);
430         query_ext.filters = $.grep(query_ext.filters, function(x) {
431             return x == filter;
432         });
433
434         this.apply_filters(query_uuid);
435     }
436
437     this.get_filters = function(query_uuid)
438     {
439         var query_ext = this.find_analyzed_query_ext(query_uuid);
440         return query_ext.filters;
441     }
442
443     this.apply_filters = function(query_uuid)
444     {
445         // Toggle visibility of records according to the different filters.
446
447         var self = this;
448         var filters = this.get_filters(query_uuid);
449         var col_value;
450
451         // Adapted from querytable._querytable_filter()
452
453         this.iter_records(query_uuid, function(record_key, record) {
454             var visible = true;
455
456             // We go through each filter and decide whether it affects the visibility of the record
457             $.each(filters, function(index, filter) {
458                 var key = filter[0];
459                 var op = filter[1];
460                 var value = filter[2];
461
462
463                 /* We do some special handling for the manifold:status filter
464                  * predicates. */
465
466                 if (key == 'manifold:status') {
467                     if (op != '=' && op != '==') {
468                         // Unsupported filter, let's ignore it
469                         console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
470                         return true; // ~ continue
471                     }
472
473                     var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
474                     var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
475
476                     switch (value) {
477                         case 'reserved':
478                             visible = (record_state == STATE_SET_IN) 
479                                    || (record_state == STATE_SET_OUT_PENDING)
480                                    || (record_state == STATE_SET_IN_SUCCESS)
481                                    || (record_state == STATE_SET_OUT_FAILURE);
482                             // visible = true  => ~ continue
483                             // visible = false => ~ break
484                             return visible; 
485
486                         case 'unconfigured':
487                             var in_set = (record_state == STATE_SET_IN) // should not have warnings
488                                    || (record_state == STATE_SET_IN_PENDING)
489                                    || (record_state == STATE_SET_IN_SUCCESS)
490                                    || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
491                             visible = (in_set && !$.isEmptyObject(record_warnings));
492                             return visible; 
493
494                         case 'pending':
495                             visible = (record_state == STATE_SET_IN_PENDING) 
496                                    || (record_state == STATE_SET_OUT_PENDING);
497                             return visible; 
498                     }
499                     return false; // ~ break
500                 }
501
502                 /* Normal filtering behaviour (according to the record content) follows... */
503                 col_value = manifold.record_get_value(record, record_key);
504
505                 // When the filter does not match, we hide the column by default
506                 if (col_value === 'undefined') {
507                     visible = false;
508                     return false; // ~ break
509                 }
510
511                 // XXX This should accept pluggable filtering functions.
512
513
514                 /* Test whether current filter is compatible with the column */
515                 if (op == '=' || op == '==') {
516                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
517                         visible = false;
518                 }else if (op == 'included') {
519                     $.each(value, function(i,x) {
520                       if(x == col_value){
521                           visible = true;
522                           return false; // ~ break
523                       }else{
524                           visible = false;
525                       }
526                     });
527                 }else if (op == '!=') {
528                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
529                         visible = false;
530                 } else if(op=='<') {
531                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
532                         visible = false;
533                 } else if(op=='>') {
534                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
535                         visible = false;
536                 } else if(op=='<=' || op=='≤') {
537                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
538                         visible = false;
539                 } else if(op=='>=' || op=='≥') {
540                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
541                         visible = false;
542                 }else{
543                     // How to break out of a loop ?
544                     alert("filter not supported");
545                     return false; // break
546                 }
547
548             });
549
550             // Set the visibility status in the query store
551             self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
552         });
553
554     }
555
556 }
557
558 /*!
559  * This namespace holds functions for globally managing query objects
560  * \Class Manifold
561  */
562 var manifold = {
563
564     /************************************************************************** 
565      * Helper functions
566      **************************************************************************/ 
567
568     separator: '__',
569
570     get_type: function(variable) {
571         switch(Object.toType(variable)) {
572             case 'number':
573             case 'string':
574                 return TYPE_VALUE;
575             case 'object':
576                 return TYPE_RECORD;
577             case 'array':
578                 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
579                     return TYPE_LIST_OF_RECORDS;
580                 else
581                     return TYPE_LIST_OF_VALUES;
582         }
583     },
584
585     /**
586      *  Args:
587      *      fields: A String instance (field name), or a set of String instances
588      *          (field names) # XXX tuple !!
589      *  Returns:
590      *      If fields is a String,  return the corresponding value.
591      *      If fields is a set, return a tuple of corresponding value.
592      *
593      *  Raises:
594      *      KeyError if at least one of the fields is not found
595      */
596     record_get_value: function(record, fields) 
597     {
598         if (typeof(fields) === 'string') {
599             if (fields.indexOf('.') != -1) {
600                 key_subkey = key.split('.', 2);
601                 key     = key_subkey[0]; 
602                 subkey  = key_subkey[1];
603
604                 if (record.indexOf(key) == -1) {
605                     return null;
606                 }
607                 // Tests if the following is an array (typeof would give object)
608                 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
609                     // Records
610                     return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
611                 } else if (typeof(record) == 'object') {
612                     // Record
613                     return manifold.record_get_value(record[key], subkey);
614                 } else {
615                     console.log('Unknown field');
616                 }
617             } else {
618                 return record[fields];
619             }
620         } else {
621             // see. get_map_entries
622             if (fields.length == 1)
623                 return manifold.record_get_value(record, fields[0])
624
625             // Build a new record
626             var ret = {};
627             $.each(fields, function(i, field) {
628                 ret[field] = manifold.record_get_value(record, field);
629             });
630             ret.hashCode = record.hashCode;
631             ret.equals = record.equals;
632             return ret;
633             // this was an array, we want a dictionary
634             //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
635                 
636         }
637     },
638
639     record_hashcode: function(key_fields)
640     {
641         return function() {
642             ret = "";
643             for (i=0; i < key_fields.length; i++)
644                 ret += "@@" + this[key_fields[i]];
645             return ret;
646         };
647     },
648
649     record_equals: function(key_fields)
650     {
651         var self = this;
652
653         return function(other) {
654             for (i=0; i < key_fields.length; i++) {
655                 var this_value  = this[key_fields[i]];
656                 var other_value = other[key_fields[i]];
657
658                 var this_type = self.get_type(this_value);
659                 var other_type = self.get_type(other_value);
660                 if (this_type != other_type)
661                     return false;
662
663                 switch (this_type) {
664                     case TYPE_VALUE:
665                     case TYPE_LIST_OF_VALUES:
666                         if (this_value != other_value)
667                             return false;
668                         break;
669                     case TYPE_RECORD:
670                         if (!(record_equals(this_value, other_value)))
671                             return false;
672                         break;
673                     case TYPE_LIST_OF_RECORDS:
674                         if (this_value.length != other_value.length)
675                             return false;
676                         for (i = 0; i < this_value.length; i++)
677                             if (!(record_equals(this_value, other_value)))
678                                 return false;
679                         break;
680                 }
681             }
682             return true;
683         };
684     },
685
686
687     /************************************************************************** 
688      * Metadata management
689      **************************************************************************/ 
690
691      metadata: {
692
693         get_table: function(method) {
694             var table = MANIFOLD_METADATA[method];
695             return (typeof table === 'undefined') ? null : table;
696         },
697
698         get_columns: function(method) {
699             var table = this.get_table(method);
700             if (!table) {
701                 return null;
702             }
703
704             return (typeof table.column === 'undefined') ? null : table.column;
705         },
706
707         get_field_names: function(method)
708         {
709             var columns = this.get_columns(method);
710             if (!columns)
711                 return null;
712             return $.map(columns, function (x) { return x.name });
713         },
714
715         get_key: function(method) {
716             var table = this.get_table(method);
717             if (!table)
718                 return null;
719
720             return (typeof table.key === 'undefined') ? null : table.key;
721         },
722
723
724         get_column: function(method, name) {
725             var columns = this.get_columns(method);
726             if (!columns)
727                 return null;
728
729             $.each(columns, function(i, c) {
730                 if (c.name == name)
731                     return c
732             });
733             return null;
734         },
735
736         get_type: function(method, name) {
737             var table = this.get_table(method);
738             if (!table)
739                 return null;
740
741             var match = $.grep(table.column, function(x) { return x.name == name });
742             if (match.length == 0) {
743                 return undefined;
744             } else {
745                 return match[0].type;
746             }
747             return (typeof table.type === 'undefined') ? null : table.type;
748         }
749
750      },
751
752     /************************************************************************** 
753      * Query management
754      **************************************************************************/ 
755
756     query_store: new QueryStore(),
757
758     // XXX Remaining functions are deprecated since they are replaced by the query store
759
760     /*!
761      * Associative array storing the set of queries active on the page
762      * \memberof Manifold
763      */
764     all_queries: {},
765
766     /*!
767      * Insert a query in the global hash table associating uuids to queries.
768      * If the query has no been analyzed yet, let's do it.
769      * \fn insert_query(query)
770      * \memberof Manifold
771      * \param ManifoldQuery query Query to be added
772      */
773     insert_query : function (query) { 
774         // NEW API
775         manifold.query_store.insert(query);
776
777         // Run
778         manifold.run_query(query);
779
780         // FORMER API
781         if (query.analyzed_query == null) {
782             query.analyze_subqueries();
783         }
784         manifold.all_queries[query.query_uuid]=query;
785     },
786
787     /*!
788      * Returns the query associated to a UUID
789      * \fn find_query(query_uuid)
790      * \memberof Manifold
791      * \param string query_uuid The UUID of the query to be returned
792      */
793     find_query : function (query_uuid) { 
794         return manifold.all_queries[query_uuid];
795     },
796
797     /************************************************************************** 
798      * Query execution
799      **************************************************************************/ 
800
801     // trigger a query asynchroneously
802     proxy_url : '/manifold/proxy/json/',
803
804     // reasonably low-noise, shows manifold requests coming in and out
805     asynchroneous_debug : true,
806     // print our more details on result publication and related callbacks
807     pubsub_debug : false,
808
809     /**
810      * \brief We use js function closure to be able to pass the query (array)
811      * to the callback function used when data is received
812      */
813     success_closure: function(query, publish_uuid, callback) {
814         return function(data, textStatus) {
815             manifold.asynchroneous_success(data, query, publish_uuid, callback);
816         }
817     },
818
819     run_query: function(query, callback)
820         {
821         // default value for callback = null
822         if (typeof callback === 'undefined')
823             callback = null; 
824
825         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
826         query_ext.query_state = QUERY_STATE_INPROGRESS;
827
828         var query_json = JSON.stringify(query);
829
830         // Inform plugins about the progress
831         query.iter_subqueries(function (sq) {
832             var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
833             sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
834
835             manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
836         });
837
838
839         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
840     },
841
842     // XXX DEPRECATED
843     // Executes all async. queries - intended for the javascript header to initialize queries
844     // input queries are specified as a list of {'query_uuid': <query_uuid> }
845     // each plugin is responsible for managing its spinner through on_query_in_progress
846     asynchroneous_exec : function (query_exec_tuples) {
847         
848         // Loop through input array, and use publish_uuid to publish back results
849         $.each(query_exec_tuples, function(index, tuple) {
850             var query=manifold.find_query(tuple.query_uuid);
851             var query_json=JSON.stringify (query);
852             var publish_uuid=tuple.publish_uuid;
853             // by default we publish using the same uuid of course
854             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
855             if (manifold.pubsub_debug) {
856                 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
857             }
858
859             query.iter_subqueries(function (sq) {
860                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
861             });
862
863             // not quite sure what happens if we send a string directly, as POST data is named..
864             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
865             $.post(manifold.proxy_url, {'json':query_json}, 
866                    manifold.success_closure(query, publish_uuid, tuple.callback));
867         })
868     },
869
870     /**
871      * \brief Forward a query to the manifold backend
872      * \param query (dict) the query to be executed asynchronously
873      * \param callback (function) the function to be called when the query terminates
874      */
875     forward: function(query, callback) {
876         var query_json = JSON.stringify(query);
877         $.post(manifold.proxy_url, {'json': query_json} , 
878                manifold.success_closure(query, query.query_uuid, callback));
879     },
880
881     /*!
882      * Returns whether a query expects a unique results.
883      * This is the case when the filters contain a key of the object
884      * \fn query_expects_unique_result(query)
885      * \memberof Manifold
886      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
887      */
888     query_expects_unique_result: function(query) {
889         /* XXX we need functions to query metadata */
890         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
891         /* TODO requires keys in metadata */
892         return true;
893     },
894
895     /*!
896      * Publish result
897      * \fn publish_result(query, results)
898      * \memberof Manifold
899      * \param ManifoldQuery query Query which has received results
900      * \param array results results corresponding to query
901      */
902     publish_result: function(query, result) {
903         if (typeof result === 'undefined')
904             result = [];
905
906         // NEW PLUGIN API
907         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
908         if (manifold.pubsub_debug)
909             messages.debug(".. publish_result (1) ");
910         var count=0;
911         $.each(result, function(i, record) {
912             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
913             count += 1;
914         });
915         if (manifold.pubsub_debug) 
916             messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
917         manifold.raise_record_event(query.query_uuid, DONE);
918         if (manifold.pubsub_debug) 
919             messages.debug(".. publish_result (3) has used NEW API to say DONE");
920
921         // OLD PLUGIN API BELOW
922         /* Publish an update announce */
923         var channel="/results/" + query.query_uuid + "/changed";
924         if (manifold.pubsub_debug) 
925             messages.debug(".. publish_result (4) OLD API on channel" + channel);
926
927         $.publish(channel, [result, query]);
928
929         if (manifold.pubsub_debug) 
930             messages.debug(".. publish_result (5) END q=" + query.__repr());
931     },
932
933     store_records: function(query, records) {
934         // Store records
935         var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
936         if (query_ext.set_query_ext) {
937             // We have a domain query
938             // The results are stored in the corresponding set_query
939             manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records)
940             
941         } else if (query_ext.domain_query_ext) {
942             // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
943             // Has it a domain query, and has it completed ?
944             $.each(records, function(i, record) {
945                 var key = manifold.metadata.get_key(query.object);
946                 var record_key = manifold.record_get_value(record, key);
947                 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
948             });
949
950         } else {
951             // We have a normal query
952             manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
953         }
954     },
955
956     /*!
957      * Recursively publish result
958      * \fn publish_result_rec(query, result)
959      * \memberof Manifold
960      * \param ManifoldQuery query Query which has received result
961      * \param array result result corresponding to query
962      *
963      * Note: this function works on the analyzed query
964      */
965     publish_result_rec: function(query, records) {
966         /* If the result is not unique, only publish the top query;
967          * otherwise, publish the main object as well as subqueries
968          * XXX how much recursive are we ?
969          */
970         if (manifold.pubsub_debug)
971              messages.debug (">>>>> publish_result_rec " + query.object);
972         if (manifold.query_expects_unique_result(query)) {
973             /* Also publish subqueries */
974             $.each(query.subqueries, function(object, subquery) {
975                 manifold.publish_result_rec(subquery, records[0][object]);
976                 /* TODO remove object from result */
977             });
978         }
979         if (manifold.pubsub_debug) 
980             messages.debug ("===== publish_result_rec " + query.object);
981
982         var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
983         query_ext.query_state = QUERY_STATE_DONE;
984
985         this.store_records(query, records);
986
987         var pub_query;
988
989         if (query_ext.set_query_ext) {
990             if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
991                 return;
992             pub_query = query_ext.set_query_ext.query;
993         } else if (query_ext.domain_query_ext) {
994             if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
995                 return;
996             pub_query = query;
997         } else {
998             pub_query = query;
999         }
1000         // We can only publish results if the query (and its related domain query) is complete
1001         manifold.publish_result(pub_query, records);
1002
1003         if (manifold.pubsub_debug) 
1004             messages.debug ("<<<<< publish_result_rec " + query.object);
1005     },
1006
1007     setup_update_query: function(query, records) {
1008         // We don't prepare an update query if the result has more than 1 entry
1009         if (records.length != 1)
1010             return;
1011         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1012
1013         var record = records[0];
1014
1015         var update_query_ext = query_ext.update_query_ext;
1016
1017         console.log("Update case not handled yet!");
1018         if (!update_query_ext)
1019             return;
1020
1021         var update_query = update_query_ext.query;
1022         var update_query_ext = query_ext.update_query_ext;
1023         var update_query_orig = query_ext.update_query_orig_ext.query;
1024
1025         // Testing whether the result has subqueries (one level deep only)
1026         // iif the query has subqueries
1027         var count = 0;
1028         var obj = query.analyzed_query.subqueries;
1029         for (method in obj) {
1030             if (obj.hasOwnProperty(method)) {
1031                 var key = manifold.metadata.get_key(method);
1032                 if (!key)
1033                     continue;
1034                 var sq_keys = [];
1035                 var subrecords = record[method];
1036                 if (!subrecords)
1037                     continue
1038                 $.each(subrecords, function (i, subrecord) {
1039                     sq_keys.push(manifold.record_get_value(subrecord, key));
1040                 });
1041                 update_query.params[method] = sq_keys;
1042                 update_query_orig.params[method] = sq_keys.slice();
1043                 count++;
1044             }
1045         }
1046
1047         if (count > 0) {
1048             update_query_ext.disabled = false;
1049             update_query_orig_ext.disabled = false;
1050         }
1051     },
1052
1053     process_get_query_records: function(query, records) {
1054         this.setup_update_query(query, records);
1055         
1056         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1057         query_ext.query_state = QUERY_STATE_DONE;
1058
1059         /* Publish full results */
1060         var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1061         manifold.publish_result_rec(tmp_query, records);
1062     },
1063
1064     make_records: function(object, records)
1065     {
1066         $.each(records, function(i, record) {
1067             manifold.make_record(object, record);
1068         });
1069     },
1070
1071     make_record: function(object, record)
1072     {
1073         // To make an object a record, we just add the hash function
1074         var key = manifold.metadata.get_key(object);
1075         record.hashCode = manifold.record_hashcode(key.sort());
1076         record.equals   = manifold.record_equals(key);
1077
1078         // Looking after subrecords
1079         for (var field in record) {
1080             var result_value = record[field];
1081
1082             switch (this.get_type(result_value)) {
1083                 case TYPE_RECORD:
1084                     var subobject = manifold.metadata.get_type(object, field);
1085                     if (subobject)
1086                         manifold.make_record(subobject, result_value);
1087                     break;
1088                 case TYPE_LIST_OF_RECORDS:
1089                     var subobject = manifold.metadata.get_type(object, field);
1090                     if (subobject)
1091                         manifold.make_records(subobject, result_value);
1092                     break;
1093             }
1094         }
1095     },
1096
1097     /**
1098      * 
1099      * What we need to do when receiving results from an update query:
1100      * - differences between what we had, what we requested, and what we obtained
1101      *    . what we had : update_query_orig (simple fields and set fields managed differently)
1102      *    . what we requested : update_query
1103      *    . what we received : records
1104      * - raise appropriate events
1105      *
1106      * The normal process is that results similar to Get will be pushed in the
1107      * pubsub mechanism, thus repopulating everything while we only need
1108      * diff's. This means we need to move the publish functionalities in the
1109      * previous 'process_get_query_records' function.
1110      */
1111     process_update_query_records: function(query, records) {
1112         // XXX XXX XXX XXX
1113         // XXX XXX XXX XXX
1114         // XXX XXX XXX XXX
1115         // XXX XXX XXX XXX
1116         // XXX XXX XXX XXX
1117         // XXX XXX XXX XXX
1118         // XXX XXX XXX XXX
1119         // XXX XXX XXX XXX
1120         // XXX XXX XXX XXX
1121         // XXX XXX XXX XXX
1122         // XXX XXX XXX XXX
1123         // XXX XXX XXX XXX
1124         // XXX XXX XXX XXX
1125         // XXX XXX XXX XXX
1126         // XXX XXX XXX XXX
1127         // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1128         var query_uuid        = query.query_uuid;
1129         var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
1130         var update_query      = query_ext.main_query_ext.update_query_ext.query;
1131         var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1132         
1133         // Since we update objects one at a time, we can get the first record
1134         var record = records[0];
1135
1136         // Let's iterate over the object properties
1137         for (var field in record) {
1138             var result_value = record[field];
1139             switch (this.get_type(result_value)) {
1140                 case TYPE_VALUE:
1141                     // Did we ask for a change ?
1142                     var update_value = update_query[field];
1143                     if (!update_value)
1144                         // Not requested, if it has changed: OUT OF SYNC
1145                         // How we can know ?
1146                         // We assume it won't have changed
1147                         continue;
1148
1149                     if (!result_value)
1150                         throw "Internal error";
1151
1152                     data = {
1153                         request: FIELD_REQUEST_CHANGE,
1154                         key   : field,
1155                         value : update_value,
1156                         status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
1157                     }
1158                     manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1159
1160                     break;
1161                 case TYPE_RECORD:
1162                     throw "Not implemented";
1163                     break;
1164
1165                 case TYPE_LIST_OF_VALUES:
1166                     // Same as list of records, but we don't have to extract keys
1167                     
1168                     // The rest of exactly the same (XXX factorize)
1169                     var update_keys  = update_query_orig.params[field];
1170                     var query_keys   = update_query.params[field];
1171                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1172                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1173
1174
1175                     $.each(added_keys, function(i, key) {
1176                         if ($.inArray(key, result_value) == -1) {
1177                             data = {
1178                                 request: FIELD_REQUEST_ADD,
1179                                 key   : field,
1180                                 value : key,
1181                                 status: FIELD_REQUEST_FAILURE,
1182                             }
1183                         } else {
1184                             data = {
1185                                 request: FIELD_REQUEST_ADD,
1186                                 key   : field,
1187                                 value : key,
1188                                 status: FIELD_REQUEST_SUCCESS,
1189                             }
1190                         }
1191                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1192                     });
1193                     $.each(removed_keys, function(i, key) {
1194                         if ($.inArray(key, result_keys) == -1) {
1195                             data = {
1196                                 request: FIELD_REQUEST_REMOVE,
1197                                 key   : field,
1198                                 value : key,
1199                                 status: FIELD_REQUEST_SUCCESS,
1200                             }
1201                         } else {
1202                             data = {
1203                                 request: FIELD_REQUEST_REMOVE,
1204                                 key   : field,
1205                                 value : key,
1206                                 status: FIELD_REQUEST_FAILURE,
1207                             }
1208                         }
1209                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1210                     });
1211
1212
1213                     break;
1214                 case TYPE_LIST_OF_RECORDS:
1215                     // example: slice.resource
1216                     //  - update_query_orig.params.resource = resources in slice before update
1217                     //  - update_query.params.resource = resource requested in slice
1218                     //  - keys from field = resources obtained
1219                     var key = manifold.metadata.get_key(field);
1220                     if (!key)
1221                         continue;
1222                     if (key.length > 1) {
1223                         throw "Not implemented";
1224                         continue;
1225                     }
1226                     key = key[0];
1227
1228                     /* XXX should be modified for multiple keys */
1229                     var result_keys  = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1230
1231                     var update_keys  = update_query_orig.params[field];
1232                     var query_keys   = update_query.params[field];
1233                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1234                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1235
1236
1237                     $.each(added_keys, function(i, key) {
1238                         if ($.inArray(key, result_keys) == -1) {
1239                             data = {
1240                                 request: FIELD_REQUEST_ADD,
1241                                 key   : field,
1242                                 value : key,
1243                                 status: FIELD_REQUEST_FAILURE,
1244                             }
1245                         } else {
1246                             data = {
1247                                 request: FIELD_REQUEST_ADD,
1248                                 key   : field,
1249                                 value : key,
1250                                 status: FIELD_REQUEST_SUCCESS,
1251                             }
1252                         }
1253                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1254                     });
1255                     $.each(removed_keys, function(i, key) {
1256                         if ($.inArray(key, result_keys) == -1) {
1257                             data = {
1258                                 request: FIELD_REQUEST_REMOVE,
1259                                 key   : field,
1260                                 value : key,
1261                                 status: FIELD_REQUEST_SUCCESS,
1262                             }
1263                         } else {
1264                             data = {
1265                                 request: FIELD_REQUEST_REMOVE,
1266                                 key   : field,
1267                                 value : key,
1268                                 status: FIELD_REQUEST_FAILURE,
1269                             }
1270                         }
1271                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1272                     });
1273
1274
1275                     break;
1276             }
1277         }
1278         
1279         // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1280         this.setup_update_query(query, records);
1281     },
1282
1283     process_query_records: function(query, records) {
1284         if (query.action == 'get') {
1285             this.process_get_query_records(query, records);
1286         } else if (query.action == 'update') {
1287             this.process_update_query_records(query, records);
1288         }
1289     },
1290
1291     // if set callback is provided it is called
1292     // most of the time publish_uuid will be query.query_uuid
1293     // however in some cases we wish to publish the result under a different uuid
1294     // e.g. an updater wants to publish its result as if from the original (get) query
1295     asynchroneous_success : function (data, query, publish_uuid, callback) {
1296         // xxx should have a nicer declaration of that enum in sync with the python code somehow
1297         
1298         var start = new Date();
1299         if (manifold.asynchroneous_debug)
1300             messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1301
1302         if (data.code == 2) { // ERROR
1303             // We need to make sense of error codes here
1304             alert("Your session has expired, please log in again");
1305             localStorage.removeItem('user');
1306             window.location="/logout/";
1307             if (manifold.asynchroneous_debug) {
1308                 duration=new Date()-start;
1309                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1310             }
1311             return;
1312         }
1313         if (data.code == 1) { // WARNING
1314             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1315             // publish error code and text message on a separate channel for whoever is interested
1316             if (publish_uuid)
1317                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1318
1319         }
1320
1321         // If a callback has been specified, we redirect results to it 
1322         if (!!callback) { 
1323             callback(data); 
1324             if (manifold.asynchroneous_debug) {
1325                 duration=new Date()-start;
1326                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1327             }
1328             return; 
1329         }
1330
1331         if (manifold.asynchroneous_debug) 
1332             messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1333
1334         // once everything is checked we can use the 'value' part of the manifoldresult
1335         var result=data.value;
1336         if (result) {
1337             /* Eventually update the content of related queries (update, etc) */
1338             manifold.make_records(query.object, result);
1339             this.process_query_records(query, result);
1340
1341             /* Publish results: disabled here, done in the previous call */
1342             //tmp_query = manifold.find_query(query.query_uuid);
1343             //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1344         }
1345         if (manifold.asynchroneous_debug) {
1346             duration=new Date()-start;
1347             messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1348         }
1349
1350     },
1351
1352     /************************************************************************** 
1353      * Plugin API helpers
1354      **************************************************************************/ 
1355
1356     raise_event_handler: function(type, query_uuid, event_type, value) {
1357         if (manifold.pubsub_debug)
1358             messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1359         if ((type != 'query') && (type != 'record'))
1360             throw 'Incorrect type for manifold.raise_event()';
1361         // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1362         // this should be fixed upstream in manifold I expect
1363         if (query_uuid === undefined) {
1364             messages.warning("undefined query in raise_event_handler");
1365             return;
1366         }
1367
1368         // notify the change to objects that either listen to this channel specifically,
1369         // or to the wildcard channel
1370         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1371
1372         $.each(channels, function(i, channel) {
1373             if (value === undefined) {
1374                 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1375                 $('.pubsub').trigger(channel, [event_type]);
1376             } else {
1377                 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1378                 $('.pubsub').trigger(channel, [event_type, value]);
1379             }
1380         });
1381     },
1382
1383     raise_query_event: function(query_uuid, event_type, value) {
1384         manifold.raise_event_handler('query', query_uuid, event_type, value);
1385     },
1386
1387     raise_record_event: function(query_uuid, event_type, value) {
1388         manifold.raise_event_handler('record', query_uuid, event_type, value);
1389     },
1390
1391
1392     raise_event: function(query_uuid, event_type, value) {
1393         // Query uuid has been updated with the key of a new element
1394         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
1395         query = query_ext.query;
1396
1397         switch(event_type) {
1398
1399             case FIELD_STATE_CHANGED:
1400                 // value is an object (request, key, value, status)
1401                 // update is only possible is the query is not pending, etc
1402                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1403                 // we should map SET_ADD on this...
1404
1405                 // 1. Update internal query store about the change in status
1406
1407                 // 2. Update the update query
1408                 update_query      = query_ext.main_query_ext.update_query_ext.query;
1409                 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1410
1411                 switch(value.request) {
1412                     case FIELD_REQUEST_CHANGE:
1413                         if (update_query.params[value.key] === undefined)
1414                             update_query.params[value.key] = Array();
1415                         update_query.params[value.key] = value.value;
1416                         break;
1417                     case FIELD_REQUEST_ADD:
1418                         if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
1419                             value.request = FIELD_REQUEST_ADD_RESET;
1420                         if (update_query.params[value.key] === undefined)
1421                             update_query.params[value.key] = Array();
1422                         update_query.params[value.key].push(value.value);
1423                         break;
1424                     case FIELD_REQUEST_REMOVE:
1425                         if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
1426                             value.request = FIELD_REQUEST_REMOVE_RESET;
1427
1428                         var arr = update_query.params[value.key];
1429                         arr = $.grep(arr, function(x) { return x != value.value; });
1430                         if (update_query.params[value.key] === undefined)
1431                             update_query.params[value.key] = Array();
1432                         update_query.params[value.key] = arr;
1433
1434                         break;
1435                     case FIELD_REQUEST_ADD_RESET:
1436                     case FIELD_REQUEST_REMOVE_RESET:
1437                         // XXX We would need to keep track of the original query
1438                         throw "Not implemented";
1439                         break;
1440                 }
1441
1442                 // 3. Inform others about the change
1443                 // a) the main query...
1444                 manifold.raise_record_event(query_uuid, event_type, value);
1445
1446                 // b) subqueries eventually (dot in the key)
1447                 // Let's unfold 
1448                 var path_array = value.key.split('.');
1449                 var value_key = value.key.split('.');
1450
1451                 var cur_query = query;
1452                 if (cur_query.analyzed_query)
1453                     cur_query = cur_query.analyzed_query;
1454                 $.each(path_array, function(i, method) {
1455                     cur_query = cur_query.subqueries[method];
1456                     value_key.shift(); // XXX check that method is indeed shifted
1457                 });
1458                 value.key = value_key;
1459
1460                 manifold.raise_record_event(cur_query.query_uuid, event_type, value);
1461
1462                 // XXX make this DOT a global variable... could be '/'
1463                 break;
1464
1465             case SET_ADD:
1466             case SET_REMOVED:
1467
1468                 /* An object has been added to / removed from a set : its
1469                  * status become pending or reset to the original state. We
1470                  * update the record status in the analyzed queries.
1471                  *
1472                  * XXX Shall we update something in the main_query ?
1473                  */
1474                 var prev_state, new_state;
1475
1476                 prev_state = manifold.query_store.get_record_state(query_uuid, value, STATE_SET);
1477                 if (prev_state === null)
1478                     prev_state = STATE_SET_OUT;
1479
1480                 if (event_type == SET_ADD) {
1481                     switch (prev_state) {
1482                         case STATE_SET_OUT:
1483                         case STATE_SET_OUT_SUCCESS:
1484                         case STATE_SET_IN_FAILURE:
1485                             new_state = STATE_SET_IN_PENDING;
1486                             break;
1487
1488                         case STATE_SET_OUT_PENDING:
1489                             new_state = STATE_SET_IN;
1490                             break;
1491
1492                         case STATE_SET_IN:
1493                         case STATE_SET_IN_PENDING:
1494                         case STATE_SET_IN_SUCCESS:
1495                         case STATE_SET_OUT_FAILURE:
1496                             console.log("Inconsistent state: already in");
1497                             return;
1498                     }
1499                 } else { // SET_REMOVE
1500                     switch (prev_state) {
1501                         case STATE_SET_IN:
1502                         case STATE_SET_IN_SUCCESS:
1503                         case STATE_SET_OUT_FAILURE:
1504                             new_state = STATE_SET_OUT_PENDING;
1505                             break;
1506
1507                         case STATE_SET_IN_PENDING:
1508                             new_state = STATE_SET_OUT;
1509                             break;  
1510
1511                         case STATE_SET_OUT:
1512                         case STATE_SET_OUT_PENDING:
1513                         case STATE_SET_OUT_SUCCESS:
1514                         case STATE_SET_IN_FAILURE:
1515                             console.log("Inconsistent state: already out");
1516                             return;
1517                     }
1518                 }
1519
1520                 
1521                 var resource_key = value;
1522
1523                 if (event_type == SET_ADD)
1524                     manifold.query_store.add_record(query_uuid, resource_key, new_state);
1525                 else
1526                     manifold.query_store.remove_record(query_uuid, resource_key, new_state);
1527
1528                 var record = manifold.query_store.get_record(query_uuid, resource_key);
1529
1530                 /* CONSTRAINTS */
1531
1532                 // CONSTRAINT_RESERVABLE_LEASE
1533                 // 
1534                 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1535                 var is_reservable = (record.exclusive == true);
1536                 if (is_reservable) {
1537                     var warnings = manifold.query_store.get_record_state(query_uuid, resource_key, STATE_WARNINGS);
1538
1539                     if (event_type == SET_ADD) {
1540                         // We should have a lease_query associated
1541                         var lease_query = query_ext.parent_query_ext.query.subqueries['lease'];
1542                         var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1543                         // Do we have lease records with this resource
1544                         var lease_records = $.grep(lease_query_ext.records, function(lease_key, lease) {
1545                             return lease['resource'] == value;
1546                         });
1547                         if (lease_records.length == 0) {
1548                             // Sets a warning
1549                             // XXX Need for a better function to manage warnings
1550                             var warn = "No lease defined for this reservable resource.";
1551                             warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1552                         } else {
1553                             // Lease are defined, delete the warning in case it was set previously
1554                             delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1555                         }
1556                     } else {
1557                         // Remove warnings attached to this resource
1558                         delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1559                     }
1560
1561                     manifold.query_store.set_record_state(query_uuid, resource_key, STATE_WARNINGS, warnings);
1562
1563                 }
1564                 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1565                 data = {
1566                     request: null,
1567                     key   : null,
1568                     value : resource_key,
1569                     status: STATE_WARNINGS
1570                 };
1571                 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1572
1573                 // -) When a lease is added, it might remove the warning associated to a reservable node
1574
1575                 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1576                 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1577
1578                 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1579                 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1580
1581                 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1582
1583                 /* END CONSTRAINTS */
1584
1585                 // update is only possible is the query is not pending, etc
1586                 // CHECK status !
1587
1588                 // XXX we can only update subqueries of the main query. Check !
1589                 // assert query_ext.parent_query == query_ext.main_query
1590                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
1591
1592                 // This SET_ADD is called on a subquery, so we have to
1593                 // recontruct the path of the key in the main_query
1594                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
1595
1596                 var path = "";
1597                 var sq = query_ext;
1598                 while (sq.parent_query_ext) {
1599                     if (path != "")
1600                         path = '.' + path;
1601                     path = sq.query.object + path;
1602                     sq = sq.parent_query_ext;
1603                 }
1604
1605                 main_query = query_ext.main_query_ext.query;
1606                 data = {
1607                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
1608                     key   : path,
1609                     value : value,
1610                     status: STATE_SET, // XXX used to be FIELD_REQUEST_PENDING, and not new_state
1611                 };
1612                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
1613
1614                 // old //update_query.params[path].push(value);
1615                 // old // console.log('Updated query params', update_query);
1616                 // NOTE: update might modify the fields in Get
1617                 // NOTE : we have to modify all child queries
1618                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
1619
1620                 // if everything is done right, update_query should not be null. 
1621                 // It is updated when we received results from the get query
1622                 // object = the same as get
1623                 // filter = key : update a single object for now
1624                 // fields = the same as get
1625                 manifold.raise_query_event(query_uuid, event_type, value);
1626
1627                 break;
1628
1629             case RUN_UPDATE:
1630                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1631                 break;
1632
1633             /* FILTERS */
1634
1635             case FILTER_ADDED: 
1636                 /* Update internal record state */
1637                 manifold.query_store.add_filter(query_uuid, value);
1638
1639                 /* Propagate the message to plugins */
1640                 manifold.raise_query_event(query_uuid, event_type, value);
1641
1642                 break;
1643
1644             case FILTER_REMOVED:
1645                 /* Update internal record state */
1646                 manifold.query_store.remove_filter(query_uuid, value);
1647
1648                 /* Propagate the message to plugins */
1649                 manifold.raise_query_event(query_uuid, event_type, value);
1650
1651                 break;
1652
1653             case FIELD_ADDED:
1654                 main_query = query_ext.main_query_ext.query;
1655                 main_update_query = query_ext.main_query_ext.update_query;
1656                 query.select(value);
1657
1658                 // Here we need the full path through all subqueries
1659                 path = ""
1660                 // XXX We might need the query name in the QueryExt structure
1661                 main_query.select(value);
1662
1663                 // XXX When is an update query associated ?
1664                 // XXX main_update_query.select(value);
1665
1666                 manifold.raise_query_event(query_uuid, event_type, value);
1667                 break;
1668
1669             case FIELD_REMOVED:
1670                 query = query_ext.query;
1671                 main_query = query_ext.main_query_ext.query;
1672                 main_update_query = query_ext.main_query_ext.update_query;
1673                 query.unselect(value);
1674                 main_query.unselect(value);
1675
1676                 // We need to inform about changes in these queries to the respective plugins
1677                 // Note: query & main_query have the same UUID
1678                 manifold.raise_query_event(query_uuid, event_type, value);
1679                 break;
1680         }
1681         // We need to inform about changes in these queries to the respective plugins
1682         // Note: query, main_query & update_query have the same UUID
1683
1684         // http://trac.myslice.info/ticket/32
1685         // Avoid multiple calls to the same event
1686         //manifold.raise_query_event(query_uuid, event_type, value);
1687
1688         // We are targeting the same object with get and update
1689         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1690         // NOTE: Editing a subquery == editing a local view on the destination
1691
1692         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1693         // For the time being, we will collect all columns during the first query
1694     },
1695
1696     /* Publish/subscribe channels for internal use */
1697     get_channel: function(type, query_uuid) {
1698         if ((type !== 'query') && (type != 'record'))
1699             return null;
1700         return '/' + type + '/' + query_uuid;
1701     },
1702
1703 }; // manifold object
1704 /* ------------------------------------------------------------ */
1705
1706 (function($) {
1707
1708     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1709     // https://gist.github.com/661855
1710     var o = $({});
1711     $.subscribe = function( channel, selector, data, fn) {
1712       /* borrowed from jQuery */
1713       if ( data == null && fn == null ) {
1714           // ( channel, fn )
1715           fn = selector;
1716           data = selector = undefined;
1717       } else if ( fn == null ) {
1718           if ( typeof selector === "string" ) {
1719               // ( channel, selector, fn )
1720               fn = data;
1721               data = undefined;
1722           } else {
1723               // ( channel, data, fn )
1724               fn = data;
1725               data = selector;
1726               selector = undefined;
1727           }
1728       }
1729       /* </ugly> */
1730   
1731       /* We use an indirection function that will clone the object passed in
1732        * parameter to the subscribe callback 
1733        * 
1734        * FIXME currently we only clone query objects which are the only ones
1735        * supported and editable, we might have the same issue with results but
1736        * the page load time will be severely affected...
1737        */
1738       o.on.apply(o, [channel, selector, data, function() { 
1739           for(i = 1; i < arguments.length; i++) {
1740               if ( arguments[i].constructor.name == 'ManifoldQuery' )
1741                   arguments[i] = arguments[i].clone();
1742           }
1743           fn.apply(o, arguments);
1744       }]);
1745     };
1746   
1747     $.unsubscribe = function() {
1748       o.off.apply(o, arguments);
1749     };
1750   
1751     $.publish = function() {
1752       o.trigger.apply(o, arguments);
1753     };
1754   
1755 }(jQuery));
1756
1757 /* ------------------------------------------------------------ */
1758
1759 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1760 //make sure to expose csrf in our outcoming ajax/post requests
1761 $.ajaxSetup({ 
1762      beforeSend: function(xhr, settings) {
1763          function getCookie(name) {
1764              var cookieValue = null;
1765              if (document.cookie && document.cookie != '') {
1766                  var cookies = document.cookie.split(';');
1767                  for (var i = 0; i < cookies.length; i++) {
1768                      var cookie = jQuery.trim(cookies[i]);
1769                      // Does this cookie string begin with the name we want?
1770                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
1771                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1772                      break;
1773                  }
1774              }
1775          }
1776          return cookieValue;
1777          }
1778          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1779              // Only send the token to relative URLs i.e. locally.
1780              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
1781          }
1782      } 
1783 });