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