ead2f0311faff02717ca0bcb0f462b732767a3b7
[mkws-moved-to-github.git] / src / mkws-team.js
1 // Factory function for team objects. As much as possible, this uses
2 // only member variables (prefixed "m_") and inner functions with
3 // private scope.
4 //
5 // Some functions are visible as member-functions to be called from
6 // outside code -- specifically, from generated HTML. These functions
7 // are that.switchView(), showDetails(), limitTarget(), limitQuery(),
8 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
9 // pagerPrev(), pagerNext().
10 //
11 function team($, teamName) {
12   var that = {};
13   var m_teamName = teamName;
14   var m_submitted = false;
15   var m_query; // initially undefined
16   var m_sortOrder; // will be set below
17   var m_perpage; // will be set below
18   var m_filterSet = filterSet(that);
19   var m_totalRecordCount = 0;
20   var m_currentPage = 1;
21   var m_currentRecordId = '';
22   var m_currentRecordData = null;
23   var m_logTime = {
24     // Timestamps for logging
25     "start": $.now(),
26     "last": $.now()
27   };
28   var m_paz; // will be initialised below
29   var m_templateText = {}; // widgets can register templates to be compiled
30   var m_template = {}; // compiled templates, from any source
31   var m_widgets = {}; // Maps widget-type to array of widget objects
32   var m_gotRecords = false;
33   
34   var config = mkws.objectInheritingFrom(mkws.config);
35   that.config = config;
36
37   that.toString = function() { return '[Team ' + teamName + ']'; };
38
39   // Accessor methods for individual widgets: readers
40   that.name = function() { return m_teamName; };
41   that.submitted = function() { return m_submitted; };
42   that.sortOrder = function() { return m_sortOrder; };
43   that.perpage = function() { return m_perpage; };
44   that.totalRecordCount = function() { return m_totalRecordCount; };
45   that.currentPage = function() { return m_currentPage; };
46   that.currentRecordId = function() { return m_currentRecordId; };
47   that.currentRecordData = function() { return m_currentRecordData; };
48   that.filters = function() { return m_filterSet; };
49   that.gotRecords = function() { return m_gotRecords; };
50
51   // Accessor methods for individual widgets: writers
52   that.set_sortOrder = function(val) { m_sortOrder = val };
53   that.set_perpage = function(val) { m_perpage = val };
54
55
56   // The following PubSub code is modified from the jQuery manual:
57   // http://api.jquery.com/jQuery.Callbacks/
58   //
59   // Use as:
60   //    team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
61   //    team.queue("eventName").publish(arg1, arg2, ...);
62   //
63   var queues = {};
64   function queue(id) {
65     if (!queues[id]) {
66       var callbacks = $.Callbacks();
67       queues[id] = {
68         publish: callbacks.fire,
69         subscribe: callbacks.add,
70         unsubscribe: callbacks.remove
71       };
72     }
73     return queues[id];
74   };
75   that.queue = queue;
76
77
78   function log(s) {
79     var now = $.now();
80     var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
81                      ((now - m_logTime.last)/1000).toFixed(3) + ") ");
82     m_logTime.last = now;
83     mkws.log(m_teamName + ": " + timestamp + s);
84     that.queue("log").publish(m_teamName, timestamp, s);
85   }
86   that.log = log;
87
88
89   log("making new widget team");
90
91   m_sortOrder = config.sort_default;
92   m_perpage = config.perpage_default;
93
94   // create a parameters array and pass it to the pz2's constructor
95   // then register the form submit event with the pz2.search function
96   // autoInit is set to true on default
97   m_paz = new pz2({ "windowid": teamName,
98                     "pazpar2path": config.pazpar2_url,
99                     "usesessions" : config.use_service_proxy ? false : true,
100                     "oninit": onInit,
101                     "onbytarget": onBytarget,
102                     "onstat": onStat,
103                     "onterm": (config.facets.length ? onTerm : undefined),
104                     "onshow": onShow,
105                     "onrecord": onRecord,
106                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
107                     "termlist": config.facets.join(',')
108                   });
109   log("created main pz2 object");
110
111   // pz2.js event handlers:
112   function onInit() {
113     log("init");
114     m_paz.stat();
115     m_paz.bytarget();
116   }
117
118   function onBytarget(data) {
119     log("bytarget");
120     queue("targets").publish(data);
121   }
122
123   function onStat(data) {
124     queue("stat").publish(data);
125     var hitcount = parseInt(data.hits[0], 10);
126     if (!m_gotRecords && hitcount > 0) {
127       m_gotRecords = true;
128       queue("firstrecords").publish(hitcount);
129     }
130     if (parseInt(data.activeclients[0], 10) === 0) {
131       log("complete");
132       queue("complete").publish(hitcount);
133     }
134   }
135
136   function onTerm(data) {
137     log("term");
138     queue("termlists").publish(data);
139   }
140
141   function onShow(data, teamName) {
142     log("show");
143     m_totalRecordCount = data.merged;
144     log("found " + m_totalRecordCount + " records");
145     queue("pager").publish(data);
146     queue("records").publish(data);
147   }
148
149   function onRecord(data, args, teamName) {
150     log("record");
151     // FIXME: record is async!!
152     clearTimeout(m_paz.recordTimer);
153     queue("record").publish(data);
154     var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
155     if (detRecordDiv.length) {
156       // in case on_show was faster to redraw element
157       return;
158     }
159     m_currentRecordData = data;
160     var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
161     var html = renderDetails(m_currentRecordData);
162     $(recordDiv).append(html);
163   }
164
165
166   // Used by the Records widget and onRecord()
167   function recordElementId(s) {
168     return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
169   }
170   that.recordElementId = recordElementId;
171
172   // Used by onRecord(), showDetails() and renderDetails()
173   function recordDetailsId(s) {
174     return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
175   }
176
177
178   that.targetFiltered = function(id) {
179     return m_filterSet.targetFiltered(id);
180   };
181
182
183   that.limitTarget = function(id, name) {
184     log("limitTarget(id=" + id + ", name=" + name + ")");
185     m_filterSet.add(targetFilter(id, name));
186     if (m_query) triggerSearch();
187     return false;
188   };
189
190
191   that.limitQuery = function(field, value) {
192     log("limitQuery(field=" + field + ", value=" + value + ")");
193     m_filterSet.add(fieldFilter(field, value));
194     if (m_query) triggerSearch();
195     return false;
196   };
197
198
199   that.limitCategory = function(id) {
200     log("limitCategory(id=" + id + ")");
201     // Only one category filter at a time
202     m_filterSet.removeMatching(function(f) { return f.type === 'category' });
203     if (id !== '') m_filterSet.add(categoryFilter(id));
204     if (m_query) triggerSearch();
205     return false;
206   };
207
208
209   that.delimitTarget = function(id) {
210     log("delimitTarget(id=" + id + ")");
211     m_filterSet.removeMatching(function(f) { return f.type === 'target' });
212     if (m_query) triggerSearch();
213     return false;
214   };
215
216
217   that.delimitQuery = function(field, value) {
218     log("delimitQuery(field=" + field + ", value=" + value + ")");
219     m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
220                                              field == f.field && value == f.value });
221     if (m_query) triggerSearch();
222     return false;
223   };
224
225
226   that.showPage = function(pageNum) {
227     m_currentPage = pageNum;
228     m_paz.showPage(m_currentPage - 1);
229   };
230
231
232   that.pagerNext = function() {
233     if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
234       m_paz.showNext();
235       m_currentPage++;
236     }
237   };
238
239
240   that.pagerPrev = function() {
241     if (m_paz.showPrev() != false)
242       m_currentPage--;
243   };
244
245
246   that.reShow = function() {
247     resetPage();
248     m_paz.show(0, m_perpage, m_sortOrder);
249   };
250
251
252   function resetPage() {
253     m_currentPage = 1;
254     m_totalRecordCount = 0;
255     m_gotRecords = false;
256   }
257   that.resetPage = resetPage;
258
259
260   function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
261     log("newSearch: " + query);
262
263     if (config.use_service_proxy && !mkws.authenticated) {
264       alert("searching before authentication");
265       return;
266     }
267
268     m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
269     triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
270     switchView('records'); // In case it's configured to start off as hidden
271     m_submitted = true;
272   }
273   that.newSearch = newSearch;
274
275
276   function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
277     resetPage();
278     queue("navi").publish();
279
280     // Continue to use previous query/sort-order unless new ones are specified
281     if (query) m_query = query;
282     if (sortOrder) m_sortOrder = sortOrder;
283     if (perpage) m_perpage = perpage;
284     if (targets) m_filterSet.add(targetFilter(targets, targets));
285
286     var pp2filter = m_filterSet.pp2filter();
287     var pp2limit = m_filterSet.pp2limit(limit);
288     var pp2catLimit = m_filterSet.pp2catLimit();
289     if (pp2catLimit) {
290       pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
291     }
292
293     var params = {};
294     if (pp2limit) params.limit = pp2limit;
295     if (maxrecs) params.maxrecs = maxrecs;
296     if (torusquery) {
297       if (!mkws.config.use_service_proxy)
298         alert("can't narrow search by torusquery when not authenticated");
299       params.torusquery = torusquery;
300     }
301
302     log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
303         "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
304
305     m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
306   }
307
308   // fetch record details to be retrieved from the record queue
309   that.fetchDetails = function(recId) {
310     log("fetchDetails() requesting record '" + recId + "'");
311     m_paz.record(recId);
312   };
313
314
315   // switching view between targets and records
316   function switchView(view) {
317     var targets = widgetNode('Targets');
318     var results = widgetNode('Results') || widgetNode('Records');
319     var blanket = widgetNode('Blanket');
320     var motd    = widgetNode('MOTD');
321
322     switch(view) {
323     case 'targets':
324       if (targets) $(targets).show();
325       if (results) $(results).hide();
326       if (blanket) $(blanket).hide();
327       if (motd) $(motd).hide();
328       break;
329     case 'records':
330       if (targets) $(targets).hide();
331       if (results) $(results).show();
332       if (blanket) $(blanket).show();
333       if (motd) $(motd).hide();
334       break;
335     default:
336       alert("Unknown view '" + view + "'");
337     }
338   }
339   that.switchView = switchView;
340
341
342   // detailed record drawing
343   that.showDetails = function(recId) {
344     var oldRecordId = m_currentRecordId;
345     m_currentRecordId = recId;
346
347     // remove current detailed view if any
348     findnode('#' + recordDetailsId(oldRecordId)).remove();
349
350     // if the same clicked, just hide
351     if (recId == oldRecordId) {
352       m_currentRecordId = '';
353       m_currentRecordData = null;
354       return;
355     }
356     // request the record
357     log("showDetails() requesting record '" + recId + "'");
358     m_paz.record(recId);
359   };
360
361
362   // Finds the node of the specified class within the current team
363   function findnode(selector, teamName) {
364     teamName = teamName || m_teamName;
365
366     if (teamName === 'AUTO') {
367       selector = (selector + '.mkwsTeam_' + teamName + ',' +
368                   selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
369     } else {
370       selector = selector + '.mkwsTeam_' + teamName;
371     }
372
373     var node = $(selector);
374     //log('findnode(' + selector + ') found ' + node.length + ' nodes');
375     return node;
376   }
377
378
379   function widgetNode(type) {
380     var w = that.widget(type);
381     return w ? w.node : undefined;
382   }
383
384   function renderDetails(data, marker) {
385     var template = loadTemplate("Record");
386     var details = template(data);
387     return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
388       'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
389   }
390   that.renderDetails = renderDetails;
391
392
393   that.registerTemplate = function(name, text) {
394     m_templateText[name] = text;
395   };
396
397
398   function loadTemplate(name, fallbackString) {
399     var template = m_template[name];
400     if (template === undefined && Handlebars.compile) {
401       var source;
402       var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
403       if (node && node.length < 1) {
404         node = $(".mkwsTemplate_" + name);
405       }
406       if (node) source = node.html();
407       if (!source) source = m_templateText[name];
408       if (source) {
409         template = Handlebars.compile(source);
410         log("compiled template '" + name + "'");
411       }
412     }
413     //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
414     if (template === undefined && Handlebars.templates) {
415       template = Handlebars.templates[name];
416     }
417     if (template === undefined && mkws.defaultTemplates) {
418       template = mkws.defaultTemplates[name];
419     }
420     if (template) {
421       m_template[name] = template;
422       return template;
423     }
424     else {
425       mkws.log("No MKWS template for " + name);
426       return null;
427     }  
428   }
429   that.loadTemplate = loadTemplate;
430
431
432   that.addWidget = function(w) {
433     if (m_widgets[w.type] === undefined) {
434       m_widgets[w.type] = [ w ];
435     } else {
436       m_widgets[w.type].push(w);
437     }
438   }
439
440   that.widget = function(type) {
441     var list = m_widgets[type];
442
443     if (!list)
444       return undefined;
445     if (list.length > 1) {
446       alert("widget('" + type + "') finds " + list.length + " widgets: using first");
447     }
448     return list[0];
449   }
450
451   that.visitWidgets = function(callback) {
452     for (var type in m_widgets) {
453       var list = m_widgets[type];
454       for (var i = 0; i < list.length; i++) {
455         var res = callback(type, list[i]);
456         if (res !== undefined) {
457           return res;
458         }
459       }
460     }
461     return undefined;
462   }
463
464
465   return that;
466 };