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