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