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