Remove outdated comment.
[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.list(); };
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(filter(id, name));
173         triggerSearch();
174         return false;
175     };
176
177
178     that.limitQuery = function(field, value) {
179         log("limitQuery(field=" + field + ", value=" + value + ")");
180         m_filterSet.add(filter(null, null, field, value));
181         triggerSearch();
182         return false;
183     };
184
185
186     that.limitCategory = function(id) {
187         log("limitCategory(id=" + id + ")");
188         // ### Add a filter
189         // ### triggerSearch() if there's a query
190         return false;
191     };
192
193
194     that.delimitTarget = function(id) {
195         log("delimitTarget(id=" + id + ")");
196         m_filterSet.removeMatching(function(f) { return f.id });
197         triggerSearch();
198         return false;
199     };
200
201
202     that.delimitQuery = function(field, value) {
203         log("delimitQuery(field=" + field + ", value=" + value + ")");
204         m_filterSet.removeMatching(function(f) { return f.field && field == f.field && value == f.value });
205         triggerSearch();
206         return false;
207     };
208
209
210     that.showPage = function(pageNum) {
211         m_currentPage = pageNum;
212         m_paz.showPage(m_currentPage - 1);
213     };
214
215
216     that.pagerNext = function() {
217         if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
218             m_paz.showNext();
219             m_currentPage++;
220         }
221     };
222
223
224     that.pagerPrev = function() {
225         if (m_paz.showPrev() != false)
226             m_currentPage--;
227     };
228
229
230     that.reShow = function() {
231         resetPage();
232         m_paz.show(0, m_perpage, m_sortOrder);
233     };
234
235
236     function resetPage() {
237         m_currentPage = 1;
238         m_totalRecordCount = 0;
239     }
240     that.resetPage = resetPage;
241
242
243     function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
244         log("newSearch: " + query);
245
246         if (m_config.use_service_proxy && !mkws.authenticated) {
247             alert("searching before authentication");
248             return;
249         }
250
251         m_filterSet = filterSet(that);
252         triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
253         switchView('records'); // In case it's configured to start off as hidden
254         m_submitted = true;
255     }
256     that.newSearch = newSearch;
257
258
259     function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
260         resetPage();
261         queue("navi").publish();
262
263
264         // Continue to use previous query/sort-order unless new ones are specified
265         if (query) {
266             m_query = query;
267         }
268         if (sortOrder) {
269             m_sortOrder = sortOrder;
270         }
271         if (perpage) {
272             m_perpage = perpage;
273         }
274         if (targets) {
275             m_filterSet.add(filter(id, id));
276         }
277
278         var pp2filter = m_filterSet.pp2filter();
279         var pp2limit = m_filterSet.pp2limit(limit);
280
281         var params = {};
282         if (pp2limit) {
283             params.limit = pp2limit;
284         }
285         if (maxrecs) {
286             params.maxrecs = maxrecs;
287         }
288         if (torusquery) {
289             if (!mkws.config.use_service_proxy)
290                 alert("can't narrow search by torusquery when Service Proxy is not in use");
291             params.torusquery = torusquery;
292         }
293
294         log("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filterSet.list()) + ", " +
295             "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
296
297         m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
298     }
299
300
301     // switching view between targets and records
302     function switchView(view) {
303         var targets = widgetNode('Targets');
304         var results = widgetNode('Results') || widgetNode('Records');
305         var blanket = widgetNode('Blanket');
306         var motd    = widgetNode('MOTD');
307
308         switch(view) {
309         case 'targets':
310             if (targets) targets.css('display', 'block');
311             if (results) results.css('display', 'none');
312             if (blanket) blanket.css('display', 'none');
313             if (motd) motd.css('display', 'none');
314             break;
315         case 'records':
316             if (targets) targets.css('display', 'none');
317             if (results) results.css('display', 'block');
318             if (blanket) blanket.css('display', 'block');
319             if (motd) motd.css('display', 'none');
320             break;
321         case 'none':
322             alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
323             if (targets) targets.css('display', 'none');
324             if (results) results.css('display', 'none');
325             if (blanket) blanket.css('display', 'none');
326             if (motd) motd.css('display', 'none');
327             break;
328         default:
329             alert("Unknown view '" + view + "'");
330         }
331     }
332     that.switchView = switchView;
333
334
335     // detailed record drawing
336     that.showDetails = function(recId) {
337         var oldRecordId = m_currentRecordId;
338         m_currentRecordId = recId;
339
340         // remove current detailed view if any
341         findnode('#' + recordDetailsId(oldRecordId)).remove();
342
343         // if the same clicked, just hide
344         if (recId == oldRecordId) {
345             m_currentRecordId = '';
346             m_currentRecordData = null;
347             return;
348         }
349         // request the record
350         log("showDetails() requesting record '" + recId + "'");
351         m_paz.record(recId);
352     };
353
354
355     /*
356      * All the HTML stuff to render the search forms and
357      * result pages.
358      */
359     function mkwsHtmlAll() {
360         mkwsSetLang();
361         if (m_config.show_lang)
362             mkwsHtmlLang();
363
364         log("HTML search form");
365         findnode('.mkwsSearch').html('\
366 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + m_teamName + '" action="" >\
367   <input class="mkwsQuery mkwsTeam_' + m_teamName + '" type="text" size="' + m_config.query_width + '" />\
368   <input class="mkwsButton mkwsTeam_' + m_teamName + '" type="submit" value="' + M('Search') + '" />\
369 </form>');
370
371         log("HTML records");
372         // If the team has a .mkwsResults, populate it in the usual
373         // way. If not, assume that it's a smarter application that
374         // defines its own subcomponents, some or all of the
375         // following:
376         //      .mkwsTermlists
377         //      .mkwsRanking
378         //      .mkwsPager
379         //      .mkwsNavi
380         //      .mkwsRecords
381         findnode(".mkwsResults").html('\
382 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
383   <tr>\
384     <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
385       <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
386     </td>\
387     <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
388       <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
389       <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
390       <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
391       <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
392     </td>\
393   </tr>\
394   <tr>\
395     <td colspan="2">\
396       <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
397     </td>\
398   </tr>\
399 </table>');
400
401         var acc = [];
402         var facets = m_config.facets;
403         acc.push('<div class="title">' + M('Termlists') + '</div>');
404         for (var i = 0; i < facets.length; i++) {
405             acc.push('<div class="mkwsFacet mkwsTeam_' + m_teamName + '" data-mkws-facet="' + facets[i] + '">');
406             acc.push('</div>');
407         }
408         findnode(".mkwsTermlists").html(acc.join(''));
409
410         var ranking_data = '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
411         if (m_config.show_sort) {
412             ranking_data +=  M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
413         }
414         if (m_config.show_perpage) {
415             ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
416         }
417         ranking_data += '</form>';
418         findnode(".mkwsRanking").html(ranking_data);
419
420         mkwsHtmlSwitch();
421
422         findnode('.mkwsSearchForm').submit(function() {
423             var val = widgetNode('Query').val();
424             newSearch(val);
425             return false;
426         });
427
428         // on first page, hide the termlist
429         $(document).ready(function() { widgetNode("Termlists").hide(); });
430         var container = findnode(".mkwsMOTDContainer");
431         if (container.length) {
432             // Move the MOTD from the provided element down into the container
433             findnode(".mkwsMOTD").appendTo(container);
434         }
435     }
436
437
438     function mkwsSetLang()  {
439         var lang = mkws.getParameterByName("lang") || m_config.lang;
440         if (!lang || !mkws.locale_lang[lang]) {
441             m_config.lang = ""
442         } else {
443             m_config.lang = lang;
444         }
445
446         log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
447         return m_config.lang;
448     }
449
450
451     /* create locale language menu */
452     function mkwsHtmlLang() {
453         var lang_default = "en";
454         var lang = m_config.lang || lang_default;
455         var list = [];
456
457         /* display a list of configured languages, or all */
458         var lang_options = m_config.lang_options || [];
459         var toBeIncluded = {};
460         for (var i = 0; i < lang_options.length; i++) {
461             toBeIncluded[lang_options[i]] = true;
462         }
463
464         for (var k in mkws.locale_lang) {
465             if (toBeIncluded[k] || lang_options.length == 0)
466                 list.push(k);
467         }
468
469         // add english link
470         if (lang_options.length == 0 || toBeIncluded[lang_default])
471             list.push(lang_default);
472
473         log("Language menu for: " + list.join(", "));
474
475         /* the HTML part */
476         var data = "";
477         for(var i = 0; i < list.length; i++) {
478             var l = list[i];
479
480             if (data)
481                 data += ' | ';
482
483             if (lang == l) {
484                 data += ' <span>' + l + '</span> ';
485             } else {
486                 data += ' <a href="?lang=' + l + '">' + l + '</a> '
487             }
488         }
489
490         findnode(".mkwsLang").html(data);
491     }
492
493
494     function mkwsHtmlSort() {
495         log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
496         var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
497
498         for(var i = 0; i < m_config.sort_options.length; i++) {
499             var opt = m_config.sort_options[i];
500             var key = opt[0];
501             var val = opt.length == 1 ? opt[0] : opt[1];
502
503             sort_html += '<option value="' + key + '"';
504             if (m_sortOrder == key || m_sortOrder == val) {
505                 sort_html += ' selected="selected"';
506             }
507             sort_html += '>' + M(val) + '</option>';
508         }
509         sort_html += '</select>';
510
511         return sort_html;
512     }
513
514
515     function mkwsHtmlPerpage() {
516         log("HTML perpage, m_perpage = " + m_perpage);
517         var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
518
519         for(var i = 0; i < m_config.perpage_options.length; i++) {
520             var key = m_config.perpage_options[i];
521
522             perpage_html += '<option value="' + key + '"';
523             if (key == m_perpage) {
524                 perpage_html += ' selected="selected"';
525             }
526             perpage_html += '>' + key + '</option>';
527         }
528         perpage_html += '</select>';
529
530         return perpage_html;
531     }
532
533
534     function mkwsHtmlSwitch() {
535         log("HTML switch for team " + m_teamName);
536
537         var node = findnode(".mkwsSwitch");
538         node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
539         node.append($("<span/>", { text: " | " }));
540         node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
541
542         log("HTML targets");
543         var node = findnode(".mkwsTargets");
544         node.html('\
545 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
546   No information available yet.\
547 </div>');
548         node.css("display", "none");
549     }
550
551
552     // Translation function. At present, this is properly a
553     // global-level function (hence the assignment to mkws.M) but we
554     // want to make it per-team so different teams can operate in
555     // different languages.
556     //
557     function M(word) {
558         var lang = m_config.lang;
559
560         if (!lang || !mkws.locale_lang[lang])
561             return word;
562
563         return mkws.locale_lang[lang][word] || word;
564     }
565     mkws.M = M; // so the Handlebars helper can use it
566
567
568     // Finds the node of the specified class within the current team
569     function findnode(selector, teamName) {
570         teamName = teamName || m_teamName;
571
572         if (teamName === 'AUTO') {
573             selector = (selector + '.mkwsTeam_' + teamName + ',' +
574                         selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
575         } else {
576             selector = selector + '.mkwsTeam_' + teamName;
577         }
578
579         var node = $(selector);
580         //log('findnode(' + selector + ') found ' + node.length + ' nodes');
581         return node;
582     }
583     that.findnode = findnode;
584
585
586     // This much simpler and more efficient function should be usable
587     // in place of most uses of findnode.
588     function widgetNode(type) {
589         var w = that.widget(type);
590         return w ? $(w.node) : undefined;
591     }
592
593     function renderDetails(data, marker) {
594         var template = loadTemplate("Record");
595         var details = template(data);
596         return '<div class="details mkwsTeam_' + m_teamName + '" ' +
597             'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
598     }
599     that.renderDetails = renderDetails;
600
601
602     function loadTemplate(name) {
603         var template = m_template[name];
604
605         if (template === undefined) {
606             // Fall back to generic template if there is no team-specific one
607             var source;
608             var node = widgetNode("Template_" + name);
609             if (!node) {
610                 node = widgetNode("Template_" + name, "ALL");
611             }
612             if (node) {
613                 source = node.html();
614             }
615
616             if (!source) {
617                 source = defaultTemplate(name);
618             }
619
620             template = Handlebars.compile(source);
621             log("compiled template '" + name + "'");
622             m_template[name] = template;
623         }
624
625         return template;
626     }
627     that.loadTemplate = loadTemplate;
628
629
630     function defaultTemplate(name) {
631         if (name === 'Record') {
632             return '\
633 <table>\
634   <tr>\
635     <th>{{translate "Title"}}</th>\
636     <td>\
637       {{md-title}}\
638       {{#if md-title-remainder}}\
639         ({{md-title-remainder}})\
640       {{/if}}\
641       {{#if md-title-responsibility}}\
642         <i>{{md-title-responsibility}}</i>\
643       {{/if}}\
644     </td>\
645   </tr>\
646   {{#if md-date}}\
647   <tr>\
648     <th>{{translate "Date"}}</th>\
649     <td>{{md-date}}</td>\
650   </tr>\
651   {{/if}}\
652   {{#if md-author}}\
653   <tr>\
654     <th>{{translate "Author"}}</th>\
655     <td>{{md-author}}</td>\
656   </tr>\
657   {{/if}}\
658   {{#if md-electronic-url}}\
659   <tr>\
660     <th>{{translate "Links"}}</th>\
661     <td>\
662       {{#each md-electronic-url}}\
663         <a href="{{this}}">Link{{index1}}</a>\
664       {{/each}}\
665     </td>\
666   </tr>\
667   {{/if}}\
668   {{#if-any location having="md-subject"}}\
669   <tr>\
670     <th>{{translate "Subject"}}</th>\
671     <td>\
672       {{#first location having="md-subject"}}\
673         {{#if md-subject}}\
674           {{#commaList md-subject}}\
675             {{this}}{{/commaList}}\
676         {{/if}}\
677       {{/first}}\
678     </td>\
679   </tr>\
680   {{/if-any}}\
681   <tr>\
682     <th>{{translate "Locations"}}</th>\
683     <td>\
684       {{#commaList location}}\
685         {{attr "@name"}}{{/commaList}}\
686     </td>\
687   </tr>\
688 </table>\
689 ';
690         } else if (name === "Summary") {
691             return '\
692 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
693   <b>{{md-title}}</b>\
694 </a>\
695 {{#if md-title-remainder}}\
696   <span>{{md-title-remainder}}</span>\
697 {{/if}}\
698 {{#if md-title-responsibility}}\
699   <span><i>{{md-title-responsibility}}</i></span>\
700 {{/if}}\
701 ';
702         } else if (name === "Image") {
703             return '\
704       <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
705         {{#first md-thumburl}}\
706           <img src="{{this}}" alt="{{../md-title}}"/>\
707         {{/first}}\
708         <br/>\
709       </a>\
710 ';
711         }
712
713         var s = "There is no default '" + name +"' template!";
714         alert(s);
715         return s;
716     }
717
718     that.addWidget = function(w) {
719         if (!m_widgets[w.type]) {
720             m_widgets[w.type] = w;
721             log("Registered '" + w.type + "' widget in team '" + m_teamName + "'");
722         } else if (typeof(m_widgets[w.type]) !== 'number') {
723             m_widgets[w.type] = 2;
724             log("Registered duplicate '" + w.type + "' widget in team '" + m_teamName + "'");
725         } else {
726             m_widgets[w.type] += 1;
727             log("Registered '" + w.type + "' widget #" + m_widgets[w.type] + "' in team '" + m_teamName + "'");
728         }
729     }
730
731     that.widgetTypes = function() {
732         var keys = [];
733         for (var k in m_widgets) keys.push(k);
734         return keys.sort();
735     }
736
737     that.widget = function(type) {
738         return m_widgets[type];
739     }
740
741     mkwsHtmlAll()
742
743     return that;
744 };