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>\
269 {{#if md-date}}, {{md-date}}\
271 , {{#mkws-first location}}{{mkws-attr "@name"}}{{/mkws-first}}\
274 <span>, {{md-medium}}</span>\
278 } else if (name === "Image") {
280 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
281 {{#mkws-first md-thumburl}}\
282 <img src="{{this}}" alt="{{../md-title}}"/>\
287 } else if (name === 'Facet') {
291 onclick="mkws.{{fn}}(\'{{team}}\', \'{{field}}\', \'{{term}}\');return false;"\
294 <span>{{count}}</span>\
302 // The following functions are dispatchers for team methods that
303 // are called from the UI using a team-name rather than implicit
305 mkws.switchView = function(tname, view) {
306 mkws.teams[tname].switchView(view);
309 mkws.showDetails = function(tname, prefixRecId) {
310 mkws.teams[tname].showDetails(prefixRecId);
313 mkws.limitTarget = function(tname, id, name) {
314 mkws.teams[tname].limitTarget(id, name);
317 mkws.limitQuery = function(tname, field, value) {
318 mkws.teams[tname].limitQuery(field, value);
321 mkws.limitCategory = function(tname, id) {
322 mkws.teams[tname].limitCategory(id);
325 mkws.delimitTarget = function(tname, id) {
326 mkws.teams[tname].delimitTarget(id);
329 mkws.delimitQuery = function(tname, field, value) {
330 mkws.teams[tname].delimitQuery(field, value);
333 mkws.showPage = function(tname, pageNum) {
334 mkws.teams[tname].showPage(pageNum);
337 mkws.pagerPrev = function(tname) {
338 mkws.teams[tname].pagerPrev();
341 mkws.pagerNext = function(tname) {
342 mkws.teams[tname].pagerNext();
346 // wrapper to provide local copy of the jQuery object.
350 function handleNodeWithTeam(node, callback) {
351 // First branch for DOM objects; second branch for jQuery objects
352 var classes = node.className || node.attr('class');
354 // For some reason, if we try to proceed when classes is
355 // undefined, we don't get an error message, but this
356 // function and its callers, up several stack level,
357 // silently return. What a crock.
358 log("handleNodeWithTeam() called on node with no classes");
361 var list = classes.split(/\s+/)
364 for (var i = 0; i < list.length; i++) {
366 if (cname.match(/^mkwsTeam_/)) {
367 teamName = cname.replace(/^mkwsTeam_/, '');
368 } else if (cname.match(/^mkws/)) {
369 type = cname.replace(/^mkws/, '');
373 if (!teamName) teamName = "AUTO";
374 callback.call(node, teamName, type);
378 function resizePage() {
379 var threshhold = mkws.config.responsive_design_width;
380 var width = $(window).width();
381 var from, to, method;
383 if ((mkws.width === undefined || mkws.width > threshhold) &&
384 width <= threshhold) {
385 from = "wide"; to = "narrow"; method = "hide";
386 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
387 width > threshhold) {
388 from = "narrow"; to = "wide"; method = "show";
393 log("changing from " + from + " to " + to + ": " + width);
394 for (var tname in mkws.teams) {
395 var team = mkws.teams[tname];
396 team.visitWidgets(function(t, w) {
397 var w1 = team.widget(t + "-Container-" + from);
398 var w2 = team.widget(t + "-Container-" + to);
404 w.node.appendTo(w2.node);
407 team.queue("resize-" + to).publish();
414 * Run service-proxy authentication in background (after page load).
415 * The username/password is configured in the apache config file
418 function authenticateSession(auth_url, auth_domain, pp2_url) {
419 log("service proxy authentication on URL: " + auth_url);
422 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
423 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
426 var request = new pzHttpRequest(auth_url, function(err) {
427 alert("HTTP call for authentication failed: " + err)
431 request.get(null, function(data) {
432 if (!$.isXMLDoc(data)) {
433 alert("service proxy auth response document is not valid XML document, give up!");
436 var status = $(data).find("status");
437 if (status.text() != "OK") {
438 alert("service proxy auth response status: " + status.text() + ", give up!");
442 log("service proxy authentication successful");
443 mkws.authenticated = true;
444 var authName = $(data).find("displayName").text();
445 // You'd think there would be a better way to do this:
446 var realm = $(data).find("realm:not(realmAttributes realm)").text();
447 for (var teamName in mkws.teams) {
448 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
456 function runAutoSearches() {
457 log("running auto searches");
459 for (var teamName in mkws.teams) {
460 mkws.teams[teamName].queue("ready").publish();
465 function selectorForAllWidgets() {
466 if (mkws.config && mkws.config.scan_all_nodes) {
467 // This is the old version, which works by telling jQuery to
468 // find every node that has a class beginning with "mkws". In
469 // theory it should be slower than the class-based selector; but
470 // instrumentation suprisnigly shows this is consistently
471 // faster. It also has the advantage that any widgets of
472 // non-registered types are logged as warnings rather than
474 return '[class^="mkws"],[class*=" mkws"]';
476 // This is the new version, which works by looking up the
477 // specific classes of all registered widget types and their
478 // resize containers. Because all it requires jQuery to do is
479 // some hash lookups in pre-built tables, it should be very
480 // fast; but it silently ignores widgets of unregistered types.
482 for (var type in mkws.widgetType2function) {
485 s += ',.mkws' + type + "-Container-wide";
486 s += ',.mkws' + type + "-Container-narrow";
493 function makeWidgetsWithin(level, node) {
494 node.find(selectorForAllWidgets()).each(function() {
495 handleNodeWithTeam(this, function(tname, type) {
496 var myTeam = mkws.teams[tname];
498 myTeam = mkws.teams[tname] = team($, tname);
499 log("made MKWS team '" + tname + "'");
502 var oldHTML = this.innerHTML;
503 var myWidget = widget($, myTeam, type, this);
504 myTeam.addWidget(myWidget);
505 var newHTML = this.innerHTML;
506 if (newHTML !== oldHTML) {
507 log("widget " + tname + ":" + type + " HTML changed: reparsing");
508 makeWidgetsWithin(level+1, $(this));
515 function init(rootsel) {
516 if (!rootsel) var rootsel = ':root';
518 if (typeof mkws_config === 'undefined') {
519 log("setting empty config");
522 log("using config: " + $.toJSON(mkws_config));
523 saved_config = mkws_config;
525 mkws.setMkwsConfig(saved_config);
527 for (var key in mkws.config) {
528 if (mkws.config.hasOwnProperty(key)) {
529 if (key.match(/^language_/)) {
530 var lang = key.replace(/^language_/, "");
531 // Copy custom languages into list
532 mkws.locale_lang[lang] = mkws.config[key];
533 log("added locally configured language '" + lang + "'");
538 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
539 if (!lang || !mkws.locale_lang[lang]) {
540 mkws.config.lang = ""
542 mkws.config.lang = lang;
545 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
547 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
548 log("reset query width to " + mkws.config.query_width);
549 mkws.config.query_width = 50;
552 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
553 if (mkws.config.pazpar2_url.match(/^\/\//)) {
554 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
555 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
558 if (mkws.config.responsive_design_width) {
559 // Responsive web design - change layout on the fly based on
560 // current screen width. Required for mobile devices.
561 $(window).resize(resizePage);
562 // initial check after page load
563 $(document).ready(resizePage);
566 // Backwards compatibility: set new magic class names on any
567 // elements that have the old magic IDs.
568 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
569 "Results", "Records", "Targets", "Ranking",
570 "Termlists", "Stat", "MOTD" ];
571 for (var i = 0; i < ids.length; i++) {
572 var id = 'mkws' + ids[i];
573 var node = $('#' + id);
574 if (node.attr('id')) {
576 log("added magic class to '" + node.attr('id') + "'");
581 makeWidgetsWithin(1, $(rootsel));
584 log("walking MKWS nodes took " + (now-then) + " ms");
587 for (var tName in mkws.teams) {
588 var myTeam = mkws.teams[tName]
589 log("team '" + tName + "' = " + myTeam + " ...");
590 myTeam.visitWidgets(function(t, w) {
591 log(" has widget of type '" + t + "': " + w);
596 if (mkws.config.use_service_proxy) {
597 authenticateSession(mkws.config.service_proxy_auth,
598 mkws.config.service_proxy_auth_domain,
599 mkws.config.pazpar2_url);
605 $(document).ready(function() {
606 var widgetSelector = selectorForAllWidgets();
607 if (widgetSelector && $(widgetSelector).length !== 0) init();