plugins: updated js framework + googlemaps and hazelnut to better handle sets and...
[myslice.git] / manifold / 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 var FIELD_STATE_CHANGED = 9;
42
43 var IN_PROGRESS    = 101;
44 var DONE           = 102;
45
46 /* Update requests related to subqueries */
47 var SET_ADD        = 201;
48 var SET_REMOVED    = 202;
49
50 // request
51 var FIELD_REQUEST_CHANGE  = 301;
52 var FIELD_REQUEST_ADD     = 302;
53 var FIELD_REQUEST_REMOVE  = 303;
54 var FIELD_REQUEST_RESET   = 304;
55 // status
56 var FIELD_REQUEST_PENDING = 401;
57 var FIELD_REQUEST_SUCCESS = 402;
58 var FIELD_REQUEST_FAILURE = 403;
59
60 /* Query status */
61 var STATUS_NONE               = 500; // Query has not been started yet
62 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
63 var STATUS_GET_RECEIVED       = 502; // Success
64 var STATUS_GET_ERROR          = 503; // Error
65 var STATUS_UPDATE_PENDING     = 504;
66 var STATUS_UPDATE_IN_PROGRESS = 505;
67 var STATUS_UPDATE_RECEIVED    = 506;
68 var STATUS_UPDATE_ERROR       = 507;
69
70 /* Requests for query cycle */
71 var RUN_UPDATE     = 601;
72
73 /* MANIFOLD types */
74 var TYPE_VALUE  = 1;
75 var TYPE_RECORD = 2;
76 var TYPE_LIST_OF_VALUES = 3;
77 var TYPE_LIST_OF_RECORDS = 4;
78
79
80 // A structure for storing queries
81
82 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
83
84     /* Constructor */
85     if (typeof query == "undefined")
86         throw "Must pass a query in QueryExt constructor";
87     this.query                 = query;
88     this.parent_query_ext      = (typeof parent_query_ext      == "undefined") ? null  : parent_query_ext;
89     this.main_query_ext        = (typeof main_query_ext        == "undefined") ? null  : main_query_ext;
90     this.update_query_ext      = (typeof update_query_ext      == "undefined") ? null  : update_query_ext;
91     this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null  : update_query_orig_ext;
92     this.disabled              = (typeof update_query_ext      == "undefined") ? false : disabled;
93     
94     this.status       = null;
95     this.results      = null;
96     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
97 }
98
99 function QueryStore() {
100
101     this.main_queries     = {};
102     this.analyzed_queries = {};
103
104     /* Insertion */
105
106     this.insert = function(query)
107     {
108         // We expect only main_queries are inserted
109
110         /* If the query has not been analyzed, then we analyze it */
111         if (query.analyzed_query == null) {
112             query.analyze_subqueries();
113         }
114
115         /* We prepare the update query corresponding to the main query and store both */
116         /* Note: they have the same UUID */
117
118         // XXX query.change_action() should become deprecated
119         update_query = query.clone();
120         update_query.action = 'update';
121         update_query.analyzed_query.action = 'update';
122         update_query.params = {};
123         update_query_ext = new QueryExt(update_query);
124
125         /* We remember the original query to be able to reset it */
126         update_query_orig_ext = new QueryExt(update_query.clone());
127
128
129         /* We store the main query */
130         query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
131         manifold.query_store.main_queries[query.query_uuid] = query_ext;
132         /* Note: the update query does not have an entry! */
133
134
135         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
136         // XXX unless we have no subqueries ???
137         // we will complete with params when records are received... this has to be done by the manager
138         // SET_ADD, SET_REMOVE will change the status of the elements of the set
139         // UPDATE will change also, etc.
140         // XXX We need a proper structure to store this information...
141
142         // We also need to insert all queries and subqueries from the analyzed_query
143         // XXX We need the root of all subqueries
144         query.iter_subqueries(function(sq, data, parent_query) {
145             if (parent_query)
146                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
147             else
148                 parent_query_ext = null;
149             // XXX parent_query_ext == false
150             // XXX main.subqueries = {} # Normal, we need analyzed_query
151             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
152             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
153         });
154
155         // XXX We have spurious update queries...
156     }
157
158     /* Searching */
159
160     this.find_query_ext = function(query_uuid)
161     {
162         return this.main_queries[query_uuid];
163     }
164
165     this.find_query = function(query_uuid)
166     {
167         return this.find_query_ext(query_uuid).query;
168     }
169
170     this.find_analyzed_query_ext = function(query_uuid)
171     {
172         return this.analyzed_queries[query_uuid];
173     }
174
175     this.find_analyzed_query = function(query_uuid)
176     {
177         return this.find_analyzed_query_ext(query_uuid).query;
178     }
179 }
180
181 /*!
182  * This namespace holds functions for globally managing query objects
183  * \Class Manifold
184  */
185 var manifold = {
186
187     /************************************************************************** 
188      * Helper functions
189      **************************************************************************/ 
190
191     separator: '__',
192
193     spin_presets: {},
194
195     spin: function(locator, active /*= true */) {
196         active = typeof active !== 'undefined' ? active : true;
197         try {
198             if (active) {
199                 $(locator).spin(manifold.spin_presets);
200             } else {
201                 $(locator).spin(false);
202             }
203         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
204     },
205
206     get_type: function(variable)
207     {
208         switch(Object.toType(variable)) {
209             case 'number':
210             case 'string':
211                 return TYPE_VALUE;
212             case 'object':
213                 return TYPE_RECORD;
214             case 'array':
215                 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
216                     return TYPE_LIST_OF_RECORDS;
217                 else
218                     return TYPE_LIST_OF_VALUES;
219         }
220     },
221
222     /************************************************************************** 
223      * Metadata management
224      **************************************************************************/ 
225
226      metadata: {
227
228         get_table: function(method)
229         {
230             var table = MANIFOLD_METADATA[method];
231             return (typeof table === 'undefined') ? null : table;
232         },
233
234         get_columns: function(method)
235         {
236             var table = this.get_table(method);
237             if (!table) {
238                 return null;
239             }
240
241             return (typeof table.column === 'undefined') ? null : table.column;
242         },
243
244         get_key: function(method)
245         {
246             var table = this.get_table(method);
247             if (!table)
248                 return null;
249
250             return (typeof table.key === 'undefined') ? null : table.key;
251         },
252
253
254         get_column: function(method, name)
255         {
256             var columns = this.get_columns(method);
257             if (!columns)
258                 return null;
259
260             $.each(columns, function(i, c) {
261                 if (c.name == name)
262                     return c
263             });
264             return null;
265         },
266
267         get_type: function(method, name)
268         {
269             var table = this.get_table(method);
270             if (!table)
271                 return null;
272
273             return (typeof table.type === 'undefined') ? null : table.type;
274         }
275
276      },
277
278     /************************************************************************** 
279      * Query management
280      **************************************************************************/ 
281
282     query_store: new QueryStore(),
283
284     // XXX Remaining functions are deprecated since they are replaced by the query store
285
286     /*!
287      * Associative array storing the set of queries active on the page
288      * \memberof Manifold
289      */
290     all_queries: {},
291
292     /*!
293      * Insert a query in the global hash table associating uuids to queries.
294      * If the query has no been analyzed yet, let's do it.
295      * \fn insert_query(query)
296      * \memberof Manifold
297      * \param ManifoldQuery query Query to be added
298      */
299     insert_query : function (query) { 
300         // NEW API
301         manifold.query_store.insert(query);
302
303         // FORMER API
304         if (query.analyzed_query == null) {
305             query.analyze_subqueries();
306         }
307         manifold.all_queries[query.query_uuid]=query;
308     },
309
310     /*!
311      * Returns the query associated to a UUID
312      * \fn find_query(query_uuid)
313      * \memberof Manifold
314      * \param string query_uuid The UUID of the query to be returned
315      */
316     find_query : function (query_uuid) { 
317         return manifold.all_queries[query_uuid];
318     },
319
320     /************************************************************************** 
321      * Query execution
322      **************************************************************************/ 
323
324     // trigger a query asynchroneously
325     proxy_url : '/manifold/proxy/json/',
326
327     asynchroneous_debug : true,
328
329     /**
330      * \brief We use js function closure to be able to pass the query (array)
331      * to the callback function used when data is received
332      */
333     success_closure: function(query, publish_uuid, callback /*domid*/)
334     {
335         return function(data, textStatus) {
336             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
337         }
338     },
339
340     run_query: function(query, callback)
341     {
342         // default value for callback = null
343         if (typeof callback === 'undefined')
344             callback = null; 
345
346         var query_json = JSON.stringify(query);
347
348         /* Nothing related to pubsub here... for the moment at least. */
349         //query.iter_subqueries(function (sq) {
350         //    manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
351         //});
352
353         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback /*domid*/));
354     },
355
356     // Executes all async. queries
357     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
358     asynchroneous_exec : function (query_publish_dom_tuples) {
359         // start spinners
360
361         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
362         //try {
363         //    if (manifold.asynchroneous_debug) 
364         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
365         //    jQuery('.need-spin').spin(manifold.spin_presets);
366         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
367         
368         // Loop through input array, and use publish_uuid to publish back results
369         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
370             var query=manifold.find_query(tuple.query_uuid);
371             var query_json=JSON.stringify (query);
372             var publish_uuid=tuple.publish_uuid;
373             // by default we publish using the same uuid of course
374             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
375             if (manifold.asynchroneous_debug) {
376                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
377                 messages.debug("... ctd... with actual query= " + query.__repr());
378             }
379
380             query.iter_subqueries(function (sq) {
381                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
382             });
383
384             // not quite sure what happens if we send a string directly, as POST data is named..
385             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
386                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
387         })
388     },
389
390     /**
391      * \brief Forward a query to the manifold backend
392      * \param query (dict) the query to be executed asynchronously
393      * \param callback (function) the function to be called when the query terminates
394      * Deprecated:
395      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
396      */
397     forward: function(query, callback /*domid*/) {
398         var query_json = JSON.stringify(query);
399         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
400     },
401
402     /*!
403      * Returns whether a query expects a unique results.
404      * This is the case when the filters contain a key of the object
405      * \fn query_expects_unique_result(query)
406      * \memberof Manifold
407      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
408      */
409     query_expects_unique_result: function(query) {
410         /* XXX we need functions to query metadata */
411         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
412         /* TODO requires keys in metadata */
413         return true;
414     },
415
416     /*!
417      * Publish result
418      * \fn publish_result(query, results)
419      * \memberof Manifold
420      * \param ManifoldQuery query Query which has received results
421      * \param array results results corresponding to query
422      */
423     publish_result: function(query, result) {
424         if (typeof result === 'undefined')
425             result = [];
426
427         // NEW PLUGIN API
428         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
429         $.each(result, function(i, record) {
430             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
431         });
432         manifold.raise_record_event(query.query_uuid, DONE);
433
434         // OLD PLUGIN API BELOW
435         /* Publish an update announce */
436         var channel="/results/" + query.query_uuid + "/changed";
437         if (manifold.asynchroneous_debug)
438             messages.debug("publishing result on " + channel);
439         jQuery.publish(channel, [result, query]);
440     },
441
442     /*!
443      * Recursively publish result
444      * \fn publish_result_rec(query, result)
445      * \memberof Manifold
446      * \param ManifoldQuery query Query which has received result
447      * \param array result result corresponding to query
448      */
449     publish_result_rec: function(query, result) {
450         /* If the result is not unique, only publish the top query;
451          * otherwise, publish the main object as well as subqueries
452          * XXX how much recursive are we ?
453          */
454         if (manifold.query_expects_unique_result(query)) {
455             /* Also publish subqueries */
456             jQuery.each(query.subqueries, function(object, subquery) {
457                 manifold.publish_result_rec(subquery, result[0][object]);
458                 /* TODO remove object from result */
459             });
460         }
461         manifold.publish_result(query, result);
462     },
463
464     setup_update_query: function(query, records)
465     {
466         // We don't prepare an update query if the result has more than 1 entry
467         if (records.length != 1)
468             return;
469         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
470
471         var record = records[0];
472
473         var update_query_ext = query_ext.update_query_ext;
474         var update_query = update_query_ext.query;
475         var update_query_ext = query_ext.update_query_ext;
476         var update_query_orig = query_ext.update_query_orig_ext.query;
477
478         // Testing whether the result has subqueries (one level deep only)
479         // iif the query has subqueries
480         var count = 0;
481         var obj = query.analyzed_query.subqueries;
482         for (method in obj) {
483             if (obj.hasOwnProperty(method)) {
484                 var key = manifold.metadata.get_key(method);
485                 if (!key)
486                     continue;
487                 if (key.length > 1)
488                     continue;
489                 key = key[0];
490                 var sq_keys = [];
491                 var subrecords = record[method];
492                 if (!subrecords)
493                     continue
494                 $.each(subrecords, function (i, subrecord) {
495                     sq_keys.push(subrecord[key]);
496                 });
497                 update_query.params[method] = sq_keys;
498                 update_query_orig.params[method] = sq_keys.slice();
499                 count++;
500             }
501         }
502
503         if (count > 0) {
504             update_query_ext.disabled = false;
505             update_query_orig_ext.disabled = false;
506         }
507     },
508
509     process_get_query_records: function(query, records)
510     {
511         this.setup_update_query(query, records);
512
513         /* Publish full results */
514         tmp_query = manifold.find_query(query.query_uuid);
515         manifold.publish_result_rec(tmp_query.analyzed_query, records);
516     },
517
518     /**
519      * 
520      * What we need to do when receiving results from an update query:
521      * - differences between what we had, what we requested, and what we obtained
522      *    . what we had : update_query_orig (simple fields and set fields managed differently)
523      *    . what we requested : update_query
524      *    . what we received : records
525      * - raise appropriate events
526      *
527      * The normal process is that results similar to Get will be pushed in the
528      * pubsub mechanism, thus repopulating everything while we only need
529      * diff's. This means we need to move the publish functionalities in the
530      * previous 'process_get_query_records' function.
531      */
532     process_update_query_records: function(query, records)
533     {
534         // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
535         var query_uuid        = query.query_uuid;
536         var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
537         var update_query      = query_ext.main_query_ext.update_query_ext.query;
538         var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
539         
540         // Since we update objects one at a time, we can get the first record
541         var record = records[0];
542
543         // Let's iterate over the object properties
544         for (var field in record) {
545             switch (this.get_type(record[field])) {
546                 case TYPE_VALUE:
547                     // Did we ask for a change ?
548                     var update_value = update_query[field];
549                     if (!update_value)
550                         // Not requested, if it has changed: OUT OF SYNC
551                         // How we can know ?
552                         // We assume it won't have changed
553                         continue;
554
555                     var result_value = record[field];
556                     if (!result_value)
557                         throw "Internal error";
558
559                     data = {
560                         request: FIELD_REQUEST_CHANGE,
561                         key   : field,
562                         value : update_value,
563                         status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
564                     }
565                     manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
566
567                     break;
568                 case TYPE_RECORD:
569                     throw "Not implemented";
570                     break;
571
572                 case TYPE_LIST_OF_VALUES:
573                     // Same as list of records, but we don't have to extract keys
574                     var result_keys  = record[field]
575                     
576                     // The rest of exactly the same (XXX factorize)
577                     var update_keys  = update_query_orig.params[field];
578                     var query_keys   = update_query.params[field];
579                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
580                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
581
582
583                     $.each(added_keys, function(i, key) {
584                         if ($.inArray(key, result_keys) == -1) {
585                             data = {
586                                 request: FIELD_REQUEST_ADD,
587                                 key   : field,
588                                 value : key,
589                                 status: FIELD_REQUEST_FAILURE,
590                             }
591                         } else {
592                             data = {
593                                 request: FIELD_REQUEST_ADD,
594                                 key   : field,
595                                 value : key,
596                                 status: FIELD_REQUEST_SUCCESS,
597                             }
598                         }
599                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
600                     });
601                     $.each(removed_keys, function(i, key) {
602                         if ($.inArray(key, result_keys) == -1) {
603                             data = {
604                                 request: FIELD_REQUEST_REMOVE,
605                                 key   : field,
606                                 value : key,
607                                 status: FIELD_REQUEST_SUCCESS,
608                             }
609                         } else {
610                             data = {
611                                 request: FIELD_REQUEST_REMOVE,
612                                 key   : field,
613                                 value : key,
614                                 status: FIELD_REQUEST_FAILURE,
615                             }
616                         }
617                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
618                     });
619
620
621                     break;
622                 case TYPE_LIST_OF_RECORDS:
623                     // example: slice.resource
624                     //  - update_query_orig.params.resource = resources in slice before update
625                     //  - update_query.params.resource = resource requested in slice
626                     //  - keys from field = resources obtained
627                     var key = manifold.metadata.get_key(field);
628                     if (!key)
629                         continue;
630                     if (key.length > 1) {
631                         throw "Not implemented";
632                         continue;
633                     }
634                     key = key[0];
635
636                     /* XXX should be modified for multiple keys */
637                     var result_keys  = $.map(record[field], function(x) { return x[key]; });
638
639                     var update_keys  = update_query_orig.params[field];
640                     var query_keys   = update_query.params[field];
641                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
642                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
643
644
645                     $.each(added_keys, function(i, key) {
646                         if ($.inArray(key, result_keys) == -1) {
647                             data = {
648                                 request: FIELD_REQUEST_ADD,
649                                 key   : field,
650                                 value : key,
651                                 status: FIELD_REQUEST_FAILURE,
652                             }
653                         } else {
654                             data = {
655                                 request: FIELD_REQUEST_ADD,
656                                 key   : field,
657                                 value : key,
658                                 status: FIELD_REQUEST_SUCCESS,
659                             }
660                         }
661                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
662                     });
663                     $.each(removed_keys, function(i, key) {
664                         if ($.inArray(key, result_keys) == -1) {
665                             data = {
666                                 request: FIELD_REQUEST_REMOVE,
667                                 key   : field,
668                                 value : key,
669                                 status: FIELD_REQUEST_SUCCESS,
670                             }
671                         } else {
672                             data = {
673                                 request: FIELD_REQUEST_REMOVE,
674                                 key   : field,
675                                 value : key,
676                                 status: FIELD_REQUEST_FAILURE,
677                             }
678                         }
679                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
680                     });
681
682
683                     break;
684             }
685         }
686         
687         // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
688         this.setup_update_query(query, records);
689     },
690
691     process_query_records: function(query, records)
692     {
693         if (query.action == 'get') {
694             this.process_get_query_records(query, records);
695         } else if (query.action == 'update') {
696             this.process_update_query_records(query, records);
697         }
698     },
699
700     // if set domid allows the result to be directed to just one plugin
701     // most of the time publish_uuid will be query.query_uuid
702     // however in some cases we wish to publish the result under a different uuid
703     // e.g. an updater wants to publish its result as if from the original (get) query
704     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
705         // xxx should have a nicer declaration of that enum in sync with the python code somehow
706
707         /* If a callback has been specified, we redirect results to it */
708         if (!!callback) { callback(data); return; }
709
710         if (data.code == 2) { // ERROR
711             // We need to make sense of error codes here
712             alert("Your session has expired, please log in again");
713             window.location="/logout/";
714             return;
715         }
716         if (data.code == 1) { // WARNING
717             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
718             // publish error code and text message on a separate channel for whoever is interested
719             if (publish_uuid)
720                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
721
722             $("#notifications").notify("create", "sticky", {
723               title: 'Warning',
724               text: data.description
725             },{
726               expires: false,
727               speed: 1000
728             });
729             
730         }
731         // once everything is checked we can use the 'value' part of the manifoldresult
732         var result=data.value;
733         if (result) {
734             /* Eventually update the content of related queries (update, etc) */
735             this.process_query_records(query, result);
736
737             /* Publish results: disabled here, done in the previous call */
738             //tmp_query = manifold.find_query(query.query_uuid);
739             //manifold.publish_result_rec(tmp_query.analyzed_query, result);
740         }
741     },
742
743     /************************************************************************** 
744      * Plugin API helpers
745      **************************************************************************/ 
746
747     raise_event_handler: function(type, query_uuid, event_type, value)
748     {
749         if ((type != 'query') && (type != 'record'))
750             throw 'Incorrect type for manifold.raise_event()';
751
752         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
753
754         $.each(channels, function(i, channel) {
755             if (value === undefined)
756                 $('.plugin').trigger(channel, [event_type]);
757             else
758                 $('.plugin').trigger(channel, [event_type, value]);
759         });
760     },
761
762     raise_query_event: function(query_uuid, event_type, value)
763     {
764         manifold.raise_event_handler('query', query_uuid, event_type, value);
765     },
766
767     raise_record_event: function(query_uuid, event_type, value)
768     {
769         manifold.raise_event_handler('record', query_uuid, event_type, value);
770     },
771
772
773     raise_event: function(query_uuid, event_type, value)
774     {
775         // Query uuid has been updated with the key of a new element
776         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
777         query = query_ext.query;
778
779         switch(event_type) {
780             case FIELD_STATE_CHANGED:
781                 // value is an object (request, key, value, status)
782                 // update is only possible is the query is not pending, etc
783                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
784                 // we should map SET_ADD on this...
785
786                 // 1. Update internal query store about the change in status
787
788                 // 2. Update the update query
789                 update_query      = query_ext.main_query_ext.update_query_ext.query;
790                 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
791
792                 switch(value.request) {
793                     case FIELD_REQUEST_CHANGE:
794                         update_query.params[value.key] = value.value;
795                         break;
796                     case FIELD_REQUEST_ADD:
797                         if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
798                             value.request = FIELD_REQUEST_RESET;
799                         update_query.params[value.key].push(value.value);
800                         break;
801                     case FIELD_REQUEST_REMOVE:
802                         if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
803                             value.request = FIELD_REQUEST_RESET;
804
805                         var arr = update_query.params[value.key];
806                         arr = $.grep(arr, function(x) { return x != value.value; });
807                         update_query.params[value.key] = arr;
808
809                         break;
810                     case FIELD_REQUEST_RESET:
811                         // XXX We would need to keep track of the original query
812                         throw "Not implemented";
813                         break;
814                 }
815
816                 // 3. Inform others about the change
817                 // a) the main query...
818                 manifold.raise_record_event(query_uuid, event_type, value);
819
820                 // b) subqueries eventually (dot in the key)
821                 // Let's unfold 
822                 var path_array = value.key.split('.');
823                 var value_key = value.key.split('.');
824
825                 var cur_query = query;
826                 if (cur_query.analyzed_query)
827                     cur_query = cur_query.analyzed_query;
828                 $.each(path_array, function(i, method) {
829                     cur_query = cur_query.subqueries[method];
830                     value_key.shift(); // XXX check that method is indeed shifted
831                 });
832                 value.key = value_key;
833
834                 manifold.raise_record_event(cur_query.query_uuid, event_type, value);
835
836                 // XXX make this DOT a global variable... could be '/'
837                 break;
838
839             case SET_ADD:
840             case SET_REMOVED:
841     
842                 // update is only possible is the query is not pending, etc
843                 // CHECK status !
844
845                 // XXX we can only update subqueries of the main query. Check !
846                 // assert query_ext.parent_query == query_ext.main_query
847                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
848
849                 // This SET_ADD is called on a subquery, so we have to
850                 // recontruct the path of the key in the main_query
851                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
852
853                 var path = "";
854                 var sq = query_ext;
855                 while (sq.parent_query_ext) {
856                     if (path != "")
857                         path = '.' + path;
858                     path = sq.query.object + path;
859                     sq = sq.parent_query_ext;
860                 }
861
862                 main_query = query_ext.main_query_ext.query;
863                 data = {
864                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
865                     key   : path,
866                     value : value,
867                     status: FIELD_REQUEST_PENDING,
868                 };
869                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
870
871                 // old //update_query.params[path].push(value);
872                 // old // console.log('Updated query params', update_query);
873                 // NOTE: update might modify the fields in Get
874                 // NOTE : we have to modify all child queries
875                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
876
877                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
878                 // object = the same as get
879                 // filter = key : update a single object for now
880                 // fields = the same as get
881                 manifold.raise_query_event(query_uuid, event_type, value);
882
883                 break;
884
885             case RUN_UPDATE:
886                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
887                 break;
888
889             case FILTER_ADDED:
890                 manifold.raise_query_event(query_uuid, event_type, value);
891                 break;
892             case FILTER_REMOVED:
893                 manifold.raise_query_event(query_uuid, event_type, value);
894                 break;
895             case FIELD_ADDED:
896                 main_query = query_ext.main_query_ext.query;
897                 main_update_query = query_ext.main_query_ext.update_query;
898                 query.select(value);
899
900                 // Here we need the full path through all subqueries
901                 path = ""
902                 // XXX We might need the query name in the QueryExt structure
903                 main_query.select(value);
904
905                 // XXX When is an update query associated ?
906                 // XXX main_update_query.select(value);
907
908                 manifold.raise_query_event(query_uuid, event_type, value);
909                 break;
910
911             case FIELD_REMOVED:
912                 query = query_ext.query;
913                 main_query = query_ext.main_query_ext.query;
914                 main_update_query = query_ext.main_query_ext.update_query;
915                 query.unselect(value);
916                 main_query.unselect(value);
917
918                 // We need to inform about changes in these queries to the respective plugins
919                 // Note: query & main_query have the same UUID
920                 manifold.raise_query_event(query_uuid, event_type, value);
921                 break;
922         }
923         // We need to inform about changes in these queries to the respective plugins
924         // Note: query, main_query & update_query have the same UUID
925         manifold.raise_query_event(query_uuid, event_type, value);
926         // We are targeting the same object with get and update
927         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
928         // NOTE: Editing a subquery == editing a local view on the destination
929
930         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
931         // For the time being, we will collect all columns during the first query
932     },
933
934     /* Publish/subscribe channels for internal use */
935     get_channel: function(type, query_uuid) 
936     {
937         if ((type !== 'query') && (type != 'record'))
938             return null;
939         return '/' + type + '/' + query_uuid;
940     },
941
942 }; // manifold object
943 /* ------------------------------------------------------------ */
944
945 (function($) {
946
947     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
948     // https://gist.github.com/661855
949     var o = $({});
950     $.subscribe = function( channel, selector, data, fn) {
951       /* borrowed from jQuery */
952       if ( data == null && fn == null ) {
953           // ( channel, fn )
954           fn = selector;
955           data = selector = undefined;
956       } else if ( fn == null ) {
957           if ( typeof selector === "string" ) {
958               // ( channel, selector, fn )
959               fn = data;
960               data = undefined;
961           } else {
962               // ( channel, data, fn )
963               fn = data;
964               data = selector;
965               selector = undefined;
966           }
967       }
968       /* </ugly> */
969   
970       /* We use an indirection function that will clone the object passed in
971        * parameter to the subscribe callback 
972        * 
973        * FIXME currently we only clone query objects which are the only ones
974        * supported and editable, we might have the same issue with results but
975        * the page load time will be severely affected...
976        */
977       o.on.apply(o, [channel, selector, data, function() { 
978           for(i = 1; i < arguments.length; i++) {
979               if ( arguments[i].constructor.name == 'ManifoldQuery' )
980                   arguments[i] = arguments[i].clone();
981           }
982           fn.apply(o, arguments);
983       }]);
984     };
985   
986     $.unsubscribe = function() {
987       o.off.apply(o, arguments);
988     };
989   
990     $.publish = function() {
991       o.trigger.apply(o, arguments);
992     };
993   
994 }(jQuery));
995
996 /* ------------------------------------------------------------ */
997
998 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
999 //make sure to expose csrf in our outcoming ajax/post requests
1000 $.ajaxSetup({ 
1001      beforeSend: function(xhr, settings) {
1002          function getCookie(name) {
1003              var cookieValue = null;
1004              if (document.cookie && document.cookie != '') {
1005                  var cookies = document.cookie.split(';');
1006                  for (var i = 0; i < cookies.length; i++) {
1007                      var cookie = jQuery.trim(cookies[i]);
1008                      // Does this cookie string begin with the name we want?
1009                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
1010                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1011                      break;
1012                  }
1013              }
1014          }
1015          return cookieValue;
1016          }
1017          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1018              // Only send the token to relative URLs i.e. locally.
1019              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
1020          }
1021      } 
1022 });
1023