Remove Search and SearchForm code, now down in the widgets.
[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         log("HTML records");
360         // If the team has a .mkwsResults, populate it in the usual
361         // way. If not, assume that it's a smarter application that
362         // defines its own subcomponents, some or all of the
363         // following:
364         //      .mkwsTermlists
365         //      .mkwsRanking
366         //      .mkwsPager
367         //      .mkwsNavi
368         //      .mkwsRecords
369         findnode(".mkwsResults").html('\
370 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
371   <tr>\
372     <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
373       <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
374     </td>\
375     <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
376       <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
377       <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
378       <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
379       <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
380     </td>\
381   </tr>\
382   <tr>\
383     <td colspan="2">\
384       <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
385     </td>\
386   </tr>\
387 </table>');
388
389         var acc = [];
390         var facets = m_config.facets;
391         acc.push('<div class="title">' + M('Termlists') + '</div>');
392         for (var i = 0; i < facets.length; i++) {
393             acc.push('<div class="mkwsFacet mkwsTeam_' + m_teamName + '" data-mkws-facet="' + facets[i] + '">');
394             acc.push('</div>');
395         }
396         findnode(".mkwsTermlists").html(acc.join(''));
397
398         var ranking_data = '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
399         if (m_config.show_sort) {
400             ranking_data +=  M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
401         }
402         if (m_config.show_perpage) {
403             ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
404         }
405         ranking_data += '</form>';
406         findnode(".mkwsRanking").html(ranking_data);
407
408         // on first page, hide the termlist
409         $(document).ready(function() {
410             var t = widgetNode("Termlists");
411             if (t) t.hide();
412         });
413         var container = findnode(".mkwsMOTDContainer");
414         if (container.length) {
415             // Move the MOTD from the provided element down into the container
416             findnode(".mkwsMOTD").appendTo(container);
417         }
418     }
419
420
421     function mkwsSetLang()  {
422         var lang = mkws.getParameterByName("lang") || m_config.lang;
423         if (!lang || !mkws.locale_lang[lang]) {
424             m_config.lang = ""
425         } else {
426             m_config.lang = lang;
427         }
428
429         log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
430         return m_config.lang;
431     }
432
433     // set or re-set "lang" URL parameter
434     function lang_url(lang) {
435         var query = location.search;
436         // no query parameters? done
437         if (!query) {
438             return "?lang=" + lang;
439         }
440
441         // parameter does not exists
442         if (!query.match(/[\?&]lang=/)) {
443             return query + "&lang=" + lang;
444         }
445
446         // replace existing parameter
447         query = query.replace(/\?lang=([^&#;]*)/, "?lang=" + lang);
448         query = query.replace(/\&lang=([^&#;]*)/, "&lang=" + lang);
449
450         return query;
451     }
452    
453         // dynamic URL or static page? /path/foo?query=test
454     /* create locale language menu */
455     function mkwsHtmlLang() {
456         var lang_default = "en";
457         var lang = m_config.lang || lang_default;
458         var list = [];
459
460         /* display a list of configured languages, or all */
461         var lang_options = m_config.lang_options || [];
462         var toBeIncluded = {};
463         for (var i = 0; i < lang_options.length; i++) {
464             toBeIncluded[lang_options[i]] = true;
465         }
466
467         for (var k in mkws.locale_lang) {
468             if (toBeIncluded[k] || lang_options.length == 0)
469                 list.push(k);
470         }
471
472         // add english link
473         if (lang_options.length == 0 || toBeIncluded[lang_default])
474             list.push(lang_default);
475
476         log("Language menu for: " + list.join(", "));
477
478         /* the HTML part */
479         var data = "";
480         for(var i = 0; i < list.length; i++) {
481             var l = list[i];
482
483             if (data)
484                 data += ' | ';
485
486             if (lang == l) {
487                 data += ' <span>' + l + '</span> ';
488             } else {
489                 data += ' <a href="' + lang_url(l) + '">' + l + '</a> '
490             }
491         }
492
493         findnode(".mkwsLang").html(data);
494     }
495
496
497     function mkwsHtmlSort() {
498         log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
499         var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
500
501         for(var i = 0; i < m_config.sort_options.length; i++) {
502             var opt = m_config.sort_options[i];
503             var key = opt[0];
504             var val = opt.length == 1 ? opt[0] : opt[1];
505
506             sort_html += '<option value="' + key + '"';
507             if (m_sortOrder == key || m_sortOrder == val) {
508                 sort_html += ' selected="selected"';
509             }
510             sort_html += '>' + M(val) + '</option>';
511         }
512         sort_html += '</select>';
513
514         return sort_html;
515     }
516
517
518     function mkwsHtmlPerpage() {
519         log("HTML perpage, m_perpage = " + m_perpage);
520         var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
521
522         for(var i = 0; i < m_config.perpage_options.length; i++) {
523             var key = m_config.perpage_options[i];
524
525             perpage_html += '<option value="' + key + '"';
526             if (key == m_perpage) {
527                 perpage_html += ' selected="selected"';
528             }
529             perpage_html += '>' + key + '</option>';
530         }
531         perpage_html += '</select>';
532
533         return perpage_html;
534     }
535
536
537     // Translation function. At present, this is properly a
538     // global-level function (hence the assignment to mkws.M) but we
539     // want to make it per-team so different teams can operate in
540     // different languages.
541     //
542     function M(word) {
543         var lang = m_config.lang;
544
545         if (!lang || !mkws.locale_lang[lang])
546             return word;
547
548         return mkws.locale_lang[lang][word] || word;
549     }
550     mkws.M = M; // so the Handlebars helper can use it
551
552
553     // Finds the node of the specified class within the current team
554     function findnode(selector, teamName) {
555         teamName = teamName || m_teamName;
556
557         if (teamName === 'AUTO') {
558             selector = (selector + '.mkwsTeam_' + teamName + ',' +
559                         selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
560         } else {
561             selector = selector + '.mkwsTeam_' + teamName;
562         }
563
564         var node = $(selector);
565         //log('findnode(' + selector + ') found ' + node.length + ' nodes');
566         return node;
567     }
568     that.findnode = findnode;
569
570
571     // This much simpler and more efficient function should be usable
572     // in place of most uses of findnode.
573     function widgetNode(type) {
574         var w = that.widget(type);
575         return w ? $(w.node) : undefined;
576     }
577
578     function renderDetails(data, marker) {
579         var template = loadTemplate("Record");
580         var details = template(data);
581         return '<div class="details mkwsTeam_' + m_teamName + '" ' +
582             'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
583     }
584     that.renderDetails = renderDetails;
585
586
587     that.registerTemplate = function(name, text) {
588         m_tempateText[name] = text;
589     };
590
591
592     function loadTemplate(name) {
593         var template = m_template[name];
594
595         if (template === undefined) {
596             // Fall back to generic template if there is no team-specific one
597             var source;
598             var node = widgetNode("Template_" + name);
599             if (!node) {
600                 node = widgetNode("Template_" + name, "ALL");
601             }
602             if (node) {
603                 source = node.html();
604             }
605
606             if (!source) {
607                 source = m_tempateText[name];
608             }
609             if (!source) {
610                 source = defaultTemplate(name);
611             }
612
613             template = Handlebars.compile(source);
614             log("compiled template '" + name + "'");
615             m_template[name] = template;
616         }
617
618         return template;
619     }
620     that.loadTemplate = loadTemplate;
621
622
623     function defaultTemplate(name) {
624         if (name === 'Record') {
625             return '\
626 <table>\
627   <tr>\
628     <th>{{translate "Title"}}</th>\
629     <td>\
630       {{md-title}}\
631       {{#if md-title-remainder}}\
632         ({{md-title-remainder}})\
633       {{/if}}\
634       {{#if md-title-responsibility}}\
635         <i>{{md-title-responsibility}}</i>\
636       {{/if}}\
637     </td>\
638   </tr>\
639   {{#if md-date}}\
640   <tr>\
641     <th>{{translate "Date"}}</th>\
642     <td>{{md-date}}</td>\
643   </tr>\
644   {{/if}}\
645   {{#if md-author}}\
646   <tr>\
647     <th>{{translate "Author"}}</th>\
648     <td>{{md-author}}</td>\
649   </tr>\
650   {{/if}}\
651   {{#if md-electronic-url}}\
652   <tr>\
653     <th>{{translate "Links"}}</th>\
654     <td>\
655       {{#each md-electronic-url}}\
656         <a href="{{this}}">Link{{index1}}</a>\
657       {{/each}}\
658     </td>\
659   </tr>\
660   {{/if}}\
661   {{#if-any location having="md-subject"}}\
662   <tr>\
663     <th>{{translate "Subject"}}</th>\
664     <td>\
665       {{#first location having="md-subject"}}\
666         {{#if md-subject}}\
667           {{#commaList md-subject}}\
668             {{this}}{{/commaList}}\
669         {{/if}}\
670       {{/first}}\
671     </td>\
672   </tr>\
673   {{/if-any}}\
674   <tr>\
675     <th>{{translate "Locations"}}</th>\
676     <td>\
677       {{#commaList location}}\
678         {{attr "@name"}}{{/commaList}}\
679     </td>\
680   </tr>\
681 </table>\
682 ';
683         } else if (name === "Summary") {
684             return '\
685 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
686   <b>{{md-title}}</b>\
687 </a>\
688 {{#if md-title-remainder}}\
689   <span>{{md-title-remainder}}</span>\
690 {{/if}}\
691 {{#if md-title-responsibility}}\
692   <span><i>{{md-title-responsibility}}</i></span>\
693 {{/if}}\
694 ';
695         } else if (name === "Image") {
696             return '\
697       <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
698         {{#first md-thumburl}}\
699           <img src="{{this}}" alt="{{../md-title}}"/>\
700         {{/first}}\
701         <br/>\
702       </a>\
703 ';
704         }
705
706         var s = "There is no default '" + name +"' template!";
707         alert(s);
708         return s;
709     }
710
711     that.addWidget = function(w) {
712         if (!m_widgets[w.type]) {
713             m_widgets[w.type] = w;
714             log("Registered '" + w.type + "' widget in team '" + m_teamName + "'");
715         } else if (typeof(m_widgets[w.type]) !== 'number') {
716             m_widgets[w.type] = 2;
717             log("Registered duplicate '" + w.type + "' widget in team '" + m_teamName + "'");
718         } else {
719             m_widgets[w.type] += 1;
720             log("Registered '" + w.type + "' widget #" + m_widgets[w.type] + "' in team '" + m_teamName + "'");
721         }
722     }
723
724     that.widgetTypes = function() {
725         var keys = [];
726         for (var k in m_widgets) keys.push(k);
727         return keys.sort();
728     }
729
730     that.widget = function(type) {
731         return m_widgets[type];
732     }
733
734     mkwsHtmlAll()
735
736     return that;
737 };