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 // Set up global mkws object. Contains truly global state such as SP
10 // authentication, and a hash of team objects, indexed by team-name.
12 // We set it as a property of window to make the global explicit as
13 // some things complain about an implicit global.
15 $: $, // Our own local copy of the jQuery object
17 authenticating: false,
19 log_level: 1, // Will be overridden from mkws.config, but
20 // initial value allows jQuery popup to use logging.
22 widgetType2function: {},
28 "Subjects": "Schlagwörter",
29 "Sources": "Daten und Quellen",
30 "source": "datenquelle",
31 "Termlists": "Termlisten",
33 "Prev": "Zurück",
35 "Sort by": "Sortieren nach",
36 "and show": "und zeige",
37 "per page": "pro Seite",
38 "Displaying": "Zeige",
46 "Subject": "Schlagwort",
47 "subject": "schlagwort",
49 "Records": "Datensätze",
50 "Targets": "Datenbanken",
56 "Authors": "Forfattere",
60 "Termlists": "Termlists",
61 "Next": "Næste",
63 "Search": "Søg",
64 "Sort by": "Sorter efter",
66 "per page": "per side",
67 "Displaying": "Viser",
72 "Author": "Forfatter",
73 "author": "forfatter",
77 "Location": "Lokation",
86 // We may be using a separate copy
87 if (typeof(mkws_jQuery) !== "undefined") {
93 mkws.log = function(string) {
97 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
101 // you need to disable use strict at the top of the file!!!
102 if (mkws.log_level >= 3) {
103 // Works in Chrome; not sure about elsewhere
105 } else if (mkws.log_level >= 2) {
106 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
112 // Translation function.
113 mkws.M = function(word) {
114 var lang = mkws.config.lang;
116 if (!lang || !mkws.locale_lang[lang])
119 return mkws.locale_lang[lang][word] || word;
123 // This function is taken from a StackOverflow answer
124 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
125 mkws.getParameterByName = function(name, url) {
126 if (!url) url = location.search;
127 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
128 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
129 results = regex.exec(url);
130 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
134 mkws.registerWidgetType = function(name, fn) {
135 mkws.widgetType2function[name] = fn;
136 mkws.log("registered widget-type '" + name + "'");
139 mkws.promotionFunction = function(name) {
140 return mkws.widgetType2function[name];
144 mkws.setMkwsConfig = function(overrides) {
145 // Set global log_level flag early so that mkws.log() works
146 // Fall back to old "debug_level" setting for backwards compatibility
147 var tmp = overrides.log_level;
148 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
149 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
151 var config_default = {
152 use_service_proxy: true,
153 pazpar2_url: undefined,
154 pp2_hostname: "sp-mkws.indexdata.com",
155 pp2_path: "service-proxy",
156 service_proxy_auth: undefined,
157 sp_auth_path: "service-proxy/",
158 sp_auth_query: "command=auth&action=perconfig",
159 sp_auth_credentials: "XXX/XXX", // Should be undefined: see bug MKSP-125.
161 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
162 perpage_options: [10, 20, 30, 50],
163 sort_default: "relevance",
166 show_lang: true, /* show/hide language menu */
167 show_sort: true, /* show/hide sort menu */
168 show_perpage: true, /* show/hide perpage menu */
169 show_switch: true, /* show/hide switch menu */
170 lang_options: [], /* display languages links for given languages, [] for all */
171 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
172 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
173 log_level: 1, /* log level for development: 0..2 */
174 template_vars: {}, /* values that may be exposed to templates */
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 // The following functions are dispatchers for team methods that
199 // are called from the UI using a team-name rather than implicit
201 mkws.switchView = function(tname, view) {
202 mkws.teams[tname].switchView(view);
205 mkws.showDetails = function(tname, prefixRecId) {
206 mkws.teams[tname].showDetails(prefixRecId);
209 mkws.limitTarget = function(tname, id, name) {
210 mkws.teams[tname].limitTarget(id, name);
213 mkws.limitQuery = function(tname, field, value) {
214 mkws.teams[tname].limitQuery(field, value);
217 mkws.limitCategory = function(tname, id) {
218 mkws.teams[tname].limitCategory(id);
221 mkws.delimitTarget = function(tname, id) {
222 mkws.teams[tname].delimitTarget(id);
225 mkws.delimitQuery = function(tname, field, value) {
226 mkws.teams[tname].delimitQuery(field, value);
229 mkws.showPage = function(tname, pageNum) {
230 mkws.teams[tname].showPage(pageNum);
233 mkws.pagerPrev = function(tname) {
234 mkws.teams[tname].pagerPrev();
237 mkws.pagerNext = function(tname) {
238 mkws.teams[tname].pagerNext();
242 mkws.pazpar2_url = function() {
243 if (mkws.config.pazpar2_url) {
244 mkws.log("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
245 return mkws.config.pazpar2_url;
247 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path + "/";
248 mkws.log("generated pazpar2_url '" + s + "'");
254 // We put a session token in window.name, as it's the only place to
255 // keep data that is preserved across reloads and within-site
256 // navigation. pz2.js picks this up and uses it as part of the
257 // cookie-name, to ensure we get a new session when we need one.
259 // We want to use different sessions for different windows/tabs (so
260 // they don't receive each other's messages), different hosts and
261 // different paths on a host (since in general these will
262 // authenticate as different libraries). So the window name needs to
263 // include the hostname and the path from the URL, plus the token.
267 token = window.name.replace(/.*\//, '');
268 mkws.log("Reusing existing window token '" + token + "'");
270 // Incredible that the standard JavaScript runtime doesn't define a
271 // unique windowId. Instead, we have to make one up. And since there's
272 // no global area shared between windows, the best we can do for
273 // ensuring uniqueness is generating a random ID and crossing our
276 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
277 // At one per second, it will take 116 million years to duplicate a token
278 token = Math.random().toString(36).slice(2, 12);
279 mkws.log("Generated new window token '" + token + "'");
282 window.name = window.location.hostname + window.location.pathname + '/' + token;
283 mkws.log("Using window.name '" + window.name + "'");
286 // wrapper to provide local copy of the jQuery object.
289 var _old2new = { // Maps old-style widget names to new-style
290 'Authname': 'auth-name',
291 'ConsoleBuilder': 'console-builder',
292 'Coverart': 'cover-art',
293 'GoogleImage': 'google-image',
295 'MOTDContainer': 'motd-container',
296 'Perpage': 'per-page',
297 'SearchForm': 'search-form',
300 function handleNodeWithTeam(node, callback) {
301 // First branch for DOM objects; second branch for jQuery objects
302 var classes = node.className || node.attr('class');
304 // For some reason, if we try to proceed when classes is
305 // undefined, we don't get an error message, but this
306 // function and its callers, up several stack level,
307 // silently return. What a crock.
308 log("handleNodeWithTeam() called on node with no classes");
311 var list = classes.split(/\s+/)
314 for (var i = 0; i < list.length; i++) {
316 if (cname.match(/^mkws-team-/)) {
317 teamName = cname.replace(/^mkws-team-/, '');
318 } else if (cname.match(/^mkws-/)) {
319 // New-style names of the form mkws-foo-bar
320 type = cname.replace(/^mkws-/, '');
321 } else if (cname.match(/^mkws/)) {
322 // Old-style names of the form mkwsFooBar
323 var tmp = cname.replace(/^mkws/, '');
324 type = _old2new[tmp] || tmp;
328 // Widgets without a team are on team "AUTO"
331 // Autosearch widgets don't join team AUTO if there is already an
332 // autosearch on the team or the team has otherwise gotten a query
333 if (node.hasAttribute("autosearch")) {
334 if (mkws.autoHasAuto ||
335 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
336 log("AUTO team already has a query, using unique team");
339 mkws.autoHasAuto = true;
343 // Widgets on team "UNIQUE" get a random team
344 if (teamName === "UNIQUE") {
345 teamName = Math.floor(Math.random() * 100000000).toString();
348 callback.call(node, teamName, type);
352 function resizePage() {
353 var threshhold = mkws.config.responsive_design_width;
354 var width = $(window).width();
355 var from, to, method;
357 if ((mkws.width === undefined || mkws.width > threshhold) &&
358 width <= threshhold) {
359 from = "wide"; to = "narrow"; method = "hide";
360 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
361 width > threshhold) {
362 from = "narrow"; to = "wide"; method = "show";
367 log("changing from " + from + " to " + to + ": " + width);
368 for (var tname in mkws.teams) {
369 var team = mkws.teams[tname];
370 team.visitWidgets(function(t, w) {
371 var w1 = team.widget(t + "-container-" + from);
372 var w2 = team.widget(t + "-container-" + to);
378 w.node.appendTo(w2.node);
381 team.queue("resize-" + to).publish();
388 * Run service-proxy authentication in background (after page load).
389 * The username/password is configured in the apache config file
392 function authenticateSession(auth_url, auth_domain, pp2_url) {
393 mkws.authenticating = true;
394 log("service proxy authentication on URL: " + auth_url);
397 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
398 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
401 var request = new pzHttpRequest(auth_url, function(err) {
402 alert("HTTP call for authentication failed: " + err)
406 request.get(null, function(data) {
407 mkws.authenticating = false;
408 if (!$.isXMLDoc(data)) {
409 alert("Service Proxy authentication response is not a valid XML document");
412 var status = $(data).find("status");
413 if (status.text() != "OK") {
414 var message = $(data).find("message");
415 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
419 log("service proxy authentication successful");
420 mkws.authenticated = true;
421 var authName = $(data).find("displayName").text();
422 // You'd think there would be a better way to do this:
423 var realm = $(data).find("realm:not(realmAttributes realm)").text();
424 for (var teamName in mkws.teams) {
425 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
433 function runAutoSearches() {
434 log("running auto searches");
436 for (var teamName in mkws.teams) {
437 mkws.teams[teamName].queue("ready").publish();
442 function selectorForAllWidgets() {
443 if (mkws.config && mkws.config.scan_all_nodes) {
444 // This is the old version, which works by telling jQuery to
445 // find every node that has a class beginning with "mkws". In
446 // theory it should be slower than the class-based selector; but
447 // instrumentation suprisnigly shows this is consistently
448 // faster. It also has the advantage that any widgets of
449 // non-registered types are logged as warnings rather than
451 return '[class^="mkws"],[class*=" mkws"]';
453 // This is the new version, which works by looking up the
454 // specific classes of all registered widget types and their
455 // resize containers. Because all it requires jQuery to do is
456 // some hash lookups in pre-built tables, it should be very
457 // fast; but it silently ignores widgets of unregistered types.
459 for (var type in mkws.widgetType2function) {
461 s += '.mkws-' + type;
462 s += ',.mkws-' + type + "-container-wide";
463 s += ',.mkws-' + type + "-container-narrow";
464 // ### Do we need to do something about old-style names?
471 function makeWidgetsWithin(level, node) {
472 if (node) var widgetNodes = node.find(selectorForAllWidgets());
473 else widgetNodes = $(selectorForAllWidgets());
474 // Return false if we parse no widgets
475 if (widgetNodes.length < 1) return false;
476 widgetNodes.each(function() {
477 handleNodeWithTeam(this, function(tname, type) {
478 var myTeam = mkws.teams[tname];
480 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
481 log("made MKWS team '" + tname + "'");
484 var oldHTML = this.innerHTML;
485 var myWidget = mkws.makeWidget($, myTeam, type, this);
486 myTeam.addWidget(myWidget);
487 var newHTML = this.innerHTML;
488 if (newHTML !== oldHTML) {
489 log("widget " + tname + ":" + type + " HTML changed: reparsing");
490 makeWidgetsWithin(level+1, $(this));
498 // The second "rootsel" parameter is passed to jQuery and is a DOM node
499 // or a selector string you would like to constrain the search for widgets to.
501 // This function has no side effects if run again on an operating session,
502 // even if the element/selector passed causes existing widgets to be reparsed:
504 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
505 // widgets, MKWS-261)
507 // * configuration is not regenerated
508 // * authentication is not performed again
509 // * autosearches are not re-run
510 mkws.init = function(message, rootsel) {
511 var greet = "MKWS initialised";
512 if (rootsel) greet += " (limited to " + rootsel + ")"
513 if (message) greet += " :: " + message;
516 // MKWS is not active until init() has been run against an object with widget nodes.
517 // We only set initial configuration when MKWS is first activated.
518 if (!mkws.isActive) {
519 var widgetSelector = selectorForAllWidgets();
520 if ($(widgetSelector).length < 1) {
521 mkws.log("no widgets found");
525 // Initial configuration
526 mkws.autoHasAuto = false;
528 if (typeof mkws_config === 'undefined') {
529 log("setting empty config");
532 log("using config: " + $.toJSON(mkws_config));
533 saved_config = mkws_config;
535 mkws.setMkwsConfig(saved_config);
537 for (var key in mkws.config) {
538 if (mkws.config.hasOwnProperty(key)) {
539 if (key.match(/^language_/)) {
540 var lang = key.replace(/^language_/, "");
541 // Copy custom languages into list
542 mkws.locale_lang[lang] = mkws.config[key];
543 log("added locally configured language '" + lang + "'");
548 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
549 if (!lang || !mkws.locale_lang[lang]) {
550 mkws.config.lang = ""
552 mkws.config.lang = lang;
555 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
557 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
558 log("reset query width to " + mkws.config.query_width);
559 mkws.config.query_width = 50;
562 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
563 if (mkws.pazpar2_url().match(/^\/\//)) {
564 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
565 log("adjusted protocol independent link to " + mkws.pazpar2_url());
568 if (mkws.config.responsive_design_width) {
569 // Responsive web design - change layout on the fly based on
570 // current screen width. Required for mobile devices.
571 $(window).resize(resizePage);
572 // initial check after page load
573 $(document).ready(resizePage);
578 // If we've made no widgets, return without starting an SP session
579 // or marking MKWS active.
580 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
585 log("walking MKWS nodes took " + (now-then) + " ms");
586 for (var tName in mkws.teams) {
587 var myTeam = mkws.teams[tName]
589 log("made PZ2 object for team '" + tName + "'");
591 myTeam.visitWidgets(function(t, w) {
592 log(" has widget of type '" + t + "': " + w);
597 function sp_auth_url(config) {
598 if (config.service_proxy_auth) {
599 mkws.log("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
600 return config.service_proxy_auth;
603 s += config.auth_hostname ? config.auth_hostname : config.pp2_hostname;
604 s += '/' + config.sp_auth_path;
605 var q = config.sp_auth_query;
609 var c = config.sp_auth_credentials;
611 s += ('&username=' + c.substr(0, c.indexOf('/')) +
612 '&password=' + c.substr(c.indexOf('/')+1));
614 mkws.log("generated sp_auth_url '" + s + "'");
619 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
620 authenticateSession(sp_auth_url(mkws.config),
621 mkws.config.service_proxy_auth_domain,
623 } else if (!mkws.authenticating) {
624 // raw pp2 or we have a session already open
628 mkws.isActive = true;
632 $(document).ready(function() {
633 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {