Move mkws.log out of immediate-execute wrapper.
[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     authenticated: false,
14     log_level: 1, // Will be overridden from mkws_config, but
15                   // initial value allows jQuery popup to use logging.
16     teams: {},
17     widgetType2function: {},
18
19     locale_lang: {
20         "de": {
21             "Authors": "Autoren",
22             "Subjects": "Schlagwörter",
23             "Sources": "Daten und Quellen",
24             "source": "datenquelle",
25             "Termlists": "Termlisten",
26             "Next": "Weiter",
27             "Prev": "Zurück",
28             "Search": "Suche",
29             "Sort by": "Sortieren nach",
30             "and show": "und zeige",
31             "per page": "pro Seite",
32             "Displaying": "Zeige",
33             "to": "von",
34             "of": "aus",
35             "found": "gefunden",
36             "Title": "Titel",
37             "Author": "Autor",
38             "author": "autor",
39             "Date": "Datum",
40             "Subject": "Schlagwort",
41             "subject": "schlagwort",
42             "Location": "Ort",
43             "Records": "Datensätze",
44             "Targets": "Datenbanken",
45
46             "dummy": "dummy"
47         },
48
49         "da": {
50             "Authors": "Forfattere",
51             "Subjects": "Emner",
52             "Sources": "Kilder",
53             "source": "kilder",
54             "Termlists": "Termlists",
55             "Next": "Næste",
56             "Prev": "Forrige",
57             "Search": "Søg",
58             "Sort by": "Sorter efter",
59             "and show": "og vis",
60             "per page": "per side",
61             "Displaying": "Viser",
62             "to": "til",
63             "of": "ud af",
64             "found": "fandt",
65             "Title": "Title",
66             "Author": "Forfatter",
67             "author": "forfatter",
68             "Date": "Dato",
69             "Subject": "Emneord",
70             "subject": "emneord",
71             "Location": "Lokation",
72             "Records": "Poster",
73             "Targets": "Baser",
74
75             "dummy": "dummy"
76         }
77     }
78 };
79
80
81 // Define empty mkws_config for simple applications that don't define it.
82 if (mkws_config == null || typeof mkws_config != 'object') {
83     var mkws_config = {};
84 }
85
86
87     mkws.log = function(string) {
88         if (!mkws.log_level)
89             return;
90
91         if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
92             return;
93         }
94
95         // you need to disable use strict at the top of the file!!!
96         if (mkws.log_level >= 3) {
97             console.log(arguments.callee.caller);
98         } else if (mkws.log_level >= 2) {
99             console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
100         }
101         console.log(string);
102     };
103
104
105
106 // wrapper to call team() after page load
107 (function(j) {
108     var log = mkws.log;
109
110     mkws.registerWidgetType = function(name, fn) {
111         mkws.widgetType2function[name] = fn;
112         log("registered widget-type '" + name + "'");
113     }
114
115     mkws.promotionFunction = function(name) {
116         return mkws.widgetType2function[name];
117     }
118
119
120     function handleNodeWithTeam(node, callback) {
121         // First branch for DOM objects; second branch for jQuery objects
122         var classes = node.className || node.attr('class');
123         if (!classes) {
124             // For some reason, if we try to proceed when classes is
125             // undefined, we don't get an error message, but this
126             // function and its callers, up several stack level,
127             // silently return. What a crock.
128             mkws.log("handleNodeWithTeam() called on node with no classes");
129             return;
130         }
131         var list = classes.split(/\s+/)
132         var teamName, type;
133
134         for (var i = 0; i < list.length; i++) {
135             var cname = list[i];
136             if (cname.match(/^mkwsTeam_/)) {
137                 teamName = cname.replace(/^mkwsTeam_/, '');
138             } else if (cname.match(/^mkws/)) {
139                 type = cname.replace(/^mkws/, '');
140             }
141         }
142         callback.call(node, teamName, type);
143     }
144
145
146     function resizePage() {
147         var list = ["mkwsSwitch", "mkwsLang"];
148
149         var width = mkws_config.responsive_design_width;
150         var parent = $(".mkwsTermlists").parent();
151
152         if ($(window).width() <= width &&
153             parent.hasClass("mkwsTermlistContainer1")) {
154             log("changing from wide to narrow: " + $(window).width());
155             $(".mkwsTermlistContainer1").hide();
156             $(".mkwsTermlistContainer2").show();
157             for (var tname in mkws.teams) {
158                 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer2.mkwsTeam_" + tname));
159                 for(var i = 0; i < list.length; i++) {
160                     $("." + list[i] + ".mkwsTeam_" + tname).hide();
161                 }
162             }
163         } else if ($(window).width() > width &&
164                    parent.hasClass("mkwsTermlistContainer2")) {
165             log("changing from narrow to wide: " + $(window).width());
166             $(".mkwsTermlistContainer1").show();
167             $(".mkwsTermlistContainer2").hide();
168             for (var tname in mkws.teams) {
169                 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer1.mkwsTeam_" + tname));
170                 for(var i = 0; i < list.length; i++) {
171                     $("." + list[i] + ".mkwsTeam_" + tname).show();
172                 }
173             }
174         }
175     };
176
177
178     // The following functions are dispatchers for team methods that
179     // are called from the UI using a team-name rather than implicit
180     // context. Apart from mkws.log, they are the ONLY public UI to
181     // this module.
182     mkws.switchView = function(tname, view) {
183         mkws.teams[tname].switchView(view);
184     }
185
186     mkws.showDetails = function(tname, prefixRecId) {
187         mkws.teams[tname].showDetails(prefixRecId);
188     }
189
190     mkws.limitTarget  = function(tname, id, name) {
191         mkws.teams[tname].limitTarget(id, name);
192     }
193
194     mkws.limitQuery  = function(tname, field, value) {
195         mkws.teams[tname].limitQuery(field, value);
196     }
197
198     mkws.delimitTarget = function(tname, id) {
199         mkws.teams[tname].delimitTarget(id);
200     }
201
202     mkws.delimitQuery = function(tname, field, value) {
203         mkws.teams[tname].delimitQuery(field, value);
204     }
205
206     mkws.showPage = function(tname, pageNum) {
207         mkws.teams[tname].showPage(pageNum);
208     }
209
210     mkws.pagerPrev = function(tname) {
211         mkws.teams[tname].pagerPrev();
212     }
213
214     mkws.pagerNext = function(tname) {
215         mkws.teams[tname].pagerNext();
216     }
217
218
219     function defaultMkwsConfig() {
220         /* default mkws config */
221         var config_default = {
222             use_service_proxy: true,
223             pazpar2_url: "//mkws.indexdata.com/service-proxy/",
224             service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
225             lang: "",
226             sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
227             perpage_options: [10, 20, 30, 50],
228             sort_default: "relevance",
229             perpage_default: 20,
230             query_width: 50,
231             show_lang: true,    /* show/hide language menu */
232             show_sort: true,    /* show/hide sort menu */
233             show_perpage: true,         /* show/hide perpage menu */
234             lang_options: [],   /* display languages links for given languages, [] for all */
235             facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
236             responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
237             log_level: 1,     /* log level for development: 0..2 */
238
239             dummy: "dummy"
240         };
241
242         // Set global log_level flag early so that log() works
243         // Fall back to old "debug_level" setting for backwards compatibility
244         var tmp = mkws_config.log_level;
245         if (typeof(tmp) === 'undefined') tmp = mkws_config.debug_level;
246
247         if (typeof(tmp) !== 'undefined') {
248             mkws.log_level = tmp;
249         } else if (typeof(config_default.log_level) !== 'undefined') {
250             mkws.log_level = config_default.log_level;
251         }
252
253         // make sure the mkws_config is a valid hash
254         if (!$.isPlainObject(mkws_config)) {
255             log("ERROR: mkws_config is not an JS object, ignore it....");
256             mkws_config = {};
257         }
258
259         /* override standard config values by function parameters */
260         for (var k in config_default) {
261             if (typeof mkws_config[k] === 'undefined')
262                 mkws_config[k] = config_default[k];
263             //log("Set config: " + k + ' => ' + mkws_config[k]);
264         }
265     }
266
267
268     /*
269      * Run service-proxy authentication in background (after page load).
270      * The username/password is configured in the apache config file
271      * for the site.
272      */
273     function authenticateSession(auth_url, auth_domain, pp2_url) {
274         log("Run service proxy auth URL: " + auth_url);
275
276         if (!auth_domain) {
277             auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
278             log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
279         }
280
281         var request = new pzHttpRequest(auth_url, function(err) {
282             alert("HTTP call for authentication failed: " + err)
283             return;
284         }, auth_domain);
285
286         request.get(null, function(data) {
287             if (!$.isXMLDoc(data)) {
288                 alert("service proxy auth response document is not valid XML document, give up!");
289                 return;
290             }
291             var status = $(data).find("status");
292             if (status.text() != "OK") {
293                 alert("service proxy auth response status: " + status.text() + ", give up!");
294                 return;
295             }
296
297             log("Service proxy auth successfully done");
298             mkws.authenticated = true;
299             var authName = $(data).find("displayName").text();
300             for (var teamName in mkws.teams) {
301                 mkws.teams[teamName].queue("authenticated").publish(authName);
302             }
303
304             runAutoSearches();
305         });
306     }
307
308
309     function runAutoSearches() {
310         log("running auto searches");
311
312         for (var teamName in mkws.teams) {
313             mkws.teams[teamName].runAutoSearch();
314         }
315     }
316
317
318     $(document).ready(function() {
319         defaultMkwsConfig();
320
321         if (mkws_config.query_width < 5 || mkws_config.query_width > 150) {
322             log("Reset query width: " + mkws_config.query_width);
323             mkws_config.query_width = 50;
324         }
325
326         for (var key in mkws_config) {
327             if (mkws_config.hasOwnProperty(key)) {
328                 if (key.match(/^language_/)) {
329                     var lang = key.replace(/^language_/, "");
330                     // Copy custom languages into list
331                     mkws.locale_lang[lang] = mkws_config[key];
332                     log("Added locally configured language '" + lang + "'");
333                 }
334             }
335         }
336
337         if (mkws_config.responsive_design_width) {
338             // Responsive web design - change layout on the fly based on
339             // current screen width. Required for mobile devices.
340             $(window).resize(resizePage);
341             // initial check after page load
342             $(document).ready(resizePage);
343         }
344
345         // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
346         if (mkws_config.pazpar2_url.match(/^\/\//)) {
347             mkws_config.pazpar2_url = document.location.protocol + mkws_config.pazpar2_url;
348             log("adjust protocol independent links: " + mkws_config.pazpar2_url);
349         }
350
351         // Backwards compatibility: set new magic class names on any
352         // elements that have the old magic IDs.
353         var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
354                     "Results", "Records", "Targets", "Ranking",
355                     "Termlists", "Stat", "MOTD" ];
356         for (var i = 0; i < ids.length; i++) {
357             var id = 'mkws' + ids[i];
358             var node = $('#' + id);
359             if (node.attr('id')) {
360                 node.addClass(id);
361                 log("added magic class to '" + node.attr('id') + "'");
362             }
363         }
364
365         // For all MKWS-classed nodes that don't have a team
366         // specified, set the team to AUTO.
367         $('[class^="mkws"],[class*=" mkws"]').each(function() {
368             if (!this.className.match(/mkwsTeam_/)) {
369                 log("adding AUTO team to node with class '" + this.className + "'");
370                 $(this).addClass('mkwsTeam_AUTO');
371             }
372         });
373
374         // Find all nodes with an MKWS class, and determine their team from
375         // the mkwsTeam_* class. Make all team objects.
376         var then = $.now();
377         $('[class^="mkws"],[class*=" mkws"]').each(function() {
378             handleNodeWithTeam(this, function(tname, type) {
379                 if (!mkws.teams[tname]) {
380                     mkws.teams[tname] = team(j, tname);
381                     log("Made MKWS team '" + tname + "'");
382                 }
383             });
384         });
385         // Second pass: make the individual widget objects. This has
386         // to be done separately, and after the team-creation, since
387         // that sometimes makes new widget nodes (e.g. creating
388         // mkwsTermlists inside mkwsResults.
389         $('[class^="mkws"],[class*=" mkws"]').each(function() {
390             handleNodeWithTeam(this, function(tname, type) {
391                 var myTeam = mkws.teams[tname];
392                 var myWidget = widget(j, myTeam, type, this);
393             });
394         });
395         var now = $.now();
396         log("Walking MKWS nodes took " + (now-then) + " ms");
397
398         if (mkws_config.use_service_proxy) {
399             authenticateSession(mkws_config.service_proxy_auth,
400                                 mkws_config.service_proxy_auth_domain,
401                                 mkws_config.pazpar2_url);
402         } else {
403             // raw pp2
404             runAutoSearches();
405         }
406     });
407 })(jQuery);