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: {},
27 "Subjects": "Schlagwörter",
28 "Sources": "Daten und Quellen",
29 "source": "datenquelle",
30 "Termlists": "Termlisten",
32 "Prev": "Zurück",
34 "Sort by": "Sortieren nach",
35 "and show": "und zeige",
36 "per page": "pro Seite",
37 "Displaying": "Zeige",
45 "Subject": "Schlagwort",
46 "subject": "schlagwort",
48 "Records": "Datensätze",
49 "Targets": "Datenbanken",
55 "Authors": "Forfattere",
59 "Termlists": "Termlists",
60 "Next": "Næste",
62 "Search": "Søg",
63 "Sort by": "Sorter efter",
65 "per page": "per side",
66 "Displaying": "Viser",
71 "Author": "Forfatter",
72 "author": "forfatter",
76 "Location": "Lokation",
85 // We may be using a separate copy
86 if (typeof(mkws_jQuery) !== "undefined") {
92 mkws.log = function(string) {
96 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
100 // you need to disable use strict at the top of the file!!!
101 if (mkws.log_level >= 3) {
102 // Works in Chrome; not sure about elsewhere
104 } else if (mkws.log_level >= 2) {
105 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
111 // Incredible that the standard JavaScript runtime doesn't define a
112 // unique windowId. Instead, we have to make one up. And since there's
113 // no global area shared between windows, the best we can do for
114 // ensuring uniqueness is generating a random ID and crossing our
115 // fingers. We stash this in window.name, as it's the only place to
116 // keep data that is preserved across reloads and within-site
117 // navigation. pz2.js picks this up and uses it as part of the
118 // cookie-name, to ensure each tab gets its own session.
120 mkws.log("Using existing window.name '" + window.name + "'");
122 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
123 // At one per second, it will take 116 million years to duplicate a session
124 window.name = Math.random().toString(36).slice(2, 12);
125 mkws.log("Generated new window.name '" + window.name + "'");
129 // Translation function.
130 mkws.M = function(word) {
131 var lang = mkws.config.lang;
133 if (!lang || !mkws.locale_lang[lang])
136 return mkws.locale_lang[lang][word] || word;
140 // This function is taken from a StackOverflow answer
141 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
142 mkws.getParameterByName = function(name, url) {
143 if (!url) url = location.search;
144 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
145 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
146 results = regex.exec(url);
147 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
151 mkws.registerWidgetType = function(name, fn) {
152 mkws.widgetType2function[name] = fn;
153 mkws.log("registered widget-type '" + name + "'");
156 mkws.promotionFunction = function(name) {
157 return mkws.widgetType2function[name];
161 mkws.setMkwsConfig = function(overrides) {
162 // Set global log_level flag early so that mkws.log() works
163 // Fall back to old "debug_level" setting for backwards compatibility
164 var tmp = overrides.log_level;
165 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
166 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
168 var config_default = {
169 use_service_proxy: true,
170 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
171 service_proxy_auth: undefined, // generally rolled from the next three properties
172 // Was: //mkws.indexdata.com/service-proxy-auth
173 pp2_hostname: "mkws.indexdata.com",
174 sp_path: "service-proxy-auth",
175 sp_auth_query: undefined, // Will be: "command=auth&action=perconfig",
176 sp_auth_credentials: undefined,
178 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
179 perpage_options: [10, 20, 30, 50],
180 sort_default: "relevance",
183 show_lang: true, /* show/hide language menu */
184 show_sort: true, /* show/hide sort menu */
185 show_perpage: true, /* show/hide perpage menu */
186 show_switch: true, /* show/hide switch menu */
187 lang_options: [], /* display languages links for given languages, [] for all */
188 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
189 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
190 log_level: 1, /* log level for development: 0..2 */
195 mkws.config = mkws.objectInheritingFrom(config_default);
196 for (var k in overrides) {
197 mkws.config[k] = overrides[k];
202 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
203 // http://javascript.crockford.com/prototypal.html
204 // mkws.objectInheritingFrom behaves the same as Object.create,
205 // but since the latter is not available in IE8 we can't use it.
207 mkws.objectInheritingFrom = function(o) {
214 mkws.defaultTemplate = function(name) {
215 if (name === 'Record') {
219 <th>{{mkws-translate "Title"}}</th>\
222 {{#if md-title-remainder}}\
223 ({{md-title-remainder}})\
225 {{#if md-title-responsibility}}\
226 <i>{{md-title-responsibility}}</i>\
232 <th>{{mkws-translate "Date"}}</th>\
233 <td>{{md-date}}</td>\
238 <th>{{mkws-translate "Author"}}</th>\
239 <td>{{md-author}}</td>\
242 {{#if md-electronic-url}}\
244 <th>{{mkws-translate "Links"}}</th>\
246 {{#each md-electronic-url}}\
247 <a href="{{this}}">Link{{mkws-index1}}</a>\
252 {{#mkws-if-any location having="md-subject"}}\
254 <th>{{mkws-translate "Subject"}}</th>\
256 {{#mkws-first location having="md-subject"}}\
258 {{#mkws-commaList md-subject}}\
259 {{this}}{{/mkws-commaList}}\
266 <th>{{mkws-translate "Locations"}}</th>\
268 {{#mkws-commaList location}}\
269 {{mkws-attr "@name"}}{{/mkws-commaList}}\
274 } else if (name === "Summary") {
276 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
279 {{#if md-title-remainder}}\
280 <span>{{md-title-remainder}}</span>\
282 {{#if md-title-responsibility}}\
283 <span><i>{{md-title-responsibility}}</i></span>\
285 {{#if md-date}}, {{md-date}}\
287 , {{#mkws-first location}}{{mkws-attr "@name"}}{{/mkws-first}}\
290 <span>, {{md-medium}}</span>\
294 } else if (name === "Image") {
296 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
297 {{#mkws-first md-thumburl}}\
298 <img src="{{this}}" alt="{{../md-title}}"/>\
303 } else if (name === 'Facet') {
307 onclick="mkws.{{fn}}(\'{{team}}\', \'{{field}}\', \'{{term}}\');return false;"\
310 <span>{{count}}</span>\
318 // The following functions are dispatchers for team methods that
319 // are called from the UI using a team-name rather than implicit
321 mkws.switchView = function(tname, view) {
322 mkws.teams[tname].switchView(view);
325 mkws.showDetails = function(tname, prefixRecId) {
326 mkws.teams[tname].showDetails(prefixRecId);
329 mkws.limitTarget = function(tname, id, name) {
330 mkws.teams[tname].limitTarget(id, name);
333 mkws.limitQuery = function(tname, field, value) {
334 mkws.teams[tname].limitQuery(field, value);
337 mkws.limitCategory = function(tname, id) {
338 mkws.teams[tname].limitCategory(id);
341 mkws.delimitTarget = function(tname, id) {
342 mkws.teams[tname].delimitTarget(id);
345 mkws.delimitQuery = function(tname, field, value) {
346 mkws.teams[tname].delimitQuery(field, value);
349 mkws.showPage = function(tname, pageNum) {
350 mkws.teams[tname].showPage(pageNum);
353 mkws.pagerPrev = function(tname) {
354 mkws.teams[tname].pagerPrev();
357 mkws.pagerNext = function(tname) {
358 mkws.teams[tname].pagerNext();
362 mkws.pazpar2_url = function() {
363 return mkws.config.pazpar2_url;
367 // wrapper to provide local copy of the jQuery object.
371 function handleNodeWithTeam(node, callback) {
372 // First branch for DOM objects; second branch for jQuery objects
373 var classes = node.className || node.attr('class');
375 // For some reason, if we try to proceed when classes is
376 // undefined, we don't get an error message, but this
377 // function and its callers, up several stack level,
378 // silently return. What a crock.
379 log("handleNodeWithTeam() called on node with no classes");
382 var list = classes.split(/\s+/)
385 for (var i = 0; i < list.length; i++) {
387 if (cname.match(/^mkwsTeam_/)) {
388 teamName = cname.replace(/^mkwsTeam_/, '');
389 } else if (cname.match(/^mkws/)) {
390 type = cname.replace(/^mkws/, '');
394 // Widgets without a team are on team "AUTO"
397 // Autosearch widgets don't join team AUTO if there is already an
398 // autosearch on the team or the team has otherwise gotten a query
399 if (node.hasAttribute("autosearch")) {
400 if (mkws.autoHasAuto ||
401 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
402 log("AUTO team already has a query, using unique team");
405 mkws.autoHasAuto = true;
409 // Widgets on team "UNIQUE" get a random team
410 if (teamName === "UNIQUE") {
411 teamName = Math.floor(Math.random() * 100000000).toString();
414 callback.call(node, teamName, type);
418 function resizePage() {
419 var threshhold = mkws.config.responsive_design_width;
420 var width = $(window).width();
421 var from, to, method;
423 if ((mkws.width === undefined || mkws.width > threshhold) &&
424 width <= threshhold) {
425 from = "wide"; to = "narrow"; method = "hide";
426 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
427 width > threshhold) {
428 from = "narrow"; to = "wide"; method = "show";
433 log("changing from " + from + " to " + to + ": " + width);
434 for (var tname in mkws.teams) {
435 var team = mkws.teams[tname];
436 team.visitWidgets(function(t, w) {
437 var w1 = team.widget(t + "-Container-" + from);
438 var w2 = team.widget(t + "-Container-" + to);
444 w.node.appendTo(w2.node);
447 team.queue("resize-" + to).publish();
454 * Run service-proxy authentication in background (after page load).
455 * The username/password is configured in the apache config file
458 function authenticateSession(auth_url, auth_domain, pp2_url) {
459 mkws.authenticating = true;
460 log("service proxy authentication on URL: " + auth_url);
463 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
464 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
467 var request = new pzHttpRequest(auth_url, function(err) {
468 alert("HTTP call for authentication failed: " + err)
472 request.get(null, function(data) {
473 mkws.authenticating = false;
474 if (!$.isXMLDoc(data)) {
475 alert("Service Proxy authentication response is not a valid XML document");
478 var status = $(data).find("status");
479 if (status.text() != "OK") {
480 var message = $(data).find("message");
481 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
485 log("service proxy authentication successful");
486 mkws.authenticated = true;
487 var authName = $(data).find("displayName").text();
488 // You'd think there would be a better way to do this:
489 var realm = $(data).find("realm:not(realmAttributes realm)").text();
490 for (var teamName in mkws.teams) {
491 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
499 function runAutoSearches() {
500 log("running auto searches");
502 for (var teamName in mkws.teams) {
503 mkws.teams[teamName].queue("ready").publish();
508 function selectorForAllWidgets() {
509 if (mkws.config && mkws.config.scan_all_nodes) {
510 // This is the old version, which works by telling jQuery to
511 // find every node that has a class beginning with "mkws". In
512 // theory it should be slower than the class-based selector; but
513 // instrumentation suprisnigly shows this is consistently
514 // faster. It also has the advantage that any widgets of
515 // non-registered types are logged as warnings rather than
517 return '[class^="mkws"],[class*=" mkws"]';
519 // This is the new version, which works by looking up the
520 // specific classes of all registered widget types and their
521 // resize containers. Because all it requires jQuery to do is
522 // some hash lookups in pre-built tables, it should be very
523 // fast; but it silently ignores widgets of unregistered types.
525 for (var type in mkws.widgetType2function) {
528 s += ',.mkws' + type + "-Container-wide";
529 s += ',.mkws' + type + "-Container-narrow";
536 function makeWidgetsWithin(level, node) {
537 if (node) var widgetNodes = node.find(selectorForAllWidgets());
538 else widgetNodes = $(selectorForAllWidgets());
539 // Return false if we parse no widgets
540 if (widgetNodes.length < 1) return false;
541 widgetNodes.each(function() {
542 handleNodeWithTeam(this, function(tname, type) {
543 var myTeam = mkws.teams[tname];
545 myTeam = mkws.teams[tname] = team($, tname);
546 log("made MKWS team '" + tname + "'");
549 var oldHTML = this.innerHTML;
550 var myWidget = widget($, myTeam, type, this);
551 myTeam.addWidget(myWidget);
552 var newHTML = this.innerHTML;
553 if (newHTML !== oldHTML) {
554 log("widget " + tname + ":" + type + " HTML changed: reparsing");
555 makeWidgetsWithin(level+1, $(this));
563 // The second "rootsel" parameter is passed to jQuery and is a DOM node
564 // or a selector string you would like to constrain the search for widgets to.
566 // This function has no side effects if run again on an operating session,
567 // even if the element/selector passed causes existing widgets to be reparsed:
569 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
570 // widgets, MKWS-261)
572 // * configuration is not regenerated
573 // * authentication is not performed again
574 // * autosearches are not re-run
575 mkws.init = function(message, rootsel) {
576 var greet = "MKWS initialised";
577 if (rootsel) greet += " (limited to " + rootsel + ")"
578 if (message) greet += " :: " + message;
581 // TODO: Let's remove this soon
582 // Backwards compatibility: set new magic class names on any
583 // elements that have the old magic IDs.
584 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
585 "Results", "Records", "Targets", "Ranking",
586 "Termlists", "Stat", "MOTD" ];
587 for (var i = 0; i < ids.length; i++) {
588 var id = 'mkws' + ids[i];
589 var node = $('#' + id);
590 if (node.attr('id')) {
592 log("added magic class to '" + node.attr('id') + "'");
596 // MKWS is not active until init() has been run against an object with widget nodes.
597 // We only set initial configuration when MKWS is first activated.
598 if (!mkws.isActive) {
599 var widgetSelector = selectorForAllWidgets();
600 if ($(widgetSelector).length < 1) {
601 mkws.log("no widgets found");
605 // Initial configuration
606 mkws.autoHasAuto = false;
608 if (typeof mkws_config === 'undefined') {
609 log("setting empty config");
612 log("using config: " + $.toJSON(mkws_config));
613 saved_config = mkws_config;
615 mkws.setMkwsConfig(saved_config);
617 for (var key in mkws.config) {
618 if (mkws.config.hasOwnProperty(key)) {
619 if (key.match(/^language_/)) {
620 var lang = key.replace(/^language_/, "");
621 // Copy custom languages into list
622 mkws.locale_lang[lang] = mkws.config[key];
623 log("added locally configured language '" + lang + "'");
628 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
629 if (!lang || !mkws.locale_lang[lang]) {
630 mkws.config.lang = ""
632 mkws.config.lang = lang;
635 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
637 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
638 log("reset query width to " + mkws.config.query_width);
639 mkws.config.query_width = 50;
642 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
643 if (mkws.config.pazpar2_url.match(/^\/\//)) {
644 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
645 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
648 if (mkws.config.responsive_design_width) {
649 // Responsive web design - change layout on the fly based on
650 // current screen width. Required for mobile devices.
651 $(window).resize(resizePage);
652 // initial check after page load
653 $(document).ready(resizePage);
658 // If we've made no widgets, return without starting an SP session
659 // or marking MKWS active.
660 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
665 log("walking MKWS nodes took " + (now-then) + " ms");
668 for (var tName in mkws.teams) {
669 var myTeam = mkws.teams[tName]
670 log("team '" + tName + "' = " + myTeam + " ...");
671 myTeam.visitWidgets(function(t, w) {
672 log(" has widget of type '" + t + "': " + w);
677 function sp_auth_url(config) {
678 if (config.service_proxy_auth) {
679 mkws.log("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
680 return config.service_proxy_auth;
683 s += config.auth_hostname ? config.auth_hostname : config.pp2_hostname;
684 s += '/' + config.sp_path;
685 var q = config.sp_auth_query;
689 var c = config.sp_auth_credentials;
691 s += ('&username=' + c.substr(0, c.indexOf('/')) +
692 '&password=' + c.substr(c.indexOf('/')+1));
694 mkws.log("generated sp_auth_url '" + s + "'");
699 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
700 authenticateSession(sp_auth_url(mkws.config),
701 mkws.config.service_proxy_auth_domain,
702 mkws.config.pazpar2_url);
703 } else if (!mkws.authenticating) {
704 // raw pp2 or we have a session already open
708 mkws.isActive = true;
712 $(document).ready(function() {
713 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {