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