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