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