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