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