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