Remove any old category filters when setting a new one.
[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_template = {};
30     var m_config = mkws.objectInheritingFrom(mkws.config);
31     var m_widgets = {}; // Maps widget-type to object
32
33     that.toString = function() { return '[Team ' + teamName + ']'; };
34
35     // Accessor methods for individual widgets: readers
36     that.name = function() { return m_teamName; };
37     that.submitted = function() { return m_submitted; };
38     that.perpage = function() { return m_perpage; };
39     that.totalRecordCount = function() { return m_totalRecordCount; };
40     that.currentPage = function() { return m_currentPage; };
41     that.currentRecordId = function() { return m_currentRecordId; };
42     that.currentRecordData = function() { return m_currentRecordData; };
43     that.filters = function() { return m_filterSet; };
44     that.config = function() { return m_config; };
45
46     // Accessor methods for individual widgets: writers
47     that.set_sortOrder = function(val) { m_sortOrder = val };
48     that.set_perpage = function(val) { m_perpage = val };
49
50
51     // The following PubSub code is modified from the jQuery manual:
52     // http://api.jquery.com/jQuery.Callbacks/
53     //
54     // Use as:
55     //  team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
56     //  team.queue("eventName").publish(arg1, arg2, ...);
57     //
58     var queues = {};
59     function queue(id) {
60         if (!queues[id]) {
61             var callbacks = $.Callbacks();
62             queues[id] = {
63                 publish: callbacks.fire,
64                 subscribe: callbacks.add,
65                 unsubscribe: callbacks.remove
66             };
67         }
68         return queues[id];
69     };
70     that.queue = queue;
71
72
73     function log(s) {
74         var now = $.now();
75         var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
76                          ((now - m_logTime.last)/1000).toFixed(3) + ") ");
77         m_logTime.last = now;
78         mkws.log(m_teamName + ": " + timestamp + s);
79         that.queue("log").publish(m_teamName, timestamp, s);
80     }
81     that.log = log;
82
83
84     log("start running MKWS");
85
86     m_sortOrder = m_config.sort_default;
87     m_perpage = m_config.perpage_default;
88
89     log("Create main pz2 object");
90     // create a parameters array and pass it to the pz2's constructor
91     // then register the form submit event with the pz2.search function
92     // autoInit is set to true on default
93     m_paz = new pz2({ "windowid": teamName,
94                       "pazpar2path": m_config.pazpar2_url,
95                       "usesessions" : m_config.use_service_proxy ? false : true,
96                       "oninit": onInit,
97                       "onbytarget": onBytarget,
98                       "onstat": onStat,
99                       "onterm": (m_config.facets.length ? onTerm : undefined),
100                       "onshow": onShow,
101                       "onrecord": onRecord,
102                       "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
103                       "termlist": m_config.facets.join(',')
104                     });
105
106     // pz2.js event handlers:
107     function onInit() {
108         log("init");
109         m_paz.stat();
110         m_paz.bytarget();
111     }
112
113     function onBytarget(data) {
114         log("target");
115         queue("targets").publish(data);
116     }
117
118     function onStat(data) {
119         queue("stat").publish(data);
120         if (parseInt(data.activeclients[0], 10) === 0)
121             queue("complete").publish(parseInt(data.hits[0], 10));
122     }
123
124     function onTerm(data) {
125         log("term");
126         queue("termlists").publish(data);
127     }
128
129     function onShow(data, teamName) {
130         log("show");
131         m_totalRecordCount = data.merged;
132         log("found " + m_totalRecordCount + " records");
133         queue("pager").publish(data);
134         queue("records").publish(data);
135     }
136
137     function onRecord(data, args, teamName) {
138         log("record");
139         // FIXME: record is async!!
140         clearTimeout(m_paz.recordTimer);
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     // Used by the Records widget and onRecord()
154     function recordElementId(s) {
155         return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
156     }
157     that.recordElementId = recordElementId;
158
159     // Used by onRecord(), showDetails() and renderDetails()
160     function recordDetailsId(s) {
161         return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
162     }
163
164
165     that.targetFiltered = function(id) {
166         return m_filterSet.targetFiltered(id);
167     };
168
169
170     that.limitTarget = function(id, name) {
171         log("limitTarget(id=" + id + ", name=" + name + ")");
172         m_filterSet.add(targetFilter(id, name));
173         if (m_query) triggerSearch();
174         return false;
175     };
176
177
178     that.limitQuery = function(field, value) {
179         log("limitQuery(field=" + field + ", value=" + value + ")");
180         m_filterSet.add(fieldFilter(field, value));
181         if (m_query) triggerSearch();
182         return false;
183     };
184
185
186     that.limitCategory = function(id) {
187         log("limitCategory(id=" + id + ")");
188         // Only one category filter at a time
189         m_filterSet.removeMatching(function(f) { return f.type === 'category' });        
190         if (id !== '') m_filterSet.add(categoryFilter(id));
191         if (m_query) triggerSearch();
192         return false;
193     };
194
195
196     that.delimitTarget = function(id) {
197         log("delimitTarget(id=" + id + ")");
198         m_filterSet.removeMatching(function(f) { return f.type === 'target' });
199         if (m_query) triggerSearch();
200         return false;
201     };
202
203
204     that.delimitQuery = function(field, value) {
205         log("delimitQuery(field=" + field + ", value=" + value + ")");
206         m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
207                                                  field == f.field && value == f.value });
208         if (m_query) triggerSearch();
209         return false;
210     };
211
212
213     that.showPage = function(pageNum) {
214         m_currentPage = pageNum;
215         m_paz.showPage(m_currentPage - 1);
216     };
217
218
219     that.pagerNext = function() {
220         if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
221             m_paz.showNext();
222             m_currentPage++;
223         }
224     };
225
226
227     that.pagerPrev = function() {
228         if (m_paz.showPrev() != false)
229             m_currentPage--;
230     };
231
232
233     that.reShow = function() {
234         resetPage();
235         m_paz.show(0, m_perpage, m_sortOrder);
236     };
237
238
239     function resetPage() {
240         m_currentPage = 1;
241         m_totalRecordCount = 0;
242     }
243     that.resetPage = resetPage;
244
245
246     function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
247         log("newSearch: " + query);
248
249         if (m_config.use_service_proxy && !mkws.authenticated) {
250             alert("searching before authentication");
251             return;
252         }
253
254         m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
255         triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
256         switchView('records'); // In case it's configured to start off as hidden
257         m_submitted = true;
258     }
259     that.newSearch = newSearch;
260
261
262     function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
263         resetPage();
264         queue("navi").publish();
265
266         // Continue to use previous query/sort-order unless new ones are specified
267         if (query) m_query = query;
268         if (sortOrder) m_sortOrder = sortOrder;
269         if (perpage) m_perpage = perpage;
270         if (targets) m_filterSet.add(targetFilter(id, id));
271
272         var pp2filter = m_filterSet.pp2filter();
273         var pp2limit = m_filterSet.pp2limit(limit);
274         var pp2catLimit = m_filterSet.pp2catLimit();
275
276         var params = {};
277         if (pp2limit) params.limit = pp2limit;
278         if (pp2catLimit) params.categoryfilter = pp2catLimit;
279         if (maxrecs) params.maxrecs = maxrecs;
280         if (torusquery) {
281             if (!mkws.config.use_service_proxy)
282                 alert("can't narrow search by torusquery when Service Proxy is not in use");
283             params.torusquery = torusquery;
284         }
285
286         log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
287             "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
288
289         m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
290     }
291
292
293     // switching view between targets and records
294     function switchView(view) {
295         var targets = widgetNode('Targets');
296         var results = widgetNode('Results') || widgetNode('Records');
297         var blanket = widgetNode('Blanket');
298         var motd    = widgetNode('MOTD');
299
300         switch(view) {
301         case 'targets':
302             if (targets) targets.css('display', 'block');
303             if (results) results.css('display', 'none');
304             if (blanket) blanket.css('display', 'none');
305             if (motd) motd.css('display', 'none');
306             break;
307         case 'records':
308             if (targets) targets.css('display', 'none');
309             if (results) results.css('display', 'block');
310             if (blanket) blanket.css('display', 'block');
311             if (motd) motd.css('display', 'none');
312             break;
313         case 'none':
314             alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
315             if (targets) targets.css('display', 'none');
316             if (results) results.css('display', 'none');
317             if (blanket) blanket.css('display', 'none');
318             if (motd) motd.css('display', 'none');
319             break;
320         default:
321             alert("Unknown view '" + view + "'");
322         }
323     }
324     that.switchView = switchView;
325
326
327     // detailed record drawing
328     that.showDetails = function(recId) {
329         var oldRecordId = m_currentRecordId;
330         m_currentRecordId = recId;
331
332         // remove current detailed view if any
333         findnode('#' + recordDetailsId(oldRecordId)).remove();
334
335         // if the same clicked, just hide
336         if (recId == oldRecordId) {
337             m_currentRecordId = '';
338             m_currentRecordData = null;
339             return;
340         }
341         // request the record
342         log("showDetails() requesting record '" + recId + "'");
343         m_paz.record(recId);
344     };
345
346
347     /*
348      * All the HTML stuff to render the search forms and
349      * result pages.
350      */
351     function mkwsHtmlAll() {
352         mkwsSetLang();
353         if (m_config.show_lang)
354             mkwsHtmlLang();
355
356         log("HTML search form");
357         findnode('.mkwsSearch').html('\
358 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + m_teamName + '" action="" >\
359   <input class="mkwsQuery mkwsTeam_' + m_teamName + '" type="text" size="' + m_config.query_width + '" />\
360   <input class="mkwsButton mkwsTeam_' + m_teamName + '" type="submit" value="' + M('Search') + '" />\
361 </form>');
362
363         log("HTML records");
364         // If the team has a .mkwsResults, populate it in the usual
365         // way. If not, assume that it's a smarter application that
366         // defines its own subcomponents, some or all of the
367         // following:
368         //      .mkwsTermlists
369         //      .mkwsRanking
370         //      .mkwsPager
371         //      .mkwsNavi
372         //      .mkwsRecords
373         findnode(".mkwsResults").html('\
374 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
375   <tr>\
376     <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
377       <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
378     </td>\
379     <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
380       <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
381       <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
382       <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
383       <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
384     </td>\
385   </tr>\
386   <tr>\
387     <td colspan="2">\
388       <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
389     </td>\
390   </tr>\
391 </table>');
392
393         var acc = [];
394         var facets = m_config.facets;
395         acc.push('<div class="title">' + M('Termlists') + '</div>');
396         for (var i = 0; i < facets.length; i++) {
397             acc.push('<div class="mkwsFacet mkwsTeam_' + m_teamName + '" data-mkws-facet="' + facets[i] + '">');
398             acc.push('</div>');
399         }
400         findnode(".mkwsTermlists").html(acc.join(''));
401
402         var ranking_data = '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
403         if (m_config.show_sort) {
404             ranking_data +=  M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
405         }
406         if (m_config.show_perpage) {
407             ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
408         }
409         ranking_data += '</form>';
410         findnode(".mkwsRanking").html(ranking_data);
411
412         mkwsHtmlSwitch();
413
414         findnode('.mkwsSearchForm').submit(function() {
415             var val = widgetNode('Query').val();
416             newSearch(val);
417             return false;
418         });
419
420         // on first page, hide the termlist
421         $(document).ready(function() { widgetNode("Termlists").hide(); });
422         var container = findnode(".mkwsMOTDContainer");
423         if (container.length) {
424             // Move the MOTD from the provided element down into the container
425             findnode(".mkwsMOTD").appendTo(container);
426         }
427     }
428
429
430     function mkwsSetLang()  {
431         var lang = mkws.getParameterByName("lang") || m_config.lang;
432         if (!lang || !mkws.locale_lang[lang]) {
433             m_config.lang = ""
434         } else {
435             m_config.lang = lang;
436         }
437
438         log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
439         return m_config.lang;
440     }
441
442
443     /* create locale language menu */
444     function mkwsHtmlLang() {
445         var lang_default = "en";
446         var lang = m_config.lang || lang_default;
447         var list = [];
448
449         /* display a list of configured languages, or all */
450         var lang_options = m_config.lang_options || [];
451         var toBeIncluded = {};
452         for (var i = 0; i < lang_options.length; i++) {
453             toBeIncluded[lang_options[i]] = true;
454         }
455
456         for (var k in mkws.locale_lang) {
457             if (toBeIncluded[k] || lang_options.length == 0)
458                 list.push(k);
459         }
460
461         // add english link
462         if (lang_options.length == 0 || toBeIncluded[lang_default])
463             list.push(lang_default);
464
465         log("Language menu for: " + list.join(", "));
466
467         /* the HTML part */
468         var data = "";
469         for(var i = 0; i < list.length; i++) {
470             var l = list[i];
471
472             if (data)
473                 data += ' | ';
474
475             if (lang == l) {
476                 data += ' <span>' + l + '</span> ';
477             } else {
478                 data += ' <a href="?lang=' + l + '">' + l + '</a> '
479             }
480         }
481
482         findnode(".mkwsLang").html(data);
483     }
484
485
486     function mkwsHtmlSort() {
487         log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
488         var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
489
490         for(var i = 0; i < m_config.sort_options.length; i++) {
491             var opt = m_config.sort_options[i];
492             var key = opt[0];
493             var val = opt.length == 1 ? opt[0] : opt[1];
494
495             sort_html += '<option value="' + key + '"';
496             if (m_sortOrder == key || m_sortOrder == val) {
497                 sort_html += ' selected="selected"';
498             }
499             sort_html += '>' + M(val) + '</option>';
500         }
501         sort_html += '</select>';
502
503         return sort_html;
504     }
505
506
507     function mkwsHtmlPerpage() {
508         log("HTML perpage, m_perpage = " + m_perpage);
509         var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
510
511         for(var i = 0; i < m_config.perpage_options.length; i++) {
512             var key = m_config.perpage_options[i];
513
514             perpage_html += '<option value="' + key + '"';
515             if (key == m_perpage) {
516                 perpage_html += ' selected="selected"';
517             }
518             perpage_html += '>' + key + '</option>';
519         }
520         perpage_html += '</select>';
521
522         return perpage_html;
523     }
524
525
526     function mkwsHtmlSwitch() {
527         log("HTML switch for team " + m_teamName);
528
529         var node = findnode(".mkwsSwitch");
530         node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
531         node.append($("<span/>", { text: " | " }));
532         node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
533
534         log("HTML targets");
535         var node = findnode(".mkwsTargets");
536         node.html('\
537 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
538   No information available yet.\
539 </div>');
540         node.css("display", "none");
541     }
542
543
544     // Translation function. At present, this is properly a
545     // global-level function (hence the assignment to mkws.M) but we
546     // want to make it per-team so different teams can operate in
547     // different languages.
548     //
549     function M(word) {
550         var lang = m_config.lang;
551
552         if (!lang || !mkws.locale_lang[lang])
553             return word;
554
555         return mkws.locale_lang[lang][word] || word;
556     }
557     mkws.M = M; // so the Handlebars helper can use it
558
559
560     // Finds the node of the specified class within the current team
561     function findnode(selector, teamName) {
562         teamName = teamName || m_teamName;
563
564         if (teamName === 'AUTO') {
565             selector = (selector + '.mkwsTeam_' + teamName + ',' +
566                         selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
567         } else {
568             selector = selector + '.mkwsTeam_' + teamName;
569         }
570
571         var node = $(selector);
572         //log('findnode(' + selector + ') found ' + node.length + ' nodes');
573         return node;
574     }
575     that.findnode = findnode;
576
577
578     // This much simpler and more efficient function should be usable
579     // in place of most uses of findnode.
580     function widgetNode(type) {
581         var w = that.widget(type);
582         return w ? $(w.node) : undefined;
583     }
584
585     function renderDetails(data, marker) {
586         var template = loadTemplate("Record");
587         var details = template(data);
588         return '<div class="details mkwsTeam_' + m_teamName + '" ' +
589             'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
590     }
591     that.renderDetails = renderDetails;
592
593
594     function loadTemplate(name) {
595         var template = m_template[name];
596
597         if (template === undefined) {
598             // Fall back to generic template if there is no team-specific one
599             var source;
600             var node = widgetNode("Template_" + name);
601             if (!node) {
602                 node = widgetNode("Template_" + name, "ALL");
603             }
604             if (node) {
605                 source = node.html();
606             }
607
608             if (!source) {
609                 source = defaultTemplate(name);
610             }
611
612             template = Handlebars.compile(source);
613             log("compiled template '" + name + "'");
614             m_template[name] = template;
615         }
616
617         return template;
618     }
619     that.loadTemplate = loadTemplate;
620
621
622     function defaultTemplate(name) {
623         if (name === 'Record') {
624             return '\
625 <table>\
626   <tr>\
627     <th>{{translate "Title"}}</th>\
628     <td>\
629       {{md-title}}\
630       {{#if md-title-remainder}}\
631         ({{md-title-remainder}})\
632       {{/if}}\
633       {{#if md-title-responsibility}}\
634         <i>{{md-title-responsibility}}</i>\
635       {{/if}}\
636     </td>\
637   </tr>\
638   {{#if md-date}}\
639   <tr>\
640     <th>{{translate "Date"}}</th>\
641     <td>{{md-date}}</td>\
642   </tr>\
643   {{/if}}\
644   {{#if md-author}}\
645   <tr>\
646     <th>{{translate "Author"}}</th>\
647     <td>{{md-author}}</td>\
648   </tr>\
649   {{/if}}\
650   {{#if md-electronic-url}}\
651   <tr>\
652     <th>{{translate "Links"}}</th>\
653     <td>\
654       {{#each md-electronic-url}}\
655         <a href="{{this}}">Link{{index1}}</a>\
656       {{/each}}\
657     </td>\
658   </tr>\
659   {{/if}}\
660   {{#if-any location having="md-subject"}}\
661   <tr>\
662     <th>{{translate "Subject"}}</th>\
663     <td>\
664       {{#first location having="md-subject"}}\
665         {{#if md-subject}}\
666           {{#commaList md-subject}}\
667             {{this}}{{/commaList}}\
668         {{/if}}\
669       {{/first}}\
670     </td>\
671   </tr>\
672   {{/if-any}}\
673   <tr>\
674     <th>{{translate "Locations"}}</th>\
675     <td>\
676       {{#commaList location}}\
677         {{attr "@name"}}{{/commaList}}\
678     </td>\
679   </tr>\
680 </table>\
681 ';
682         } else if (name === "Summary") {
683             return '\
684 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
685   <b>{{md-title}}</b>\
686 </a>\
687 {{#if md-title-remainder}}\
688   <span>{{md-title-remainder}}</span>\
689 {{/if}}\
690 {{#if md-title-responsibility}}\
691   <span><i>{{md-title-responsibility}}</i></span>\
692 {{/if}}\
693 ';
694         } else if (name === "Image") {
695             return '\
696       <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
697         {{#first md-thumburl}}\
698           <img src="{{this}}" alt="{{../md-title}}"/>\
699         {{/first}}\
700         <br/>\
701       </a>\
702 ';
703         }
704
705         var s = "There is no default '" + name +"' template!";
706         alert(s);
707         return s;
708     }
709
710     that.addWidget = function(w) {
711         if (!m_widgets[w.type]) {
712             m_widgets[w.type] = w;
713             log("Registered '" + w.type + "' widget in team '" + m_teamName + "'");
714         } else if (typeof(m_widgets[w.type]) !== 'number') {
715             m_widgets[w.type] = 2;
716             log("Registered duplicate '" + w.type + "' widget in team '" + m_teamName + "'");
717         } else {
718             m_widgets[w.type] += 1;
719             log("Registered '" + w.type + "' widget #" + m_widgets[w.type] + "' in team '" + m_teamName + "'");
720         }
721     }
722
723     that.widgetTypes = function() {
724         var keys = [];
725         for (var k in m_widgets) keys.push(k);
726         return keys.sort();
727     }
728
729     that.widget = function(type) {
730         return m_widgets[type];
731     }
732
733     mkwsHtmlAll()
734
735     return that;
736 };