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: {},
24 "Subjects": "Schlagwörter",
25 "Sources": "Daten und Quellen",
26 "source": "datenquelle",
27 "Termlists": "Termlisten",
29 "Prev": "Zurück",
31 "Sort by": "Sortieren nach",
32 "and show": "und zeige",
33 "per page": "pro Seite",
34 "Displaying": "Zeige",
42 "Subject": "Schlagwort",
43 "subject": "schlagwort",
45 "Records": "Datensätze",
46 "Targets": "Datenbanken",
52 "Authors": "Forfattere",
56 "Termlists": "Termlists",
57 "Next": "Næste",
59 "Search": "Søg",
60 "Sort by": "Sorter efter",
62 "per page": "per side",
63 "Displaying": "Viser",
68 "Author": "Forfatter",
69 "author": "forfatter",
73 "Location": "Lokation",
82 // We may be using a separate copy
83 if (typeof(mkws_jQuery) !== "undefined") {
89 mkws.log = function(string) {
93 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
97 // you need to disable use strict at the top of the file!!!
98 if (mkws.log_level >= 3) {
99 // Works in Chrome; not sure about elsewhere
101 } else if (mkws.log_level >= 2) {
102 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
108 // Incredible that the standard JavaScript runtime doesn't define a
109 // unique windowId. Instead, we have to make one up. And since there's
110 // no global area shared between windows, the best we can do for
111 // ensuring uniqueness is generating a random ID and crossing our
112 // fingers. We stash this in window.name, as it's the only place to
113 // keep data that is preserved across reloads and within-site
114 // navigation. pz2.js picks this up and uses it as part of the
115 // cookie-name, to ensure each tab gets its own session.
117 mkws.log("Using existing window.name '" + window.name + "'");
119 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
120 // At one per second, it will take 116 million years to duplicate a session
121 window.name = Math.random().toString(36).slice(2, 12);
122 mkws.log("Generated new window.name '" + window.name + "'");
126 // Translation function.
127 mkws.M = function(word) {
128 var lang = mkws.config.lang;
130 if (!lang || !mkws.locale_lang[lang])
133 return mkws.locale_lang[lang][word] || word;
137 // This function is taken from a StackOverflow answer
138 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
139 mkws.getParameterByName = function(name, url) {
140 if (!url) url = location.search;
141 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
142 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
143 results = regex.exec(url);
144 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
148 mkws.registerWidgetType = function(name, fn) {
149 mkws.widgetType2function[name] = fn;
150 mkws.log("registered widget-type '" + name + "'");
153 mkws.promotionFunction = function(name) {
154 return mkws.widgetType2function[name];
158 mkws.setMkwsConfig = function(overrides) {
159 // Set global log_level flag early so that mkws.log() works
160 // Fall back to old "debug_level" setting for backwards compatibility
161 var tmp = overrides.log_level;
162 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
163 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
165 var config_default = {
166 use_service_proxy: true,
167 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
168 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
170 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
171 perpage_options: [10, 20, 30, 50],
172 sort_default: "relevance",
175 show_lang: true, /* show/hide language menu */
176 show_sort: true, /* show/hide sort menu */
177 show_perpage: true, /* show/hide perpage menu */
178 show_switch: true, /* show/hide switch menu */
179 lang_options: [], /* display languages links for given languages, [] for all */
180 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
181 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
182 log_level: 1, /* log level for development: 0..2 */
183 template_vars: {}, /* values that may be exposed to templates */
188 mkws.config = mkws.objectInheritingFrom(config_default);
189 for (var k in overrides) {
190 mkws.config[k] = overrides[k];
195 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
196 // http://javascript.crockford.com/prototypal.html
197 // mkws.objectInheritingFrom behaves the same as Object.create,
198 // but since the latter is not available in IE8 we can't use it.
200 mkws.objectInheritingFrom = function(o) {
207 // The following functions are dispatchers for team methods that
208 // are called from the UI using a team-name rather than implicit
210 mkws.switchView = function(tname, view) {
211 mkws.teams[tname].switchView(view);
214 mkws.showDetails = function(tname, prefixRecId) {
215 mkws.teams[tname].showDetails(prefixRecId);
218 mkws.limitTarget = function(tname, id, name) {
219 mkws.teams[tname].limitTarget(id, name);
222 mkws.limitQuery = function(tname, field, value) {
223 mkws.teams[tname].limitQuery(field, value);
226 mkws.limitCategory = function(tname, id) {
227 mkws.teams[tname].limitCategory(id);
230 mkws.delimitTarget = function(tname, id) {
231 mkws.teams[tname].delimitTarget(id);
234 mkws.delimitQuery = function(tname, field, value) {
235 mkws.teams[tname].delimitQuery(field, value);
238 mkws.showPage = function(tname, pageNum) {
239 mkws.teams[tname].showPage(pageNum);
242 mkws.pagerPrev = function(tname) {
243 mkws.teams[tname].pagerPrev();
246 mkws.pagerNext = function(tname) {
247 mkws.teams[tname].pagerNext();
251 // wrapper to provide local copy of the jQuery object.
255 function handleNodeWithTeam(node, callback) {
256 // First branch for DOM objects; second branch for jQuery objects
257 var classes = node.className || node.attr('class');
259 // For some reason, if we try to proceed when classes is
260 // undefined, we don't get an error message, but this
261 // function and its callers, up several stack level,
262 // silently return. What a crock.
263 log("handleNodeWithTeam() called on node with no classes");
266 var list = classes.split(/\s+/)
269 for (var i = 0; i < list.length; i++) {
271 if (cname.match(/^mkwsTeam_/)) {
272 teamName = cname.replace(/^mkwsTeam_/, '');
273 } else if (cname.match(/^mkws/)) {
274 type = cname.replace(/^mkws/, '');
278 if (!teamName) teamName = "AUTO";
279 callback.call(node, teamName, type);
283 function resizePage() {
284 var threshhold = mkws.config.responsive_design_width;
285 var width = $(window).width();
286 var from, to, method;
288 if ((mkws.width === undefined || mkws.width > threshhold) &&
289 width <= threshhold) {
290 from = "wide"; to = "narrow"; method = "hide";
291 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
292 width > threshhold) {
293 from = "narrow"; to = "wide"; method = "show";
298 log("changing from " + from + " to " + to + ": " + width);
299 for (var tname in mkws.teams) {
300 var team = mkws.teams[tname];
301 team.visitWidgets(function(t, w) {
302 var w1 = team.widget(t + "-Container-" + from);
303 var w2 = team.widget(t + "-Container-" + to);
309 w.node.appendTo(w2.node);
312 team.queue("resize-" + to).publish();
319 * Run service-proxy authentication in background (after page load).
320 * The username/password is configured in the apache config file
323 function authenticateSession(auth_url, auth_domain, pp2_url) {
324 log("service proxy authentication on URL: " + auth_url);
327 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
328 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
331 var request = new pzHttpRequest(auth_url, function(err) {
332 alert("HTTP call for authentication failed: " + err)
336 request.get(null, function(data) {
337 if (!$.isXMLDoc(data)) {
338 alert("Service Proxy authentication response is not a valid XML document");
341 var status = $(data).find("status");
342 if (status.text() != "OK") {
343 var message = $(data).find("message");
344 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
348 log("service proxy authentication successful");
349 mkws.authenticated = true;
350 var authName = $(data).find("displayName").text();
351 // You'd think there would be a better way to do this:
352 var realm = $(data).find("realm:not(realmAttributes realm)").text();
353 for (var teamName in mkws.teams) {
354 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
362 function runAutoSearches() {
363 log("running auto searches");
365 for (var teamName in mkws.teams) {
366 mkws.teams[teamName].queue("ready").publish();
371 function selectorForAllWidgets() {
372 if (mkws.config && mkws.config.scan_all_nodes) {
373 // This is the old version, which works by telling jQuery to
374 // find every node that has a class beginning with "mkws". In
375 // theory it should be slower than the class-based selector; but
376 // instrumentation suprisnigly shows this is consistently
377 // faster. It also has the advantage that any widgets of
378 // non-registered types are logged as warnings rather than
380 return '[class^="mkws"],[class*=" mkws"]';
382 // This is the new version, which works by looking up the
383 // specific classes of all registered widget types and their
384 // resize containers. Because all it requires jQuery to do is
385 // some hash lookups in pre-built tables, it should be very
386 // fast; but it silently ignores widgets of unregistered types.
388 for (var type in mkws.widgetType2function) {
391 s += ',.mkws' + type + "-Container-wide";
392 s += ',.mkws' + type + "-Container-narrow";
399 function makeWidgetsWithin(level, node) {
400 node.find(selectorForAllWidgets()).each(function() {
401 handleNodeWithTeam(this, function(tname, type) {
402 var myTeam = mkws.teams[tname];
404 myTeam = mkws.teams[tname] = team($, tname);
405 log("made MKWS team '" + tname + "'");
408 var oldHTML = this.innerHTML;
409 var myWidget = widget($, myTeam, type, this);
410 myTeam.addWidget(myWidget);
411 var newHTML = this.innerHTML;
412 if (newHTML !== oldHTML) {
413 log("widget " + tname + ":" + type + " HTML changed: reparsing");
414 makeWidgetsWithin(level+1, $(this));
421 function init(rootsel) {
422 if (!rootsel) var rootsel = ':root';
424 if (typeof mkws_config === 'undefined') {
425 log("setting empty config");
428 log("using config: " + $.toJSON(mkws_config));
429 saved_config = mkws_config;
431 mkws.setMkwsConfig(saved_config);
433 for (var key in mkws.config) {
434 if (mkws.config.hasOwnProperty(key)) {
435 if (key.match(/^language_/)) {
436 var lang = key.replace(/^language_/, "");
437 // Copy custom languages into list
438 mkws.locale_lang[lang] = mkws.config[key];
439 log("added locally configured language '" + lang + "'");
444 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
445 if (!lang || !mkws.locale_lang[lang]) {
446 mkws.config.lang = ""
448 mkws.config.lang = lang;
451 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
453 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
454 log("reset query width to " + mkws.config.query_width);
455 mkws.config.query_width = 50;
458 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
459 if (mkws.config.pazpar2_url.match(/^\/\//)) {
460 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
461 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
464 if (mkws.config.responsive_design_width) {
465 // Responsive web design - change layout on the fly based on
466 // current screen width. Required for mobile devices.
467 $(window).resize(resizePage);
468 // initial check after page load
469 $(document).ready(resizePage);
472 // Backwards compatibility: set new magic class names on any
473 // elements that have the old magic IDs.
474 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
475 "Results", "Records", "Targets", "Ranking",
476 "Termlists", "Stat", "MOTD" ];
477 for (var i = 0; i < ids.length; i++) {
478 var id = 'mkws' + ids[i];
479 var node = $('#' + id);
480 if (node.attr('id')) {
482 log("added magic class to '" + node.attr('id') + "'");
487 makeWidgetsWithin(1, $(rootsel));
490 log("walking MKWS nodes took " + (now-then) + " ms");
493 for (var tName in mkws.teams) {
494 var myTeam = mkws.teams[tName]
495 log("team '" + tName + "' = " + myTeam + " ...");
496 myTeam.visitWidgets(function(t, w) {
497 log(" has widget of type '" + t + "': " + w);
502 if (mkws.config.use_service_proxy) {
503 authenticateSession(mkws.config.service_proxy_auth,
504 mkws.config.service_proxy_auth_domain,
505 mkws.config.pazpar2_url);
511 $(document).ready(function() {
512 var widgetSelector = selectorForAllWidgets();
513 if (widgetSelector && $(widgetSelector).length !== 0) init();