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