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",
83 mkws.log = function(string) {
87 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
91 // you need to disable use strict at the top of the file!!!
92 if (mkws.log_level >= 3) {
93 // Works in Chrome; not sure about elsewhere
95 } else if (mkws.log_level >= 2) {
96 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
102 // Translation function.
103 mkws.M = function(word) {
104 var lang = mkws.config.lang;
106 if (!lang || !mkws.locale_lang[lang])
109 return mkws.locale_lang[lang][word] || word;
113 // This function is taken from a StackOverflow answer
114 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
115 mkws.getParameterByName = function(name, url) {
116 if (!url) url = location.search;
117 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
118 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
119 results = regex.exec(url);
120 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
124 mkws.registerWidgetType = function(name, fn) {
125 mkws.widgetType2function[name] = fn;
126 mkws.log("registered widget-type '" + name + "'");
129 mkws.promotionFunction = function(name) {
130 return mkws.widgetType2function[name];
134 mkws.setMkwsConfig = function(overrides) {
135 // Set global log_level flag early so that mkws.log() works
136 // Fall back to old "debug_level" setting for backwards compatibility
137 var tmp = overrides.log_level;
138 if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
139 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
141 var config_default = {
142 use_service_proxy: true,
143 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
144 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
146 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
147 perpage_options: [10, 20, 30, 50],
148 sort_default: "relevance",
151 show_lang: true, /* show/hide language menu */
152 show_sort: true, /* show/hide sort menu */
153 show_perpage: true, /* show/hide perpage menu */
154 show_switch: true, /* show/hide switch menu */
155 lang_options: [], /* display languages links for given languages, [] for all */
156 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
157 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
158 log_level: 1, /* log level for development: 0..2 */
163 mkws.config = mkws.objectInheritingFrom(config_default);
164 for (var k in overrides) {
165 mkws.config[k] = overrides[k];
170 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
171 // http://javascript.crockford.com/prototypal.html
172 // mkws.objectInheritingFrom behaves the same as Object.create,
173 // but since the latter is not available in IE8 we can't use it.
175 mkws.objectInheritingFrom = function(o) {
182 // The following functions are dispatchers for team methods that
183 // are called from the UI using a team-name rather than implicit
185 mkws.switchView = function(tname, view) {
186 mkws.teams[tname].switchView(view);
189 mkws.showDetails = function(tname, prefixRecId) {
190 mkws.teams[tname].showDetails(prefixRecId);
193 mkws.limitTarget = function(tname, id, name) {
194 mkws.teams[tname].limitTarget(id, name);
197 mkws.limitQuery = function(tname, field, value) {
198 mkws.teams[tname].limitQuery(field, value);
201 mkws.limitCategory = function(tname, id) {
202 mkws.teams[tname].limitCategory(id);
205 mkws.delimitTarget = function(tname, id) {
206 mkws.teams[tname].delimitTarget(id);
209 mkws.delimitQuery = function(tname, field, value) {
210 mkws.teams[tname].delimitQuery(field, value);
213 mkws.showPage = function(tname, pageNum) {
214 mkws.teams[tname].showPage(pageNum);
217 mkws.pagerPrev = function(tname) {
218 mkws.teams[tname].pagerPrev();
221 mkws.pagerNext = function(tname) {
222 mkws.teams[tname].pagerNext();
226 // wrapper to provide local copy of the jQuery object.
230 function handleNodeWithTeam(node, callback) {
231 // First branch for DOM objects; second branch for jQuery objects
232 var classes = node.className || node.attr('class');
234 // For some reason, if we try to proceed when classes is
235 // undefined, we don't get an error message, but this
236 // function and its callers, up several stack level,
237 // silently return. What a crock.
238 log("handleNodeWithTeam() called on node with no classes");
241 var list = classes.split(/\s+/)
244 for (var i = 0; i < list.length; i++) {
246 if (cname.match(/^mkwsTeam_/)) {
247 teamName = cname.replace(/^mkwsTeam_/, '');
248 } else if (cname.match(/^mkws/)) {
249 type = cname.replace(/^mkws/, '');
253 if (!teamName) teamName = "AUTO";
254 callback.call(node, teamName, type);
258 function resizePage() {
259 var threshhold = mkws.config.responsive_design_width;
260 var width = $(window).width();
261 var from, to, method;
263 if ((mkws.width === undefined || mkws.width > threshhold) &&
264 width <= threshhold) {
265 from = "wide"; to = "narrow"; method = "hide";
266 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
267 width > threshhold) {
268 from = "narrow"; to = "wide"; method = "show";
273 log("changing from " + from + " to " + to + ": " + width);
274 for (var tname in mkws.teams) {
275 var team = mkws.teams[tname];
276 team.visitWidgets(function(t, w) {
277 var w1 = team.widget(t + "-Container-" + from);
278 var w2 = team.widget(t + "-Container-" + to);
284 w.node.appendTo(w2.node);
287 team.queue("resize-" + to).publish();
294 * Run service-proxy authentication in background (after page load).
295 * The username/password is configured in the apache config file
298 function authenticateSession(auth_url, auth_domain, pp2_url) {
299 log("service proxy authentication on URL: " + auth_url);
302 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
303 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
306 var request = new pzHttpRequest(auth_url, function(err) {
307 alert("HTTP call for authentication failed: " + err)
311 request.get(null, function(data) {
312 if (!$.isXMLDoc(data)) {
313 alert("service proxy auth response document is not valid XML document, give up!");
316 var status = $(data).find("status");
317 if (status.text() != "OK") {
318 alert("service proxy auth response status: " + status.text() + ", give up!");
322 log("service proxy authentication successful");
323 mkws.authenticated = true;
324 var authName = $(data).find("displayName").text();
325 // You'd think there would be a better way to do this:
326 var realm = $(data).find("realm:not(realmAttributes realm)").text();
327 for (var teamName in mkws.teams) {
328 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
336 function runAutoSearches() {
337 log("running auto searches");
339 for (var teamName in mkws.teams) {
340 mkws.teams[teamName].queue("ready").publish();
345 function selectorForAllWidgets() {
346 if (mkws.config && mkws.config.scan_all_nodes) {
347 // This is the old version, which works by telling jQuery to
348 // find every node that has a class beginning with "mkws". In
349 // theory it should be slower than the class-based selector; but
350 // instrumentation suprisnigly shows this is consistently
351 // faster. It also has the advantage that any widgets of
352 // non-registered types are logged as warnings rather than
354 return '[class^="mkws"],[class*=" mkws"]';
356 // This is the new version, which works by looking up the
357 // specific classes of all registered widget types and their
358 // resize containers. Because all it requires jQuery to do is
359 // some hash lookups in pre-built tables, it should be very
360 // fast; but it silently ignores widgets of unregistered types.
362 for (var type in mkws.widgetType2function) {
365 s += ',.mkws' + type + "-Container-wide";
366 s += ',.mkws' + type + "-Container-narrow";
373 function makeWidgetsWithin(level, node) {
374 node.find(selectorForAllWidgets()).each(function() {
375 handleNodeWithTeam(this, function(tname, type) {
376 var myTeam = mkws.teams[tname];
378 myTeam = mkws.teams[tname] = team($, tname);
379 log("made MKWS team '" + tname + "'");
382 var oldHTML = this.innerHTML;
383 var myWidget = widget($, myTeam, type, this);
384 myTeam.addWidget(myWidget);
385 var newHTML = this.innerHTML;
386 if (newHTML !== oldHTML) {
387 log("widget " + tname + ":" + type + " HTML changed: reparsing");
388 makeWidgetsWithin(level+1, $(this));
395 function init(rootsel) {
396 if (!rootsel) var rootsel = ':root';
398 if (typeof mkws_config === 'undefined') {
399 log("setting empty config");
402 log("using config: " + $.toJSON(mkws_config));
403 saved_config = mkws_config;
405 mkws.setMkwsConfig(saved_config);
407 for (var key in mkws.config) {
408 if (mkws.config.hasOwnProperty(key)) {
409 if (key.match(/^language_/)) {
410 var lang = key.replace(/^language_/, "");
411 // Copy custom languages into list
412 mkws.locale_lang[lang] = mkws.config[key];
413 log("added locally configured language '" + lang + "'");
418 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
419 if (!lang || !mkws.locale_lang[lang]) {
420 mkws.config.lang = ""
422 mkws.config.lang = lang;
425 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
427 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
428 log("reset query width to " + mkws.config.query_width);
429 mkws.config.query_width = 50;
432 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
433 if (mkws.config.pazpar2_url.match(/^\/\//)) {
434 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
435 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
438 if (mkws.config.responsive_design_width) {
439 // Responsive web design - change layout on the fly based on
440 // current screen width. Required for mobile devices.
441 $(window).resize(resizePage);
442 // initial check after page load
443 $(document).ready(resizePage);
446 // Backwards compatibility: set new magic class names on any
447 // elements that have the old magic IDs.
448 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
449 "Results", "Records", "Targets", "Ranking",
450 "Termlists", "Stat", "MOTD" ];
451 for (var i = 0; i < ids.length; i++) {
452 var id = 'mkws' + ids[i];
453 var node = $('#' + id);
454 if (node.attr('id')) {
456 log("added magic class to '" + node.attr('id') + "'");
461 makeWidgetsWithin(1, $(rootsel));
464 log("walking MKWS nodes took " + (now-then) + " ms");
467 for (var tName in mkws.teams) {
468 var myTeam = mkws.teams[tName]
469 log("team '" + tName + "' = " + myTeam + " ...");
470 myTeam.visitWidgets(function(t, w) {
471 log(" has widget of type '" + t + "': " + w);
476 if (mkws.config.use_service_proxy) {
477 authenticateSession(mkws.config.service_proxy_auth,
478 mkws.config.service_proxy_auth_domain,
479 mkws.config.pazpar2_url);
485 $(document).ready(function() {
486 var widgetSelector = selectorForAllWidgets();
487 if (widgetSelector && $(widgetSelector).length !== 0) init();