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