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 "Facets": "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 "Facets": "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 if(mkws._old2new.hasOwnProperty(name)) {
136 mkws.log("Warning: registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
137 name = mkws._old2new[name];
140 mkws.widgetType2function[name] = fn;
141 mkws.log("registered widget-type '" + name + "'");
144 mkws.promotionFunction = function(name) {
145 return mkws.widgetType2function[name];
149 mkws.setMkwsConfig = function(overrides) {
150 // Set global log_level flag early so that mkws.log() works
151 var tmp = overrides.log_level;
152 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
154 var config_default = {
155 use_service_proxy: true,
156 pazpar2_url: undefined,
157 pp2_hostname: "sp-mkws.indexdata.com",
158 pp2_path: "service-proxy/",
159 service_proxy_auth: undefined,
160 sp_auth_path: undefined,
161 sp_auth_query: "command=auth&action=perconfig",
162 sp_auth_credentials: undefined,
164 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
165 perpage_options: [10, 20, 30, 50],
166 sort_default: "relevance",
168 show_lang: true, /* show/hide language menu */
169 show_sort: true, /* show/hide sort menu */
170 show_perpage: true, /* show/hide perpage menu */
171 show_switch: true, /* show/hide switch menu */
172 lang_options: [], /* display languages links for given languages, [] for all */
173 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
174 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
175 log_level: 1, /* log level for development: 0..2 */
176 template_vars: {}, /* values that may be exposed to templates */
181 mkws.config = mkws.objectInheritingFrom(config_default);
182 for (var k in overrides) {
183 mkws.config[k] = overrides[k];
188 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
189 // http://javascript.crockford.com/prototypal.html
190 // mkws.objectInheritingFrom behaves the same as Object.create,
191 // but since the latter is not available in IE8 we can't use it.
193 mkws.objectInheritingFrom = function(o) {
200 // The following functions are dispatchers for team methods that
201 // are called from the UI using a team-name rather than implicit
203 mkws.switchView = function(tname, view) {
204 mkws.teams[tname].switchView(view);
207 mkws.showDetails = function(tname, prefixRecId) {
208 mkws.teams[tname].showDetails(prefixRecId);
211 mkws.limitTarget = function(tname, id, name) {
212 mkws.teams[tname].limitTarget(id, name);
215 mkws.limitQuery = function(tname, field, value) {
216 mkws.teams[tname].limitQuery(field, value);
219 mkws.limitCategory = function(tname, id) {
220 mkws.teams[tname].limitCategory(id);
223 mkws.delimitTarget = function(tname, id) {
224 mkws.teams[tname].delimitTarget(id);
227 mkws.delimitQuery = function(tname, field, value) {
228 mkws.teams[tname].delimitQuery(field, value);
231 mkws.showPage = function(tname, pageNum) {
232 mkws.teams[tname].showPage(pageNum);
235 mkws.pagerPrev = function(tname) {
236 mkws.teams[tname].pagerPrev();
239 mkws.pagerNext = function(tname) {
240 mkws.teams[tname].pagerNext();
244 mkws.pazpar2_url = function() {
245 if (mkws.config.pazpar2_url) {
246 mkws.log("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
247 return mkws.config.pazpar2_url;
249 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
250 mkws.log("generated pazpar2_url '" + s + "'");
256 // We put a session token in window.name, as it's the only place to
257 // keep data that is preserved across reloads and within-site
258 // navigation. pz2.js picks this up and uses it as part of the
259 // cookie-name, to ensure we get a new session when we need one.
261 // We want to use different sessions for different windows/tabs (so
262 // they don't receive each other's messages), different hosts and
263 // different paths on a host (since in general these will
264 // authenticate as different libraries). So the window name needs to
265 // include the hostname and the path from the URL, plus the token.
269 token = window.name.replace(/.*\//, '');
270 mkws.log("Reusing existing window token '" + token + "'");
272 // Incredible that the standard JavaScript runtime doesn't define a
273 // unique windowId. Instead, we have to make one up. And since there's
274 // no global area shared between windows, the best we can do for
275 // ensuring uniqueness is generating a random ID and crossing our
278 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
279 // At one per second, it will take 116 million years to duplicate a token
280 token = Math.random().toString(36).slice(2, 12);
281 mkws.log("Generated new window token '" + token + "'");
284 window.name = window.location.hostname + window.location.pathname + '/' + token;
285 mkws.log("Using window.name '" + window.name + "'");
288 // wrapper to provide local copy of the jQuery object.
291 var _old2new = { // Maps old-style widget names to new-style
292 'Authname': 'auth-name',
293 'ConsoleBuilder': 'console-builder',
294 'Coverart': 'cover-art',
295 'GoogleImage': 'google-image',
297 'MOTDContainer': 'motd-container',
298 'Perpage': 'per-page',
299 'SearchForm': 'search-form',
300 'ReferenceUniverse': 'reference-universe',
301 'Termlists': 'facets'
303 // Annoyingly, there is no built-in way to invert a hash
305 for (var key in _old2new) {
306 if(_old2new.hasOwnProperty(key)) {
307 _new2old[_old2new[key]] = key;
311 mkws._old2new = _old2new;
313 function handleNodeWithTeam(node, callback) {
314 // First branch for DOM objects; second branch for jQuery objects
315 var classes = node.className || node.attr('class');
317 // For some reason, if we try to proceed when classes is
318 // undefined, we don't get an error message, but this
319 // function and its callers, up several stack level,
320 // silently return. What a crock.
321 log("handleNodeWithTeam() called on node with no classes");
324 var list = classes.split(/\s+/)
327 for (var i = 0; i < list.length; i++) {
329 if (cname.match(/^mkws-team-/)) {
330 // New-style teamnames of the form mkws-team-xyz
331 teamName = cname.replace(/^mkws-team-/, '');
332 } else if (cname.match(/^mkwsTeam_/)) {
333 // Old-style teamnames of the form mkwsTeam_xyz
334 teamName = cname.replace(/^mkwsTeam_/, '');
335 } else if (cname.match(/^mkws-/)) {
336 // New-style names of the from mkws-foo-bar
337 type = cname.replace(/^mkws-/, '');
338 } else if (cname.match(/^mkws/)) {
339 // Old-style names of the form mkwsFooBar
340 var tmp = cname.replace(/^mkws/, '');
341 type = _old2new[tmp] || tmp.toLowerCase();
345 // Widgets without a team are on team "AUTO"
348 // Autosearch widgets don't join team AUTO if there is already an
349 // autosearch on the team or the team has otherwise gotten a query
350 if (node.getAttribute("autosearch")) {
351 if (mkws.autoHasAuto ||
352 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
353 log("AUTO team already has a query, using unique team");
356 mkws.autoHasAuto = true;
360 // Widgets on team "UNIQUE" get a random team
361 if (teamName === "UNIQUE") {
362 teamName = Math.floor(Math.random() * 100000000).toString();
365 callback.call(node, teamName, type);
369 function resizePage() {
370 var threshhold = mkws.config.responsive_design_width;
371 var width = $(window).width();
372 var from, to, method;
374 if ((mkws.width === undefined || mkws.width > threshhold) &&
375 width <= threshhold) {
376 from = "wide"; to = "narrow"; method = "hide";
377 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
378 width > threshhold) {
379 from = "narrow"; to = "wide"; method = "show";
384 log("changing from " + from + " to " + to + ": " + width);
385 for (var tname in mkws.teams) {
386 var team = mkws.teams[tname];
387 team.visitWidgets(function(t, w) {
388 var w1 = team.widget(t + "-container-" + from);
389 var w2 = team.widget(t + "-container-" + to);
395 w.node.appendTo(w2.node);
398 team.queue("resize-" + to).publish();
405 * Run service-proxy authentication in background (after page load).
406 * The username/password is configured in the apache config file
409 function authenticateSession(auth_url, auth_domain, pp2_url) {
410 mkws.authenticating = true;
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 mkws.authenticating = false;
425 if (!$.isXMLDoc(data)) {
426 alert("Service Proxy authentication response is not a valid XML document");
429 var status = $(data).find("status");
430 if (status.text() != "OK") {
431 var message = $(data).find("message");
432 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
436 log("service proxy authentication successful");
437 mkws.authenticated = true;
438 var authName = $(data).find("displayName").text();
439 // You'd think there would be a better way to do this:
440 var realm = $(data).find("realm:not(realmAttributes realm)").text();
441 for (var teamName in mkws.teams) {
442 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
450 function runAutoSearches() {
451 log("running auto searches");
453 for (var teamName in mkws.teams) {
454 mkws.teams[teamName].queue("ready").publish();
459 function selectorForAllWidgets() {
460 if (mkws.config && mkws.config.scan_all_nodes) {
461 // This is the old version, which works by telling jQuery to
462 // find every node that has a class beginning with "mkws". In
463 // theory it should be slower than the class-based selector; but
464 // instrumentation suprisingly shows this is consistently
465 // faster. It also has the advantage that any widgets of
466 // non-registered types are logged as warnings rather than
468 return '[class^="mkws"],[class*=" mkws"]';
470 // This is the new version, which works by looking up the
471 // specific classes of all registered widget types and their
472 // resize containers. Because all it requires jQuery to do is
473 // some hash lookups in pre-built tables, it should be very
474 // fast; but it silently ignores widgets of unregistered types.
476 for (var type in mkws.widgetType2function) {
478 s += '.mkws-' + type;
479 s += ',.mkws-' + type + "-container-wide";
480 s += ',.mkws-' + type + "-container-narrow";
481 // Annoyingly, we also need to recognise old-style names
482 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
483 s += ',.mkws' + oldtype;
484 s += ',.mkws' + oldtype + "-Container-wide";
485 s += ',.mkws' + oldtype + "-Container-narrow";
492 function makeWidgetsWithin(level, node) {
493 if (node) var widgetNodes = node.find(selectorForAllWidgets());
494 else widgetNodes = $(selectorForAllWidgets());
495 // Return false if we parse no widgets
496 if (widgetNodes.length < 1) return false;
497 widgetNodes.each(function() {
498 handleNodeWithTeam(this, function(tname, type) {
499 var myTeam = mkws.teams[tname];
501 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
504 var oldHTML = this.innerHTML;
505 var myWidget = mkws.makeWidget($, myTeam, type, this);
506 myTeam.addWidget(myWidget);
507 var newHTML = this.innerHTML;
508 if (newHTML !== oldHTML) {
509 myTeam.log("widget " + type + " HTML changed: reparsing");
510 makeWidgetsWithin(level+1, $(this));
518 // The second "rootsel" parameter is passed to jQuery and is a DOM node
519 // or a selector string you would like to constrain the search for widgets to.
521 // This function has no side effects if run again on an operating session,
522 // even if the element/selector passed causes existing widgets to be reparsed:
524 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
525 // widgets, MKWS-261)
527 // * configuration is not regenerated
528 // * authentication is not performed again
529 // * autosearches are not re-run
530 mkws.init = function(message, rootsel) {
531 var greet = "MKWS initialised";
532 if (rootsel) greet += " (limited to " + rootsel + ")"
533 if (message) greet += " :: " + message;
536 // MKWS is not active until init() has been run against an object with widget nodes.
537 // We only set initial configuration when MKWS is first activated.
538 if (!mkws.isActive) {
539 var widgetSelector = selectorForAllWidgets();
540 if ($(widgetSelector).length < 1) {
541 mkws.log("no widgets found");
545 // Initial configuration
546 mkws.autoHasAuto = false;
548 if (typeof mkws_config === 'undefined') {
549 log("setting empty config");
552 log("using config: " + $.toJSON(mkws_config));
553 saved_config = mkws_config;
555 mkws.setMkwsConfig(saved_config);
557 for (var key in mkws.config) {
558 if (mkws.config.hasOwnProperty(key)) {
559 if (key.match(/^language_/)) {
560 var lang = key.replace(/^language_/, "");
561 // Copy custom languages into list
562 mkws.locale_lang[lang] = mkws.config[key];
563 log("added locally configured language '" + lang + "'");
568 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
569 if (!lang || !mkws.locale_lang[lang]) {
570 mkws.config.lang = ""
572 mkws.config.lang = lang;
575 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
577 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
578 if (mkws.pazpar2_url().match(/^\/\//)) {
579 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
580 log("adjusted protocol independent link to " + mkws.pazpar2_url());
583 if (mkws.config.responsive_design_width) {
584 // Responsive web design - change layout on the fly based on
585 // current screen width. Required for mobile devices.
586 $(window).resize(resizePage);
587 // initial check after page load
588 $(document).ready(resizePage);
593 // If we've made no widgets, return without starting an SP session
594 // or marking MKWS active.
595 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
600 log("walking MKWS nodes took " + (now-then) + " ms");
601 for (var tName in mkws.teams) {
602 var myTeam = mkws.teams[tName]
604 myTeam.log("made PZ2 object");
606 myTeam.visitWidgets(function(t, w) {
607 log(" has widget of type '" + t + "': " + w);
612 function sp_auth_url(config) {
613 if (config.service_proxy_auth) {
614 mkws.log("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
615 return config.service_proxy_auth;
618 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
620 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
621 var q = config.sp_auth_query;
625 var c = config.sp_auth_credentials;
627 s += ('&username=' + c.substr(0, c.indexOf('/')) +
628 '&password=' + c.substr(c.indexOf('/')+1));
630 mkws.log("generated sp_auth_url '" + s + "'");
635 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
636 authenticateSession(sp_auth_url(mkws.config),
637 mkws.config.service_proxy_auth_domain,
639 } else if (!mkws.authenticating) {
640 // raw pp2 or we have a session already open
644 mkws.isActive = true;
648 $(document).ready(function() {
649 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {