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   active: false,
18   log_level: 1, // Will be overridden from mkws.config, but
19                 // initial value allows jQuery popup to use logging.
20   teams: {},
21   widgetType2function: {},
22   defaultTemplates: {},
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:        "//mkws.indexdata.com/service-proxy/",
171     service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
172     lang: "",
173     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
174     perpage_options: [10, 20, 30, 50],
175     sort_default: "relevance",
176     perpage_default: 20,
177     query_width: 50,
178     show_lang: true,    /* show/hide language menu */
179     show_sort: true,    /* show/hide sort menu */
180     show_perpage: true, /* show/hide perpage menu */
181     show_switch: true,  /* show/hide switch menu */
182     lang_options: [],   /* display languages links for given languages, [] for all */
183     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
184     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
185     log_level: 1,     /* log level for development: 0..2 */
186     template_vars: {}, /* values that may be exposed to templates */
187
188     dummy: "dummy"
189   };
190
191   mkws.config = mkws.objectInheritingFrom(config_default);
192   for (var k in overrides) {
193     mkws.config[k] = overrides[k];
194   }
195 };
196
197
198 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
199 // http://javascript.crockford.com/prototypal.html
200 // mkws.objectInheritingFrom behaves the same as Object.create,
201 // but since the latter is not available in IE8 we can't use it.
202 //
203 mkws.objectInheritingFrom = function(o) {
204   function F() {}
205   F.prototype = o;
206   return new F();
207 }
208
209
210 // The following functions are dispatchers for team methods that
211 // are called from the UI using a team-name rather than implicit
212 // context.
213 mkws.switchView = function(tname, view) {
214   mkws.teams[tname].switchView(view);
215 };
216
217 mkws.showDetails = function(tname, prefixRecId) {
218   mkws.teams[tname].showDetails(prefixRecId);
219 };
220
221 mkws.limitTarget  = function(tname, id, name) {
222   mkws.teams[tname].limitTarget(id, name);
223 };
224
225 mkws.limitQuery  = function(tname, field, value) {
226   mkws.teams[tname].limitQuery(field, value);
227 };
228
229 mkws.limitCategory  = function(tname, id) {
230   mkws.teams[tname].limitCategory(id);
231 };
232
233 mkws.delimitTarget = function(tname, id) {
234   mkws.teams[tname].delimitTarget(id);
235 };
236
237 mkws.delimitQuery = function(tname, field, value) {
238   mkws.teams[tname].delimitQuery(field, value);
239 };
240
241 mkws.showPage = function(tname, pageNum) {
242   mkws.teams[tname].showPage(pageNum);
243 };
244
245 mkws.pagerPrev = function(tname) {
246   mkws.teams[tname].pagerPrev();
247 };
248
249 mkws.pagerNext = function(tname) {
250   mkws.teams[tname].pagerNext();
251 };
252
253
254 // wrapper to provide local copy of the jQuery object.
255 (function($) {
256   var log = mkws.log;
257
258   function handleNodeWithTeam(node, callback) {
259     // First branch for DOM objects; second branch for jQuery objects
260     var classes = node.className || node.attr('class');
261     if (!classes) {
262       // For some reason, if we try to proceed when classes is
263       // undefined, we don't get an error message, but this
264       // function and its callers, up several stack level,
265       // silently return. What a crock.
266       log("handleNodeWithTeam() called on node with no classes");
267       return;
268     }
269     var list = classes.split(/\s+/)
270     var teamName, type;
271
272     for (var i = 0; i < list.length; i++) {
273       var cname = list[i];
274       if (cname.match(/^mkwsTeam_/)) {
275         teamName = cname.replace(/^mkwsTeam_/, '');
276       } else if (cname.match(/^mkws/)) {
277         type = cname.replace(/^mkws/, '');
278       }
279     }
280
281     // Widgets without a team are on team "AUTO"
282     if (!teamName) {
283       teamName = "AUTO";
284       // Autosearch widgets don't join team AUTO if there is already an
285       // autosearch on the team or the team has otherwise gotten a query
286       if (node.hasAttribute("autosearch")) {
287         if (mkws.autoHasAuto ||
288             mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
289           log("AUTO team already has a query, using unique team");
290           teamName = "UNIQUE";
291         }
292         mkws.autoHasAuto = true;
293       }
294     }
295
296     // Widgets on team "UNIQUE" get a random team
297     if (teamName === "UNIQUE") {
298       teamName = Math.floor(Math.random() * 100000000).toString();
299     }
300
301     callback.call(node, teamName, type);
302   }
303
304
305   function resizePage() {
306     var threshhold = mkws.config.responsive_design_width;
307     var width = $(window).width();
308     var from, to, method;
309
310     if ((mkws.width === undefined || mkws.width > threshhold) &&
311         width <= threshhold) {
312       from = "wide"; to = "narrow"; method = "hide";
313     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
314                width > threshhold) {
315       from = "narrow"; to = "wide"; method = "show";
316     }
317     mkws.width = width;
318
319     if (from) {
320       log("changing from " + from + " to " + to + ": " + width);
321       for (var tname in mkws.teams) {
322         var team = mkws.teams[tname];
323         team.visitWidgets(function(t, w) {
324           var w1 = team.widget(t + "-Container-" + from);
325           var w2 = team.widget(t + "-Container-" + to);
326           if (w1) {
327             w1.node.hide();
328           }
329           if (w2) {
330             w2.node.show();
331             w.node.appendTo(w2.node);
332           }
333         });
334         team.queue("resize-" + to).publish();
335       }
336     }
337   };
338
339
340   /*
341    * Run service-proxy authentication in background (after page load).
342    * The username/password is configured in the apache config file
343    * for the site.
344    */
345   function authenticateSession(auth_url, auth_domain, pp2_url) {
346     log("service proxy authentication on URL: " + auth_url);
347
348     if (!auth_domain) {
349       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
350       log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
351     }
352
353     var request = new pzHttpRequest(auth_url, function(err) {
354       alert("HTTP call for authentication failed: " + err)
355       return;
356     }, auth_domain);
357
358     request.get(null, function(data) {
359       if (!$.isXMLDoc(data)) {
360         alert("Service Proxy authentication response is not a valid XML document");
361         return;
362       }
363       var status = $(data).find("status");
364       if (status.text() != "OK") {
365         var message = $(data).find("message");
366         alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
367         return;
368       }
369
370       log("service proxy authentication successful");
371       mkws.authenticated = true;
372       var authName = $(data).find("displayName").text();
373       // You'd think there would be a better way to do this:
374       var realm = $(data).find("realm:not(realmAttributes realm)").text();
375       for (var teamName in mkws.teams) {
376         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
377       }
378
379       runAutoSearches();
380     });
381   }
382
383
384   function runAutoSearches() {
385     log("running auto searches");
386
387     for (var teamName in mkws.teams) {
388       mkws.teams[teamName].queue("ready").publish();
389     }
390   }
391
392
393   function selectorForAllWidgets() {
394     if (mkws.config && mkws.config.scan_all_nodes) {
395       // This is the old version, which works by telling jQuery to
396       // find every node that has a class beginning with "mkws". In
397       // theory it should be slower than the class-based selector; but
398       // instrumentation suprisnigly shows this is consistently
399       // faster. It also has the advantage that any widgets of
400       // non-registered types are logged as warnings rather than
401       // silently ignored.
402       return '[class^="mkws"],[class*=" mkws"]';
403     } else {
404       // This is the new version, which works by looking up the
405       // specific classes of all registered widget types and their
406       // resize containers. Because all it requires jQuery to do is
407       // some hash lookups in pre-built tables, it should be very
408       // fast; but it silently ignores widgets of unregistered types.
409       var s = "";
410       for (var type in mkws.widgetType2function) {
411         if (s) s += ',';
412         s += '.mkws' + type;
413         s += ',.mkws' + type + "-Container-wide";
414         s += ',.mkws' + type + "-Container-narrow";
415       }
416       return s;
417     }
418   }
419
420
421   function makeWidgetsWithin(level, node) {
422     if (node) var widgetNodes = node.find(selectorForAllWidgets());
423     else widgetNodes = $(selectorForAllWidgets());
424     // Return false if we parse no widgets
425     if (widgetNodes.length < 1) return false;
426     widgetNodes.each(function() {
427       handleNodeWithTeam(this, function(tname, type) {
428         var myTeam = mkws.teams[tname];
429         if (!myTeam) {
430           myTeam = mkws.teams[tname] = team($, tname);
431           log("made MKWS team '" + tname + "'");
432         }
433
434         var oldHTML = this.innerHTML;
435         var myWidget = widget($, myTeam, type, this);
436         myTeam.addWidget(myWidget);
437         var newHTML = this.innerHTML;
438         if (newHTML !== oldHTML) {
439           log("widget " + tname + ":" + type + " HTML changed: reparsing");
440           makeWidgetsWithin(level+1, $(this));
441         }
442       });
443     });
444     return true;
445   }
446
447
448   // This function should have no side effects if run again on an operating session, even if 
449   // the element/selector passed causes existing widgets to be reparsed: 
450   //
451   // * configuration is not regenerated
452   // * authentication is not performed again
453   // * autosearches are not re-run
454   mkws.init = function(message, rootsel) {
455     if (message) mkws.log(message);
456
457     // TODO: Let's remove this soon
458     // Backwards compatibility: set new magic class names on any
459     // elements that have the old magic IDs.
460     var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
461                 "Results", "Records", "Targets", "Ranking",
462                 "Termlists", "Stat", "MOTD" ];
463     for (var i = 0; i < ids.length; i++) {
464       var id = 'mkws' + ids[i];
465       var node = $('#' + id);
466       if (node.attr('id')) {
467         node.addClass(id);
468         log("added magic class to '" + node.attr('id') + "'");
469       }
470     }
471
472     // MKWS is not active until init() has been run against an object with widget nodes.
473     // We only set initial configuration when MKWS is first activated.
474     if (!mkws.isActive) {
475       var widgetSelector = selectorForAllWidgets();
476       if ($(widgetSelector).length < 1) {
477         mkws.log("no widgets found");
478         return;
479       }
480
481       // Initial configuration
482       mkws.autoHasAuto = false;
483       var saved_config;
484       if (typeof mkws_config === 'undefined') {
485         log("setting empty config");
486         saved_config = {};
487       } else {
488         log("using config: " + $.toJSON(mkws_config));
489         saved_config = mkws_config;
490       }
491       mkws.setMkwsConfig(saved_config);
492
493       for (var key in mkws.config) {
494         if (mkws.config.hasOwnProperty(key)) {
495           if (key.match(/^language_/)) {
496             var lang = key.replace(/^language_/, "");
497             // Copy custom languages into list
498             mkws.locale_lang[lang] = mkws.config[key];
499             log("added locally configured language '" + lang + "'");
500           }
501         }
502       }
503
504       var lang = mkws.getParameterByName("lang") || mkws.config.lang;
505       if (!lang || !mkws.locale_lang[lang]) {
506         mkws.config.lang = ""
507       } else {
508         mkws.config.lang = lang;
509       }
510
511       log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
512
513       if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
514         log("reset query width to " + mkws.config.query_width);
515         mkws.config.query_width = 50;
516       }
517
518       // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
519       if (mkws.config.pazpar2_url.match(/^\/\//)) {
520         mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
521         log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
522       }
523
524       if (mkws.config.responsive_design_width) {
525         // Responsive web design - change layout on the fly based on
526         // current screen width. Required for mobile devices.
527         $(window).resize(resizePage);
528         // initial check after page load
529         $(document).ready(resizePage);
530       }
531     }
532
533     var then = $.now();
534     // If we've made no widgets, return without starting an SP session
535     // or marking MKWS active.
536     if (makeWidgetsWithin(1, rootsel) === false) return false;
537     var now = $.now();
538
539     log("walking MKWS nodes took " + (now-then) + " ms");
540
541     /*
542       for (var tName in mkws.teams) {
543       var myTeam = mkws.teams[tName]
544       log("team '" + tName + "' = " + myTeam + " ...");
545       myTeam.visitWidgets(function(t, w) {
546       log("  has widget of type '" + t + "': " + w);
547       });
548       }
549     */
550
551     if (mkws.config.use_service_proxy && !mkws.authenticated) {
552       authenticateSession(mkws.config.service_proxy_auth,
553                           mkws.config.service_proxy_auth_domain,
554                           mkws.config.pazpar2_url);
555     } else {
556       // raw pp2 or we have a session already open
557       runAutoSearches();
558     }
559     
560     mkws.isActive = true;
561     return true;
562   };
563
564   $(document).ready(function() {
565     mkws.init();
566   });
567
568 })(mkws.$);