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 */
159 template_vars: {}, /* values that may be exposed to templates */
164 mkws.config = mkws.objectInheritingFrom(config_default);
165 for (var k in overrides) {
166 mkws.config[k] = overrides[k];
171 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
172 // http://javascript.crockford.com/prototypal.html
173 // mkws.objectInheritingFrom behaves the same as Object.create,
174 // but since the latter is not available in IE8 we can't use it.
176 mkws.objectInheritingFrom = function(o) {
183 // The following functions are dispatchers for team methods that
184 // are called from the UI using a team-name rather than implicit
186 mkws.switchView = function(tname, view) {
187 mkws.teams[tname].switchView(view);
190 mkws.showDetails = function(tname, prefixRecId) {
191 mkws.teams[tname].showDetails(prefixRecId);
194 mkws.limitTarget = function(tname, id, name) {
195 mkws.teams[tname].limitTarget(id, name);
198 mkws.limitQuery = function(tname, field, value) {
199 mkws.teams[tname].limitQuery(field, value);
202 mkws.limitCategory = function(tname, id) {
203 mkws.teams[tname].limitCategory(id);
206 mkws.delimitTarget = function(tname, id) {
207 mkws.teams[tname].delimitTarget(id);
210 mkws.delimitQuery = function(tname, field, value) {
211 mkws.teams[tname].delimitQuery(field, value);
214 mkws.showPage = function(tname, pageNum) {
215 mkws.teams[tname].showPage(pageNum);
218 mkws.pagerPrev = function(tname) {
219 mkws.teams[tname].pagerPrev();
222 mkws.pagerNext = function(tname) {
223 mkws.teams[tname].pagerNext();
227 // wrapper to provide local copy of the jQuery object.
231 function handleNodeWithTeam(node, callback) {
232 // First branch for DOM objects; second branch for jQuery objects
233 var classes = node.className || node.attr('class');
235 // For some reason, if we try to proceed when classes is
236 // undefined, we don't get an error message, but this
237 // function and its callers, up several stack level,
238 // silently return. What a crock.
239 log("handleNodeWithTeam() called on node with no classes");
242 var list = classes.split(/\s+/)
245 for (var i = 0; i < list.length; i++) {
247 if (cname.match(/^mkwsTeam_/)) {
248 teamName = cname.replace(/^mkwsTeam_/, '');
249 } else if (cname.match(/^mkws/)) {
250 type = cname.replace(/^mkws/, '');
254 if (!teamName) teamName = "AUTO";
255 callback.call(node, teamName, type);
259 function resizePage() {
260 var threshhold = mkws.config.responsive_design_width;
261 var width = $(window).width();
262 var from, to, method;
264 if ((mkws.width === undefined || mkws.width > threshhold) &&
265 width <= threshhold) {
266 from = "wide"; to = "narrow"; method = "hide";
267 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
268 width > threshhold) {
269 from = "narrow"; to = "wide"; method = "show";
274 log("changing from " + from + " to " + to + ": " + width);
275 for (var tname in mkws.teams) {
276 var team = mkws.teams[tname];
277 team.visitWidgets(function(t, w) {
278 var w1 = team.widget(t + "-Container-" + from);
279 var w2 = team.widget(t + "-Container-" + to);
285 w.node.appendTo(w2.node);
288 team.queue("resize-" + to).publish();
295 * Run service-proxy authentication in background (after page load).
296 * The username/password is configured in the apache config file
299 function authenticateSession(auth_url, auth_domain, pp2_url) {
300 log("service proxy authentication on URL: " + auth_url);
303 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
304 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
307 var request = new pzHttpRequest(auth_url, function(err) {
308 alert("HTTP call for authentication failed: " + err)
312 request.get(null, function(data) {
313 if (!$.isXMLDoc(data)) {
314 alert("service proxy auth response document is not valid XML document, give up!");
317 var status = $(data).find("status");
318 if (status.text() != "OK") {
319 alert("service proxy auth response status: " + status.text() + ", give up!");
323 log("service proxy authentication successful");
324 mkws.authenticated = true;
325 var authName = $(data).find("displayName").text();
326 // You'd think there would be a better way to do this:
327 var realm = $(data).find("realm:not(realmAttributes realm)").text();
328 for (var teamName in mkws.teams) {
329 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
337 function runAutoSearches() {
338 log("running auto searches");
340 for (var teamName in mkws.teams) {
341 mkws.teams[teamName].queue("ready").publish();
346 function selectorForAllWidgets() {
347 if (mkws.config && mkws.config.scan_all_nodes) {
348 // This is the old version, which works by telling jQuery to
349 // find every node that has a class beginning with "mkws". In
350 // theory it should be slower than the class-based selector; but
351 // instrumentation suprisnigly shows this is consistently
352 // faster. It also has the advantage that any widgets of
353 // non-registered types are logged as warnings rather than
355 return '[class^="mkws"],[class*=" mkws"]';
357 // This is the new version, which works by looking up the
358 // specific classes of all registered widget types and their
359 // resize containers. Because all it requires jQuery to do is
360 // some hash lookups in pre-built tables, it should be very
361 // fast; but it silently ignores widgets of unregistered types.
363 for (var type in mkws.widgetType2function) {
366 s += ',.mkws' + type + "-Container-wide";
367 s += ',.mkws' + type + "-Container-narrow";
374 function makeWidgetsWithin(level, node) {
375 node.find(selectorForAllWidgets()).each(function() {
376 handleNodeWithTeam(this, function(tname, type) {
377 var myTeam = mkws.teams[tname];
379 myTeam = mkws.teams[tname] = team($, tname);
380 log("made MKWS team '" + tname + "'");
383 var oldHTML = this.innerHTML;
384 var myWidget = widget($, myTeam, type, this);
385 myTeam.addWidget(myWidget);
386 var newHTML = this.innerHTML;
387 if (newHTML !== oldHTML) {
388 log("widget " + tname + ":" + type + " HTML changed: reparsing");
389 makeWidgetsWithin(level+1, $(this));
396 function init(rootsel) {
397 if (!rootsel) var rootsel = ':root';
399 if (typeof mkws_config === 'undefined') {
400 log("setting empty config");
403 log("using config: " + $.toJSON(mkws_config));
404 saved_config = mkws_config;
406 mkws.setMkwsConfig(saved_config);
408 for (var key in mkws.config) {
409 if (mkws.config.hasOwnProperty(key)) {
410 if (key.match(/^language_/)) {
411 var lang = key.replace(/^language_/, "");
412 // Copy custom languages into list
413 mkws.locale_lang[lang] = mkws.config[key];
414 log("added locally configured language '" + lang + "'");
419 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
420 if (!lang || !mkws.locale_lang[lang]) {
421 mkws.config.lang = ""
423 mkws.config.lang = lang;
426 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
428 if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
429 log("reset query width to " + mkws.config.query_width);
430 mkws.config.query_width = 50;
433 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
434 if (mkws.config.pazpar2_url.match(/^\/\//)) {
435 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
436 log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
439 if (mkws.config.responsive_design_width) {
440 // Responsive web design - change layout on the fly based on
441 // current screen width. Required for mobile devices.
442 $(window).resize(resizePage);
443 // initial check after page load
444 $(document).ready(resizePage);
447 // Backwards compatibility: set new magic class names on any
448 // elements that have the old magic IDs.
449 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
450 "Results", "Records", "Targets", "Ranking",
451 "Termlists", "Stat", "MOTD" ];
452 for (var i = 0; i < ids.length; i++) {
453 var id = 'mkws' + ids[i];
454 var node = $('#' + id);
455 if (node.attr('id')) {
457 log("added magic class to '" + node.attr('id') + "'");
462 makeWidgetsWithin(1, $(rootsel));
465 log("walking MKWS nodes took " + (now-then) + " ms");
468 for (var tName in mkws.teams) {
469 var myTeam = mkws.teams[tName]
470 log("team '" + tName + "' = " + myTeam + " ...");
471 myTeam.visitWidgets(function(t, w) {
472 log(" has widget of type '" + t + "': " + w);
477 if (mkws.config.use_service_proxy) {
478 authenticateSession(mkws.config.service_proxy_auth,
479 mkws.config.service_proxy_auth_domain,
480 mkws.config.pazpar2_url);
486 $(document).ready(function() {
487 var widgetSelector = selectorForAllWidgets();
488 if (widgetSelector && $(widgetSelector).length !== 0) init();