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
18 log_level: 1, // Will be overridden from mkws.config, but
19 // initial value allows jQuery popup to use logging.
21 widgetType2function: {},
26 "Subjects": "Schlagwörter",
27 "Sources": "Daten und Quellen",
28 "source": "datenquelle",
29 "Termlists": "Termlisten",
31 "Prev": "Zurück",
33 "Sort by": "Sortieren nach",
34 "and show": "und zeige",
35 "per page": "pro Seite",
36 "Displaying": "Zeige",
44 "Subject": "Schlagwort",
45 "subject": "schlagwort",
47 "Records": "Datensätze",
48 "Targets": "Datenbanken",
54 "Authors": "Forfattere",
58 "Termlists": "Termlists",
59 "Next": "Næste",
61 "Search": "Søg",
62 "Sort by": "Sorter efter",
64 "per page": "per side",
65 "Displaying": "Viser",
70 "Author": "Forfatter",
71 "author": "forfatter",
75 "Location": "Lokation",
84 // We may be using a separate copy
85 if (typeof(mkws_jQuery) !== "undefined") {
91 mkws.log = function(string) {
95 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
99 // you need to disable use strict at the top of the file!!!
100 if (mkws.log_level >= 3) {
101 // Works in Chrome; not sure about elsewhere
103 } else if (mkws.log_level >= 2) {
104 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
110 // Incredible that the standard JavaScript runtime doesn't define a
111 // unique windowId. Instead, we have to make one up. And since there's
112 // no global area shared between windows, the best we can do for
113 // ensuring uniqueness is generating a random ID and crossing our
114 // fingers. We stash this in window.name, as it's the only place to
115 // keep data that is preserved across reloads and within-site
116 // navigation. pz2.js picks this up and uses it as part of the
117 // cookie-name, to ensure each tab gets its own session.
119 mkws.log("Using existing window.name '" + window.name + "'");
121 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
122 // At one per second, it will take 116 million years to duplicate a session
123 window.name = Math.random().toString(36).slice(2, 12);
124 mkws.log("Generated new window.name '" + window.name + "'");
128 // Translation function.
129 mkws.M = function(word) {
130 var lang = mkws.config.lang;
132 if (!lang || !mkws.locale_lang[lang])
135 return mkws.locale_lang[lang][word] || word;
139 // This function is taken from a StackOverflow answer
140 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
141 mkws.getParameterByName = function(name, url) {
142 if (!url) url = location.search;
143 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
144 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
145 results = regex.exec(url);
146 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
150 mkws.registerWidgetType = function(name, fn) {
151 mkws.widgetType2function[name] = fn;
152 mkws.log("registered widget-type '" + name + "'");
155 mkws.promotionFunction = function(name) {
156 return mkws.widgetType2function[name];
160 mkws.setMkwsConfig = function(overrides) {
161 // Set global log_level flag early so that mkws.log() works
162 // Fall back to old "debug_level" setting for backwards compatibility
163 var tmp = overrides.log_level;
164 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
165 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
167 var config_default = {
168 use_service_proxy: true,
169 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
170 service_proxy_auth: undefined, // generally rolled from the next three properties
171 // Was: //mkws.indexdata.com/service-proxy-auth
172 pp2_hostname: "mkws.indexdata.com",
173 sp_path: "service-proxy-auth",
174 credentials: undefined,
176 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
177 perpage_options: [10, 20, 30, 50],
178 sort_default: "relevance",
181 show_lang: true, /* show/hide language menu */
182 show_sort: true, /* show/hide sort menu */
183 show_perpage: true, /* show/hide perpage menu */
184 show_switch: true, /* show/hide switch menu */
185 lang_options: [], /* display languages links for given languages, [] for all */
186 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
187 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
188 log_level: 1, /* log level for development: 0..2 */
193 mkws.config = mkws.objectInheritingFrom(config_default);
194 for (var k in overrides) {
195 mkws.config[k] = overrides[k];
200 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
201 // http://javascript.crockford.com/prototypal.html
202 // mkws.objectInheritingFrom behaves the same as Object.create,
203 // but since the latter is not available in IE8 we can't use it.
205 mkws.objectInheritingFrom = function(o) {
212 mkws.defaultTemplate = function(name) {
213 if (name === 'Record') {
217 <th>{{mkws-translate "Title"}}</th>\
220 {{#if md-title-remainder}}\
221 ({{md-title-remainder}})\
223 {{#if md-title-responsibility}}\
224 <i>{{md-title-responsibility}}</i>\
230 <th>{{mkws-translate "Date"}}</th>\
231 <td>{{md-date}}</td>\
236 <th>{{mkws-translate "Author"}}</th>\
237 <td>{{md-author}}</td>\
240 {{#if md-electronic-url}}\
242 <th>{{mkws-translate "Links"}}</th>\
244 {{#each md-electronic-url}}\
245 <a href="{{this}}">Link{{mkws-index1}}</a>\
250 {{#mkws-if-any location having="md-subject"}}\
252 <th>{{mkws-translate "Subject"}}</th>\
254 {{#mkws-first location having="md-subject"}}\
256 {{#mkws-commaList md-subject}}\
257 {{this}}{{/mkws-commaList}}\
264 <th>{{mkws-translate "Locations"}}</th>\
266 {{#mkws-commaList location}}\
267 {{mkws-attr "@name"}}{{/mkws-commaList}}\
272 } else if (name === "Summary") {
274 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
277 {{#if md-title-remainder}}\
278 <span>{{md-title-remainder}}</span>\
280 {{#if md-title-responsibility}}\
281 <span><i>{{md-title-responsibility}}</i></span>\
283 {{#if md-date}}, {{md-date}}\
285 , {{#mkws-first location}}{{mkws-attr "@name"}}{{/mkws-first}}\
288 <span>, {{md-medium}}</span>\
292 } else if (name === "Image") {
294 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
295 {{#mkws-first md-thumburl}}\
296 <img src="{{this}}" alt="{{../md-title}}"/>\
301 } else if (name === 'Facet') {
305 onclick="mkws.{{fn}}(\'{{team}}\', \'{{field}}\', \'{{term}}\');return false;"\
308 <span>{{count}}</span>\
316 // The following functions are dispatchers for team methods that
317 // are called from the UI using a team-name rather than implicit
319 mkws.switchView = function(tname, view) {
320 mkws.teams[tname].switchView(view);
323 mkws.showDetails = function(tname, prefixRecId) {
324 mkws.teams[tname].showDetails(prefixRecId);
327 mkws.limitTarget = function(tname, id, name) {
328 mkws.teams[tname].limitTarget(id, name);
331 mkws.limitQuery = function(tname, field, value) {
332 mkws.teams[tname].limitQuery(field, value);
335 mkws.limitCategory = function(tname, id) {
336 mkws.teams[tname].limitCategory(id);
339 mkws.delimitTarget = function(tname, id) {
340 mkws.teams[tname].delimitTarget(id);
343 mkws.delimitQuery = function(tname, field, value) {
344 mkws.teams[tname].delimitQuery(field, value);
347 mkws.showPage = function(tname, pageNum) {
348 mkws.teams[tname].showPage(pageNum);
351 mkws.pagerPrev = function(tname) {
352 mkws.teams[tname].pagerPrev();
355 mkws.pagerNext = function(tname) {
356 mkws.teams[tname].pagerNext();
360 // wrapper to provide local copy of the jQuery object.
364 function handleNodeWithTeam(node, callback) {
365 // First branch for DOM objects; second branch for jQuery objects
366 var classes = node.className || node.attr('class');
368 // For some reason, if we try to proceed when classes is
369 // undefined, we don't get an error message, but this
370 // function and its callers, up several stack level,
371 // silently return. What a crock.
372 log("handleNodeWithTeam() called on node with no classes");
375 var list = classes.split(/\s+/)
378 for (var i = 0; i < list.length; i++) {
380 if (cname.match(/^mkwsTeam_/)) {
381 teamName = cname.replace(/^mkwsTeam_/, '');
382 } else if (cname.match(/^mkws/)) {
383 type = cname.replace(/^mkws/, '');
387 // Widgets without a team are on team "AUTO"
390 // Autosearch widgets don't join team AUTO if there is already an
391 // autosearch on the team or the team has otherwise gotten a query
392 if (node.hasAttribute("autosearch")) {
393 if (mkws.autoHasAuto ||
394 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
395 log("AUTO team already has a query, using unique team");
398 mkws.autoHasAuto = true;
402 // Widgets on team "UNIQUE" get a random team
403 if (teamName === "UNIQUE") {
404 teamName = Math.floor(Math.random() * 100000000).toString();
407 callback.call(node, teamName, type);
411 function resizePage() {
412 var threshhold = mkws.config.responsive_design_width;
413 var width = $(window).width();
414 var from, to, method;
416 if ((mkws.width === undefined || mkws.width > threshhold) &&
417 width <= threshhold) {
418 from = "wide"; to = "narrow"; method = "hide";
419 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
420 width > threshhold) {
421 from = "narrow"; to = "wide"; method = "show";
426 log("changing from " + from + " to " + to + ": " + width);
427 for (var tname in mkws.teams) {
428 var team = mkws.teams[tname];
429 team.visitWidgets(function(t, w) {
430 var w1 = team.widget(t + "-Container-" + from);
431 var w2 = team.widget(t + "-Container-" + to);
437 w.node.appendTo(w2.node);
440 team.queue("resize-" + to).publish();
447 * Run service-proxy authentication in background (after page load).
448 * The username/password is configured in the apache config file
451 function authenticateSession(auth_url, auth_domain, pp2_url) {
452 log("service proxy authentication on URL: " + auth_url);
455 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
456 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
459 var request = new pzHttpRequest(auth_url, function(err) {
460 alert("HTTP call for authentication failed: " + err)
464 request.get(null, function(data) {
465 if (!$.isXMLDoc(data)) {
466 alert("Service Proxy authentication response is not a valid XML document");
469 var status = $(data).find("status");
470 if (status.text() != "OK") {
471 var message = $(data).find("message");
472 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
476 log("service proxy authentication successful");
477 mkws.authenticated = true;
478 var authName = $(data).find("displayName").text();
479 // You'd think there would be a better way to do this:
480 var realm = $(data).find("realm:not(realmAttributes realm)").text();
481 for (var teamName in mkws.teams) {
482 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
490 function runAutoSearches() {
491 log("running auto searches");
493 for (var teamName in mkws.teams) {
494 mkws.teams[teamName].queue("ready").publish();
499 function selectorForAllWidgets() {
500 if (mkws.config && mkws.config.scan_all_nodes) {
501 // This is the old version, which works by telling jQuery to
502 // find every node that has a class beginning with "mkws". In
503 // theory it should be slower than the class-based selector; but
504 // instrumentation suprisnigly shows this is consistently
505 // faster. It also has the advantage that any widgets of
506 // non-registered types are logged as warnings rather than
508 return '[class^="mkws"],[class*=" mkws"]';
510 // This is the new version, which works by looking up the
511 // specific classes of all registered widget types and their
512 // resize containers. Because all it requires jQuery to do is
513 // some hash lookups in pre-built tables, it should be very
514 // fast; but it silently ignores widgets of unregistered types.
516 for (var type in mkws.widgetType2function) {
519 s += ',.mkws' + type + "-Container-wide";
520 s += ',.mkws' + type + "-Container-narrow";
527 function makeWidgetsWithin(level, node) {
528 if (node) var widgetNodes = node.find(selectorForAllWidgets());
529 else widgetNodes = $(selectorForAllWidgets());
530 // Return false if we parse no widgets
531 if (widgetNodes.length < 1) return false;
532 widgetNodes.each(function() {
533 handleNodeWithTeam(this, function(tname, type) {
534 var myTeam = mkws.teams[tname];
536 myTeam = mkws.teams[tname] = team($, tname);
537 log("made MKWS team '" + tname + "'");
540 var oldHTML = this.innerHTML;
541 var myWidget = widget($, myTeam, type, this);
542 myTeam.addWidget(myWidget);
543 var newHTML = this.innerHTML;
544 if (newHTML !== oldHTML) {
545 log("widget " + tname + ":" + type + " HTML changed: reparsing");
546 makeWidgetsWithin(level+1, $(this));
554 // This function should have no side effects if run again on an operating session, even if
555 // the element/selector passed causes existing widgets to be reparsed:
557 // * configuration is not regenerated
558 // * authentication is not performed again
559 // * autosearches are not re-run
560 mkws.init = function(message, rootsel) {
561 if (message) mkws.log(message);
563 // TODO: Let's remove this soon
564 // Backwards compatibility: set new magic class names on any
565 // elements that have the old magic IDs.
566 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
567 "Results", "Records", "Targets", "Ranking",
568 "Termlists", "Stat", "MOTD" ];
569 for (var i = 0; i < ids.length; i++) {
570 var id = 'mkws' + ids[i];
571 var node = $('#' + id);
572 if (node.attr('id')) {
574 log("added magic class to '" + node.attr('id') + "'");
578 // MKWS is not active until init() has been run against an object with widget nodes.
579 // We only set initial configuration when MKWS is first activated.
580 if (!mkws.isActive) {
581 var widgetSelector = selectorForAllWidgets();
582 if ($(widgetSelector).length < 1) {
583 mkws.log("no widgets found");
587 // Initial configuration
588 mkws.autoHasAuto = false;
590 if (typeof mkws_config === 'undefined') {
591 log("setting empty config");
594 log("using config: " + $.toJSON(mkws_config));
595 saved_config = mkws_config;
597 mkws.setMkwsConfig(saved_config);
599 for (var key in mkws.config) {
600 if (mkws.config.hasOwnProperty(key)) {
601 if (key.match(/^language_/)) {
602 var lang = key.replace(/^language_/, "");
603 // Copy custom languages into list
604 mkws.locale_lang[lang] = mkws.config[key];
605 log("added locally configured language '" + lang + "'");
610 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
611 if (!lang || !mkws.locale_lang[lang]) {
612 mkws.config.lang = ""
614 mkws.config.lang = lang;
617 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
619 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
620 log("reset query width to " + mkws.config.query_width);
621 mkws.config.query_width = 50;
624 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
625 if (mkws.config.pazpar2_url.match(/^\/\//)) {
626 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
627 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
630 if (mkws.config.responsive_design_width) {
631 // Responsive web design - change layout on the fly based on
632 // current screen width. Required for mobile devices.
633 $(window).resize(resizePage);
634 // initial check after page load
635 $(document).ready(resizePage);
640 // If we've made no widgets, return without starting an SP session
641 // or marking MKWS active.
642 if (makeWidgetsWithin(1, rootsel) === false) return false;
645 log("walking MKWS nodes took " + (now-then) + " ms");
648 for (var tName in mkws.teams) {
649 var myTeam = mkws.teams[tName]
650 log("team '" + tName + "' = " + myTeam + " ...");
651 myTeam.visitWidgets(function(t, w) {
652 log(" has widget of type '" + t + "': " + w);
657 function sp_auth_url(config) {
658 if (config.service_proxy_auth) {
659 mkws.log("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
660 return config.service_proxy_auth;
663 s += config.auth_hostname ? config.auth_hostname : config.pp2_hostname;
664 s += '/' + config.sp_path + '?command=auth&action=perconfig';
665 var c = config.credentials;
668 s += ('&username=' + c.substr(0, c.indexOf('/')) +
669 '&password=' + c.substr(c.indexOf('/')+1));
672 mkws.log("generated sp_auth_url '" + s + "'");
677 if (mkws.config.use_service_proxy) {
678 if (!mkws.authenticated) {
679 authenticateSession(sp_auth_url(mkws.config),
680 mkws.config.service_proxy_auth_domain,
681 mkws.config.pazpar2_url);
688 mkws.isActive = true;
692 $(document).ready(function() {