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