Initial templatification + Records widget
[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 var mkws = {
13   $: $, // Our own local copy of the jQuery object
14   authenticated: false,
15   log_level: 1, // Will be overridden from mkws.config, but
16                 // initial value allows jQuery popup to use logging.
17   teams: {},
18   widgetType2function: {},
19   defaultTemplates: {},
20
21   locale_lang: {
22     "de": {
23       "Authors": "Autoren",
24       "Subjects": "Schlagwörter",
25       "Sources": "Daten und Quellen",
26       "source": "datenquelle",
27       "Termlists": "Termlisten",
28       "Next": "Weiter",
29       "Prev": "Zurück",
30       "Search": "Suche",
31       "Sort by": "Sortieren nach",
32       "and show": "und zeige",
33       "per page": "pro Seite",
34       "Displaying": "Zeige",
35       "to": "von",
36       "of": "aus",
37       "found": "gefunden",
38       "Title": "Titel",
39       "Author": "Autor",
40       "author": "autor",
41       "Date": "Datum",
42       "Subject": "Schlagwort",
43       "subject": "schlagwort",
44       "Location": "Ort",
45       "Records": "Datensätze",
46       "Targets": "Datenbanken",
47
48       "dummy": "dummy"
49     },
50
51     "da": {
52       "Authors": "Forfattere",
53       "Subjects": "Emner",
54       "Sources": "Kilder",
55       "source": "kilder",
56       "Termlists": "Termlists",
57       "Next": "Næste",
58       "Prev": "Forrige",
59       "Search": "Søg",
60       "Sort by": "Sorter efter",
61       "and show": "og vis",
62       "per page": "per side",
63       "Displaying": "Viser",
64       "to": "til",
65       "of": "ud af",
66       "found": "fandt",
67       "Title": "Title",
68       "Author": "Forfatter",
69       "author": "forfatter",
70       "Date": "Dato",
71       "Subject": "Emneord",
72       "subject": "emneord",
73       "Location": "Lokation",
74       "Records": "Poster",
75       "Targets": "Baser",
76
77       "dummy": "dummy"
78     }
79   }
80 };
81
82
83 mkws.log = function(string) {
84   if (!mkws.log_level)
85     return;
86
87   if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
88     return;
89   }
90
91   // you need to disable use strict at the top of the file!!!
92   if (mkws.log_level >= 3) {
93     // Works in Chrome; not sure about elsewhere
94     console.trace();
95   } else if (mkws.log_level >= 2) {
96     console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
97   }
98   console.log(string);
99 };
100
101
102 // Translation function.
103 mkws.M = function(word) {
104   var lang = mkws.config.lang;
105
106   if (!lang || !mkws.locale_lang[lang])
107     return word;
108
109   return mkws.locale_lang[lang][word] || word;
110 };
111
112
113 // This function is taken from a StackOverflow answer
114 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
115 mkws.getParameterByName = function(name, url) {
116   if (!url) url = location.search;
117   name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
118   var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
119   results = regex.exec(url);
120   return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
121 }
122
123
124 mkws.registerWidgetType = function(name, fn) {
125   mkws.widgetType2function[name] = fn;
126   mkws.log("registered widget-type '" + name + "'");
127 };
128
129 mkws.promotionFunction = function(name) {
130   return mkws.widgetType2function[name];
131 };
132
133
134 mkws.setMkwsConfig = function(overrides) {
135   // Set global log_level flag early so that mkws.log() works
136   // Fall back to old "debug_level" setting for backwards compatibility
137   var tmp = overrides.log_level;
138   if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
139   if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
140
141   var config_default = {
142     use_service_proxy: true,
143     pazpar2_url: "//mkws.indexdata.com/service-proxy/",
144     service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
145     lang: "",
146     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
147     perpage_options: [10, 20, 30, 50],
148     sort_default: "relevance",
149     perpage_default: 20,
150     query_width: 50,
151     show_lang: true,    /* show/hide language menu */
152     show_sort: true,    /* show/hide sort menu */
153     show_perpage: true, /* show/hide perpage menu */
154     show_switch: true,  /* show/hide switch menu */
155     lang_options: [],   /* display languages links for given languages, [] for all */
156     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
157     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
158     log_level: 1,     /* log level for development: 0..2 */
159
160     dummy: "dummy"
161   };
162
163   mkws.config = mkws.objectInheritingFrom(config_default);
164   for (var k in overrides) {
165     mkws.config[k] = overrides[k];
166   }
167 };
168
169
170 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
171 // http://javascript.crockford.com/prototypal.html
172 // mkws.objectInheritingFrom behaves the same as Object.create,
173 // but since the latter is not available in IE8 we can't use it.
174 //
175 mkws.objectInheritingFrom = function(o) {
176   function F() {}
177   F.prototype = o;
178   return new F();
179 }
180
181
182 // The following functions are dispatchers for team methods that
183 // are called from the UI using a team-name rather than implicit
184 // context.
185 mkws.switchView = function(tname, view) {
186   mkws.teams[tname].switchView(view);
187 };
188
189 mkws.showDetails = function(tname, prefixRecId) {
190   mkws.teams[tname].showDetails(prefixRecId);
191 };
192
193 mkws.limitTarget  = function(tname, id, name) {
194   mkws.teams[tname].limitTarget(id, name);
195 };
196
197 mkws.limitQuery  = function(tname, field, value) {
198   mkws.teams[tname].limitQuery(field, value);
199 };
200
201 mkws.limitCategory  = function(tname, id) {
202   mkws.teams[tname].limitCategory(id);
203 };
204
205 mkws.delimitTarget = function(tname, id) {
206   mkws.teams[tname].delimitTarget(id);
207 };
208
209 mkws.delimitQuery = function(tname, field, value) {
210   mkws.teams[tname].delimitQuery(field, value);
211 };
212
213 mkws.showPage = function(tname, pageNum) {
214   mkws.teams[tname].showPage(pageNum);
215 };
216
217 mkws.pagerPrev = function(tname) {
218   mkws.teams[tname].pagerPrev();
219 };
220
221 mkws.pagerNext = function(tname) {
222   mkws.teams[tname].pagerNext();
223 };
224
225
226 // wrapper to provide local copy of the jQuery object.
227 (function($) {
228   var log = mkws.log;
229
230   function handleNodeWithTeam(node, callback) {
231     // First branch for DOM objects; second branch for jQuery objects
232     var classes = node.className || node.attr('class');
233     if (!classes) {
234       // For some reason, if we try to proceed when classes is
235       // undefined, we don't get an error message, but this
236       // function and its callers, up several stack level,
237       // silently return. What a crock.
238       log("handleNodeWithTeam() called on node with no classes");
239       return;
240     }
241     var list = classes.split(/\s+/)
242     var teamName, type;
243
244     for (var i = 0; i < list.length; i++) {
245       var cname = list[i];
246       if (cname.match(/^mkwsTeam_/)) {
247         teamName = cname.replace(/^mkwsTeam_/, '');
248       } else if (cname.match(/^mkws/)) {
249         type = cname.replace(/^mkws/, '');
250       }
251     }
252
253     if (!teamName) teamName = "AUTO";
254     callback.call(node, teamName, type);
255   }
256
257
258   function resizePage() {
259     var threshhold = mkws.config.responsive_design_width;
260     var width = $(window).width();
261     var from, to, method;
262
263     if ((mkws.width === undefined || mkws.width > threshhold) &&
264         width <= threshhold) {
265       from = "wide"; to = "narrow"; method = "hide";
266     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
267                width > threshhold) {
268       from = "narrow"; to = "wide"; method = "show";
269     }
270     mkws.width = width;
271
272     if (from) {
273       log("changing from " + from + " to " + to + ": " + width);
274       for (var tname in mkws.teams) {
275         var team = mkws.teams[tname];
276         team.visitWidgets(function(t, w) {
277           var w1 = team.widget(t + "-Container-" + from);
278           var w2 = team.widget(t + "-Container-" + to);
279           if (w1) {
280             w1.node.hide();
281           }
282           if (w2) {
283             w2.node.show();
284             w.node.appendTo(w2.node);
285           }
286         });
287         team.queue("resize-" + to).publish();
288       }
289     }
290   };
291
292
293   /*
294    * Run service-proxy authentication in background (after page load).
295    * The username/password is configured in the apache config file
296    * for the site.
297    */
298   function authenticateSession(auth_url, auth_domain, pp2_url) {
299     log("service proxy authentication on URL: " + auth_url);
300
301     if (!auth_domain) {
302       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
303       log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
304     }
305
306     var request = new pzHttpRequest(auth_url, function(err) {
307       alert("HTTP call for authentication failed: " + err)
308       return;
309     }, auth_domain);
310
311     request.get(null, function(data) {
312       if (!$.isXMLDoc(data)) {
313         alert("service proxy auth response document is not valid XML document, give up!");
314         return;
315       }
316       var status = $(data).find("status");
317       if (status.text() != "OK") {
318         alert("service proxy auth response status: " + status.text() + ", give up!");
319         return;
320       }
321
322       log("service proxy authentication successful");
323       mkws.authenticated = true;
324       var authName = $(data).find("displayName").text();
325       // You'd think there would be a better way to do this:
326       var realm = $(data).find("realm:not(realmAttributes realm)").text();
327       for (var teamName in mkws.teams) {
328         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
329       }
330
331       runAutoSearches();
332     });
333   }
334
335
336   function runAutoSearches() {
337     log("running auto searches");
338
339     for (var teamName in mkws.teams) {
340       mkws.teams[teamName].queue("ready").publish();
341     }
342   }
343
344
345   function selectorForAllWidgets() {
346     if (mkws.config && mkws.config.scan_all_nodes) {
347       // This is the old version, which works by telling jQuery to
348       // find every node that has a class beginning with "mkws". In
349       // theory it should be slower than the class-based selector; but
350       // instrumentation suprisnigly shows this is consistently
351       // faster. It also has the advantage that any widgets of
352       // non-registered types are logged as warnings rather than
353       // silently ignored.
354       return '[class^="mkws"],[class*=" mkws"]';
355     } else {
356       // This is the new version, which works by looking up the
357       // specific classes of all registered widget types and their
358       // resize containers. Because all it requires jQuery to do is
359       // some hash lookups in pre-built tables, it should be very
360       // fast; but it silently ignores widgets of unregistered types.
361       var s = "";
362       for (var type in mkws.widgetType2function) {
363         if (s) s += ',';
364         s += '.mkws' + type;
365         s += ',.mkws' + type + "-Container-wide";
366         s += ',.mkws' + type + "-Container-narrow";
367       }
368       return s;
369     }
370   }
371
372
373   function makeWidgetsWithin(level, node) {
374     node.find(selectorForAllWidgets()).each(function() {
375       handleNodeWithTeam(this, function(tname, type) {
376         var myTeam = mkws.teams[tname];
377         if (!myTeam) {
378           myTeam = mkws.teams[tname] = team($, tname);
379           log("made MKWS team '" + tname + "'");
380         }
381
382         var oldHTML = this.innerHTML;
383         var myWidget = widget($, myTeam, type, this);
384         myTeam.addWidget(myWidget);
385         var newHTML = this.innerHTML;
386         if (newHTML !== oldHTML) {
387           log("widget " + tname + ":" + type + " HTML changed: reparsing");
388           makeWidgetsWithin(level+1, $(this));
389         }
390       });
391     });
392   }
393
394
395   function init(rootsel) {
396     if (!rootsel) var rootsel = ':root';
397     var saved_config;
398     if (typeof mkws_config === 'undefined') {
399       log("setting empty config");
400       saved_config = {};
401     } else {
402       log("using config: " + $.toJSON(mkws_config));
403       saved_config = mkws_config;
404     }
405     mkws.setMkwsConfig(saved_config);
406
407     for (var key in mkws.config) {
408       if (mkws.config.hasOwnProperty(key)) {
409         if (key.match(/^language_/)) {
410           var lang = key.replace(/^language_/, "");
411           // Copy custom languages into list
412           mkws.locale_lang[lang] = mkws.config[key];
413           log("added locally configured language '" + lang + "'");
414         }
415       }
416     }
417
418     var lang = mkws.getParameterByName("lang") || mkws.config.lang;
419     if (!lang || !mkws.locale_lang[lang]) {
420       mkws.config.lang = ""
421     } else {
422       mkws.config.lang = lang;
423     }
424
425     log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
426
427     if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
428       log("reset query width to " + mkws.config.query_width);
429       mkws.config.query_width = 50;
430     }
431
432     // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
433     if (mkws.config.pazpar2_url.match(/^\/\//)) {
434       mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
435       log("adjusted protocol independent link to " + mkws.config.pazpar2_url);
436     }
437
438     if (mkws.config.responsive_design_width) {
439       // Responsive web design - change layout on the fly based on
440       // current screen width. Required for mobile devices.
441       $(window).resize(resizePage);
442       // initial check after page load
443       $(document).ready(resizePage);
444     }
445
446     // Backwards compatibility: set new magic class names on any
447     // elements that have the old magic IDs.
448     var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
449                 "Results", "Records", "Targets", "Ranking",
450                 "Termlists", "Stat", "MOTD" ];
451     for (var i = 0; i < ids.length; i++) {
452       var id = 'mkws' + ids[i];
453       var node = $('#' + id);
454       if (node.attr('id')) {
455         node.addClass(id);
456         log("added magic class to '" + node.attr('id') + "'");
457       }
458     }
459
460     var then = $.now();
461     makeWidgetsWithin(1, $(rootsel));
462     var now = $.now();
463
464     log("walking MKWS nodes took " + (now-then) + " ms");
465
466     /*
467       for (var tName in mkws.teams) {
468       var myTeam = mkws.teams[tName]
469       log("team '" + tName + "' = " + myTeam + " ...");
470       myTeam.visitWidgets(function(t, w) {
471       log("  has widget of type '" + t + "': " + w);
472       });
473       }
474     */
475
476     if (mkws.config.use_service_proxy) {
477       authenticateSession(mkws.config.service_proxy_auth,
478                           mkws.config.service_proxy_auth_domain,
479                           mkws.config.pazpar2_url);
480     } else {
481       // raw pp2
482       runAutoSearches();
483     }
484   };
485   $(document).ready(function() {
486     var widgetSelector = selectorForAllWidgets();
487     if (widgetSelector && $(widgetSelector).length !== 0) init();
488   });
489 })(jQuery);