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