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 log_level >= 2
9 // Incredible that the standard JavaScript runtime doesn't define a
10 // unique windowId. Instead, we have to make one up. And since there's
11 // no global area shared between windows, the best we can do for
12 // ensuring uniqueness is generating a random ID and crossing our
13 // fingers. We stash this in window.name, as it's the only place to
14 // keep data that is preserved across reloads and within-site
15 // navigation. pz2.js picks this up and uses it as part of the
16 // cookie-name, to ensure each tab gets its own session.
18 console.log("Using existing window.name '" + window.name + "'");
20 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
21 // At one per second, it will take 116 million years to duplicate a session
22 window.name = Math.random().toString(36).slice(2, 12);
23 console.log("Generated new window.name '" + window.name + "'");
26 // Set up global mkws object. Contains truly global state such as SP
27 // authentication, and a hash of team objects, indexed by team-name.
30 $: $, // Our own local copy of the jQuery object
32 log_level: 1, // Will be overridden from mkws.config, but
33 // initial value allows jQuery popup to use logging.
35 widgetType2function: {},
40 "Subjects": "Schlagwörter",
41 "Sources": "Daten und Quellen",
42 "source": "datenquelle",
43 "Termlists": "Termlisten",
45 "Prev": "Zurück",
47 "Sort by": "Sortieren nach",
48 "and show": "und zeige",
49 "per page": "pro Seite",
50 "Displaying": "Zeige",
58 "Subject": "Schlagwort",
59 "subject": "schlagwort",
61 "Records": "Datensätze",
62 "Targets": "Datenbanken",
68 "Authors": "Forfattere",
72 "Termlists": "Termlists",
73 "Next": "Næste",
75 "Search": "Søg",
76 "Sort by": "Sorter efter",
78 "per page": "per side",
79 "Displaying": "Viser",
84 "Author": "Forfatter",
85 "author": "forfatter",
89 "Location": "Lokation",
99 mkws.log = function(string) {
103 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
107 // you need to disable use strict at the top of the file!!!
108 if (mkws.log_level >= 3) {
109 // Works in Chrome; not sure about elsewhere
111 } else if (mkws.log_level >= 2) {
112 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
118 // Translation function.
119 mkws.M = function(word) {
120 var lang = mkws.config.lang;
122 if (!lang || !mkws.locale_lang[lang])
125 return mkws.locale_lang[lang][word] || word;
129 // This function is taken from a StackOverflow answer
130 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
131 mkws.getParameterByName = function(name, url) {
132 if (!url) url = location.search;
133 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
134 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
135 results = regex.exec(url);
136 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
140 mkws.registerWidgetType = function(name, fn) {
141 mkws.widgetType2function[name] = fn;
142 mkws.log("registered widget-type '" + name + "'");
145 mkws.promotionFunction = function(name) {
146 return mkws.widgetType2function[name];
150 mkws.setMkwsConfig = function(overrides) {
151 // Set global log_level flag early so that mkws.log() works
152 // Fall back to old "debug_level" setting for backwards compatibility
153 var tmp = overrides.log_level;
154 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
155 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
157 var config_default = {
158 use_service_proxy: true,
159 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
160 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
162 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
163 perpage_options: [10, 20, 30, 50],
164 sort_default: "relevance",
167 show_lang: true, /* show/hide language menu */
168 show_sort: true, /* show/hide sort menu */
169 show_perpage: true, /* show/hide perpage menu */
170 show_switch: true, /* show/hide switch menu */
171 lang_options: [], /* display languages links for given languages, [] for all */
172 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
173 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
174 log_level: 1, /* log level for development: 0..2 */
179 mkws.config = mkws.objectInheritingFrom(config_default);
180 for (var k in overrides) {
181 mkws.config[k] = overrides[k];
186 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
187 // http://javascript.crockford.com/prototypal.html
188 // mkws.objectInheritingFrom behaves the same as Object.create,
189 // but since the latter is not available in IE8 we can't use it.
191 mkws.objectInheritingFrom = function(o) {
198 mkws.defaultTemplate = function(name) {
199 if (name === 'Record') {
203 <th>{{mkws-translate "Title"}}</th>\
206 {{#if md-title-remainder}}\
207 ({{md-title-remainder}})\
209 {{#if md-title-responsibility}}\
210 <i>{{md-title-responsibility}}</i>\
216 <th>{{mkws-translate "Date"}}</th>\
217 <td>{{md-date}}</td>\
222 <th>{{mkws-translate "Author"}}</th>\
223 <td>{{md-author}}</td>\
226 {{#if md-electronic-url}}\
228 <th>{{mkws-translate "Links"}}</th>\
230 {{#each md-electronic-url}}\
231 <a href="{{this}}">Link{{mkws-index1}}</a>\
236 {{#mkws-if-any location having="md-subject"}}\
238 <th>{{mkws-translate "Subject"}}</th>\
240 {{#mkws-first location having="md-subject"}}\
242 {{#mkws-commaList md-subject}}\
243 {{this}}{{/mkws-commaList}}\
250 <th>{{mkws-translate "Locations"}}</th>\
252 {{#mkws-commaList location}}\
253 {{mkws-attr "@name"}}{{/mkws-commaList}}\
258 } else if (name === "Summary") {
260 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
263 {{#if md-title-remainder}}\
264 <span>{{md-title-remainder}}</span>\
266 {{#if md-title-responsibility}}\
267 <span><i>{{md-title-responsibility}}</i></span>\
270 } else if (name === "Image") {
272 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
273 {{#mkws-first md-thumburl}}\
274 <img src="{{this}}" alt="{{../md-title}}"/>\
279 } else if (name === 'Facet') {
283 onclick="mkws.{{fn}}(\'{{team}}\', \'{{field}}\', \'{{term}}\');return false;"\
286 <span>{{count}}</span>\
294 // The following functions are dispatchers for team methods that
295 // are called from the UI using a team-name rather than implicit
297 mkws.switchView = function(tname, view) {
298 mkws.teams[tname].switchView(view);
301 mkws.showDetails = function(tname, prefixRecId) {
302 mkws.teams[tname].showDetails(prefixRecId);
305 mkws.limitTarget = function(tname, id, name) {
306 mkws.teams[tname].limitTarget(id, name);
309 mkws.limitQuery = function(tname, field, value) {
310 mkws.teams[tname].limitQuery(field, value);
313 mkws.limitCategory = function(tname, id) {
314 mkws.teams[tname].limitCategory(id);
317 mkws.delimitTarget = function(tname, id) {
318 mkws.teams[tname].delimitTarget(id);
321 mkws.delimitQuery = function(tname, field, value) {
322 mkws.teams[tname].delimitQuery(field, value);
325 mkws.showPage = function(tname, pageNum) {
326 mkws.teams[tname].showPage(pageNum);
329 mkws.pagerPrev = function(tname) {
330 mkws.teams[tname].pagerPrev();
333 mkws.pagerNext = function(tname) {
334 mkws.teams[tname].pagerNext();
338 // wrapper to provide local copy of the jQuery object.
342 function handleNodeWithTeam(node, callback) {
343 // First branch for DOM objects; second branch for jQuery objects
344 var classes = node.className || node.attr('class');
346 // For some reason, if we try to proceed when classes is
347 // undefined, we don't get an error message, but this
348 // function and its callers, up several stack level,
349 // silently return. What a crock.
350 log("handleNodeWithTeam() called on node with no classes");
353 var list = classes.split(/\s+/)
356 for (var i = 0; i < list.length; i++) {
358 if (cname.match(/^mkwsTeam_/)) {
359 teamName = cname.replace(/^mkwsTeam_/, '');
360 } else if (cname.match(/^mkws/)) {
361 type = cname.replace(/^mkws/, '');
365 if (!teamName) teamName = "AUTO";
366 callback.call(node, teamName, type);
370 function resizePage() {
371 var threshhold = mkws.config.responsive_design_width;
372 var width = $(window).width();
373 var from, to, method;
375 if ((mkws.width === undefined || mkws.width > threshhold) &&
376 width <= threshhold) {
377 from = "wide"; to = "narrow"; method = "hide";
378 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
379 width > threshhold) {
380 from = "narrow"; to = "wide"; method = "show";
385 log("changing from " + from + " to " + to + ": " + width);
386 for (var tname in mkws.teams) {
387 var team = mkws.teams[tname];
388 team.visitWidgets(function(t, w) {
389 var w1 = team.widget(t + "-Container-" + from);
390 var w2 = team.widget(t + "-Container-" + to);
396 w.node.appendTo(w2.node);
399 team.queue("resize-" + to).publish();
406 * Run service-proxy authentication in background (after page load).
407 * The username/password is configured in the apache config file
410 function authenticateSession(auth_url, auth_domain, pp2_url) {
411 log("service proxy authentication on URL: " + auth_url);
414 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
415 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
418 var request = new pzHttpRequest(auth_url, function(err) {
419 alert("HTTP call for authentication failed: " + err)
423 request.get(null, function(data) {
424 if (!$.isXMLDoc(data)) {
425 alert("service proxy auth response document is not valid XML document, give up!");
428 var status = $(data).find("status");
429 if (status.text() != "OK") {
430 alert("service proxy auth response status: " + status.text() + ", give up!");
434 log("service proxy authentication successful");
435 mkws.authenticated = true;
436 var authName = $(data).find("displayName").text();
437 // You'd think there would be a better way to do this:
438 var realm = $(data).find("realm:not(realmAttributes realm)").text();
439 for (var teamName in mkws.teams) {
440 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
448 function runAutoSearches() {
449 log("running auto searches");
451 for (var teamName in mkws.teams) {
452 mkws.teams[teamName].queue("ready").publish();
457 function selectorForAllWidgets() {
458 if (mkws.config && mkws.config.scan_all_nodes) {
459 // This is the old version, which works by telling jQuery to
460 // find every node that has a class beginning with "mkws". In
461 // theory it should be slower than the class-based selector; but
462 // instrumentation suprisnigly shows this is consistently
463 // faster. It also has the advantage that any widgets of
464 // non-registered types are logged as warnings rather than
466 return '[class^="mkws"],[class*=" mkws"]';
468 // This is the new version, which works by looking up the
469 // specific classes of all registered widget types and their
470 // resize containers. Because all it requires jQuery to do is
471 // some hash lookups in pre-built tables, it should be very
472 // fast; but it silently ignores widgets of unregistered types.
474 for (var type in mkws.widgetType2function) {
477 s += ',.mkws' + type + "-Container-wide";
478 s += ',.mkws' + type + "-Container-narrow";
485 function makeWidgetsWithin(level, node) {
486 node.find(selectorForAllWidgets()).each(function() {
487 handleNodeWithTeam(this, function(tname, type) {
488 var myTeam = mkws.teams[tname];
490 myTeam = mkws.teams[tname] = team($, tname);
491 log("made MKWS team '" + tname + "'");
494 var oldHTML = this.innerHTML;
495 var myWidget = widget($, myTeam, type, this);
496 myTeam.addWidget(myWidget);
497 var newHTML = this.innerHTML;
498 if (newHTML !== oldHTML) {
499 log("widget " + tname + ":" + type + " HTML changed: reparsing");
500 makeWidgetsWithin(level+1, $(this));
507 function init(rootsel) {
508 if (!rootsel) var rootsel = ':root';
510 if (typeof mkws_config === 'undefined') {
511 log("setting empty config");
514 log("using config: " + $.toJSON(mkws_config));
515 saved_config = mkws_config;
517 mkws.setMkwsConfig(saved_config);
519 for (var key in mkws.config) {
520 if (mkws.config.hasOwnProperty(key)) {
521 if (key.match(/^language_/)) {
522 var lang = key.replace(/^language_/, "");
523 // Copy custom languages into list
524 mkws.locale_lang[lang] = mkws.config[key];
525 log("added locally configured language '" + lang + "'");
530 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
531 if (!lang || !mkws.locale_lang[lang]) {
532 mkws.config.lang = ""
534 mkws.config.lang = lang;
537 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
539 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
540 log("reset query width to " + mkws.config.query_width);
541 mkws.config.query_width = 50;
544 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
545 if (mkws.config.pazpar2_url.match(/^\/\//)) {
546 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
547 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
550 if (mkws.config.responsive_design_width) {
551 // Responsive web design - change layout on the fly based on
552 // current screen width. Required for mobile devices.
553 $(window).resize(resizePage);
554 // initial check after page load
555 $(document).ready(resizePage);
558 // Backwards compatibility: set new magic class names on any
559 // elements that have the old magic IDs.
560 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
561 "Results", "Records", "Targets", "Ranking",
562 "Termlists", "Stat", "MOTD" ];
563 for (var i = 0; i < ids.length; i++) {
564 var id = 'mkws' + ids[i];
565 var node = $('#' + id);
566 if (node.attr('id')) {
568 log("added magic class to '" + node.attr('id') + "'");
573 makeWidgetsWithin(1, $(rootsel));
576 log("walking MKWS nodes took " + (now-then) + " ms");
579 for (var tName in mkws.teams) {
580 var myTeam = mkws.teams[tName]
581 log("team '" + tName + "' = " + myTeam + " ...");
582 myTeam.visitWidgets(function(t, w) {
583 log(" has widget of type '" + t + "': " + w);
588 if (mkws.config.use_service_proxy) {
589 authenticateSession(mkws.config.service_proxy_auth,
590 mkws.config.service_proxy_auth_domain,
591 mkws.config.pazpar2_url);
597 $(document).ready(function() {
598 var widgetSelector = selectorForAllWidgets();
599 if (widgetSelector && $(widgetSelector).length !== 0) init();