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 };
52 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
53 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
55 mkws.log(m_teamName + ": " + timestamp + s);
59 log("start running MKWS");
61 m_sortOrder = m_config.sort_default;
62 m_perpage = m_config.perpage_default;
64 log("Create main pz2 object");
65 // create a parameters array and pass it to the pz2's constructor
66 // then register the form submit event with the pz2.search function
67 // autoInit is set to true on default
68 m_paz = new pz2({ "windowid": teamName,
69 "pazpar2path": m_config.pazpar2_url,
70 "usesessions" : m_config.use_service_proxy ? false : true,
72 "onbytarget": onBytarget,
74 "onterm": (m_config.facets.length ? onTerm : undefined),
77 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
78 "termlist": m_config.facets.join(',')
82 // pz2.js event handlers:
89 function onBytarget(data) {
91 queue("targets").publish(data);
94 function onStat(data) {
96 queue("stat").publish(data);
99 function onTerm(data) {
101 queue("termlists").publish(data);
104 function onShow(data, teamName) {
106 m_totalRecordCount = data.merged;
107 queue("pager").publish(data);
108 queue("records").publish(data);
111 function onRecord(data, args, teamName) {
113 // FIXME: record is async!!
114 clearTimeout(m_paz.recordTimer);
115 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
116 if (detRecordDiv.length) {
117 // in case on_show was faster to redraw element
120 m_currentRecordData = data;
121 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
122 var html = renderDetails(m_currentRecordData);
123 $(recordDiv).append(html);
127 // Used by the Records widget and onRecord()
128 function recordElementId(s) {
129 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
131 that.recordElementId = recordElementId;
133 // Used by onRecord(), showDetails() and renderDetails()
134 function recordDetailsId(s) {
135 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
139 that.targetFiltered = function(id) {
140 for (var i = 0; i < m_filters.length; i++) {
141 if (m_filters[i].id === id ||
142 m_filters[i].id === 'pz:id=' + id) {
150 that.limitTarget = function(id, name)
152 log("limitTarget(id=" + id + ", name=" + name + ")");
153 m_filters.push({ id: id, name: name });
159 that.limitQuery = function(field, value)
161 log("limitQuery(field=" + field + ", value=" + value + ")");
162 m_filters.push({ field: field, value: value });
168 that.delimitTarget = function(id)
170 log("delimitTarget(id=" + id + ")");
171 removeMatchingFilters(function(f) { return f.id });
177 that.delimitQuery = function(field, value)
179 log("delimitQuery(field=" + field + ", value=" + value + ")");
180 removeMatchingFilters(function(f) { return f.field && field == f.field && value == f.value });
186 function removeMatchingFilters(matchFn) {
188 for (var i in m_filters) {
189 var filter = m_filters[i];
190 if (matchFn(filter)) {
191 log("removeMatchingFilters() removing filter " + $.toJSON(filter));
193 log("removeMatchingFilters() keeping filter " + $.toJSON(filter));
194 newFilters.push(filter);
197 m_filters = newFilters;
201 that.showPage = function(pageNum)
203 m_currentPage = pageNum;
204 m_paz.showPage(m_currentPage - 1);
208 that.pagerNext = function() {
209 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
216 that.pagerPrev = function() {
217 if (m_paz.showPrev() != false)
222 that.reShow = function() {
223 m_paz.show(0, m_perpage, m_sortOrder);
230 m_totalRecordCount = 0;
232 that.resetPage = resetPage;
235 function newSearch(query, sortOrder, targets)
237 log("newSearch: " + query);
239 if (m_config.use_service_proxy && !mkws.authenticated) {
240 alert("searching before authentication");
245 triggerSearch(query, sortOrder, targets);
246 switchView('records'); // In case it's configured to start off as hidden
251 function triggerSearch(query, sortOrder, targets)
254 queue("navi").publish();
259 // Continue to use previous query/sort-order unless new ones are specified
264 m_sortOrder = sortOrder;
267 m_filters.push({ id: targets, name: targets });
270 for (var i in m_filters) {
271 var filter = m_filters[i];
275 if (filter.id.match(/^[a-z:]+[=~]/)) {
276 log("filter '" + filter.id + "' already begins with SETTING OP");
278 filter.id = 'pz:id=' + filter.id;
280 pp2filter += filter.id;
284 pp2limit += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
290 params.limit = pp2limit;
293 log("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", " +
294 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
296 // We can use: params.torusquery = "udb=NAME"
297 // Note: that won't work when running against raw pazpar2
298 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
302 // switching view between targets and records
303 function switchView(view) {
304 var targets = findnode('.mkwsTargets');
305 var results = findnode('.mkwsResults,.mkwsRecords');
306 var blanket = findnode('.mkwsBlanket');
307 var motd = findnode('.mkwsMOTD');
311 if (targets) targets.css('display', 'block');
312 if (results) results.css('display', 'none');
313 if (blanket) blanket.css('display', 'none');
314 if (motd) motd.css('display', 'none');
317 if (targets) targets.css('display', 'none');
318 if (results) results.css('display', 'block');
319 if (blanket) blanket.css('display', 'block');
320 if (motd) motd.css('display', 'none');
323 alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
324 if (targets) targets.css('display', 'none');
325 if (results) results.css('display', 'none');
326 if (blanket) blanket.css('display', 'none');
327 if (motd) motd.css('display', 'none');
330 alert("Unknown view '" + view + "'");
333 that.switchView = switchView;
336 // detailed record drawing
337 that.showDetails = function(recId) {
338 var oldRecordId = m_currentRecordId;
339 m_currentRecordId = recId;
341 // remove current detailed view if any
342 // ##### restrict to current team
343 var detRecordDiv = document.getElementById(recordDetailsId(oldRecordId));
346 detRecordDiv.parentNode.removeChild(detRecordDiv);
348 // if the same clicked, just hide
349 if (recId == oldRecordId) {
350 m_currentRecordId = '';
351 m_currentRecordData = null;
354 // request the record
355 log("showDetails() requesting record '" + recId + "'");
361 * All the HTML stuff to render the search forms and
364 function mkwsHtmlAll() {
366 if (m_config.show_lang)
369 log("HTML search form");
370 findnode('.mkwsSearch').html('\
371 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + m_teamName + '" action="" >\
372 <input class="mkwsQuery mkwsTeam_' + m_teamName + '" type="text" size="' + m_config.query_width + '" />\
373 <input class="mkwsButton mkwsTeam_' + m_teamName + '" type="submit" value="' + M('Search') + '" />\
377 // If the team has a .mkwsResults, populate it in the usual
378 // way. If not, assume that it's a smarter application that
379 // defines its own subcomponents, some or all of the
386 findnode(".mkwsResults").html('\
387 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
389 <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
390 <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
392 <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
393 <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
394 <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
395 <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
396 <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
401 <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
406 var ranking_data = '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
407 if (m_config.show_sort) {
408 ranking_data += M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
410 if (m_config.show_perpage) {
411 ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
413 ranking_data += '</form>';
414 findnode(".mkwsRanking").html(ranking_data);
418 findnode('.mkwsSearchForm').submit(function() {
419 var val = findnode('.mkwsQuery').val();
424 // on first page, hide the termlist
425 $(document).ready(function() { findnode(".mkwsTermlists").hide(); });
426 var container = findnode(".mkwsMOTDContainer");
427 if (container.length) {
428 // Move the MOTD from the provided element down into the container
429 findnode(".mkwsMOTD").appendTo(container);
434 function mkwsSetLang() {
435 var lang = getParameterByName("lang") || m_config.lang;
436 if (!lang || !mkws.locale_lang[lang]) {
439 m_config.lang = lang;
442 log("Locale language: " + (m_config.lang ? m_config.lang : "none"));
443 return m_config.lang;
447 /* create locale language menu */
448 function mkwsHtmlLang() {
449 var lang_default = "en";
450 var lang = m_config.lang || lang_default;
453 /* display a list of configured languages, or all */
454 var lang_options = m_config.lang_options || [];
455 var toBeIncluded = {};
456 for (var i = 0; i < lang_options.length; i++) {
457 toBeIncluded[lang_options[i]] = true;
460 for (var k in mkws.locale_lang) {
461 if (toBeIncluded[k] || lang_options.length == 0)
466 if (lang_options.length == 0 || toBeIncluded[lang_default])
467 list.push(lang_default);
469 log("Language menu for: " + list.join(", "));
473 for(var i = 0; i < list.length; i++) {
480 data += ' <span>' + l + '</span> ';
482 data += ' <a href="?lang=' + l + '">' + l + '</a> '
486 findnode(".mkwsLang").html(data);
490 function mkwsHtmlSort() {
491 log("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
492 var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
494 for(var i = 0; i < m_config.sort_options.length; i++) {
495 var opt = m_config.sort_options[i];
497 var val = opt.length == 1 ? opt[0] : opt[1];
499 sort_html += '<option value="' + key + '"';
500 if (m_sortOrder == key || m_sortOrder == val) {
501 sort_html += ' selected="selected"';
503 sort_html += '>' + M(val) + '</option>';
505 sort_html += '</select>';
511 function mkwsHtmlPerpage() {
512 log("HTML perpage, m_perpage = " + m_perpage);
513 var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
515 for(var i = 0; i < m_config.perpage_options.length; i++) {
516 var key = m_config.perpage_options[i];
518 perpage_html += '<option value="' + key + '"';
519 if (key == m_perpage) {
520 perpage_html += ' selected="selected"';
522 perpage_html += '>' + key + '</option>';
524 perpage_html += '</select>';
530 function mkwsHtmlSwitch() {
531 log("HTML switch for team " + m_teamName);
533 var node = findnode(".mkwsSwitch");
534 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
535 node.append($("<span/>", { text: " | " }));
536 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
539 var node = findnode(".mkwsTargets");
541 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
542 No information available yet.\
544 node.css("display", "none");
548 that.runAutoSearch = function() {
549 var node = findnode('.mkwsRecords,.mkwsTermlists');
550 var query = node.attr('autosearch');
554 if (query.match(/^!param!/)) {
555 var param = query.replace(/^!param!/, '');
556 query = getParameterByName(param);
557 log("obtained query '" + query + "' from param '" + param + "'");
559 alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
561 } else if (query.match(/^!path!/)) {
562 var index = query.replace(/^!path!/, '');
563 var path = window.location.pathname.split('/');
564 query = path[path.length - index];
565 log("obtained query '" + query + "' from path-component '" + index + "'");
567 alert("This page has a MasterKey widget that needs a query specified by the path-component " + index);
571 log("node=" + node + ", class='" + node.className + "', query=" + query);
573 var sortOrder = node.attr('sort');
574 var targets = node.attr('targets');
575 var s = "running auto search: '" + query + "'";
576 if (sortOrder) s += " sorted by '" + sortOrder + "'";
577 if (targets) s += " in targets '" + targets + "'";
580 newSearch(query, sortOrder, targets);
584 // This function is taken from a StackOverflow answer
585 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
586 function getParameterByName(name) {
587 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
588 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
589 results = regex.exec(location.search);
590 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
594 // Translation function. At present, this is properly a
595 // global-level function (hence the assignment to mkws.M) but we
596 // want to make it per-team so different teams can operate in
597 // different languages.
600 var lang = m_config.lang;
602 if (!lang || !mkws.locale_lang[lang])
605 return mkws.locale_lang[lang][word] || word;
607 mkws.M = M; // so the Handlebars helper can use it
610 // Finds the node of the specified class within the current team
611 // Multiple OR-clauses separated by commas are handled
612 // More complex cases may not work
614 function findnode(selector, teamName) {
615 teamName = teamName || m_teamName;
617 selector = $.map(selector.split(','), function(s, i) {
618 return s + '.mkwsTeam_' + teamName;
621 var node = $(selector);
622 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
627 function renderDetails(data, marker)
629 var template = loadTemplate("Record");
630 var details = template(data);
631 return '<div class="details mkwsTeam_' + m_teamName + '" ' +
632 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
634 that.renderDetails = renderDetails;
637 function loadTemplate(name)
639 var template = m_template[name];
641 if (template === undefined) {
642 // Fall back to generic template if there is no team-specific one
643 var node = findnode(".mkwsTemplate_" + name);
645 node = findnode(".mkwsTemplate_" + name, "ALL");
648 var source = node.html();
650 source = defaultTemplate(name);
653 template = Handlebars.compile(source);
654 log("compiled template '" + name + "'");
655 m_template[name] = template;
660 that.loadTemplate = loadTemplate;
663 function defaultTemplate(name)
665 if (name === 'Record') {
669 <th>{{translate "Title"}}</th>\
672 {{#if md-title-remainder}}\
673 ({{md-title-remainder}})\
675 {{#if md-title-responsibility}}\
676 <i>{{md-title-responsibility}}</i>\
682 <th>{{translate "Date"}}</th>\
683 <td>{{md-date}}</td>\
688 <th>{{translate "Author"}}</th>\
689 <td>{{md-author}}</td>\
692 {{#if md-electronic-url}}\
694 <th>{{translate "Links"}}</th>\
696 {{#each md-electronic-url}}\
697 <a href="{{this}}">Link{{index1}}</a>\
702 {{#if-any location having="md-subject"}}\
704 <th>{{translate "Subject"}}</th>\
706 {{#first location having="md-subject"}}\
708 {{#commaList md-subject}}\
709 {{this}}{{/commaList}}\
716 <th>{{translate "Locations"}}</th>\
718 {{#commaList location}}\
719 {{attr "@name"}}{{/commaList}}\
724 } else if (name === "Summary") {
726 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
729 {{#if md-title-remainder}}\
730 <span>{{md-title-remainder}}</span>\
732 {{#if md-title-responsibility}}\
733 <span><i>{{md-title-responsibility}}</i></span>\
738 var s = "There is no default '" + name +"' template!";
744 // The following PubSub code is modified from the jQuery manual:
745 // https://api.jquery.com/jQuery.Callbacks/
748 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
749 // team.queue("eventName").publish(arg1, arg2, ...);
752 var queue = function(id) {
754 var callbacks = $.Callbacks();
756 publish: callbacks.fire,
757 subscribe: callbacks.add,
758 unsubscribe: callbacks.remove