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 // delimitTarget(), delimitQuery(), showPage(), pagerPrev(),
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
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 = Object.create(mkws.config);
32 that.toString = function() { return '[Team ' + teamName + ']'; };
34 // Accessor methods for individual widgets: readers
35 that.name = function() { return m_teamName; };
36 that.submitted = function() { return m_submitted; };
37 that.perpage = function() { return m_perpage; };
38 that.totalRecordCount = function() { return m_totalRecordCount; };
39 that.currentPage = function() { return m_currentPage; };
40 that.currentRecordId = function() { return m_currentRecordId; };
41 that.currentRecordData = function() { return m_currentRecordData; };
42 that.filters = function() { return m_filters; };
43 that.config = function() { return m_config; };
45 // Accessor methods for individual widgets: writers
46 that.set_sortOrder = function(val) { m_sortOrder = val };
47 that.set_perpage = function(val) { m_perpage = val };
50 // The following PubSub code is modified from the jQuery manual:
51 // https://api.jquery.com/jQuery.Callbacks/
54 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
55 // team.queue("eventName").publish(arg1, arg2, ...);
60 var callbacks = $.Callbacks();
62 publish: callbacks.fire,
63 subscribe: callbacks.add,
64 unsubscribe: callbacks.remove
74 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
75 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
77 mkws.log(m_teamName + ": " + timestamp + s);
78 that.queue("log").publish(m_teamName, timestamp, s);
83 log("start running MKWS");
85 m_sortOrder = m_config.sort_default;
86 m_perpage = m_config.perpage_default;
88 log("Create main pz2 object");
89 // create a parameters array and pass it to the pz2's constructor
90 // then register the form submit event with the pz2.search function
91 // autoInit is set to true on default
92 m_paz = new pz2({ "windowid": teamName,
93 "pazpar2path": m_config.pazpar2_url,
94 "usesessions" : m_config.use_service_proxy ? false : true,
96 "onbytarget": onBytarget,
98 "onterm": (m_config.facets.length ? onTerm : undefined),
100 "onrecord": onRecord,
101 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
102 "termlist": m_config.facets.join(',')
105 // pz2.js event handlers:
112 function onBytarget(data) {
114 queue("targets").publish(data);
117 function onStat(data) {
119 queue("stat").publish(data);
122 function onTerm(data) {
124 queue("termlists").publish(data);
127 function onShow(data, teamName) {
129 m_totalRecordCount = data.merged;
130 queue("pager").publish(data);
131 queue("records").publish(data);
134 function onRecord(data, args, teamName) {
136 // FIXME: record is async!!
137 clearTimeout(m_paz.recordTimer);
138 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
139 if (detRecordDiv.length) {
140 // in case on_show was faster to redraw element
143 m_currentRecordData = data;
144 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
145 var html = renderDetails(m_currentRecordData);
146 $(recordDiv).append(html);
150 // Used by the Records widget and onRecord()
151 function recordElementId(s) {
152 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
154 that.recordElementId = recordElementId;
156 // Used by onRecord(), showDetails() and renderDetails()
157 function recordDetailsId(s) {
158 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
162 that.targetFiltered = function(id) {
163 for (var i = 0; i < m_filters.length; i++) {
164 if (m_filters[i].id === id ||
165 m_filters[i].id === 'pz:id=' + id) {
173 that.limitTarget = function(id, name) {
174 log("limitTarget(id=" + id + ", name=" + name + ")");
175 m_filters.push({ id: id, name: name });
181 that.limitQuery = function(field, value) {
182 log("limitQuery(field=" + field + ", value=" + value + ")");
183 m_filters.push({ field: field, value: value });
189 that.delimitTarget = function(id) {
190 log("delimitTarget(id=" + id + ")");
191 removeMatchingFilters(function(f) { return f.id });
197 that.delimitQuery = function(field, value) {
198 log("delimitQuery(field=" + field + ", value=" + value + ")");
199 removeMatchingFilters(function(f) { return f.field && field == f.field && value == f.value });
205 function removeMatchingFilters(matchFn) {
207 for (var i in m_filters) {
208 var filter = m_filters[i];
209 if (matchFn(filter)) {
210 log("removeMatchingFilters() removing filter " + $.toJSON(filter));
212 log("removeMatchingFilters() keeping filter " + $.toJSON(filter));
213 newFilters.push(filter);
216 m_filters = newFilters;
220 that.showPage = function(pageNum) {
221 m_currentPage = pageNum;
222 m_paz.showPage(m_currentPage - 1);
226 that.pagerNext = function() {
227 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
234 that.pagerPrev = function() {
235 if (m_paz.showPrev() != false)
240 that.reShow = function() {
241 m_paz.show(0, m_perpage, m_sortOrder);
245 function resetPage() {
247 m_totalRecordCount = 0;
249 that.resetPage = resetPage;
252 function newSearch(query, sortOrder, perpage, limit, targets, torusquery) {
253 log("newSearch: " + query);
255 if (m_config.use_service_proxy && !mkws.authenticated) {
256 alert("searching before authentication");
261 triggerSearch(query, sortOrder, perpage, limit, targets, torusquery);
262 switchView('records'); // In case it's configured to start off as hidden
265 that.newSearch = newSearch;
268 function triggerSearch(query, sortOrder, perpage, limit, targets, torusquery) {
270 queue("navi").publish();
273 var pp2limit = limit || "";
275 // Continue to use previous query/sort-order unless new ones are specified
280 m_sortOrder = sortOrder;
286 m_filters.push({ id: targets, name: targets });
289 for (var i in m_filters) {
290 var filter = m_filters[i];
294 if (filter.id.match(/^[a-z:]+[=~]/)) {
295 log("filter '" + filter.id + "' already begins with SETTING OP");
297 filter.id = 'pz:id=' + filter.id;
299 pp2filter += filter.id;
303 pp2limit += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
309 params.limit = pp2limit;
312 if (!mkws.config.use_service_proxy)
313 alert("can't narrow search by torusquery when Service Proxy is not in use");
314 params.torusquery = torusquery;
317 log("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", " +
318 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
320 // We can use: params.torusquery = "udb=NAME"
321 // Note: that won't work when running against raw pazpar2
322 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
326 // switching view between targets and records
327 function switchView(view) {
328 var targets = findnode('.mkwsTargets');
329 var results = findnode('.mkwsResults,.mkwsRecords');
330 var blanket = findnode('.mkwsBlanket');
331 var motd = findnode('.mkwsMOTD');
335 if (targets) targets.css('display', 'block');
336 if (results) results.css('display', 'none');
337 if (blanket) blanket.css('display', 'none');
338 if (motd) motd.css('display', 'none');
341 if (targets) targets.css('display', 'none');
342 if (results) results.css('display', 'block');
343 if (blanket) blanket.css('display', 'block');
344 if (motd) motd.css('display', 'none');
347 alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
348 if (targets) targets.css('display', 'none');
349 if (results) results.css('display', 'none');
350 if (blanket) blanket.css('display', 'none');
351 if (motd) motd.css('display', 'none');
354 alert("Unknown view '" + view + "'");
357 that.switchView = switchView;
360 // detailed record drawing
361 that.showDetails = function(recId) {
362 var oldRecordId = m_currentRecordId;
363 m_currentRecordId = recId;
365 // remove current detailed view if any
366 findnode('#' + recordDetailsId(oldRecordId)).remove();
368 // if the same clicked, just hide
369 if (recId == oldRecordId) {
370 m_currentRecordId = '';
371 m_currentRecordData = null;
374 // request the record
375 log("showDetails() requesting record '" + recId + "'");
381 * All the HTML stuff to render the search forms and
384 function mkwsHtmlAll() {
386 if (m_config.show_lang)
389 log("HTML search form");
390 findnode('.mkwsSearch').html('\
391 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + m_teamName + '" action="" >\
392 <input class="mkwsQuery mkwsTeam_' + m_teamName + '" type="text" size="' + m_config.query_width + '" />\
393 <input class="mkwsButton mkwsTeam_' + m_teamName + '" type="submit" value="' + M('Search') + '" />\
397 // If the team has a .mkwsResults, populate it in the usual
398 // way. If not, assume that it's a smarter application that
399 // defines its own subcomponents, some or all of the
406 findnode(".mkwsResults").html('\
407 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
409 <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
410 <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
412 <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
413 <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
414 <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
415 <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
416 <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
421 <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
426 var ranking_data = '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
427 if (m_config.show_sort) {
428 ranking_data += M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
430 if (m_config.show_perpage) {
431 ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
433 ranking_data += '</form>';
434 findnode(".mkwsRanking").html(ranking_data);
438 findnode('.mkwsSearchForm').submit(function() {
439 var val = findnode('.mkwsQuery').val();
444 // on first page, hide the termlist
445 $(document).ready(function() { findnode(".mkwsTermlists").hide(); });
446 var container = findnode(".mkwsMOTDContainer");
447 if (container.length) {
448 // Move the MOTD from the provided element down into the container
449 findnode(".mkwsMOTD").appendTo(container);
454 function mkwsSetLang() {
455 var lang = mkws.getParameterByName("lang") || m_config.lang;
456 if (!lang || !mkws.locale_lang[lang]) {
459 m_config.lang = lang;
462 log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
463 return m_config.lang;
467 /* create locale language menu */
468 function mkwsHtmlLang() {
469 var lang_default = "en";
470 var lang = m_config.lang || lang_default;
473 /* display a list of configured languages, or all */
474 var lang_options = m_config.lang_options || [];
475 var toBeIncluded = {};
476 for (var i = 0; i < lang_options.length; i++) {
477 toBeIncluded[lang_options[i]] = true;
480 for (var k in mkws.locale_lang) {
481 if (toBeIncluded[k] || lang_options.length == 0)
486 if (lang_options.length == 0 || toBeIncluded[lang_default])
487 list.push(lang_default);
489 log("Language menu for: " + list.join(", "));
493 for(var i = 0; i < list.length; i++) {
500 data += ' <span>' + l + '</span> ';
502 data += ' <a href="?lang=' + l + '">' + l + '</a> '
506 findnode(".mkwsLang").html(data);
510 function mkwsHtmlSort() {
511 log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
512 var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
514 for(var i = 0; i < m_config.sort_options.length; i++) {
515 var opt = m_config.sort_options[i];
517 var val = opt.length == 1 ? opt[0] : opt[1];
519 sort_html += '<option value="' + key + '"';
520 if (m_sortOrder == key || m_sortOrder == val) {
521 sort_html += ' selected="selected"';
523 sort_html += '>' + M(val) + '</option>';
525 sort_html += '</select>';
531 function mkwsHtmlPerpage() {
532 log("HTML perpage, m_perpage = " + m_perpage);
533 var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
535 for(var i = 0; i < m_config.perpage_options.length; i++) {
536 var key = m_config.perpage_options[i];
538 perpage_html += '<option value="' + key + '"';
539 if (key == m_perpage) {
540 perpage_html += ' selected="selected"';
542 perpage_html += '>' + key + '</option>';
544 perpage_html += '</select>';
550 function mkwsHtmlSwitch() {
551 log("HTML switch for team " + m_teamName);
553 var node = findnode(".mkwsSwitch");
554 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
555 node.append($("<span/>", { text: " | " }));
556 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
559 var node = findnode(".mkwsTargets");
561 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
562 No information available yet.\
564 node.css("display", "none");
568 // Translation function. At present, this is properly a
569 // global-level function (hence the assignment to mkws.M) but we
570 // want to make it per-team so different teams can operate in
571 // different languages.
574 var lang = m_config.lang;
576 if (!lang || !mkws.locale_lang[lang])
579 return mkws.locale_lang[lang][word] || word;
581 mkws.M = M; // so the Handlebars helper can use it
584 // Finds the node of the specified class within the current team
585 // Multiple OR-clauses separated by commas are handled
586 // More complex cases may not work
588 function findnode(selector, teamName) {
589 teamName = teamName || m_teamName;
591 selector = $.map(selector.split(','), function(s, i) {
592 return s + '.mkwsTeam_' + teamName;
595 var node = $(selector);
596 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
601 function renderDetails(data, marker) {
602 var template = loadTemplate("Record");
603 var details = template(data);
604 return '<div class="details mkwsTeam_' + m_teamName + '" ' +
605 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
607 that.renderDetails = renderDetails;
610 function loadTemplate(name) {
611 var template = m_template[name];
613 if (template === undefined) {
614 // Fall back to generic template if there is no team-specific one
615 var node = findnode(".mkwsTemplate_" + name);
617 node = findnode(".mkwsTemplate_" + name, "ALL");
620 var source = node.html();
622 source = defaultTemplate(name);
625 template = Handlebars.compile(source);
626 log("compiled template '" + name + "'");
627 m_template[name] = template;
632 that.loadTemplate = loadTemplate;
635 function defaultTemplate(name) {
636 if (name === 'Record') {
640 <th>{{translate "Title"}}</th>\
643 {{#if md-title-remainder}}\
644 ({{md-title-remainder}})\
646 {{#if md-title-responsibility}}\
647 <i>{{md-title-responsibility}}</i>\
653 <th>{{translate "Date"}}</th>\
654 <td>{{md-date}}</td>\
659 <th>{{translate "Author"}}</th>\
660 <td>{{md-author}}</td>\
663 {{#if md-electronic-url}}\
665 <th>{{translate "Links"}}</th>\
667 {{#each md-electronic-url}}\
668 <a href="{{this}}">Link{{index1}}</a>\
673 {{#if-any location having="md-subject"}}\
675 <th>{{translate "Subject"}}</th>\
677 {{#first location having="md-subject"}}\
679 {{#commaList md-subject}}\
680 {{this}}{{/commaList}}\
687 <th>{{translate "Locations"}}</th>\
689 {{#commaList location}}\
690 {{attr "@name"}}{{/commaList}}\
695 } else if (name === "Summary") {
697 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
700 {{#if md-title-remainder}}\
701 <span>{{md-title-remainder}}</span>\
703 {{#if md-title-responsibility}}\
704 <span><i>{{md-title-responsibility}}</i></span>\
709 var s = "There is no default '" + name +"' template!";