1 // Factory function for team objects. As much as possible, this uses
2 // only member variables (prefixed "m_") and inner functions with
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().
11 function team($, teamName) {
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;
24 // Timestamps for logging
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
34 that.toString = function() { return '[Team ' + teamName + ']'; };
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; };
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 };
52 // The following PubSub code is modified from the jQuery manual:
53 // http://api.jquery.com/jQuery.Callbacks/
56 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
57 // team.queue("eventName").publish(arg1, arg2, ...);
62 var callbacks = $.Callbacks();
64 publish: callbacks.fire,
65 subscribe: callbacks.add,
66 unsubscribe: callbacks.remove
76 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
77 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
79 mkws.log(m_teamName + ": " + timestamp + s);
80 that.queue("log").publish(m_teamName, timestamp, s);
85 log("start running MKWS");
87 m_sortOrder = m_config.sort_default;
88 m_perpage = m_config.perpage_default;
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,
98 "onbytarget": onBytarget,
100 "onterm": (m_config.facets.length ? onTerm : undefined),
102 "onrecord": onRecord,
103 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
104 "termlist": m_config.facets.join(',')
107 // pz2.js event handlers:
114 function onBytarget(data) {
116 queue("targets").publish(data);
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));
125 function onTerm(data) {
127 queue("termlists").publish(data);
130 function onShow(data, teamName) {
132 m_totalRecordCount = data.merged;
133 log("found " + m_totalRecordCount + " records");
134 queue("pager").publish(data);
135 queue("records").publish(data);
138 function onRecord(data, args, teamName) {
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
147 m_currentRecordData = data;
148 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
149 var html = renderDetails(m_currentRecordData);
150 $(recordDiv).append(html);
154 // Used by the Records widget and onRecord()
155 function recordElementId(s) {
156 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
158 that.recordElementId = recordElementId;
160 // Used by onRecord(), showDetails() and renderDetails()
161 function recordDetailsId(s) {
162 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
166 that.targetFiltered = function(id) {
167 return m_filterSet.targetFiltered(id);
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();
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();
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();
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();
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();
214 that.showPage = function(pageNum) {
215 m_currentPage = pageNum;
216 m_paz.showPage(m_currentPage - 1);
220 that.pagerNext = function() {
221 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
228 that.pagerPrev = function() {
229 if (m_paz.showPrev() != false)
234 that.reShow = function() {
236 m_paz.show(0, m_perpage, m_sortOrder);
240 function resetPage() {
242 m_totalRecordCount = 0;
244 that.resetPage = resetPage;
247 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
248 log("newSearch: " + query);
250 if (m_config.use_service_proxy && !mkws.authenticated) {
251 alert("searching before authentication");
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
260 that.newSearch = newSearch;
263 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
265 queue("navi").publish();
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));
273 var pp2filter = m_filterSet.pp2filter();
274 var pp2limit = m_filterSet.pp2limit(limit);
275 var pp2catLimit = m_filterSet.pp2catLimit();
277 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
281 if (pp2limit) params.limit = pp2limit;
282 if (maxrecs) params.maxrecs = maxrecs;
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;
289 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
290 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
292 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
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');
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');
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');
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');
324 alert("Unknown view '" + view + "'");
327 that.switchView = switchView;
330 // detailed record drawing
331 that.showDetails = function(recId) {
332 var oldRecordId = m_currentRecordId;
333 m_currentRecordId = recId;
335 // remove current detailed view if any
336 findnode('#' + recordDetailsId(oldRecordId)).remove();
338 // if the same clicked, just hide
339 if (recId == oldRecordId) {
340 m_currentRecordId = '';
341 m_currentRecordData = null;
344 // request the record
345 log("showDetails() requesting record '" + recId + "'");
351 * All the HTML stuff to render the search forms and
354 function mkwsHtmlAll() {
356 if (m_config.show_lang)
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() + ' ';
363 if (m_config.show_perpage) {
364 ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
366 ranking_data += '</form>';
367 findnode(".mkwsRanking").html(ranking_data);
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);
377 function mkwsSetLang() {
378 var lang = mkws.getParameterByName("lang") || m_config.lang;
379 if (!lang || !mkws.locale_lang[lang]) {
382 m_config.lang = lang;
385 log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
386 return m_config.lang;
389 // set or re-set "lang" URL parameter
390 function lang_url(lang) {
391 var query = location.search;
392 // no query parameters? done
394 return "?lang=" + lang;
397 // parameter does not exists
398 if (!query.match(/[\?&]lang=/)) {
399 return query + "&lang=" + lang;
402 // replace existing parameter
403 query = query.replace(/\?lang=([^&#;]*)/, "?lang=" + lang);
404 query = query.replace(/\&lang=([^&#;]*)/, "&lang=" + lang);
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;
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;
423 for (var k in mkws.locale_lang) {
424 if (toBeIncluded[k] || lang_options.length == 0)
429 if (lang_options.length == 0 || toBeIncluded[lang_default])
430 list.push(lang_default);
432 log("Language menu for: " + list.join(", "));
436 for(var i = 0; i < list.length; i++) {
443 data += ' <span>' + l + '</span> ';
445 data += ' <a href="' + lang_url(l) + '">' + l + '</a> '
449 findnode(".mkwsLang").html(data);
453 function mkwsHtmlSort() {
454 log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
455 var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
457 for(var i = 0; i < m_config.sort_options.length; i++) {
458 var opt = m_config.sort_options[i];
460 var val = opt.length == 1 ? opt[0] : opt[1];
462 sort_html += '<option value="' + key + '"';
463 if (m_sortOrder == key || m_sortOrder == val) {
464 sort_html += ' selected="selected"';
466 sort_html += '>' + M(val) + '</option>';
468 sort_html += '</select>';
474 function mkwsHtmlPerpage() {
475 log("HTML perpage, m_perpage = " + m_perpage);
476 var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
478 for(var i = 0; i < m_config.perpage_options.length; i++) {
479 var key = m_config.perpage_options[i];
481 perpage_html += '<option value="' + key + '"';
482 if (key == m_perpage) {
483 perpage_html += ' selected="selected"';
485 perpage_html += '>' + key + '</option>';
487 perpage_html += '</select>';
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.
499 var lang = m_config.lang;
501 if (!lang || !mkws.locale_lang[lang])
504 return mkws.locale_lang[lang][word] || word;
506 mkws.M = M; // so the Handlebars helper can use it
509 // Finds the node of the specified class within the current team
510 function findnode(selector, teamName) {
511 teamName = teamName || m_teamName;
513 if (teamName === 'AUTO') {
514 selector = (selector + '.mkwsTeam_' + teamName + ',' +
515 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
517 selector = selector + '.mkwsTeam_' + teamName;
520 var node = $(selector);
521 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
524 that.findnode = findnode;
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;
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>';
540 that.renderDetails = renderDetails;
543 that.registerTemplate = function(name, text) {
544 m_tempateText[name] = text;
548 function loadTemplate(name) {
549 var template = m_template[name];
551 if (template === undefined) {
552 // Fall back to generic template if there is no team-specific one
554 var node = widgetNode("Template_" + name);
556 node = widgetNode("Template_" + name, "ALL");
559 source = node.html();
563 source = m_tempateText[name];
566 source = defaultTemplate(name);
569 template = Handlebars.compile(source);
570 log("compiled template '" + name + "'");
571 m_template[name] = template;
576 that.loadTemplate = loadTemplate;
579 function defaultTemplate(name) {
580 if (name === 'Record') {
584 <th>{{translate "Title"}}</th>\
587 {{#if md-title-remainder}}\
588 ({{md-title-remainder}})\
590 {{#if md-title-responsibility}}\
591 <i>{{md-title-responsibility}}</i>\
597 <th>{{translate "Date"}}</th>\
598 <td>{{md-date}}</td>\
603 <th>{{translate "Author"}}</th>\
604 <td>{{md-author}}</td>\
607 {{#if md-electronic-url}}\
609 <th>{{translate "Links"}}</th>\
611 {{#each md-electronic-url}}\
612 <a href="{{this}}">Link{{index1}}</a>\
617 {{#if-any location having="md-subject"}}\
619 <th>{{translate "Subject"}}</th>\
621 {{#first location having="md-subject"}}\
623 {{#commaList md-subject}}\
624 {{this}}{{/commaList}}\
631 <th>{{translate "Locations"}}</th>\
633 {{#commaList location}}\
634 {{attr "@name"}}{{/commaList}}\
639 } else if (name === "Summary") {
641 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
644 {{#if md-title-remainder}}\
645 <span>{{md-title-remainder}}</span>\
647 {{#if md-title-responsibility}}\
648 <span><i>{{md-title-responsibility}}</i></span>\
651 } else if (name === "Image") {
653 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
654 {{#first md-thumburl}}\
655 <img src="{{this}}" alt="{{../md-title}}"/>\
662 var s = "There is no default '" + name +"' template!";
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 + "'");
675 m_widgets[w.type] += 1;
676 log("Registered '" + w.type + "' widget #" + m_widgets[w.type] + "' in team '" + m_teamName + "'");
680 that.widgetTypes = function() {
682 for (var k in m_widgets) keys.push(k);
686 that.widget = function(type) {
687 return m_widgets[type];