correct danish translation
[mkws-moved-to-github.git] / src / mkws-core.js
1 /*! MKWS, the MasterKey Widget Set.
2  *  Copyright (C) 2013-2015 Index Data
3  *  See the file LICENSE for details
4  */
5
6 "use strict";
7
8
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.
11 //
12 // We set it as a property of window to make the global explicit as
13 // some things complain about an implicit global.
14 window.mkws = {
15   $: $, // Our own local copy of the jQuery object
16   authenticated: false,
17   authenticating: false,
18   active: false,
19   logger: undefined,
20   log_level: "info",
21   teams: {},
22   widgetType2function: {},
23   defaultTemplates: {},
24
25   locale_lang: {
26     "de": {
27       "Authors": "Autoren",
28       "Subjects": "Schlagwörter",
29       "Sources": "Daten und Quellen",
30       "source": "datenquelle",
31       "Facets": "Termlisten",
32       "Next": "Weiter",
33       "Prev": "Zurück",
34       "Search": "Suche",
35       "Sort by": "Sortieren nach",
36       "and show": "und zeige",
37       "per page": "pro Seite",
38       "Displaying": "Zeige",
39       "to": "von",
40       "of": "aus",
41       "found": "gefunden",
42       "Title": "Titel",
43       "Author": "Autor",
44       "author": "autor",
45       "Date": "Datum",
46       "Subject": "Schlagwort",
47       "subject": "schlagwort",
48       "Location": "Bestand",
49       "Locations": "Bestand",
50       "Records": "Datensätze",
51       "Targets": "Datenbanken",
52       "State": "Status",
53       "relevance": "Relevanz",
54       "title": "Titel",
55       "newest": "Neueste",
56       "oldest": "Älteste",
57
58       "dummy": "dummy"
59     },
60
61     "da": {
62       "Authors": "Forfattere",
63       "Subjects": "Emner",
64       "Sources": "Kilder",
65       "source": "kilder",
66       "Facets": "Termlists",
67       "Next": "Næste",
68       "Prev": "Forrige",
69       "Search": "Søg",
70       "Sort by": "Sorter efter",
71       "and show": "og vis",
72       "per page": "per side",
73       "Displaying": "Viser",
74       "to": "til",
75       "of": "ud af",
76       "found": "fandt",
77       "Title": "Title",
78       "Author": "Forfatter",
79       "author": "forfatter",
80       "Date": "Dato",
81       "Subject": "Emneord",
82       "subject": "emneord",
83       "Location": "Lokation",
84       "Locations": "Lokationer",
85       "Records": "Poster",
86       "Targets": "Baser",
87       "State": "Status",
88       "relevance": "Relevans",
89       "title": "Titel",
90       "newest": "Nyeste",
91       "oldest": "Ældste",
92
93       "dummy": "dummy"
94     }
95   }
96 };
97
98 // We may be using a separate copy
99 if (typeof(mkws_jQuery) !== "undefined") {
100   mkws.$ = mkws_jQuery;
101 } else {
102   mkws.$ = jQuery;
103 }
104
105 // It's ridiculous that JSNLog doesn't provide this
106 mkws.stringToLevel = function(s) {
107   if (s === 'trace') {
108     return JL.getTraceLevel();
109   } else if (s === 'debug') {
110     return JL.getDebugLevel();
111   } else if (s === 'info') {
112     return JL.getInfoLevel();
113   } else if (s === 'warn') {
114     return JL.getWarnLevel();
115   } else if (s === 'error') {
116     return JL.getErrorLevel();
117   } else if (s === 'fatal') {
118     return JL.getFatalLevel();
119   } else {
120     throw "bad log-level '" + s + "'";
121   }
122 }
123
124 mkws.logger = JL('mkws');
125 var consoleAppender = JL.createConsoleAppender('consoleAppender');
126 mkws.logger.setOptions({ "appenders": [consoleAppender] });
127
128
129 function _log() {
130   var argsAsARealArray = Array.prototype.slice.call(arguments);
131   var fn = argsAsARealArray.shift();
132   fn.apply(mkws.logger, argsAsARealArray);
133 };
134 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
135 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
136 mkws.info = function(x) { _log(mkws.logger.info, x) };
137 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
138 mkws.error = function(x) { _log(mkws.logger.error, x) };
139 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
140
141
142 // Translation function.
143 mkws.M = function(word) {
144   var lang = mkws.config.lang;
145
146   if (!lang || !mkws.locale_lang[lang])
147     return word;
148
149   return mkws.locale_lang[lang][word] || word;
150 };
151
152
153 // This function is taken from a StackOverflow answer
154 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
155 mkws.getParameterByName = function(name, url) {
156   if (!url) url = location.search;
157   name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
158   var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
159   results = regex.exec(url);
160   return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
161 }
162
163
164 mkws.registerWidgetType = function(name, fn) {
165   if(mkws._old2new.hasOwnProperty(name)) {
166       mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
167       name = mkws._old2new[name];
168   }
169
170   mkws.widgetType2function[name] = fn;
171   mkws.info("registered widget-type '" + name + "'");
172 };
173
174 mkws.aliasWidgetType = function(newName, oldName) {
175   mkws.widgetType2function[newName] = mkws.widgetType2function[oldName];
176   mkws.info("aliased widget-type '" + newName + "' to '" + oldName + "'");
177
178 };
179
180 mkws.promotionFunction = function(name) {
181   return mkws.widgetType2function[name];
182 };
183
184
185 mkws.setMkwsConfig = function(overrides) {
186   var config_default = {
187     use_service_proxy: true,
188     pazpar2_url: undefined,
189     pp2_hostname: "sp-mkws.indexdata.com",
190     pp2_path: "service-proxy/",
191     service_proxy_auth: undefined,
192     sp_auth_path: undefined,
193     sp_auth_query: "command=auth&action=perconfig",
194     sp_auth_credentials: undefined,
195     lang: "",
196     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
197     perpage_options: [10, 20, 30, 50],
198     sort_default: "relevance",
199     perpage_default: 20,
200     show_lang: true,    /* show/hide language menu */
201     show_sort: true,    /* show/hide sort menu */
202     show_perpage: true, /* show/hide perpage menu */
203     show_switch: true,  /* show/hide switch menu */
204     lang_options: [],   /* display languages links for given languages, [] for all */
205     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
206     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
207     log_level: 1,     /* log level for development: 0..2 */
208     template_vars: {}, /* values that may be exposed to templates */
209
210     dummy: "dummy"
211   };
212
213   mkws.config = mkws.objectInheritingFrom(config_default);
214   for (var k in overrides) {
215     mkws.config[k] = overrides[k];
216   }
217 };
218
219
220 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
221 // http://javascript.crockford.com/prototypal.html
222 // mkws.objectInheritingFrom behaves the same as Object.create,
223 // but since the latter is not available in IE8 we can't use it.
224 //
225 mkws.objectInheritingFrom = function(o) {
226   function F() {}
227   F.prototype = o;
228   return new F();
229 }
230
231
232 // The following functions are dispatchers for team methods that
233 // are called from the UI using a team-name rather than implicit
234 // context.
235 mkws.switchView = function(tname, view) {
236   mkws.teams[tname].switchView(view);
237 };
238
239 mkws.showDetails = function(tname, prefixRecId) {
240   mkws.teams[tname].showDetails(prefixRecId);
241 };
242
243 mkws.limitTarget  = function(tname, id, name) {
244   mkws.teams[tname].limitTarget(id, name);
245 };
246
247 mkws.limitQuery  = function(tname, field, value) {
248   mkws.teams[tname].limitQuery(field, value);
249 };
250
251 mkws.limitCategory  = function(tname, id) {
252   mkws.teams[tname].limitCategory(id);
253 };
254
255 mkws.delimitTarget = function(tname, id) {
256   mkws.teams[tname].delimitTarget(id);
257 };
258
259 mkws.delimitQuery = function(tname, field, value) {
260   mkws.teams[tname].delimitQuery(field, value);
261 };
262
263 mkws.showPage = function(tname, pageNum) {
264   mkws.teams[tname].showPage(pageNum);
265 };
266
267 mkws.pagerPrev = function(tname) {
268   mkws.teams[tname].pagerPrev();
269 };
270
271 mkws.pagerNext = function(tname) {
272   mkws.teams[tname].pagerNext();
273 };
274
275
276 mkws.pazpar2_url = function() {
277   if (mkws.config.pazpar2_url) {
278     mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
279     return mkws.config.pazpar2_url;
280   } else {
281     var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
282     mkws.info("generated pazpar2_url '" + s + "'");
283     return s;
284   }
285 };
286
287
288 // We put a session token in window.name, as it's the only place to
289 // keep data that is preserved across reloads and within-site
290 // navigation. pz2.js picks this up and uses it as part of the
291 // cookie-name, to ensure we get a new session when we need one.
292 //
293 // We want to use different sessions for different windows/tabs (so
294 // they don't receive each other's messages), different hosts and
295 // different paths on a host (since in general these will
296 // authenticate as different libraries). So the window name needs to
297 // include the hostname and the path from the URL, plus the token.
298 //
299 var token;
300 if (window.name) {
301   token = window.name.replace(/.*\//, '');
302   mkws.debug("Reusing existing window token '" + token + "'");
303 } else {
304   // Incredible that the standard JavaScript runtime doesn't define a
305   // unique windowId. Instead, we have to make one up. And since there's
306   // no global area shared between windows, the best we can do for
307   // ensuring uniqueness is generating a random ID and crossing our
308   // fingers.
309   //
310   // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
311   // At one per second, it will take 116 million years to duplicate a token
312   token = Math.random().toString(36).slice(2, 12);
313   mkws.debug("Generated new window token '" + token + "'");
314 }
315
316 window.name = window.location.hostname + window.location.pathname + '/' + token;
317 mkws.info("Using window.name '" + window.name + "'");
318
319
320 // wrapper to provide local copy of the jQuery object.
321 (function($) {
322   var _old2new = { // Maps old-style widget names to new-style
323     'Authname': 'auth-name',
324     'ConsoleBuilder': 'console-builder',
325     'Coverart': 'cover-art',
326     'GoogleImage': 'google-image',
327     'MOTD': 'motd',
328     'MOTDContainer': 'motd-container',
329     'Perpage': 'per-page',
330     'SearchForm': 'search-form',
331     'ReferenceUniverse': 'reference-universe',
332     'Termlists': 'facets'
333   };
334   // Annoyingly, there is no built-in way to invert a hash
335   var _new2old = {};
336   for (var key in _old2new) {
337     if(_old2new.hasOwnProperty(key)) {
338       _new2old[_old2new[key]] = key;
339     }
340   }
341
342   mkws._old2new = _old2new;
343
344   function handleNodeWithTeam(node, callback) {
345     // First branch for DOM objects; second branch for jQuery objects
346     var classes = node.className || node.attr('class');
347     if (!classes) {
348       // For some reason, if we try to proceed when classes is
349       // undefined, we don't get an error message, but this
350       // function and its callers, up several stack level,
351       // silently return. What a crock.
352       mkws.fatal("handleNodeWithTeam() called on node with no classes");
353       return;
354     }
355     var list = classes.split(/\s+/)
356     var teamName, type;
357
358     for (var i = 0; i < list.length; i++) {
359       var cname = list[i];
360       if (cname.match(/^mkws-team-/)) {
361         // New-style teamnames of the form mkws-team-xyz
362         teamName = cname.replace(/^mkws-team-/, '');
363       } else if (cname.match(/^mkwsTeam_/)) {
364         // Old-style teamnames of the form mkwsTeam_xyz
365         teamName = cname.replace(/^mkwsTeam_/, '');
366       } else if (cname.match(/^mkws-/)) {
367         // New-style names of the from mkws-foo-bar
368         type = cname.replace(/^mkws-/, '');
369       } else if (cname.match(/^mkws/)) {
370         // Old-style names of the form mkwsFooBar
371         var tmp = cname.replace(/^mkws/, '');
372         type = _old2new[tmp] || tmp.toLowerCase();
373       }
374     }
375
376     // Widgets without a team are on team "AUTO"
377     if (!teamName) {
378       teamName = "AUTO";
379       // Autosearch widgets don't join team AUTO if there is already an
380       // autosearch on the team or the team has otherwise gotten a query
381       if (node.getAttribute("autosearch")) {
382         if (mkws.autoHasAuto ||
383             mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
384           mkws.warn("AUTO team already has a query, using unique team");
385           teamName = "UNIQUE";
386         }
387         mkws.autoHasAuto = true;
388       }
389     }
390
391     // Widgets on team "UNIQUE" get a random team
392     if (teamName === "UNIQUE") {
393       teamName = Math.floor(Math.random() * 100000000).toString();
394     }
395
396     callback.call(node, teamName, type);
397   }
398
399
400   function resizePage() {
401     var threshhold = mkws.config.responsive_design_width;
402     var width = $(window).width();
403     var from, to, method;
404
405     if ((mkws.width === undefined || mkws.width > threshhold) &&
406         width <= threshhold) {
407       from = "wide"; to = "narrow"; method = "hide";
408     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
409                width > threshhold) {
410       from = "narrow"; to = "wide"; method = "show";
411     }
412     mkws.width = width;
413
414     if (from) {
415       mkws.info("changing from " + from + " to " + to + ": " + width);
416       for (var tname in mkws.teams) {
417         var team = mkws.teams[tname];
418         team.visitWidgets(function(t, w) {
419           var w1 = team.widget(t + "-container-" + from);
420           var w2 = team.widget(t + "-container-" + to);
421           if (w1) {
422             w1.node.hide();
423           }
424           if (w2) {
425             w2.node.show();
426             w.node.appendTo(w2.node);
427           }
428         });
429         team.queue("resize-" + to).publish();
430       }
431     }
432   };
433
434
435   /*
436    * Run service-proxy authentication in background (after page load).
437    * The username/password is configured in the apache config file
438    * for the site.
439    */
440   function authenticateSession(auth_url, auth_domain, pp2_url) {
441     mkws.authenticating = true;
442     mkws.info("service proxy authentication on URL: " + auth_url);
443
444     if (!auth_domain) {
445       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
446       mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
447     }
448
449     var request = new pzHttpRequest(auth_url, function(err) {
450       alert("HTTP call for authentication failed: " + err)
451       return;
452     }, auth_domain);
453
454     request.get(null, function(data) {
455       mkws.authenticating = false;
456       if (!$.isXMLDoc(data)) {
457         alert("Service Proxy authentication response is not a valid XML document");
458         return;
459       }
460       var status = $(data).find("status");
461       if (status.text() != "OK") {
462         var message = $(data).find("message");
463         alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
464         return;
465       }
466
467       mkws.info("service proxy authentication successful");
468       mkws.authenticated = true;
469       var authName = $(data).find("displayName").text();
470       // You'd think there would be a better way to do this:
471       var realm = $(data).find("realm:not(realmAttributes realm)").text();
472       for (var teamName in mkws.teams) {
473         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
474       }
475
476       runAutoSearches();
477     });
478   }
479
480
481   function runAutoSearches() {
482     mkws.info("running auto searches");
483
484     for (var teamName in mkws.teams) {
485       mkws.teams[teamName].queue("ready").publish();
486     }
487   }
488
489
490   function selectorForAllWidgets() {
491     if (mkws.config && mkws.config.scan_all_nodes) {
492       // This is the old version, which works by telling jQuery to
493       // find every node that has a class beginning with "mkws". In
494       // theory it should be slower than the class-based selector; but
495       // instrumentation suprisingly shows this is consistently
496       // faster. It also has the advantage that any widgets of
497       // non-registered types are logged as warnings rather than
498       // silently ignored.
499       return '[class^="mkws"],[class*=" mkws"]';
500     } else {
501       // This is the new version, which works by looking up the
502       // specific classes of all registered widget types and their
503       // resize containers. Because all it requires jQuery to do is
504       // some hash lookups in pre-built tables, it should be very
505       // fast; but it silently ignores widgets of unregistered types.
506       var s = "";
507       for (var type in mkws.widgetType2function) {
508         if (s) s += ',';
509         s += '.mkws-' + type;
510         s += ',.mkws-' + type + "-container-wide";
511         s += ',.mkws-' + type + "-container-narrow";
512         // Annoyingly, we also need to recognise old-style names
513         var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
514         s += ',.mkws' + oldtype;
515         s += ',.mkws' + oldtype + "-Container-wide";
516         s += ',.mkws' + oldtype + "-Container-narrow";
517       }
518       return s;
519     }
520   }
521
522
523   function makeWidgetsWithin(level, node) {
524     if (node) var widgetNodes = node.find(selectorForAllWidgets());
525     else widgetNodes = $(selectorForAllWidgets());
526     // Return false if we parse no widgets
527     if (widgetNodes.length < 1) return false;
528     widgetNodes.each(function() {
529       handleNodeWithTeam(this, function(tname, type) {
530         var myTeam = mkws.teams[tname];
531         if (!myTeam) {
532           myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
533         }
534
535         var oldHTML = this.innerHTML;
536         var myWidget = mkws.makeWidget($, myTeam, type, this);
537         myTeam.addWidget(myWidget);
538         var newHTML = this.innerHTML;
539         if (newHTML !== oldHTML) {
540           myTeam.info("widget " + type + " HTML changed: reparsing");
541           makeWidgetsWithin(level+1, $(this));
542         }
543       });
544     });
545     return true;
546   }
547
548
549   // The second "rootsel" parameter is passed to jQuery and is a DOM node
550   // or a selector string you would like to constrain the search for widgets to.
551   //
552   // This function has no side effects if run again on an operating session,
553   // even if the element/selector passed causes existing widgets to be reparsed:
554   //
555   // (TODO: that last bit isn't true and we currently have to avoid reinitialising
556   // widgets, MKWS-261)
557   //
558   // * configuration is not regenerated
559   // * authentication is not performed again
560   // * autosearches are not re-run
561   mkws.init = function(message, rootsel) {
562     var greet = "MKWS initialised";
563     if (rootsel) greet += " (limited to " + rootsel + ")"
564     if (message) greet += " :: " + message;
565     mkws.info(greet);
566
567     // MKWS is not active until init() has been run against an object with widget nodes.
568     // We only set initial configuration when MKWS is first activated.
569     if (!mkws.isActive) {
570       var widgetSelector = selectorForAllWidgets();
571       if ($(widgetSelector).length < 1) {
572         mkws.warn("no widgets found");
573         return;
574       }
575
576       // Initial configuration
577       mkws.autoHasAuto = false;
578       var saved_config;
579       if (typeof mkws_config === 'undefined') {
580         mkws.info("setting empty config");
581         saved_config = {};
582       } else {
583         mkws.info("using config: " + $.toJSON(mkws_config));
584         saved_config = mkws_config;
585       }
586       mkws.setMkwsConfig(saved_config);
587
588       for (var key in mkws.config) {
589         if (mkws.config.hasOwnProperty(key)) {
590           if (key.match(/^language_/)) {
591             var lang = key.replace(/^language_/, "");
592             // Copy custom languages into list
593             mkws.locale_lang[lang] = mkws.config[key];
594             mkws.info("added locally configured language '" + lang + "'");
595           }
596         }
597       }
598
599       var lang = mkws.getParameterByName("lang") || mkws.config.lang;
600       if (!lang || !mkws.locale_lang[lang]) {
601         mkws.config.lang = ""
602       } else {
603         mkws.config.lang = lang;
604       }
605
606       mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
607
608       // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
609       if (mkws.pazpar2_url().match(/^\/\//)) {
610         mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
611         mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
612       }
613
614       if (mkws.config.responsive_design_width) {
615         // Responsive web design - change layout on the fly based on
616         // current screen width. Required for mobile devices.
617         $(window).resize(resizePage);
618         // initial check after page load
619         $(document).ready(resizePage);
620       }
621     }
622
623     var then = $.now();
624     // If we've made no widgets, return without starting an SP session
625     // or marking MKWS active.
626     if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
627       return false;
628     }
629     var now = $.now();
630
631     mkws.info("walking MKWS nodes took " + (now-then) + " ms");
632     for (var tName in mkws.teams) {
633       var myTeam = mkws.teams[tName]
634       myTeam.makePz2();
635       myTeam.info("made PZ2 object");
636       /*
637         myTeam.visitWidgets(function(t, w) {
638           mkws.debug("  has widget of type '" + t + "': " + w);
639         });
640       */
641     }
642
643     function sp_auth_url(config) {
644       if (config.service_proxy_auth) {
645         mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
646         return config.service_proxy_auth;
647       } else {
648         var s = '//';
649         s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
650         s += '/';
651         s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
652         var q = config.sp_auth_query;
653         if (q) {
654           s += '?' + q;
655         }
656         var c = config.sp_auth_credentials;
657         if (c) {
658           s += ('&username=' + c.substr(0, c.indexOf('/')) +
659                 '&password=' + c.substr(c.indexOf('/')+1));
660         }
661         mkws.info("generated sp_auth_url '" + s + "'");
662         return s;
663       }
664     }
665
666     if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
667       authenticateSession(sp_auth_url(mkws.config),
668                           mkws.config.service_proxy_auth_domain,
669                           mkws.pazpar2_url());
670     } else if (!mkws.authenticating) {
671       // raw pp2 or we have a session already open
672       runAutoSearches();
673       for (var teamName in mkws.teams) {
674         mkws.teams[teamName].queue("authenticated").publish();
675       }
676     }
677
678     mkws.isActive = true;
679     return true;
680   };
681
682   $(document).ready(function() {
683     if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
684        mkws.init();
685     }
686   });
687
688   // Set global log_level flag early so that _log() works
689   if (typeof mkws_config !== 'undefined') {
690     var tmp = mkws_config.log_level;
691     if (typeof tmp !== 'undefined') {
692       mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });
693     }
694   }
695 })(mkws.$);