94e4469f401e357da412dc2314bb75471d24087c
[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 /* ------------------------------------------------------------ */
21
22 // Constants that should be somehow moved to a plugin.js file
23 var FILTER_ADDED   = 1;
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS  = 3;
26 var FIELD_ADDED    = 4;
27 var FIELD_REMOVED  = 5;
28 var CLEAR_FIELDS   = 6;
29 var NEW_RECORD     = 7;
30 var CLEAR_RECORDS  = 8;
31 var FIELD_STATE_CHANGED = 9;
32
33 var IN_PROGRESS    = 101;
34 var DONE           = 102;
35
36 /* Update requests related to subqueries */
37 var SET_ADD        = 201;
38 var SET_REMOVED    = 202;
39
40 // request
41 var FIELD_REQUEST_CHANGE  = 301;
42 var FIELD_REQUEST_ADD     = 302;
43 var FIELD_REQUEST_REMOVE  = 303;
44 var FIELD_REQUEST_RESET   = 304;
45 // status
46 var FIELD_REQUEST_PENDING = 301;
47 var FIELD_REQUEST_SUCCESS = 302;
48 var FIELD_REQUEST_FAILURE = 303;
49
50 /* Query status */
51 var STATUS_NONE               = 500; // Query has not been started yet
52 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
53 var STATUS_GET_RECEIVED       = 502; // Success
54 var STATUS_GET_ERROR          = 503; // Error
55 var STATUS_UPDATE_PENDING     = 504;
56 var STATUS_UPDATE_IN_PROGRESS = 505;
57 var STATUS_UPDATE_RECEIVED    = 506;
58 var STATUS_UPDATE_ERROR       = 507;
59
60 /* Requests for query cycle */
61 var RUN_UPDATE     = 601;
62
63 // A structure for storing queries
64
65
66
67 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
68
69     /* Constructor */
70     if (typeof query == "undefined")
71         throw "Must pass a query in QueryExt constructor";
72     this.query            = query
73     this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext
74     this.main_query_ext   = (typeof main_query_ext   == "undefined") ? null : main_query_ext
75     this.update_query_ext = (typeof update_query_ext   == "undefined") ? null : update_query_ext
76     this.disabled         = (typeof update_query_ext   == "undefined") ? false : disabled
77     
78     this.status       = null;
79     this.results      = null;
80     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
81 }
82
83 function QueryStore() {
84
85     this.main_queries     = {};
86     this.analyzed_queries = {};
87
88     /* Insertion */
89
90     this.insert = function(query)
91     {
92         // We expect only main_queries are inserted
93
94         /* If the query has not been analyzed, then we analyze it */
95         if (query.analyzed_query == null) {
96             query.analyze_subqueries();
97         }
98
99         /* We prepare the update query corresponding to the main query and store both */
100         /* Note: they have the same UUID */
101
102         // XXX query.change_action() should become deprecated
103         update_query = query.clone();
104         update_query.action = 'update';
105         update_query.analyzed_query.action = 'update';
106         update_query.params = {};
107         update_query_ext = new QueryExt(update_query);
108         console.log("Update query created from Get query", update_query);
109
110         /* We store the main query */
111         query_ext = new QueryExt(query, null, null, update_query_ext, false);
112         manifold.query_store.main_queries[query.query_uuid] = query_ext;
113         /* Note: the update query does not have an entry! */
114
115
116         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
117         // XXX unless we have no subqueries ???
118         // we will complete with params when records are received... this has to be done by the manager
119         // SET_ADD, SET_REMOVE will change the status of the elements of the set
120         // UPDATE will change also, etc.
121         // XXX We need a proper structure to store this information...
122
123         // We also need to insert all queries and subqueries from the analyzed_query
124         // XXX We need the root of all subqueries
125         query.iter_subqueries(function(sq, data, parent_query) {
126             if (parent_query)
127                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
128             else
129                 parent_query_ext = null;
130             // XXX parent_query_ext == false
131             // XXX main.subqueries = {} # Normal, we need analyzed_query
132             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
133             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
134         });
135
136         // XXX We have spurious update queries...
137     }
138
139     /* Searching */
140
141     this.find_query_ext = function(query_uuid)
142     {
143         return this.main_queries[query_uuid];
144     }
145
146     this.find_query = function(query_uuid)
147     {
148         return this.find_query_ext(query_uuid).query;
149     }
150
151     this.find_analyzed_query_ext = function(query_uuid)
152     {
153         return this.analyzed_queries[query_uuid];
154     }
155
156     this.find_analyzed_query = function(query_uuid)
157     {
158         return this.find_analyzed_query_ext(query_uuid).query;
159     }
160 }
161
162 /*!
163  * This namespace holds functions for globally managing query objects
164  * \Class Manifold
165  */
166 var manifold = {
167
168     /************************************************************************** 
169      * Helper functions
170      **************************************************************************/ 
171
172     separator: '__',
173
174     spin_presets: {},
175
176     spin: function(locator, active /*= true */) {
177         active = typeof active !== 'undefined' ? active : true;
178         try {
179             if (active) {
180                 $(locator).spin(manifold.spin_presets);
181             } else {
182                 $(locator).spin(false);
183             }
184         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
185     },
186
187     /************************************************************************** 
188      * Metadata management
189      **************************************************************************/ 
190
191      metadata: {
192
193         get_table: function(method)
194         {
195             var table = MANIFOLD_METADATA[method];
196             return (typeof table === 'undefined') ? null : table;
197         },
198
199         get_columns: function(method)
200         {
201             var table = this.get_table(method);
202             if (!table) {
203                 return null;
204             }
205
206             return (typeof table.column === 'undefined') ? null : table.column;
207         },
208
209         get_key: function(method)
210         {
211             var table = this.get_table(method);
212             if (!table)
213                 return null;
214
215             return (typeof table.key === 'undefined') ? null : table.key;
216         },
217
218
219         get_column: function(method, name)
220         {
221             var columns = this.get_columns(method);
222             if (!columns)
223                 return null;
224
225             $.each(columns, function(i, c) {
226                 if (c.name == name)
227                     return c
228             });
229             return null;
230         },
231
232         get_type: function(method, name)
233         {
234             var table = this.get_table(method);
235             if (!table)
236                 return null;
237
238             return (typeof table.type === 'undefined') ? null : table.type;
239         }
240
241      },
242
243     /************************************************************************** 
244      * Query management
245      **************************************************************************/ 
246
247     query_store: new QueryStore(),
248
249     // XXX Remaining functions are deprecated since they are replaced by the query store
250
251     /*!
252      * Associative array storing the set of queries active on the page
253      * \memberof Manifold
254      */
255     all_queries: {},
256
257     /*!
258      * Insert a query in the global hash table associating uuids to queries.
259      * If the query has no been analyzed yet, let's do it.
260      * \fn insert_query(query)
261      * \memberof Manifold
262      * \param ManifoldQuery query Query to be added
263      */
264     insert_query : function (query) { 
265         // NEW API
266         manifold.query_store.insert(query);
267
268         // FORMER API
269         if (query.analyzed_query == null) {
270             query.analyze_subqueries();
271         }
272         manifold.all_queries[query.query_uuid]=query;
273     },
274
275     /*!
276      * Returns the query associated to a UUID
277      * \fn find_query(query_uuid)
278      * \memberof Manifold
279      * \param string query_uuid The UUID of the query to be returned
280      */
281     find_query : function (query_uuid) { 
282         return manifold.all_queries[query_uuid];
283     },
284
285     /************************************************************************** 
286      * Query execution
287      **************************************************************************/ 
288
289     // trigger a query asynchroneously
290     proxy_url : '/manifold/proxy/json/',
291
292     asynchroneous_debug : true,
293
294     /**
295      * \brief We use js function closure to be able to pass the query (array)
296      * to the callback function used when data is received
297      */
298     success_closure: function(query, publish_uuid, callback /*domid*/)
299     {
300         return function(data, textStatus) {
301             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
302         }
303     },
304
305     run_query: function(query, callback)
306     {
307         // default value for callback = null
308         if (typeof callback === 'undefined')
309             callback = null; 
310
311         var query_json = JSON.stringify(query);
312
313         /* Nothing related to pubsub here... for the moment at least. */
314         //query.iter_subqueries(function (sq) {
315         //    manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
316         //});
317
318         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback /*domid*/));
319     },
320
321     // Executes all async. queries
322     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
323     asynchroneous_exec : function (query_publish_dom_tuples) {
324         // start spinners
325
326         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
327         //try {
328         //    if (manifold.asynchroneous_debug) 
329         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
330         //    jQuery('.need-spin').spin(manifold.spin_presets);
331         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
332         
333         // Loop through input array, and use publish_uuid to publish back results
334         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
335             var query=manifold.find_query(tuple.query_uuid);
336             var query_json=JSON.stringify (query);
337             var publish_uuid=tuple.publish_uuid;
338             // by default we publish using the same uuid of course
339             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
340             if (manifold.asynchroneous_debug) {
341                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
342                 messages.debug("... ctd... with actual query= " + query.__repr());
343             }
344
345             query.iter_subqueries(function (sq) {
346                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
347             });
348
349             // not quite sure what happens if we send a string directly, as POST data is named..
350             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
351                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
352         })
353     },
354
355     /**
356      * \brief Forward a query to the manifold backend
357      * \param query (dict) the query to be executed asynchronously
358      * \param callback (function) the function to be called when the query terminates
359      * Deprecated:
360      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
361      */
362     forward: function(query, callback /*domid*/) {
363         var query_json = JSON.stringify(query);
364         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
365     },
366
367     /*!
368      * Returns whether a query expects a unique results.
369      * This is the case when the filters contain a key of the object
370      * \fn query_expects_unique_result(query)
371      * \memberof Manifold
372      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
373      */
374     query_expects_unique_result: function(query) {
375         /* XXX we need functions to query metadata */
376         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
377         /* TODO requires keys in metadata */
378         return true;
379     },
380
381     /*!
382      * Publish result
383      * \fn publish_result(query, results)
384      * \memberof Manifold
385      * \param ManifoldQuery query Query which has received results
386      * \param array results results corresponding to query
387      */
388     publish_result: function(query, result) {
389         if (typeof result === 'undefined')
390             result = [];
391
392         // NEW PLUGIN API
393         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
394         $.each(result, function(i, record) {
395             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
396         });
397         manifold.raise_record_event(query.query_uuid, DONE);
398
399         // OLD PLUGIN API BELOW
400         /* Publish an update announce */
401         var channel="/results/" + query.query_uuid + "/changed";
402         if (manifold.asynchroneous_debug)
403             messages.debug("publishing result on " + channel);
404         jQuery.publish(channel, [result, query]);
405     },
406
407     /*!
408      * Recursively publish result
409      * \fn publish_result_rec(query, result)
410      * \memberof Manifold
411      * \param ManifoldQuery query Query which has received result
412      * \param array result result corresponding to query
413      */
414     publish_result_rec: function(query, result) {
415         /* If the result is not unique, only publish the top query;
416          * otherwise, publish the main object as well as subqueries
417          * XXX how much recursive are we ?
418          */
419         if (manifold.query_expects_unique_result(query)) {
420             /* Also publish subqueries */
421             jQuery.each(query.subqueries, function(object, subquery) {
422                 manifold.publish_result_rec(subquery, result[0][object]);
423                 /* TODO remove object from result */
424             });
425         }
426         manifold.publish_result(query, result);
427     },
428
429     // if set domid allows the result to be directed to just one plugin
430     // most of the time publish_uuid will be query.query_uuid
431     // however in some cases we wish to publish the result under a different uuid
432     // e.g. an updater wants to publish its result as if from the original (get) query
433     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
434         // xxx should have a nicer declaration of that enum in sync with the python code somehow
435
436         /* If a callback has been specified, we redirect results to it */
437         if (!!callback) { callback(data); return; }
438
439         if (data.code == 2) { // ERROR
440             // We need to make sense of error codes here
441             alert("Your session has expired, please log in again");
442             window.location="/logout/";
443             return;
444         }
445         if (data.code == 1) { // WARNING
446             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
447             // publish error code and text message on a separate channel for whoever is interested
448             if (publish_uuid)
449                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
450
451             $("#notifications").notify("create", "sticky", {
452               title: 'Warning',
453               text: data.description
454             },{
455               expires: false,
456               speed: 1000
457             });
458             
459         }
460         // once everything is checked we can use the 'value' part of the manifoldresult
461         var result=data.value;
462         if (result) {
463             //if (!!callback /* domid */) {
464             //    /* Directly inform the requestor */
465             //    if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
466             //    callback(result);
467             //    //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
468             //    //jQuery('#' + domid).trigger('results', [result]);
469             //} else {
470                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
471                 /* query is the query we sent to the backend; we need to find the
472                  * corresponding analyezd_query in manifold.all_queries
473                  */
474
475                 // XXX We might need to update the corresponding update_query here 
476                 query_ext = manifold.query_store.find_query_ext(query.query_uuid);
477                 query = query_ext.query;
478
479                 // We don't prepare an update query if the result has more than 1 entry
480                 if (result.length == 1) {
481                     var res = result[0];
482
483                     console.log("Locating update query for updating params", update_query);
484                     update_query_ext = query_ext.update_query_ext;
485                     update_query = update_query_ext.query;
486
487                     // Testing whether the result has subqueries (one level deep only)
488                     // iif the query has subqueries
489                     var count = 0;
490                     var obj = query.analyzed_query.subqueries;
491                     for (method in obj) {
492                         if (obj.hasOwnProperty(method)) {
493                             var key = manifold.metadata.get_key(method);
494                             if (!key)
495                                 continue;
496                             if (key.length > 1)
497                                 continue;
498                             key = key[0];
499                             var sq_keys = [];
500                             var records = res[method];
501                             if (!records)
502                                 continue
503                             $.each(records, function (i, obj) {
504                                 sq_keys.push(obj[key]);
505                             });
506                             update_query.params[method] = sq_keys;
507                             count++;
508                         }
509                     }
510
511                     if (count > 0) {
512                         update_query_ext.disabled = false;
513                     }
514
515                 }
516
517
518                 
519                 // We have results from the main query
520                 // inspect subqueries and get the key for each
521
522                 // XXX note that we might need the name for each relation, but
523                 // this might be for SET_ADD, since we need to recursively find
524                 // the path from the main query
525
526
527                 tmp_query = manifold.find_query(query.query_uuid);
528                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
529             //}
530
531         }
532     },
533
534     /************************************************************************** 
535      * Plugin API helpers
536      **************************************************************************/ 
537
538     raise_event_handler: function(type, query_uuid, event_type, value)
539     {
540         if ((type != 'query') && (type != 'record'))
541             throw 'Incorrect type for manifold.raise_event()';
542
543         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
544
545         $.each(channels, function(i, channel) {
546             if (value === undefined)
547                 $('.plugin').trigger(channel, [event_type]);
548             else
549                 $('.plugin').trigger(channel, [event_type, value]);
550         });
551     },
552
553     raise_query_event: function(query_uuid, event_type, value)
554     {
555         manifold.raise_event_handler('query', query_uuid, event_type, value);
556     },
557
558     raise_record_event: function(query_uuid, event_type, value)
559     {
560         manifold.raise_event_handler('record', query_uuid, event_type, value);
561     },
562
563
564     raise_event: function(query_uuid, event_type, value)
565     {
566         // Query uuid has been updated with the key of a new element
567         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
568         query = query_ext.query;
569
570         switch(event_type) {
571             case FIELD_STATE_CHANGED:
572                 // value is an object (request, key, value, status)
573                 // update is only possible is the query is not pending, etc
574                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
575                 // we should map SET_ADD on this...
576
577                 // 1. Update internal query store about the change in status
578
579                 // 2. Update the update query
580                 update_query = query_ext.main_query_ext.update_query_ext.query;
581                 update_query.params[value.key].push(value.value);
582
583                 // 3. Inform others about the change
584                 // a) the main query...
585                 manifold.raise_record_event(query_uuid, event_type, value);
586
587                 // b) subqueries eventually (dot in the key)
588                 // XXX make this DOT a global variable... could be '/'
589                 break;
590
591             case SET_ADD:
592             case SET_REMOVED:
593     
594                 // update is only possible is the query is not pending, etc
595                 // CHECK status !
596
597                 // XXX we can only update subqueries of the main query. Check !
598                 // assert query_ext.parent_query == query_ext.main_query
599                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
600
601                 // This SET_ADD is called on a subquery, so we have to
602                 // recontruct the path of the key in the main_query
603                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
604
605                 var path = "";
606                 var sq = query_ext;
607                 while (sq.parent_query_ext) {
608                     if (path != "")
609                         path = '.' + path;
610                     path = sq.query.object + path;
611                     sq = sq.parent_query_ext;
612                 }
613
614                 main_query = query_ext.main_query_ext.query;
615                 data = {
616                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
617                     key   : path,
618                     value : value,
619                     status: FIELD_REQUEST_PENDING,
620                 };
621                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
622
623                 // old //update_query.params[path].push(value);
624                 // old // console.log('Updated query params', update_query);
625                 // NOTE: update might modify the fields in Get
626                 // NOTE : we have to modify all child queries
627                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
628
629                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
630                 // object = the same as get
631                 // filter = key : update a single object for now
632                 // fields = the same as get
633                 manifold.raise_query_event(query_uuid, event_type, value);
634
635                 break;
636
637             case RUN_UPDATE:
638                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
639                 break;
640
641             case FILTER_ADDED:
642                 manifold.raise_query_event(query_uuid, event_type, value);
643                 break;
644             case FILTER_REMOVED:
645                 manifold.raise_query_event(query_uuid, event_type, value);
646                 break;
647             case FIELD_ADDED:
648                 main_query = query_ext.main_query_ext.query;
649                 main_update_query = query_ext.main_query_ext.update_query;
650                 query.select(value);
651
652                 // Here we need the full path through all subqueries
653                 path = ""
654                 // XXX We might need the query name in the QueryExt structure
655                 main_query.select(value);
656
657                 // XXX When is an update query associated ?
658                 // XXX main_update_query.select(value);
659
660                 manifold.raise_query_event(query_uuid, event_type, value);
661                 break;
662
663             case FIELD_REMOVED:
664                 query = query_ext.query;
665                 main_query = query_ext.main_query_ext.query;
666                 main_update_query = query_ext.main_query_ext.update_query;
667                 query.unselect(value);
668                 main_query.unselect(value);
669
670                 // We need to inform about changes in these queries to the respective plugins
671                 // Note: query & main_query have the same UUID
672                 manifold.raise_query_event(query_uuid, event_type, value);
673                 break;
674         }
675         // We need to inform about changes in these queries to the respective plugins
676         // Note: query, main_query & update_query have the same UUID
677         manifold.raise_query_event(query_uuid, event_type, value);
678         // We are targeting the same object with get and update
679         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
680         // NOTE: Editing a subquery == editing a local view on the destination
681
682         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
683         // For the time being, we will collect all columns during the first query
684     },
685
686     /* Publish/subscribe channels for internal use */
687     get_channel: function(type, query_uuid) 
688     {
689         if ((type !== 'query') && (type != 'record'))
690             return null;
691         return '/' + type + '/' + query_uuid;
692     },
693
694 }; // manifold object
695 /* ------------------------------------------------------------ */
696
697 (function($) {
698
699     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
700     // https://gist.github.com/661855
701     var o = $({});
702     $.subscribe = function( channel, selector, data, fn) {
703       /* borrowed from jQuery */
704       if ( data == null && fn == null ) {
705           // ( channel, fn )
706           fn = selector;
707           data = selector = undefined;
708       } else if ( fn == null ) {
709           if ( typeof selector === "string" ) {
710               // ( channel, selector, fn )
711               fn = data;
712               data = undefined;
713           } else {
714               // ( channel, data, fn )
715               fn = data;
716               data = selector;
717               selector = undefined;
718           }
719       }
720       /* </ugly> */
721   
722       /* We use an indirection function that will clone the object passed in
723        * parameter to the subscribe callback 
724        * 
725        * FIXME currently we only clone query objects which are the only ones
726        * supported and editable, we might have the same issue with results but
727        * the page load time will be severely affected...
728        */
729       o.on.apply(o, [channel, selector, data, function() { 
730           for(i = 1; i < arguments.length; i++) {
731               if ( arguments[i].constructor.name == 'ManifoldQuery' )
732                   arguments[i] = arguments[i].clone();
733           }
734           fn.apply(o, arguments);
735       }]);
736     };
737   
738     $.unsubscribe = function() {
739       o.off.apply(o, arguments);
740     };
741   
742     $.publish = function() {
743       o.trigger.apply(o, arguments);
744     };
745   
746 }(jQuery));
747
748 /* ------------------------------------------------------------ */
749
750 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
751 //make sure to expose csrf in our outcoming ajax/post requests
752 $.ajaxSetup({ 
753      beforeSend: function(xhr, settings) {
754          function getCookie(name) {
755              var cookieValue = null;
756              if (document.cookie && document.cookie != '') {
757                  var cookies = document.cookie.split(';');
758                  for (var i = 0; i < cookies.length; i++) {
759                      var cookie = jQuery.trim(cookies[i]);
760                      // Does this cookie string begin with the name we want?
761                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
762                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
763                      break;
764                  }
765              }
766          }
767          return cookieValue;
768          }
769          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
770              // Only send the token to relative URLs i.e. locally.
771              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
772          }
773      } 
774 });
775