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 "Termlists": "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 "Termlists": "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 // Incredible that the standard JavaScript runtime doesn't define a
113 // unique windowId. Instead, we have to make one up. And since there's
114 // no global area shared between windows, the best we can do for
115 // ensuring uniqueness is generating a random ID and crossing our
116 // fingers. We stash this in window.name, as it's the only place to
117 // keep data that is preserved across reloads and within-site
118 // navigation. pz2.js picks this up and uses it as part of the
119 // cookie-name, to ensure each tab gets its own session.
121 mkws.log("Using existing window.name '" + window.name + "'");
123 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
124 // At one per second, it will take 116 million years to duplicate a session
125 window.name = Math.random().toString(36).slice(2, 12);
126 mkws.log("Generated new window.name '" + window.name + "'");
130 // Translation function.
131 mkws.M = function(word) {
132 var lang = mkws.config.lang;
134 if (!lang || !mkws.locale_lang[lang])
137 return mkws.locale_lang[lang][word] || word;
141 // This function is taken from a StackOverflow answer
142 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
143 mkws.getParameterByName = function(name, url) {
144 if (!url) url = location.search;
145 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
146 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
147 results = regex.exec(url);
148 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
152 mkws.registerWidgetType = function(name, fn) {
153 mkws.widgetType2function[name] = fn;
154 mkws.log("registered widget-type '" + name + "'");
157 mkws.promotionFunction = function(name) {
158 return mkws.widgetType2function[name];
162 mkws.setMkwsConfig = function(overrides) {
163 // Set global log_level flag early so that mkws.log() works
164 // Fall back to old "debug_level" setting for backwards compatibility
165 var tmp = overrides.log_level;
166 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
167 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
169 var config_default = {
170 use_service_proxy: true,
171 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
172 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
174 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
175 perpage_options: [10, 20, 30, 50],
176 sort_default: "relevance",
179 show_lang: true, /* show/hide language menu */
180 show_sort: true, /* show/hide sort menu */
181 show_perpage: true, /* show/hide perpage menu */
182 show_switch: true, /* show/hide switch menu */
183 lang_options: [], /* display languages links for given languages, [] for all */
184 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
185 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
186 log_level: 1, /* log level for development: 0..2 */
187 template_vars: {}, /* values that may be exposed to templates */
192 mkws.config = mkws.objectInheritingFrom(config_default);
193 for (var k in overrides) {
194 mkws.config[k] = overrides[k];
199 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
200 // http://javascript.crockford.com/prototypal.html
201 // mkws.objectInheritingFrom behaves the same as Object.create,
202 // but since the latter is not available in IE8 we can't use it.
204 mkws.objectInheritingFrom = function(o) {
211 // The following functions are dispatchers for team methods that
212 // are called from the UI using a team-name rather than implicit
214 mkws.switchView = function(tname, view) {
215 mkws.teams[tname].switchView(view);
218 mkws.showDetails = function(tname, prefixRecId) {
219 mkws.teams[tname].showDetails(prefixRecId);
222 mkws.limitTarget = function(tname, id, name) {
223 mkws.teams[tname].limitTarget(id, name);
226 mkws.limitQuery = function(tname, field, value) {
227 mkws.teams[tname].limitQuery(field, value);
230 mkws.limitCategory = function(tname, id) {
231 mkws.teams[tname].limitCategory(id);
234 mkws.delimitTarget = function(tname, id) {
235 mkws.teams[tname].delimitTarget(id);
238 mkws.delimitQuery = function(tname, field, value) {
239 mkws.teams[tname].delimitQuery(field, value);
242 mkws.showPage = function(tname, pageNum) {
243 mkws.teams[tname].showPage(pageNum);
246 mkws.pagerPrev = function(tname) {
247 mkws.teams[tname].pagerPrev();
250 mkws.pagerNext = function(tname) {
251 mkws.teams[tname].pagerNext();
255 // wrapper to provide local copy of the jQuery object.
259 function handleNodeWithTeam(node, callback) {
260 // First branch for DOM objects; second branch for jQuery objects
261 var classes = node.className || node.attr('class');
263 // For some reason, if we try to proceed when classes is
264 // undefined, we don't get an error message, but this
265 // function and its callers, up several stack level,
266 // silently return. What a crock.
267 log("handleNodeWithTeam() called on node with no classes");
270 var list = classes.split(/\s+/)
273 for (var i = 0; i < list.length; i++) {
275 if (cname.match(/^mkwsTeam_/)) {
276 teamName = cname.replace(/^mkwsTeam_/, '');
277 } else if (cname.match(/^mkws/)) {
278 type = cname.replace(/^mkws/, '');
282 // Widgets without a team are on team "AUTO"
285 // Autosearch widgets don't join team AUTO if there is already an
286 // autosearch on the team or the team has otherwise gotten a query
287 if (node.hasAttribute("autosearch")) {
288 if (mkws.autoHasAuto ||
289 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
290 log("AUTO team already has a query, using unique team");
293 mkws.autoHasAuto = true;
297 // Widgets on team "UNIQUE" get a random team
298 if (teamName === "UNIQUE") {
299 teamName = Math.floor(Math.random() * 100000000).toString();
302 callback.call(node, teamName, type);
306 function resizePage() {
307 var threshhold = mkws.config.responsive_design_width;
308 var width = $(window).width();
309 var from, to, method;
311 if ((mkws.width === undefined || mkws.width > threshhold) &&
312 width <= threshhold) {
313 from = "wide"; to = "narrow"; method = "hide";
314 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
315 width > threshhold) {
316 from = "narrow"; to = "wide"; method = "show";
321 log("changing from " + from + " to " + to + ": " + width);
322 for (var tname in mkws.teams) {
323 var team = mkws.teams[tname];
324 team.visitWidgets(function(t, w) {
325 var w1 = team.widget(t + "-Container-" + from);
326 var w2 = team.widget(t + "-Container-" + to);
332 w.node.appendTo(w2.node);
335 team.queue("resize-" + to).publish();
342 * Run service-proxy authentication in background (after page load).
343 * The username/password is configured in the apache config file
346 function authenticateSession(auth_url, auth_domain, pp2_url) {
347 mkws.authenticating = true;
348 log("service proxy authentication on URL: " + auth_url);
351 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
352 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
355 var request = new pzHttpRequest(auth_url, function(err) {
356 alert("HTTP call for authentication failed: " + err)
360 request.get(null, function(data) {
361 mkws.authenticating = false;
362 if (!$.isXMLDoc(data)) {
363 alert("Service Proxy authentication response is not a valid XML document");
366 var status = $(data).find("status");
367 if (status.text() != "OK") {
368 var message = $(data).find("message");
369 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
373 log("service proxy authentication successful");
374 mkws.authenticated = true;
375 var authName = $(data).find("displayName").text();
376 // You'd think there would be a better way to do this:
377 var realm = $(data).find("realm:not(realmAttributes realm)").text();
378 for (var teamName in mkws.teams) {
379 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
387 function runAutoSearches() {
388 log("running auto searches");
390 for (var teamName in mkws.teams) {
391 mkws.teams[teamName].queue("ready").publish();
396 function selectorForAllWidgets() {
397 if (mkws.config && mkws.config.scan_all_nodes) {
398 // This is the old version, which works by telling jQuery to
399 // find every node that has a class beginning with "mkws". In
400 // theory it should be slower than the class-based selector; but
401 // instrumentation suprisnigly shows this is consistently
402 // faster. It also has the advantage that any widgets of
403 // non-registered types are logged as warnings rather than
405 return '[class^="mkws"],[class*=" mkws"]';
407 // This is the new version, which works by looking up the
408 // specific classes of all registered widget types and their
409 // resize containers. Because all it requires jQuery to do is
410 // some hash lookups in pre-built tables, it should be very
411 // fast; but it silently ignores widgets of unregistered types.
413 for (var type in mkws.widgetType2function) {
416 s += ',.mkws' + type + "-Container-wide";
417 s += ',.mkws' + type + "-Container-narrow";
424 function makeWidgetsWithin(level, node) {
425 if (node) var widgetNodes = node.find(selectorForAllWidgets());
426 else widgetNodes = $(selectorForAllWidgets());
427 // Return false if we parse no widgets
428 if (widgetNodes.length < 1) return false;
429 widgetNodes.each(function() {
430 handleNodeWithTeam(this, function(tname, type) {
431 var myTeam = mkws.teams[tname];
433 myTeam = mkws.teams[tname] = team($, tname);
434 log("made MKWS team '" + tname + "'");
437 var oldHTML = this.innerHTML;
438 var myWidget = widget($, myTeam, type, this);
439 myTeam.addWidget(myWidget);
440 var newHTML = this.innerHTML;
441 if (newHTML !== oldHTML) {
442 log("widget " + tname + ":" + type + " HTML changed: reparsing");
443 makeWidgetsWithin(level+1, $(this));
451 // The second "rootsel" parameter is passed to jQuery and is a DOM node
452 // or a selector string you would like to constrain the search for widgets to.
454 // This function has no side effects if run again on an operating session,
455 // even if the element/selector passed causes existing widgets to be reparsed:
457 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
458 // widgets, MKWS-261)
460 // * configuration is not regenerated
461 // * authentication is not performed again
462 // * autosearches are not re-run
463 mkws.init = function(message, rootsel) {
464 var greet = "MKWS initialised";
465 if (rootsel) greet += " (limited to " + rootsel + ")"
466 if (message) greet += " :: " + message;
469 // TODO: Let's remove this soon
470 // Backwards compatibility: set new magic class names on any
471 // elements that have the old magic IDs.
472 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
473 "Results", "Records", "Targets", "Ranking",
474 "Termlists", "Stat", "MOTD" ];
475 for (var i = 0; i < ids.length; i++) {
476 var id = 'mkws' + ids[i];
477 var node = $('#' + id);
478 if (node.attr('id')) {
480 log("added magic class to '" + node.attr('id') + "'");
484 // MKWS is not active until init() has been run against an object with widget nodes.
485 // We only set initial configuration when MKWS is first activated.
486 if (!mkws.isActive) {
487 var widgetSelector = selectorForAllWidgets();
488 if ($(widgetSelector).length < 1) {
489 mkws.log("no widgets found");
493 // Initial configuration
494 mkws.autoHasAuto = false;
496 if (typeof mkws_config === 'undefined') {
497 log("setting empty config");
500 log("using config: " + $.toJSON(mkws_config));
501 saved_config = mkws_config;
503 mkws.setMkwsConfig(saved_config);
505 for (var key in mkws.config) {
506 if (mkws.config.hasOwnProperty(key)) {
507 if (key.match(/^language_/)) {
508 var lang = key.replace(/^language_/, "");
509 // Copy custom languages into list
510 mkws.locale_lang[lang] = mkws.config[key];
511 log("added locally configured language '" + lang + "'");
516 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
517 if (!lang || !mkws.locale_lang[lang]) {
518 mkws.config.lang = ""
520 mkws.config.lang = lang;
523 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
525 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
526 log("reset query width to " + mkws.config.query_width);
527 mkws.config.query_width = 50;
530 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
531 if (mkws.config.pazpar2_url.match(/^\/\//)) {
532 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
533 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
536 if (mkws.config.responsive_design_width) {
537 // Responsive web design - change layout on the fly based on
538 // current screen width. Required for mobile devices.
539 $(window).resize(resizePage);
540 // initial check after page load
541 $(document).ready(resizePage);
546 // If we've made no widgets, return without starting an SP session
547 // or marking MKWS active.
548 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
553 log("walking MKWS nodes took " + (now-then) + " ms");
556 for (var tName in mkws.teams) {
557 var myTeam = mkws.teams[tName]
558 log("team '" + tName + "' = " + myTeam + " ...");
559 myTeam.visitWidgets(function(t, w) {
560 log(" has widget of type '" + t + "': " + w);
565 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
566 authenticateSession(mkws.config.service_proxy_auth,
567 mkws.config.service_proxy_auth_domain,
568 mkws.config.pazpar2_url);
569 } else if (!mkws.authenticating) {
570 // raw pp2 or we have a session already open
574 mkws.isActive = true;
578 $(document).ready(function() {
579 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {