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
30 var m_config = mkws.objectInheritingFrom(mkws.config);
31 var m_widgets = {}; // Maps widget-type to object
33 that.toString = function() { return '[Team ' + teamName + ']'; };
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; };
44 that.config = function() { return m_config; };
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 };
51 // The following PubSub code is modified from the jQuery manual:
52 // http://api.jquery.com/jQuery.Callbacks/
55 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
56 // team.queue("eventName").publish(arg1, arg2, ...);
61 var callbacks = $.Callbacks();
63 publish: callbacks.fire,
64 subscribe: callbacks.add,
65 unsubscribe: callbacks.remove
75 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
76 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
78 mkws.log(m_teamName + ": " + timestamp + s);
79 that.queue("log").publish(m_teamName, timestamp, s);
84 log("start running MKWS");
86 m_sortOrder = m_config.sort_default;
87 m_perpage = m_config.perpage_default;
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,
97 "onbytarget": onBytarget,
99 "onterm": (m_config.facets.length ? onTerm : undefined),
101 "onrecord": onRecord,
102 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
103 "termlist": m_config.facets.join(',')
106 // pz2.js event handlers:
113 function onBytarget(data) {
115 queue("targets").publish(data);
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));
124 function onTerm(data) {
126 queue("termlists").publish(data);
129 function onShow(data, teamName) {
131 m_totalRecordCount = data.merged;
132 log("found " + m_totalRecordCount + " records");
133 queue("pager").publish(data);
134 queue("records").publish(data);
137 function onRecord(data, args, teamName) {
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
146 m_currentRecordData = data;
147 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
148 var html = renderDetails(m_currentRecordData);
149 $(recordDiv).append(html);
153 // Used by the Records widget and onRecord()
154 function recordElementId(s) {
155 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
157 that.recordElementId = recordElementId;
159 // Used by onRecord(), showDetails() and renderDetails()
160 function recordDetailsId(s) {
161 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
165 that.targetFiltered = function(id) {
166 return m_filterSet.targetFiltered(id);
170 that.limitTarget = function(id, name) {
171 log("limitTarget(id=" + id + ", name=" + name + ")");
172 m_filterSet.add(targetFilter(id, name));
173 if (m_query) triggerSearch();
178 that.limitQuery = function(field, value) {
179 log("limitQuery(field=" + field + ", value=" + value + ")");
180 m_filterSet.add(fieldFilter(field, value));
181 if (m_query) triggerSearch();
186 that.limitCategory = function(id) {
187 log("limitCategory(id=" + id + ")");
188 // Only one category filter at a time
189 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
190 if (id !== '') m_filterSet.add(categoryFilter(id));
191 if (m_query) triggerSearch();
196 that.delimitTarget = function(id) {
197 log("delimitTarget(id=" + id + ")");
198 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
199 if (m_query) triggerSearch();
204 that.delimitQuery = function(field, value) {
205 log("delimitQuery(field=" + field + ", value=" + value + ")");
206 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
207 field == f.field && value == f.value });
208 if (m_query) triggerSearch();
213 that.showPage = function(pageNum) {
214 m_currentPage = pageNum;
215 m_paz.showPage(m_currentPage - 1);
219 that.pagerNext = function() {
220 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
227 that.pagerPrev = function() {
228 if (m_paz.showPrev() != false)
233 that.reShow = function() {
235 m_paz.show(0, m_perpage, m_sortOrder);
239 function resetPage() {
241 m_totalRecordCount = 0;
243 that.resetPage = resetPage;
246 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
247 log("newSearch: " + query);
249 if (m_config.use_service_proxy && !mkws.authenticated) {
250 alert("searching before authentication");
254 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
255 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
256 switchView('records'); // In case it's configured to start off as hidden
259 that.newSearch = newSearch;
262 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
264 queue("navi").publish();
266 // Continue to use previous query/sort-order unless new ones are specified
267 if (query) m_query = query;
268 if (sortOrder) m_sortOrder = sortOrder;
269 if (perpage) m_perpage = perpage;
270 if (targets) m_filterSet.add(targetFilter(targets, targets));
272 var pp2filter = m_filterSet.pp2filter();
273 var pp2limit = m_filterSet.pp2limit(limit);
274 var pp2catLimit = m_filterSet.pp2catLimit();
276 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
280 if (pp2limit) params.limit = pp2limit;
281 if (maxrecs) params.maxrecs = maxrecs;
283 if (!mkws.config.use_service_proxy)
284 alert("can't narrow search by torusquery when Service Proxy is not in use");
285 params.torusquery = torusquery;
288 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
289 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
291 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
295 // switching view between targets and records
296 function switchView(view) {
297 var targets = widgetNode('Targets');
298 var results = widgetNode('Results') || widgetNode('Records');
299 var blanket = widgetNode('Blanket');
300 var motd = widgetNode('MOTD');
304 if (targets) targets.css('display', 'block');
305 if (results) results.css('display', 'none');
306 if (blanket) blanket.css('display', 'none');
307 if (motd) motd.css('display', 'none');
310 if (targets) targets.css('display', 'none');
311 if (results) results.css('display', 'block');
312 if (blanket) blanket.css('display', 'block');
313 if (motd) motd.css('display', 'none');
316 alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
317 if (targets) targets.css('display', 'none');
318 if (results) results.css('display', 'none');
319 if (blanket) blanket.css('display', 'none');
320 if (motd) motd.css('display', 'none');
323 alert("Unknown view '" + view + "'");
326 that.switchView = switchView;
329 // detailed record drawing
330 that.showDetails = function(recId) {
331 var oldRecordId = m_currentRecordId;
332 m_currentRecordId = recId;
334 // remove current detailed view if any
335 findnode('#' + recordDetailsId(oldRecordId)).remove();
337 // if the same clicked, just hide
338 if (recId == oldRecordId) {
339 m_currentRecordId = '';
340 m_currentRecordData = null;
343 // request the record
344 log("showDetails() requesting record '" + recId + "'");
350 * All the HTML stuff to render the search forms and
353 function mkwsHtmlAll() {
355 if (m_config.show_lang)
358 log("HTML search form");
359 findnode('.mkwsSearch').html('\
360 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + m_teamName + '" action="" >\
361 <input class="mkwsQuery mkwsTeam_' + m_teamName + '" type="text" size="' + m_config.query_width + '" />\
362 <input class="mkwsButton mkwsTeam_' + m_teamName + '" type="submit" value="' + M('Search') + '" />\
366 // If the team has a .mkwsResults, populate it in the usual
367 // way. If not, assume that it's a smarter application that
368 // defines its own subcomponents, some or all of the
375 findnode(".mkwsResults").html('\
376 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
378 <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
379 <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
381 <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
382 <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
383 <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
384 <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
385 <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
390 <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
396 var facets = m_config.facets;
397 acc.push('<div class="title">' + M('Termlists') + '</div>');
398 for (var i = 0; i < facets.length; i++) {
399 acc.push('<div class="mkwsFacet mkwsTeam_' + m_teamName + '" data-mkws-facet="' + facets[i] + '">');
402 findnode(".mkwsTermlists").html(acc.join(''));
404 var ranking_data = '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
405 if (m_config.show_sort) {
406 ranking_data += M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
408 if (m_config.show_perpage) {
409 ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
411 ranking_data += '</form>';
412 findnode(".mkwsRanking").html(ranking_data);
416 findnode('.mkwsSearchForm').submit(function() {
417 var val = widgetNode('Query').val();
422 // on first page, hide the termlist
423 $(document).ready(function() {
424 var t = widgetNode("Termlists");
427 var container = findnode(".mkwsMOTDContainer");
428 if (container.length) {
429 // Move the MOTD from the provided element down into the container
430 findnode(".mkwsMOTD").appendTo(container);
435 function mkwsSetLang() {
436 var lang = mkws.getParameterByName("lang") || m_config.lang;
437 if (!lang || !mkws.locale_lang[lang]) {
440 m_config.lang = lang;
443 log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
444 return m_config.lang;
447 // set or re-set "lang" URL parameter
448 function lang_url(lang) {
449 var query = location.search;
450 // no query parameters? done
452 return "?lang=" + lang;
455 // parameter does not exists
456 if (!query.match(/[\?&]lang=/)) {
457 return query + "&lang=" + lang;
460 // replace existing parameter
461 query = query.replace(/\?lang=([^&#;]*)/, "?lang=" + lang);
462 query = query.replace(/\&lang=([^&#;]*)/, "&lang=" + lang);
467 // dynamic URL or static page? /path/foo?query=test
468 /* create locale language menu */
469 function mkwsHtmlLang() {
470 var lang_default = "en";
471 var lang = m_config.lang || lang_default;
474 /* display a list of configured languages, or all */
475 var lang_options = m_config.lang_options || [];
476 var toBeIncluded = {};
477 for (var i = 0; i < lang_options.length; i++) {
478 toBeIncluded[lang_options[i]] = true;
481 for (var k in mkws.locale_lang) {
482 if (toBeIncluded[k] || lang_options.length == 0)
487 if (lang_options.length == 0 || toBeIncluded[lang_default])
488 list.push(lang_default);
490 log("Language menu for: " + list.join(", "));
494 for(var i = 0; i < list.length; i++) {
501 data += ' <span>' + l + '</span> ';
503 data += ' <a href="' + lang_url(l) + '">' + l + '</a> '
507 findnode(".mkwsLang").html(data);
511 function mkwsHtmlSort() {
512 log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
513 var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
515 for(var i = 0; i < m_config.sort_options.length; i++) {
516 var opt = m_config.sort_options[i];
518 var val = opt.length == 1 ? opt[0] : opt[1];
520 sort_html += '<option value="' + key + '"';
521 if (m_sortOrder == key || m_sortOrder == val) {
522 sort_html += ' selected="selected"';
524 sort_html += '>' + M(val) + '</option>';
526 sort_html += '</select>';
532 function mkwsHtmlPerpage() {
533 log("HTML perpage, m_perpage = " + m_perpage);
534 var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
536 for(var i = 0; i < m_config.perpage_options.length; i++) {
537 var key = m_config.perpage_options[i];
539 perpage_html += '<option value="' + key + '"';
540 if (key == m_perpage) {
541 perpage_html += ' selected="selected"';
543 perpage_html += '>' + key + '</option>';
545 perpage_html += '</select>';
551 function mkwsHtmlSwitch() {
552 log("HTML switch for team " + m_teamName);
554 var node = findnode(".mkwsSwitch");
555 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
556 node.append($("<span/>", { text: " | " }));
557 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
560 var node = findnode(".mkwsTargets");
562 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
563 No information available yet.\
565 node.css("display", "none");
569 // Translation function. At present, this is properly a
570 // global-level function (hence the assignment to mkws.M) but we
571 // want to make it per-team so different teams can operate in
572 // different languages.
575 var lang = m_config.lang;
577 if (!lang || !mkws.locale_lang[lang])
580 return mkws.locale_lang[lang][word] || word;
582 mkws.M = M; // so the Handlebars helper can use it
585 // Finds the node of the specified class within the current team
586 function findnode(selector, teamName) {
587 teamName = teamName || m_teamName;
589 if (teamName === 'AUTO') {
590 selector = (selector + '.mkwsTeam_' + teamName + ',' +
591 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
593 selector = selector + '.mkwsTeam_' + teamName;
596 var node = $(selector);
597 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
600 that.findnode = findnode;
603 // This much simpler and more efficient function should be usable
604 // in place of most uses of findnode.
605 function widgetNode(type) {
606 var w = that.widget(type);
607 return w ? $(w.node) : undefined;
610 function renderDetails(data, marker) {
611 var template = loadTemplate("Record");
612 var details = template(data);
613 return '<div class="details mkwsTeam_' + m_teamName + '" ' +
614 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
616 that.renderDetails = renderDetails;
619 function loadTemplate(name) {
620 var template = m_template[name];
622 if (template === undefined) {
623 // Fall back to generic template if there is no team-specific one
625 var node = widgetNode("Template_" + name);
627 node = widgetNode("Template_" + name, "ALL");
630 source = node.html();
634 source = defaultTemplate(name);
637 template = Handlebars.compile(source);
638 log("compiled template '" + name + "'");
639 m_template[name] = template;
644 that.loadTemplate = loadTemplate;
647 function defaultTemplate(name) {
648 if (name === 'Record') {
652 <th>{{translate "Title"}}</th>\
655 {{#if md-title-remainder}}\
656 ({{md-title-remainder}})\
658 {{#if md-title-responsibility}}\
659 <i>{{md-title-responsibility}}</i>\
665 <th>{{translate "Date"}}</th>\
666 <td>{{md-date}}</td>\
671 <th>{{translate "Author"}}</th>\
672 <td>{{md-author}}</td>\
675 {{#if md-electronic-url}}\
677 <th>{{translate "Links"}}</th>\
679 {{#each md-electronic-url}}\
680 <a href="{{this}}">Link{{index1}}</a>\
685 {{#if-any location having="md-subject"}}\
687 <th>{{translate "Subject"}}</th>\
689 {{#first location having="md-subject"}}\
691 {{#commaList md-subject}}\
692 {{this}}{{/commaList}}\
699 <th>{{translate "Locations"}}</th>\
701 {{#commaList location}}\
702 {{attr "@name"}}{{/commaList}}\
707 } else if (name === "Summary") {
709 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
712 {{#if md-title-remainder}}\
713 <span>{{md-title-remainder}}</span>\
715 {{#if md-title-responsibility}}\
716 <span><i>{{md-title-responsibility}}</i></span>\
719 } else if (name === "Image") {
721 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
722 {{#first md-thumburl}}\
723 <img src="{{this}}" alt="{{../md-title}}"/>\
730 var s = "There is no default '" + name +"' template!";
735 that.addWidget = function(w) {
736 if (!m_widgets[w.type]) {
737 m_widgets[w.type] = w;
738 log("Registered '" + w.type + "' widget in team '" + m_teamName + "'");
739 } else if (typeof(m_widgets[w.type]) !== 'number') {
740 m_widgets[w.type] = 2;
741 log("Registered duplicate '" + w.type + "' widget in team '" + m_teamName + "'");
743 m_widgets[w.type] += 1;
744 log("Registered '" + w.type + "' widget #" + m_widgets[w.type] + "' in team '" + m_teamName + "'");
748 that.widgetTypes = function() {
750 for (var k in m_widgets) keys.push(k);
754 that.widget = function(type) {
755 return m_widgets[type];