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