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