1 /*! MKWS, the MasterKey Widget Set.
2 * Copyright (C) 2013-2014 Index Data
3 * See the file LICENSE for details
6 "use strict"; // HTML5: disable for debug_level >= 2
10 Handlebars.registerHelper('json', function(obj) {
15 Handlebars.registerHelper('translate', function(s) {
20 // We need {{attr '@name'}} because Handlebars can't parse {{@name}}
21 Handlebars.registerHelper('attr', function(attrName) {
22 return this[attrName];
27 * Use as follows: {{#if-any NAME1 having="NAME2"}}
28 * Applicable when NAME1 is the name of an array
29 * The guarded code runs only if at least one element of the NAME1
30 * array has a subelement called NAME2.
32 Handlebars.registerHelper('if-any', function(items, options) {
33 var having = options.hash.having;
34 for (var i in items) {
36 if (!having || item[having]) {
37 return options.fn(this);
44 Handlebars.registerHelper('first', function(items, options) {
45 var having = options.hash.having;
46 for (var i in items) {
48 if (!having || item[having]) {
49 return options.fn(item);
56 Handlebars.registerHelper('commaList', function(items, options) {
59 for (var i in items) {
60 if (i > 0) out += ", ";
61 out += options.fn(items[i])
68 Handlebars.registerHelper('index1', function(obj) {
69 return obj.data.index + 1;
74 // Set up global mkws object. Contains truly global state such as SP
75 // authentication, and a hash of team objects, indexed by team-name.
79 debug_level: 1, // Will be overridden from mkws_config, but
80 // initial value allows jQuery popup to use logging.
81 paz: undefined, // will be set up during initialisation
86 "Subjects": "Schlagwörter",
87 "Sources": "Daten und Quellen",
88 "source": "datenquelle",
89 "Termlists": "Termlisten",
91 "Prev": "Zurück",
93 "Sort by": "Sortieren nach",
94 "and show": "und zeige",
95 "per page": "pro Seite",
96 "Displaying": "Zeige",
104 "Subject": "Schlagwort",
105 "subject": "schlagwort",
107 "Records": "Datensätze",
108 "Targets": "Datenbanken",
114 "Authors": "Forfattere",
118 "Termlists": "Termlists",
119 "Next": "Næste",
121 "Search": "Søg",
122 "Sort by": "Sorter efter",
123 "and show": "og vis",
124 "per page": "per side",
125 "Displaying": "Viser",
130 "Author": "Forfatter",
131 "author": "forfatter",
133 "Subject": "Emneord",
134 "subject": "emneord",
135 "Location": "Lokation",
145 // Define empty mkws_config for simple applications that don't define it.
146 if (mkws_config == null || typeof mkws_config != 'object') {
147 var mkws_config = {};
151 // Factory function for widget objects.
152 function widget($, team, type, node) {
161 if (type === 'Targets') {
163 } else if (type === 'Stat') {
165 } else if (type === 'Termlists') {
167 } else if (type === 'Pager') {
169 } else if (type === 'Records') {
172 // ### Handle other types here
175 mkws.debug("made widget(team=" + team.name() + ", type=" + type + ", node=" + node);
179 // Functions follow for promoting the regular widget object into
180 // widgets of specific types. These could be moved outside of the
181 // widget object, or even into their own source files.
183 function promoteTargets() {
184 team.queue("targets").subscribe(function(data) {
185 if (node.length === 0) alert("huh?!");
187 var table ='<table><thead><tr>' +
188 '<td>' + M('Target ID') + '</td>' +
189 '<td>' + M('Hits') + '</td>' +
190 '<td>' + M('Diags') + '</td>' +
191 '<td>' + M('Records') + '</td>' +
192 '<td>' + M('State') + '</td>' +
193 '</tr></thead><tbody>';
195 for (var i = 0; i < data.length; i++) {
196 table += "<tr><td>" + data[i].id +
197 "</td><td>" + data[i].hits +
198 "</td><td>" + data[i].diagnostic +
199 "</td><td>" + data[i].records +
200 "</td><td>" + data[i].state + "</td></tr>";
203 table += '</tbody></table>';
204 var subnode = $(node).children('.mkwsBytarget');
210 function promoteStat() {
211 team.queue("stat").subscribe(function(data) {
212 if (node.length === 0) alert("huh?!");
214 $(node).html('<span class="head">' + M('Status info') + '</span>' +
216 '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
218 '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>');
223 function promoteTermlists() {
224 team.queue("termlists").subscribe(function(data) {
225 mkws.debug("in termlist consumer");
227 alert("termlists event when there are no termlists");
231 // no facets: this should never happen
232 if (!mkws_config.facets || mkws_config.facets.length == 0) {
233 alert("onTerm called even though we have no facets: " + $.toJSON(data));
238 // display if we first got results
242 acc.push('<div class="title">' + M('Termlists') + '</div>');
243 var facets = mkws_config.facets;
245 for (var i = 0; i < facets.length; i++) {
246 if (facets[i] == "xtargets") {
247 addSingleFacet(acc, "Sources", data.xtargets, 16, null);
248 } else if (facets[i] == "subject") {
249 addSingleFacet(acc, "Subjects", data.subject, 10, "subject");
250 } else if (facets[i] == "author") {
251 addSingleFacet(acc, "Authors", data.author, 10, "author");
253 alert("bad facet configuration: '" + facets[i] + "'");
257 $(node).html(acc.join(''));
259 function addSingleFacet(acc, caption, data, max, pzIndex) {
260 acc.push('<div class="facet mkwsFacet' + caption + ' mkwsTeam_' + team.name() + '">');
261 acc.push('<div class="termtitle">' + M(caption) + '</div>');
262 for (var i = 0; i < data.length && i < max; i++) {
263 acc.push('<div class="term">');
264 acc.push('<a href="#" ');
267 // Special case: target selection
268 acc.push('target_id='+data[i].id+' ');
269 if (!team.targetFiltered(data[i].id)) {
270 action = 'mkws.limitTarget(\'' + team.name() + '\', this.getAttribute(\'target_id\'),this.firstChild.nodeValue)';
273 action = 'mkws.limitQuery(\'' + team.name() + '\', \'' + pzIndex + '\', this.firstChild.nodeValue)';
275 acc.push('onclick="' + action + ';return false;">' + data[i].name + '</a>'
276 + ' <span>' + data[i].freq + '</span>');
285 function promotePager() {
286 team.queue("pager").subscribe(function(data) {
287 $(node).html(drawPager(data))
289 function drawPager(data) {
290 var s = '<div style="float: right">' + M('Displaying') + ': '
291 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
292 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
293 + data.total + ')</div>';
295 //client indexes pages from 1 but pz2 from 0
297 var pages = Math.ceil(team.totalRecordCount() / team.perpage());
298 var currentPage = team.currentPage();
300 var firstClkbl = (currentPage - onsides > 0)
301 ? currentPage - onsides
304 var lastClkbl = firstClkbl + 2*onsides < pages
305 ? firstClkbl + 2*onsides
308 var prev = '<span class="mkwsPrev"><< ' + M('Prev') + '</span><b> | </b>';
310 prev = '<a href="#" class="mkwsPrev" onclick="mkws.pagerPrev(\'' + team.name() + '\');">'
311 +'<< ' + M('Prev') + '</a><b> | </b>';
314 for(var i = firstClkbl; i <= lastClkbl; i++) {
317 numLabel = '<b>' + i + '</b>';
319 middle += '<a href="#" onclick="mkws.showPage(\'' + team.name() + '\', ' + i + ')"> '
320 + numLabel + ' </a>';
323 var next = '<b> | </b><span class="mkwsNext">' + M('Next') + ' >></span>';
324 if (pages - currentPage > 0)
325 next = '<b> | </b><a href="#" class="mkwsNext" onclick="mkws.pagerNext(\'' + team.name() + '\')">'
326 + M('Next') + ' >></a>';
333 if (lastClkbl < pages)
336 s += '<div style="float: clear">'
337 + prev + predots + middle + postdots + next + '</div>';
345 function promoteRecords() {
346 team.queue("records").subscribe(function(data) {
348 for (var i = 0; i < data.hits.length; i++) {
349 var hit = data.hits[i];
350 html.push('<div class="record" id="mkwsRecdiv_' + team.name() + '_' + hit.recid + '" >',
353 // ### At some point, we may be able to move the
354 // m_currentRecordId and m_currentRecordData members
355 // from the team object into this widget.
356 if (hit.recid == team.currentRecordId()) {
357 if (team.currentRecordData())
358 html.push(renderDetails(team.currentRecordData()));
361 $(node).html(html.join(''));
363 function renderSummary(hit)
365 var template = team.loadTemplate("Summary");
366 hit._id = "mkwsRec_" + hit.recid;
367 hit._onclick = "mkws.showDetails('" + team.name() + "', this.id);return false;"
368 return template(hit);
375 // Factory function for team objects. As much as possible, this uses
376 // only member variables (prefixed "m_") and inner functions with
377 // private scope. Some functions are visibl as member-functions to be
378 // called from outside code -- specifically, from generated
379 // HTML. These functions are that.switchView(), showDetails(),
380 // limitTarget(), limitQuery(), delimitTarget(), delimitQuery(),
381 // pagerPrev(), pagerNext(), showPage().
383 function team($, teamName) {
385 var m_teamName = teamName;
386 var m_submitted = false;
387 var m_query; // initially undefined
388 var m_sortOrder; // will be set below
389 var m_perpage; // will be set below
391 var m_totalRecordCount = 0;
392 var m_currentPage = 1;
393 var m_currentRecordId = '';
394 var m_currentRecordData = null;
396 // Timestamps for logging
400 var m_paz; // will be initialised below
403 that.name = function() { return m_teamName; }
404 that.perpage = function() { return m_perpage; }
405 that.totalRecordCount = function() { return m_totalRecordCount; }
406 that.currentPage = function() { return m_currentPage; }
407 that.currentRecordId = function() { return m_currentRecordId; }
408 that.currentRecordData = function() { return m_currentRecordData; }
410 var debug = function (s) {
412 var timestamp = ((now - m_debugTime.start)/1000).toFixed(3) + " (+" + ((now - m_debugTime.last)/1000).toFixed(3) + ") "
413 m_debugTime.last = now;
415 mkws.debug(m_teamName + ": " + timestamp + s);
418 debug("start running MKWS");
420 m_sortOrder = mkws_config.sort_default;
421 m_perpage = mkws_config.perpage_default;
423 debug("Create main pz2 object");
424 // create a parameters array and pass it to the pz2's constructor
425 // then register the form submit event with the pz2.search function
426 // autoInit is set to true on default
427 m_paz = new pz2({ "windowid": teamName,
428 "pazpar2path": mkws_config.pazpar2_url,
429 "usesessions" : mkws_config.use_service_proxy ? false : true,
431 "onbytarget": onBytarget,
433 "onterm": (mkws_config.facets.length ? onTerm : undefined),
435 "onrecord": onRecord,
436 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
437 "termlist": mkws_config.facets.join(',')
442 // pz2.js event handlers:
451 function onBytarget(data) {
453 queue("targets").publish(data);
457 function onStat(data) {
459 queue("stat").publish(data);
463 function onTerm(data) {
465 queue("termlists").publish(data);
469 function onShow(data, teamName) {
471 m_totalRecordCount = data.merged;
472 queue("pager").publish(data);
473 queue("records").publish(data);
477 function onRecord(data, args, teamName) {
479 // FIXME: record is async!!
480 clearTimeout(m_paz.recordTimer);
481 // in case on_show was faster to redraw element
482 var detRecordDiv = document.getElementById('mkwsDet_' + teamName + '_' + data.recid);
483 if (detRecordDiv) return;
484 m_currentRecordData = data;
485 // Can't use jQuery's $('#x') syntax to find this ID, because it contains spaces.
486 var recordDiv = document.getElementById('mkwsRecdiv_' + teamName + '_' + m_currentRecordData.recid);
487 var html = renderDetails(m_currentRecordData);
488 $(recordDiv).append(html);
492 that.targetFiltered = function(id) {
493 for (var i = 0; i < m_filters.length; i++) {
494 if (m_filters[i].id === id ||
495 m_filters[i].id === 'pz:id=' + id) {
503 ////////////////////////////////////////////////////////////////////////////////
504 ////////////////////////////////////////////////////////////////////////////////
507 // when search button pressed
508 function onFormSubmitEventHandler()
510 var val = findnode('.mkwsQuery').val();
516 function newSearch(query, sortOrder, targets)
518 debug("newSearch: " + query);
520 if (mkws_config.use_service_proxy && !mkws.authenticated) {
521 alert("searching before authentication");
529 triggerSearch(query, sortOrder, targets);
530 switchView('records'); // In case it's configured to start off as hidden
535 function onSelectDdChange()
537 if (!m_submitted) return false;
540 m_paz.show(0, m_perpage, m_sortOrder);
545 function redrawNavi ()
547 var navi = findnode('.mkwsNavi');
551 for (var i in m_filters) {
555 var filter = m_filters[i];
557 text += M('source') + ': <a class="crossout" href="#" onclick="mkws.delimitTarget(\'' + m_teamName +
558 "', '" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
560 text += M(filter.field) + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(\'' + m_teamName +
561 "', '" + filter.field + "', '" + filter.value + "'" +
562 ');return false;">' + filter.value + '</a>';
573 m_totalRecordCount = 0;
577 function loadSelect ()
579 var node = findnode('.mkwsSort');
580 if (node.length && node.val() != m_sortOrder) {
581 debug("changing m_sortOrder from " + m_sortOrder + " to " + node.val());
582 m_sortOrder = node.val();
584 node = findnode('.mkwsPerpage');
585 if (node.length && node.val() != m_perpage) {
586 debug("changing m_perpage from " + m_perpage + " to " + node.val());
587 m_perpage = node.val();
592 function triggerSearch (query, sortOrder, targets)
597 // Continue to use previous query/sort-order unless new ones are specified
602 m_sortOrder = sortOrder;
605 m_filters.push({ id: targets, name: targets });
608 for (var i in m_filters) {
609 var filter = m_filters[i];
613 if (filter.id.match(/^[a-z:]+[=~]/)) {
614 debug("filter '" + filter.id + "' already begins with SETTING OP");
616 filter.id = 'pz:id=' + filter.id;
618 pp2filter += filter.id;
622 pp2limit += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
628 params.limit = pp2limit;
631 debug("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
633 // We can use: params.torusquery = "udb=NAME"
634 // Note: that won't work when running against raw pazpar2
635 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
639 // limit by target functions
640 that.limitTarget = function (id, name)
642 debug("limitTarget(id=" + id + ", name=" + name + ")");
643 m_filters.push({ id: id, name: name });
652 // limit the query after clicking the facet
653 that.limitQuery = function (field, value)
655 debug("limitQuery(field=" + field + ", value=" + value + ")");
656 m_filters.push({ field: field, value: value });
665 that.delimitTarget = function (id)
667 debug("delimitTarget(id=" + id + ")");
669 for (var i in m_filters) {
670 var filter = m_filters[i];
672 debug("delimitTarget() removing filter " + $.toJSON(filter));
674 debug("delimitTarget() keeping filter " + $.toJSON(filter));
675 newFilters.push(filter);
678 m_filters = newFilters;
688 that.delimitQuery = function (field, value)
690 debug("delimitQuery(field=" + field + ", value=" + value + ")");
692 for (var i in m_filters) {
693 var filter = m_filters[i];
695 field == filter.field &&
696 value == filter.value) {
697 debug("delimitQuery() removing filter " + $.toJSON(filter));
699 debug("delimitQuery() keeping filter " + $.toJSON(filter));
700 newFilters.push(filter);
703 m_filters = newFilters;
713 that.showPage = function (pageNum)
715 m_currentPage = pageNum;
716 m_paz.showPage(m_currentPage - 1);
720 // simple paging functions
721 that.pagerNext = function () {
722 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
729 that.pagerPrev = function () {
730 if (m_paz.showPrev() != false)
735 // switching view between targets and records
736 function switchView(view) {
737 var targets = findnode('.mkwsTargets');
738 var results = findnode('.mkwsResults,.mkwsRecords');
739 var blanket = findnode('.mkwsBlanket');
740 var motd = findnode('.mkwsMOTD');
744 if (targets) targets.css('display', 'block');
745 if (results) results.css('display', 'none');
746 if (blanket) blanket.css('display', 'none');
747 if (motd) motd.css('display', 'none');
750 if (targets) targets.css('display', 'none');
751 if (results) results.css('display', 'block');
752 if (blanket) blanket.css('display', 'block');
753 if (motd) motd.css('display', 'none');
756 alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
757 if (targets) targets.css('display', 'none');
758 if (results) results.css('display', 'none');
759 if (blanket) blanket.css('display', 'none');
760 if (motd) motd.css('display', 'none');
763 alert("Unknown view '" + view + "'");
768 that.switchView = switchView;
771 // detailed record drawing
772 that.showDetails = function (prefixRecId) {
773 var recId = prefixRecId.replace('mkwsRec_', '');
774 var oldRecordId = m_currentRecordId;
775 m_currentRecordId = recId;
777 // remove current detailed view if any
778 var detRecordDiv = document.getElementById('mkwsDet_' + m_teamName + '_' + oldRecordId);
781 detRecordDiv.parentNode.removeChild(detRecordDiv);
783 // if the same clicked, just hide
784 if (recId == oldRecordId) {
785 m_currentRecordId = '';
786 m_currentRecordData = null;
789 // request the record
790 debug("showDetails() requesting record '" + recId + "'");
796 * All the HTML stuff to render the search forms and
799 function mkwsHtmlAll() {
801 if (mkws_config.show_lang)
804 debug("HTML search form");
805 mkws.handleNodeWithTeam(findnode('.mkwsSearch'), function(tname) {
807 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + tname + '" action="" >\
808 <input class="mkwsQuery mkwsTeam_' + tname + '" type="text" size="' + mkws_config.query_width + '" />\
809 <input class="mkwsButton mkwsTeam_' + tname + '" type="submit" value="' + M('Search') + '" />\
813 debug("HTML records");
814 // If the team has a .mkwsResults, populate it in the usual
815 // way. If not, assume that it's a smarter application that
816 // defines its own subcomponents, some or all of the
823 if (findnode(".mkwsResults").length) {
824 findnode(".mkwsResults").html('\
825 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
827 <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
828 <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
830 <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
831 <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
832 <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
833 <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
834 <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
839 <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
845 var node = findnode(".mkwsRanking");
847 var ranking_data = '';
848 ranking_data += '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
849 if (mkws_config.show_sort) {
850 ranking_data += M('Sort by') + ' ' + mkwsHtmlSort() + ' ';
852 if (mkws_config.show_perpage) {
853 ranking_data += M('and show') + ' ' + mkwsHtmlPerpage() + ' ' + M('per page') + '.';
855 ranking_data += '</form>';
857 node.html(ranking_data);
863 node = findnode('.mkwsSearchForm');
865 node.submit(onFormSubmitEventHandler);
866 node = findnode('.mkwsSort');
868 node.change(onSelectDdChange);
869 node = findnode('.mkwsPerpage');
871 node.change(onSelectDdChange);
873 // on first page, hide the termlist
874 $(document).ready(function() { findnode(".mkwsTermlists").hide(); });
875 var motd = findnode(".mkwsMOTD");
876 var container = findnode(".mkwsMOTDContainer");
877 if (motd.length && container.length) {
878 // Move the MOTD from the provided element down into the container
879 motd.appendTo(container);
884 function mkwsSetLang() {
885 var lang = mkws.getParameterByName("lang") || mkws_config.lang;
886 if (!lang || !mkws.locale_lang[lang]) {
887 mkws_config.lang = ""
889 mkws_config.lang = lang;
892 debug("Locale language: " + (mkws_config.lang ? mkws_config.lang : "none"));
893 return mkws_config.lang;
897 /* create locale language menu */
898 function mkwsHtmlLang() {
899 var lang_default = "en";
900 var lang = mkws_config.lang || lang_default;
903 /* display a list of configured languages, or all */
904 var lang_options = mkws_config.lang_options || [];
905 var toBeIncluded = {};
906 for (var i = 0; i < lang_options.length; i++) {
907 toBeIncluded[lang_options[i]] = true;
910 for (var k in mkws.locale_lang) {
911 if (toBeIncluded[k] || lang_options.length == 0)
916 if (lang_options.length == 0 || toBeIncluded[lang_default])
917 list.push(lang_default);
919 debug("Language menu for: " + list.join(", "));
923 for(var i = 0; i < list.length; i++) {
930 data += ' <span>' + l + '</span> ';
932 data += ' <a href="?lang=' + l + '">' + l + '</a> '
936 findnode(".mkwsLang").html(data);
940 function mkwsHtmlSort() {
941 debug("HTML sort, m_sortOrder = '" + m_sortOrder + "'");
942 var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
944 for(var i = 0; i < mkws_config.sort_options.length; i++) {
945 var opt = mkws_config.sort_options[i];
947 var val = opt.length == 1 ? opt[0] : opt[1];
949 sort_html += '<option value="' + key + '"';
950 if (m_sortOrder == key || m_sortOrder == val) {
951 sort_html += ' selected="selected"';
953 sort_html += '>' + M(val) + '</option>';
955 sort_html += '</select>';
961 function mkwsHtmlPerpage() {
962 debug("HTML perpage, m_perpage = " + m_perpage);
963 var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
965 for(var i = 0; i < mkws_config.perpage_options.length; i++) {
966 var key = mkws_config.perpage_options[i];
968 perpage_html += '<option value="' + key + '"';
969 if (key == m_perpage) {
970 perpage_html += ' selected="selected"';
972 perpage_html += '>' + key + '</option>';
974 perpage_html += '</select>';
980 function mkwsHtmlSwitch() {
981 debug("HTML switch for team " + m_teamName);
983 var node = findnode(".mkwsSwitch");
984 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
985 node.append($("<span/>", { text: " | " }));
986 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
988 debug("HTML targets");
989 var node = findnode(".mkwsTargets");
991 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
992 No information available yet.\
994 node.css("display", "none");
998 that.runAutoSearch = function() {
999 var node = findnode('.mkwsRecords,.mkwsTermlists');
1000 var query = node.attr('autosearch');
1004 if (query.match(/^!param!/)) {
1005 var param = query.replace(/^!param!/, '');
1006 query = mkws.getParameterByName(param);
1007 debug("obtained query '" + query + "' from param '" + param + "'");
1009 alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
1011 } else if (query.match(/^!path!/)) {
1012 var index = query.replace(/^!path!/, '');
1013 var path = window.location.pathname.split('/');
1014 query = path[path.length - index];
1015 debug("obtained query '" + query + "' from path-component '" + index + "'");
1017 alert("This page has a MasterKey widget that needs a query specified by the path-component " + index);
1021 debug("node=" + node + ", class='" + node.className + "', query=" + query);
1023 var sortOrder = node.attr('sort');
1024 var targets = node.attr('targets');
1025 var s = "running auto search: '" + query + "'";
1026 if (sortOrder) s += " sorted by '" + sortOrder + "'";
1027 if (targets) s += " in targets '" + targets + "'";
1030 newSearch(query, sortOrder, targets);
1034 // Translation function. At present, this is properly a
1035 // global-level function (hence the assignment to mkws.M) but we
1036 // want to make it per-team so different teams can operate in
1037 // different languages.
1040 var lang = mkws_config.lang;
1042 if (!lang || !mkws.locale_lang[lang])
1045 return mkws.locale_lang[lang][word] || word;
1047 mkws.M = M; // so the Handlebars helper can use it
1050 // Finds the node of the specified class within the current team
1051 // Multiple OR-clauses separated by commas are handled
1052 // More complex cases may not work
1054 function findnode(selector, teamName) {
1055 teamName = teamName || m_teamName;
1057 selector = $.map(selector.split(','), function(s, i) {
1058 return s + '.mkwsTeam_' + teamName;
1065 function renderDetails(data, marker)
1067 var template = loadTemplate("Record");
1068 var details = template(data);
1069 return '<div class="details" id="mkwsDet_' + m_teamName + '_' + data.recid + '">' + details + '</div>';
1073 function loadTemplate(name)
1075 var template = m_template[name];
1077 if (template === undefined) {
1078 // Fall back to generic template if there is no team-specific one
1079 var node = findnode(".mkwsTemplate_" + name);
1081 node = findnode(".mkwsTemplate_" + name, "ALL");
1084 var source = node.html();
1086 source = mkws.defaultTemplate(name);
1089 template = Handlebars.compile(source);
1090 debug("compiled template '" + name + "'");
1091 m_template[name] = template;
1096 that.loadTemplate = loadTemplate;
1099 // The following PubSub code is modified from the jQuery manual:
1100 // https://api.jquery.com/jQuery.Callbacks/
1103 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
1104 // team.queue("eventName").publish(arg1, arg2, ...);
1107 var queue = function(id) {
1109 var callbacks = $.Callbacks();
1111 publish: callbacks.fire,
1112 subscribe: callbacks.add,
1113 unsubscribe: callbacks.remove
1129 mkws_config.error = e.message;
1130 // alert(e.message);
1134 // Bizarrely, 'that' is just an empty hash. All its state is in
1135 // the closure variables defined earlier in this function.
1140 // wrapper to call team() after page load
1142 mkws.debug = function (string) {
1143 if (!mkws.debug_level)
1146 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
1150 // you need to disable use strict at the top of the file!!!
1151 if (mkws.debug_level >= 3) {
1152 console.log(arguments.callee.caller);
1153 } else if (mkws.debug_level >= 2) {
1154 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
1156 console.log(string);
1158 var debug = mkws.debug;
1161 mkws.handleNodeWithTeam = function(node, callback) {
1162 // First branch for DOM objects; second branch for jQuery objects
1163 var classes = node.className || node.attr('class');
1165 // For some reason, if we try to proceed when classes is
1166 // undefined, we don't get an error message, but this
1167 // function and its callers, up several stack level,
1168 // silently return. What a crock.
1169 mkws.debug("handleNodeWithTeam() called on node with no classes");
1172 var list = classes.split(/\s+/)
1175 for (var i = 0; i < list.length; i++) {
1176 var cname = list[i];
1177 if (cname.match(/^mkwsTeam_/)) {
1178 teamName = cname.replace(/^mkwsTeam_/, '');
1179 } else if (cname.match(/^mkws/)) {
1180 type = cname.replace(/^mkws/, '');
1183 callback.call(node, teamName, type);
1187 mkws.resizePage = function () {
1188 var list = ["mkwsSwitch", "mkwsLang"];
1190 var width = mkws_config.responsive_design_width;
1191 var parent = $(".mkwsTermlists").parent();
1193 if ($(window).width() <= width &&
1194 parent.hasClass("mkwsTermlistContainer1")) {
1195 debug("changing from wide to narrow: " + $(window).width());
1196 $(".mkwsTermlistContainer1").hide();
1197 $(".mkwsTermlistContainer2").show();
1198 for (var tname in mkws.teams) {
1199 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer2.mkwsTeam_" + tname));
1200 for(var i = 0; i < list.length; i++) {
1201 $("." + list[i] + ".mkwsTeam_" + tname).hide();
1204 } else if ($(window).width() > width &&
1205 parent.hasClass("mkwsTermlistContainer2")) {
1206 debug("changing from narrow to wide: " + $(window).width());
1207 $(".mkwsTermlistContainer1").show();
1208 $(".mkwsTermlistContainer2").hide();
1209 for (var tname in mkws.teams) {
1210 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer1.mkwsTeam_" + tname));
1211 for(var i = 0; i < list.length; i++) {
1212 $("." + list[i] + ".mkwsTeam_" + tname).show();
1219 mkws.switchView = function(tname, view) {
1220 mkws.teams[tname].switchView(view);
1223 mkws.showDetails = function (tname, prefixRecId) {
1224 mkws.teams[tname].showDetails(prefixRecId);
1227 mkws.limitTarget = function (tname, id, name) {
1228 mkws.teams[tname].limitTarget(id, name);
1231 mkws.limitQuery = function (tname, field, value) {
1232 mkws.teams[tname].limitQuery(field, value);
1235 mkws.delimitTarget = function (tname, id) {
1236 mkws.teams[tname].delimitTarget(id);
1239 mkws.delimitQuery = function (tname, field, value) {
1240 mkws.teams[tname].delimitQuery(field, value);
1243 mkws.showPage = function (tname, pageNum) {
1244 mkws.teams[tname].showPage(pageNum);
1247 mkws.pagerPrev = function (tname) {
1248 mkws.teams[tname].pagerPrev();
1251 mkws.pagerNext = function (tname) {
1252 mkws.teams[tname].pagerNext();
1256 // This function is taken from a StackOverflow answer
1257 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
1258 mkws.getParameterByName = function(name) {
1259 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
1260 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
1261 results = regex.exec(location.search);
1262 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
1266 mkws.defaultTemplate = function(name)
1268 if (name === 'Record') {
1272 <th>{{translate "Title"}}</th>\
1275 {{#if md-title-remainder}}\
1276 ({{md-title-remainder}})\
1278 {{#if md-title-responsibility}}\
1279 <i>{{md-title-responsibility}}</i>\
1285 <th>{{translate "Date"}}</th>\
1286 <td>{{md-date}}</td>\
1291 <th>{{translate "Author"}}</th>\
1292 <td>{{md-author}}</td>\
1295 {{#if md-electronic-url}}\
1297 <th>{{translate "Links"}}</th>\
1299 {{#each md-electronic-url}}\
1300 <a href="{{this}}">Link{{index1}}</a>\
1305 {{#if-any location having="md-subject"}}\
1307 <th>{{translate "Subject"}}</th>\
1309 {{#first location having="md-subject"}}\
1311 {{#commaList md-subject}}\
1312 {{this}}{{/commaList}}\
1319 <th>{{translate "Locations"}}</th>\
1321 {{#commaList location}}\
1322 {{attr "@name"}}{{/commaList}}\
1327 } else if (name === "Summary") {
1329 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
1330 <b>{{md-title}}</b>\
1332 {{#if md-title-remainder}}\
1333 <span>{{md-title-remainder}}</span>\
1335 {{#if md-title-responsibility}}\
1336 <span><i>{{md-title-responsibility}}</i></span>\
1341 var s = "There is no default '" + name +"' template!";
1347 function defaultMkwsConfig() {
1348 /* default mkws config */
1349 var config_default = {
1350 use_service_proxy: true,
1351 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
1352 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
1354 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
1355 perpage_options: [10, 20, 30, 50],
1356 sort_default: "relevance",
1357 perpage_default: 20,
1359 show_lang: true, /* show/hide language menu */
1360 show_sort: true, /* show/hide sort menu */
1361 show_perpage: true, /* show/hide perpage menu */
1362 lang_options: [], /* display languages links for given languages, [] for all */
1363 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
1364 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
1365 debug_level: 1, /* debug level for development: 0..2 */
1370 /* Set global debug_level flag early so that debug() works */
1371 if (typeof mkws_config.debug_level !== 'undefined') {
1372 mkws.debug_level = mkws_config.debug_level;
1373 } else if (typeof config_default.debug_level !== 'undefined') {
1374 mkws.debug_level = config_default.debug_level;
1377 // make sure the mkws_config is a valid hash
1378 if (!$.isPlainObject(mkws_config)) {
1379 debug("ERROR: mkws_config is not an JS object, ignore it....");
1383 /* override standard config values by function parameters */
1384 for (var k in config_default) {
1385 if (typeof mkws_config[k] === 'undefined')
1386 mkws_config[k] = config_default[k];
1387 //debug("Set config: " + k + ' => ' + mkws_config[k]);
1393 * Run service-proxy authentication in background (after page load).
1394 * The username/password is configured in the apache config file
1397 function authenticateSession(auth_url, auth_domain, pp2_url) {
1398 debug("Run service proxy auth URL: " + auth_url);
1401 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
1402 debug("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
1405 var request = new pzHttpRequest(auth_url, function(err) {
1406 alert("HTTP call for authentication failed: " + err)
1410 request.get(null, function(data) {
1411 if (!$.isXMLDoc(data)) {
1412 alert("service proxy auth response document is not valid XML document, give up!");
1415 var status = $(data).find("status");
1416 if (status.text() != "OK") {
1417 alert("service proxy auth repsonse status: " + status.text() + ", give up!");
1421 debug("Service proxy auth successfully done");
1422 mkws.authenticated = true;
1428 function runAutoSearches() {
1429 debug("running auto searches");
1431 for (var teamName in mkws.teams) {
1432 mkws.teams[teamName].runAutoSearch();
1437 $(document).ready(function() {
1438 debug("on load ready");
1439 defaultMkwsConfig();
1441 if (mkws_config.query_width < 5 || mkws_config.query_width > 150) {
1442 debug("Reset query width: " + mkws_config.query_width);
1443 mkws_config.query_width = 50;
1446 for (var key in mkws_config) {
1447 if (mkws_config.hasOwnProperty(key)) {
1448 if (key.match(/^language_/)) {
1449 var lang = key.replace(/^language_/, "");
1450 // Copy custom languages into list
1451 mkws.locale_lang[lang] = mkws_config[key];
1452 debug("Added locally configured language '" + lang + "'");
1457 if (mkws_config.responsive_design_width) {
1458 // Responsive web design - change layout on the fly based on
1459 // current screen width. Required for mobile devices.
1460 $(window).resize(function(e) { mkws.resizePage() });
1461 // initial check after page load
1462 $(document).ready(function() { mkws.resizePage() });
1465 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
1466 if (mkws_config.pazpar2_url.match(/^\/\//)) {
1467 mkws_config.pazpar2_url = document.location.protocol + mkws_config.pazpar2_url;
1468 debug("adjust protocol independent links: " + mkws_config.pazpar2_url);
1471 // Backwards compatibility: set new magic class names on any
1472 // elements that have the old magic IDs.
1473 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
1474 "Results", "Records", "Targets", "Ranking",
1475 "Termlists", "Stat", "MOTD" ];
1476 for (var i = 0; i < ids.length; i++) {
1477 var id = 'mkws' + ids[i];
1478 var node = $('#' + id);
1479 if (node.attr('id')) {
1481 debug("added magic class to '" + node.attr('id') + "'");
1485 // For all MKWS-classed nodes that don't have a team
1486 // specified, set the team to AUTO.
1487 $('[class^="mkws"],[class*=" mkws"]').each(function () {
1488 if (!this.className.match(/mkwsTeam_/)) {
1489 debug("adding AUTO team to node with class '" + this.className + "'");
1490 $(this).addClass('mkwsTeam_AUTO');
1494 // Find all nodes with an MKWS class, and determine their team from
1495 // the mkwsTeam_* class. Make all team objects.
1497 $('[class^="mkws"],[class*=" mkws"]').each(function () {
1498 mkws.handleNodeWithTeam(this, function(tname, type) {
1499 if (!mkws.teams[tname]) {
1500 mkws.teams[tname] = team(j, tname);
1501 debug("Made MKWS team '" + tname + "'");
1505 // Second pass: make the individual widget objects. This has
1506 // to be done separately, and after the team-creation, since
1507 // that sometimes makes new widget nodes (e.g. creating
1508 // mkwsTermlists instead mkwsResults.
1509 $('[class^="mkws"],[class*=" mkws"]').each(function () {
1510 mkws.handleNodeWithTeam(this, function(tname, type) {
1511 var myTeam = mkws.teams[tname];
1512 var myWidget = widget(j, myTeam, type, this);
1516 debug("Walking MKWS nodes took " + (now-then) + " ms");
1518 if (mkws_config.use_service_proxy) {
1519 authenticateSession(mkws_config.service_proxy_auth,
1520 mkws_config.service_proxy_auth_domain,
1521 mkws_config.pazpar2_url);