Merge branch 'master' into templateallthemarkup
[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   log_level: 1, // Will be overridden from mkws.config, but
18                 // initial value allows jQuery popup to use logging.
19   teams: {},
20   widgetType2function: {},
21   defaultTemplates: {},
22
23   locale_lang: {
24     "de": {
25       "Authors": "Autoren",
26       "Subjects": "Schlagwörter",
27       "Sources": "Daten und Quellen",
28       "source": "datenquelle",
29       "Termlists": "Termlisten",
30       "Next": "Weiter",
31       "Prev": "Zurück",
32       "Search": "Suche",
33       "Sort by": "Sortieren nach",
34       "and show": "und zeige",
35       "per page": "pro Seite",
36       "Displaying": "Zeige",
37       "to": "von",
38       "of": "aus",
39       "found": "gefunden",
40       "Title": "Titel",
41       "Author": "Autor",
42       "author": "autor",
43       "Date": "Datum",
44       "Subject": "Schlagwort",
45       "subject": "schlagwort",
46       "Location": "Ort",
47       "Records": "Datensätze",
48       "Targets": "Datenbanken",
49
50       "dummy": "dummy"
51     },
52
53     "da": {
54       "Authors": "Forfattere",
55       "Subjects": "Emner",
56       "Sources": "Kilder",
57       "source": "kilder",
58       "Termlists": "Termlists",
59       "Next": "Næste",
60       "Prev": "Forrige",
61       "Search": "Søg",
62       "Sort by": "Sorter efter",
63       "and show": "og vis",
64       "per page": "per side",
65       "Displaying": "Viser",
66       "to": "til",
67       "of": "ud af",
68       "found": "fandt",
69       "Title": "Title",
70       "Author": "Forfatter",
71       "author": "forfatter",
72       "Date": "Dato",
73       "Subject": "Emneord",
74       "subject": "emneord",
75       "Location": "Lokation",
76       "Records": "Poster",
77       "Targets": "Baser",
78
79       "dummy": "dummy"
80     }
81   }
82 };
83
84 // We may be using a separate copy
85 if (typeof(mkws_jQuery) !== "undefined") {
86   mkws.$ = mkws_jQuery;
87 } else {
88   mkws.$ = jQuery;
89 }
90
91 mkws.log = function(string) {
92   if (!mkws.log_level)
93     return;
94
95   if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
96     return;
97   }
98
99   // you need to disable use strict at the top of the file!!!
100   if (mkws.log_level >= 3) {
101     // Works in Chrome; not sure about elsewhere
102     console.trace();
103   } else if (mkws.log_level >= 2) {
104     console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
105   }
106   console.log(string);
107 };
108
109
110 // Incredible that the standard JavaScript runtime doesn't define a
111 // unique windowId. Instead, we have to make one up. And since there's
112 // no global area shared between windows, the best we can do for
113 // ensuring uniqueness is generating a random ID and crossing our
114 // fingers. We stash this in window.name, as it's the only place to
115 // keep data that is preserved across reloads and within-site
116 // navigation. pz2.js picks this up and uses it as part of the
117 // cookie-name, to ensure each tab gets its own session.
118 if (window.name) {
119   mkws.log("Using existing window.name '" + window.name + "'");
120 } else {
121   // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
122   // At one per second, it will take 116 million years to duplicate a session
123   window.name = Math.random().toString(36).slice(2, 12);
124   mkws.log("Generated new window.name '" + window.name + "'");
125 }
126
127
128 // Translation function.
129 mkws.M = function(word) {
130   var lang = mkws.config.lang;
131
132   if (!lang || !mkws.locale_lang[lang])
133     return word;
134
135   return mkws.locale_lang[lang][word] || word;
136 };
137
138
139 // This function is taken from a StackOverflow answer
140 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
141 mkws.getParameterByName = function(name, url) {
142   if (!url) url = location.search;
143   name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
144   var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
145   results = regex.exec(url);
146   return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
147 }
148
149
150 mkws.registerWidgetType = function(name, fn) {
151   mkws.widgetType2function[name] = fn;
152   mkws.log("registered widget-type '" + name + "'");
153 };
154
155 mkws.promotionFunction = function(name) {
156   return mkws.widgetType2function[name];
157 };
158
159
160 mkws.setMkwsConfig = function(overrides) {
161   // Set global log_level flag early so that mkws.log() works
162   // Fall back to old "debug_level" setting for backwards compatibility
163   var tmp = overrides.log_level;
164   if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
165   if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
166
167   var config_default = {
168     use_service_proxy: true,
169     pazpar2_url:        "//mkws.indexdata.com/service-proxy/",
170     service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
171     lang: "",
172     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
173     perpage_options: [10, 20, 30, 50],
174     sort_default: "relevance",
175     perpage_default: 20,
176     query_width: 50,
177     show_lang: true,    /* show/hide language menu */
178     show_sort: true,    /* show/hide sort menu */
179     show_perpage: true, /* show/hide perpage menu */
180     show_switch: true,  /* show/hide switch menu */
181     lang_options: [],   /* display languages links for given languages, [] for all */
182     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
183     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
184     log_level: 1,     /* log level for development: 0..2 */
185     template_vars: {}, /* values that may be exposed to templates */
186
187     dummy: "dummy"
188   };
189
190   mkws.config = mkws.objectInheritingFrom(config_default);
191   for (var k in overrides) {
192     mkws.config[k] = overrides[k];
193   }
194 };
195
196
197 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
198 // http://javascript.crockford.com/prototypal.html
199 // mkws.objectInheritingFrom behaves the same as Object.create,
200 // but since the latter is not available in IE8 we can't use it.
201 //
202 mkws.objectInheritingFrom = function(o) {
203   function F() {}
204   F.prototype = o;
205   return new F();
206 }
207
208
209 // The following functions are dispatchers for team methods that
210 // are called from the UI using a team-name rather than implicit
211 // context.
212 mkws.switchView = function(tname, view) {
213   mkws.teams[tname].switchView(view);
214 };
215
216 mkws.showDetails = function(tname, prefixRecId) {
217   mkws.teams[tname].showDetails(prefixRecId);
218 };
219
220 mkws.limitTarget  = function(tname, id, name) {
221   mkws.teams[tname].limitTarget(id, name);
222 };
223
224 mkws.limitQuery  = function(tname, field, value) {
225   mkws.teams[tname].limitQuery(field, value);
226 };
227
228 mkws.limitCategory  = function(tname, id) {
229   mkws.teams[tname].limitCategory(id);
230 };
231
232 mkws.delimitTarget = function(tname, id) {
233   mkws.teams[tname].delimitTarget(id);
234 };
235
236 mkws.delimitQuery = function(tname, field, value) {
237   mkws.teams[tname].delimitQuery(field, value);
238 };
239
240 mkws.showPage = function(tname, pageNum) {
241   mkws.teams[tname].showPage(pageNum);
242 };
243
244 mkws.pagerPrev = function(tname) {
245   mkws.teams[tname].pagerPrev();
246 };
247
248 mkws.pagerNext = function(tname) {
249   mkws.teams[tname].pagerNext();
250 };
251
252
253 // wrapper to provide local copy of the jQuery object.
254 (function($) {
255   var log = mkws.log;
256
257   function handleNodeWithTeam(node, callback) {
258     // First branch for DOM objects; second branch for jQuery objects
259     var classes = node.className || node.attr('class');
260     if (!classes) {
261       // For some reason, if we try to proceed when classes is
262       // undefined, we don't get an error message, but this
263       // function and its callers, up several stack level,
264       // silently return. What a crock.
265       log("handleNodeWithTeam() called on node with no classes");
266       return;
267     }
268     var list = classes.split(/\s+/)
269     var teamName, type;
270
271     for (var i = 0; i < list.length; i++) {
272       var cname = list[i];
273       if (cname.match(/^mkwsTeam_/)) {
274         teamName = cname.replace(/^mkwsTeam_/, '');
275       } else if (cname.match(/^mkws/)) {
276         type = cname.replace(/^mkws/, '');
277       }
278     }
279
280     // Widgets without a team are on team "AUTO"
281     if (!teamName) {
282       teamName = "AUTO";
283       // Autosearch widgets don't join team AUTO if there is already an
284       // autosearch on the team or the team has otherwise gotten a query
285       if (node.hasAttribute("autosearch")) {
286         if (mkws.autoHasAuto ||
287             mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
288           log("AUTO team already has a query, using unique team");
289           teamName = "UNIQUE";
290         }
291         mkws.autoHasAuto = true;
292       }
293     }
294
295     // Widgets on team "UNIQUE" get a random team
296     if (teamName === "UNIQUE") {
297       teamName = Math.floor(Math.random() * 100000000).toString();
298     }
299
300     callback.call(node, teamName, type);
301   }
302
303
304   function resizePage() {
305     var threshhold = mkws.config.responsive_design_width;
306     var width = $(window).width();
307     var from, to, method;
308
309     if ((mkws.width === undefined || mkws.width > threshhold) &&
310         width <= threshhold) {
311       from = "wide"; to = "narrow"; method = "hide";
312     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
313                width > threshhold) {
314       from = "narrow"; to = "wide"; method = "show";
315     }
316     mkws.width = width;
317
318     if (from) {
319       log("changing from " + from + " to " + to + ": " + width);
320       for (var tname in mkws.teams) {
321         var team = mkws.teams[tname];
322         team.visitWidgets(function(t, w) {
323           var w1 = team.widget(t + "-Container-" + from);
324           var w2 = team.widget(t + "-Container-" + to);
325           if (w1) {
326             w1.node.hide();
327           }
328           if (w2) {
329             w2.node.show();
330             w.node.appendTo(w2.node);
331           }
332         });
333         team.queue("resize-" + to).publish();
334       }
335     }
336   };
337
338
339   /*
340    * Run service-proxy authentication in background (after page load).
341    * The username/password is configured in the apache config file
342    * for the site.
343    */
344   function authenticateSession(auth_url, auth_domain, pp2_url) {
345     log("service proxy authentication on URL: " + auth_url);
346
347     if (!auth_domain) {
348       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
349       log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
350     }
351
352     var request = new pzHttpRequest(auth_url, function(err) {
353       alert("HTTP call for authentication failed: " + err)
354       return;
355     }, auth_domain);
356
357     request.get(null, function(data) {
358       if (!$.isXMLDoc(data)) {
359         alert("Service Proxy authentication response is not a valid XML document");
360         return;
361       }
362       var status = $(data).find("status");
363       if (status.text() != "OK") {
364         var message = $(data).find("message");
365         alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
366         return;
367       }
368
369       log("service proxy authentication successful");
370       mkws.authenticated = true;
371       var authName = $(data).find("displayName").text();
372       // You'd think there would be a better way to do this:
373       var realm = $(data).find("realm:not(realmAttributes realm)").text();
374       for (var teamName in mkws.teams) {
375         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
376       }
377
378       runAutoSearches();
379     });
380   }
381
382
383   function runAutoSearches() {
384     log("running auto searches");
385
386     for (var teamName in mkws.teams) {
387       mkws.teams[teamName].queue("ready").publish();
388     }
389   }
390
391
392   function selectorForAllWidgets() {
393     if (mkws.config && mkws.config.scan_all_nodes) {
394       // This is the old version, which works by telling jQuery to
395       // find every node that has a class beginning with "mkws". In
396       // theory it should be slower than the class-based selector; but
397       // instrumentation suprisnigly shows this is consistently
398       // faster. It also has the advantage that any widgets of
399       // non-registered types are logged as warnings rather than
400       // silently ignored.
401       return '[class^="mkws"],[class*=" mkws"]';
402     } else {
403       // This is the new version, which works by looking up the
404       // specific classes of all registered widget types and their
405       // resize containers. Because all it requires jQuery to do is
406       // some hash lookups in pre-built tables, it should be very
407       // fast; but it silently ignores widgets of unregistered types.
408       var s = "";
409       for (var type in mkws.widgetType2function) {
410         if (s) s += ',';
411         s += '.mkws' + type;
412         s += ',.mkws' + type + "-Container-wide";
413         s += ',.mkws' + type + "-Container-narrow";
414       }
415       return s;
416     }
417   }
418
419
420   function makeWidgetsWithin(level, node) {
421     node.find(selectorForAllWidgets()).each(function() {
422       handleNodeWithTeam(this, function(tname, type) {
423         var myTeam = mkws.teams[tname];
424         if (!myTeam) {
425           myTeam = mkws.teams[tname] = team($, tname);
426           log("made MKWS team '" + tname + "'");
427         }
428
429         var oldHTML = this.innerHTML;
430         var myWidget = widget($, myTeam, type, this);
431         myTeam.addWidget(myWidget);
432         var newHTML = this.innerHTML;
433         if (newHTML !== oldHTML) {
434           log("widget " + tname + ":" + type + " HTML changed: reparsing");
435           makeWidgetsWithin(level+1, $(this));
436         }
437       });
438     });
439   }
440
441
442   function init(rootsel) {
443     mkws.autoHasAuto = false;
444     if (!rootsel) var rootsel = ':root';
445     var saved_config;
446     if (typeof mkws_config === 'undefined') {
447       log("setting empty config");
448       saved_config = {};
449     } else {
450       log("using config: " + $.toJSON(mkws_config));
451       saved_config = mkws_config;
452     }
453     mkws.setMkwsConfig(saved_config);
454
455     for (var key in mkws.config) {
456       if (mkws.config.hasOwnProperty(key)) {
457         if (key.match(/^language_/)) {
458           var lang = key.replace(/^language_/, "");
459           // Copy custom languages into list
460           mkws.locale_lang[lang] = mkws.config[key];
461           log("added locally configured language '" + lang + "'");
462         }
463       }
464     }
465
466     var lang = mkws.getParameterByName("lang") || mkws.config.lang;
467     if (!lang || !mkws.locale_lang[lang]) {
468       mkws.config.lang = ""
469     } else {
470       mkws.config.lang = lang;
471     }
472
473     log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
474
475     if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
476       log("reset query width to " + mkws.config.query_width);
477       mkws.config.query_width = 50;
478     }
479
480     // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
481     if (mkws.config.pazpar2_url.match(/^\/\//)) {
482       mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
483       log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
484     }
485
486     if (mkws.config.responsive_design_width) {
487       // Responsive web design - change layout on the fly based on
488       // current screen width. Required for mobile devices.
489       $(window).resize(resizePage);
490       // initial check after page load
491       $(document).ready(resizePage);
492     }
493
494     // Backwards compatibility: set new magic class names on any
495     // elements that have the old magic IDs.
496     var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
497                 "Results", "Records", "Targets", "Ranking",
498                 "Termlists", "Stat", "MOTD" ];
499     for (var i = 0; i < ids.length; i++) {
500       var id = 'mkws' + ids[i];
501       var node = $('#' + id);
502       if (node.attr('id')) {
503         node.addClass(id);
504         log("added magic class to '" + node.attr('id') + "'");
505       }
506     }
507
508     var then = $.now();
509     makeWidgetsWithin(1, $(rootsel));
510     var now = $.now();
511
512     log("walking MKWS nodes took " + (now-then) + " ms");
513
514     /*
515       for (var tName in mkws.teams) {
516       var myTeam = mkws.teams[tName]
517       log("team '" + tName + "' = " + myTeam + " ...");
518       myTeam.visitWidgets(function(t, w) {
519       log("  has widget of type '" + t + "': " + w);
520       });
521       }
522     */
523
524     if (mkws.config.use_service_proxy) {
525       authenticateSession(mkws.config.service_proxy_auth,
526                           mkws.config.service_proxy_auth_domain,
527                           mkws.config.pazpar2_url);
528     } else {
529       // raw pp2
530       runAutoSearches();
531     }
532   };
533   $(document).ready(function() {
534     var widgetSelector = selectorForAllWidgets();
535     if (widgetSelector && $(widgetSelector).length !== 0) init();
536   });
537 })(mkws.$);