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