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