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