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