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.
13 $: $, // Our own local copy of the jQuery object
15 log_level: 1, // Will be overridden from mkws.config, but
16 // initial value allows jQuery popup to use logging.
18 widgetType2function: {},
23 "Subjects": "Schlagwörter",
24 "Sources": "Daten und Quellen",
25 "source": "datenquelle",
26 "Termlists": "Termlisten",
28 "Prev": "Zurück",
30 "Sort by": "Sortieren nach",
31 "and show": "und zeige",
32 "per page": "pro Seite",
33 "Displaying": "Zeige",
41 "Subject": "Schlagwort",
42 "subject": "schlagwort",
44 "Records": "Datensätze",
45 "Targets": "Datenbanken",
51 "Authors": "Forfattere",
55 "Termlists": "Termlists",
56 "Next": "Næste",
58 "Search": "Søg",
59 "Sort by": "Sorter efter",
61 "per page": "per side",
62 "Displaying": "Viser",
67 "Author": "Forfatter",
68 "author": "forfatter",
72 "Location": "Lokation",
82 mkws.log = function(string) {
86 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
90 // you need to disable use strict at the top of the file!!!
91 if (mkws.log_level >= 3) {
92 // Works in Chrome; not sure about elsewhere
94 } else if (mkws.log_level >= 2) {
95 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
101 // Translation function.
102 mkws.M = function(word) {
103 var lang = mkws.config.lang;
105 if (!lang || !mkws.locale_lang[lang])
108 return mkws.locale_lang[lang][word] || word;
112 // This function is taken from a StackOverflow answer
113 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
114 mkws.getParameterByName = function(name, url) {
115 if (!url) url = location.search;
116 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
117 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
118 results = regex.exec(url);
119 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
123 mkws.registerWidgetType = function(name, fn) {
124 mkws.widgetType2function[name] = fn;
125 mkws.log("registered widget-type '" + name + "'");
128 mkws.promotionFunction = function(name) {
129 return mkws.widgetType2function[name];
133 mkws.setMkwsConfig = function(overrides) {
134 // Set global log_level flag early so that mkws.log() works
135 // Fall back to old "debug_level" setting for backwards compatibility
136 var tmp = overrides.log_level;
137 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
138 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
140 var config_default = {
141 use_service_proxy: true,
142 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
143 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
145 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
146 perpage_options: [10, 20, 30, 50],
147 sort_default: "relevance",
150 show_lang: true, /* show/hide language menu */
151 show_sort: true, /* show/hide sort menu */
152 show_perpage: true, /* show/hide perpage menu */
153 show_switch: true, /* show/hide switch menu */
154 lang_options: [], /* display languages links for given languages, [] for all */
155 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
156 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
157 log_level: 1, /* log level for development: 0..2 */
162 mkws.config = mkws.objectInheritingFrom(config_default);
163 for (var k in overrides) {
164 mkws.config[k] = overrides[k];
169 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
170 // http://javascript.crockford.com/prototypal.html
171 // mkws.objectInheritingFrom behaves the same as Object.create,
172 // but since the latter is not available in IE8 we can't use it.
174 mkws.objectInheritingFrom = function(o) {
181 mkws.defaultTemplate = function(name) {
182 if (name === 'Record') {
186 <th>{{mkws-translate "Title"}}</th>\
189 {{#if md-title-remainder}}\
190 ({{md-title-remainder}})\
192 {{#if md-title-responsibility}}\
193 <i>{{md-title-responsibility}}</i>\
199 <th>{{mkws-translate "Date"}}</th>\
200 <td>{{md-date}}</td>\
205 <th>{{mkws-translate "Author"}}</th>\
206 <td>{{md-author}}</td>\
209 {{#if md-electronic-url}}\
211 <th>{{mkws-translate "Links"}}</th>\
213 {{#each md-electronic-url}}\
214 <a href="{{this}}">Link{{mkws-index1}}</a>\
219 {{#mkws-if-any location having="md-subject"}}\
221 <th>{{mkws-translate "Subject"}}</th>\
223 {{#mkws-first location having="md-subject"}}\
225 {{#mkws-commaList md-subject}}\
226 {{this}}{{/mkws-commaList}}\
233 <th>{{mkws-translate "Locations"}}</th>\
235 {{#mkws-commaList location}}\
236 {{mkws-attr "@name"}}{{/mkws-commaList}}\
241 } else if (name === "Summary") {
243 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
246 {{#if md-title-remainder}}\
247 <span>{{md-title-remainder}}</span>\
249 {{#if md-title-responsibility}}\
250 <span><i>{{md-title-responsibility}}</i></span>\
253 } else if (name === "Image") {
255 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
256 {{#mkws-first md-thumburl}}\
257 <img src="{{this}}" alt="{{../md-title}}"/>\
264 var s = "There is no default '" + name +"' template!";
270 // The following functions are dispatchers for team methods that
271 // are called from the UI using a team-name rather than implicit
273 mkws.switchView = function(tname, view) {
274 mkws.teams[tname].switchView(view);
277 mkws.showDetails = function(tname, prefixRecId) {
278 mkws.teams[tname].showDetails(prefixRecId);
281 mkws.limitTarget = function(tname, id, name) {
282 mkws.teams[tname].limitTarget(id, name);
285 mkws.limitQuery = function(tname, field, value) {
286 mkws.teams[tname].limitQuery(field, value);
289 mkws.limitCategory = function(tname, id) {
290 mkws.teams[tname].limitCategory(id);
293 mkws.delimitTarget = function(tname, id) {
294 mkws.teams[tname].delimitTarget(id);
297 mkws.delimitQuery = function(tname, field, value) {
298 mkws.teams[tname].delimitQuery(field, value);
301 mkws.showPage = function(tname, pageNum) {
302 mkws.teams[tname].showPage(pageNum);
305 mkws.pagerPrev = function(tname) {
306 mkws.teams[tname].pagerPrev();
309 mkws.pagerNext = function(tname) {
310 mkws.teams[tname].pagerNext();
314 // wrapper to provide local copy of the jQuery object.
318 function handleNodeWithTeam(node, callback) {
319 // First branch for DOM objects; second branch for jQuery objects
320 var classes = node.className || node.attr('class');
322 // For some reason, if we try to proceed when classes is
323 // undefined, we don't get an error message, but this
324 // function and its callers, up several stack level,
325 // silently return. What a crock.
326 log("handleNodeWithTeam() called on node with no classes");
329 var list = classes.split(/\s+/)
332 for (var i = 0; i < list.length; i++) {
334 if (cname.match(/^mkwsTeam_/)) {
335 teamName = cname.replace(/^mkwsTeam_/, '');
336 } else if (cname.match(/^mkws/)) {
337 type = cname.replace(/^mkws/, '');
341 if (!teamName) teamName = "AUTO";
342 callback.call(node, teamName, type);
346 function resizePage() {
347 var threshhold = mkws.config.responsive_design_width;
348 var width = $(window).width();
349 var from, to, method;
351 if ((mkws.width === undefined || mkws.width > threshhold) &&
352 width <= threshhold) {
353 from = "wide"; to = "narrow"; method = "hide";
354 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
355 width > threshhold) {
356 from = "narrow"; to = "wide"; method = "show";
361 log("changing from " + from + " to " + to + ": " + width);
362 for (var tname in mkws.teams) {
363 var team = mkws.teams[tname];
364 team.visitWidgets(function(t, w) {
365 var w1 = team.widget(t + "-Container-" + from);
366 var w2 = team.widget(t + "-Container-" + to);
372 w.node.appendTo(w2.node);
375 team.queue("resize-" + to).publish();
382 * Run service-proxy authentication in background (after page load).
383 * The username/password is configured in the apache config file
386 function authenticateSession(auth_url, auth_domain, pp2_url) {
387 log("service proxy authentication on URL: " + auth_url);
390 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
391 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
394 var request = new pzHttpRequest(auth_url, function(err) {
395 alert("HTTP call for authentication failed: " + err)
399 request.get(null, function(data) {
400 if (!$.isXMLDoc(data)) {
401 alert("service proxy auth response document is not valid XML document, give up!");
404 var status = $(data).find("status");
405 if (status.text() != "OK") {
406 alert("service proxy auth response status: " + status.text() + ", give up!");
410 log("service proxy authentication successful");
411 mkws.authenticated = true;
412 var authName = $(data).find("displayName").text();
413 // You'd think there would be a better way to do this:
414 var realm = $(data).find("realm:not(realmAttributes realm)").text();
415 for (var teamName in mkws.teams) {
416 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
424 function runAutoSearches() {
425 log("running auto searches");
427 for (var teamName in mkws.teams) {
428 mkws.teams[teamName].queue("ready").publish();
433 function selectorForAllWidgets() {
434 if (mkws.config && mkws.config.scan_all_nodes) {
435 // This is the old version, which works by telling jQuery to
436 // find every node that has a class beginning with "mkws". In
437 // theory it should be slower than the class-based selector; but
438 // instrumentation suprisnigly shows this is consistently
439 // faster. It also has the advantage that any widgets of
440 // non-registered types are logged as warnings rather than
442 return '[class^="mkws"],[class*=" mkws"]';
444 // This is the new version, which works by looking up the
445 // specific classes of all registered widget types and their
446 // resize containers. Because all it requires jQuery to do is
447 // some hash lookups in pre-built tables, it should be very
448 // fast; but it silently ignores widgets of unregistered types.
450 for (var type in mkws.widgetType2function) {
453 s += ',.mkws' + type + "-Container-wide";
454 s += ',.mkws' + type + "-Container-narrow";
461 function makeWidgetsWithin(level, node) {
462 node.find(selectorForAllWidgets()).each(function() {
463 handleNodeWithTeam(this, function(tname, type) {
464 var myTeam = mkws.teams[tname];
466 myTeam = mkws.teams[tname] = team($, tname);
467 log("made MKWS team '" + tname + "'");
470 var oldHTML = this.innerHTML;
471 var myWidget = widget($, myTeam, type, this);
472 myTeam.addWidget(myWidget);
473 var newHTML = this.innerHTML;
474 if (newHTML !== oldHTML) {
475 log("widget " + tname + ":" + type + " HTML changed: reparsing");
476 makeWidgetsWithin(level+1, $(this));
483 function init(rootsel) {
484 if (!rootsel) var rootsel = ':root';
486 if (typeof mkws_config === 'undefined') {
487 log("setting empty config");
490 log("using config: " + $.toJSON(mkws_config));
491 saved_config = mkws_config;
493 mkws.setMkwsConfig(saved_config);
495 for (var key in mkws.config) {
496 if (mkws.config.hasOwnProperty(key)) {
497 if (key.match(/^language_/)) {
498 var lang = key.replace(/^language_/, "");
499 // Copy custom languages into list
500 mkws.locale_lang[lang] = mkws.config[key];
501 log("added locally configured language '" + lang + "'");
506 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
507 if (!lang || !mkws.locale_lang[lang]) {
508 mkws.config.lang = ""
510 mkws.config.lang = lang;
513 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
515 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
516 log("reset query width to " + mkws.config.query_width);
517 mkws.config.query_width = 50;
520 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
521 if (mkws.config.pazpar2_url.match(/^\/\//)) {
522 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
523 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
526 if (mkws.config.responsive_design_width) {
527 // Responsive web design - change layout on the fly based on
528 // current screen width. Required for mobile devices.
529 $(window).resize(resizePage);
530 // initial check after page load
531 $(document).ready(resizePage);
534 // Backwards compatibility: set new magic class names on any
535 // elements that have the old magic IDs.
536 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
537 "Results", "Records", "Targets", "Ranking",
538 "Termlists", "Stat", "MOTD" ];
539 for (var i = 0; i < ids.length; i++) {
540 var id = 'mkws' + ids[i];
541 var node = $('#' + id);
542 if (node.attr('id')) {
544 log("added magic class to '" + node.attr('id') + "'");
549 makeWidgetsWithin(1, $(rootsel));
552 log("walking MKWS nodes took " + (now-then) + " ms");
555 for (var tName in mkws.teams) {
556 var myTeam = mkws.teams[tName]
557 log("team '" + tName + "' = " + myTeam + " ...");
558 myTeam.visitWidgets(function(t, w) {
559 log(" has widget of type '" + t + "': " + w);
564 if (mkws.config.use_service_proxy) {
565 authenticateSession(mkws.config.service_proxy_auth,
566 mkws.config.service_proxy_auth_domain,
567 mkws.config.pazpar2_url);
573 $(document).ready(function() {
574 var widgetSelector = selectorForAllWidgets();
575 if (widgetSelector && $(widgetSelector).length !== 0) init();