More comment.
[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     function log(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     mkws.log = 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     // The following functions are dispatchers for team methods that
165     // are called from the UI using a team-name rather than implicit
166     // context. Apart from mkws.log, they are the ONLY public UI to
167     // this module.
168     mkws.switchView = function(tname, view) {
169         mkws.teams[tname].switchView(view);
170     }
171
172     mkws.showDetails = function (tname, prefixRecId) {
173         mkws.teams[tname].showDetails(prefixRecId);
174     }
175
176     mkws.limitTarget  = function (tname, id, name) {
177         mkws.teams[tname].limitTarget(id, name);
178     }
179
180     mkws.limitQuery  = function (tname, field, value) {
181         mkws.teams[tname].limitQuery(field, value);
182     }
183
184     mkws.delimitTarget = function (tname, id) {
185         mkws.teams[tname].delimitTarget(id);
186     }
187
188     mkws.delimitQuery = function (tname, field, value) {
189         mkws.teams[tname].delimitQuery(field, value);
190     }
191
192     mkws.showPage = function (tname, pageNum) {
193         mkws.teams[tname].showPage(pageNum);
194     }
195
196     mkws.pagerPrev = function (tname) {
197         mkws.teams[tname].pagerPrev();
198     }
199
200     mkws.pagerNext = function (tname) {
201         mkws.teams[tname].pagerNext();
202     }
203
204
205     function defaultMkwsConfig() {
206         /* default mkws config */
207         var config_default = {
208             use_service_proxy: true,
209             pazpar2_url: "//mkws.indexdata.com/service-proxy/",
210             service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
211             lang: "",
212             sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
213             perpage_options: [10, 20, 30, 50],
214             sort_default: "relevance",
215             perpage_default: 20,
216             query_width: 50,
217             show_lang: true,    /* show/hide language menu */
218             show_sort: true,    /* show/hide sort menu */
219             show_perpage: true,         /* show/hide perpage menu */
220             lang_options: [],   /* display languages links for given languages, [] for all */
221             facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
222             responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
223             log_level: 1,     /* log level for development: 0..2 */
224
225             dummy: "dummy"
226         };
227
228         // Set global log_level flag early so that log() works
229         // Fall back to old "debug_level" setting for backwards compatibility
230         var tmp = mkws_config.log_level;
231         if (typeof(tmp) === 'undefined') tmp = mkws_config.debug_level;
232
233         if (typeof(tmp) !== 'undefined') {
234             mkws.log_level = tmp;
235         } else if (typeof(config_default.log_level) !== 'undefined') {
236             mkws.log_level = config_default.log_level;
237         }
238
239         // make sure the mkws_config is a valid hash
240         if (!$.isPlainObject(mkws_config)) {
241             log("ERROR: mkws_config is not an JS object, ignore it....");
242             mkws_config = {};
243         }
244
245         /* override standard config values by function parameters */
246         for (var k in config_default) {
247             if (typeof mkws_config[k] === 'undefined')
248                 mkws_config[k] = config_default[k];
249             //log("Set config: " + k + ' => ' + mkws_config[k]);
250         }
251     }
252
253
254     /*
255      * Run service-proxy authentication in background (after page load).
256      * The username/password is configured in the apache config file
257      * for the site.
258      */
259     function authenticateSession(auth_url, auth_domain, pp2_url) {
260         log("Run service proxy auth URL: " + auth_url);
261
262         if (!auth_domain) {
263             auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
264             log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
265         }
266
267         var request = new pzHttpRequest(auth_url, function(err) {
268             alert("HTTP call for authentication failed: " + err)
269             return;
270         }, auth_domain);
271
272         request.get(null, function(data) {
273             if (!$.isXMLDoc(data)) {
274                 alert("service proxy auth response document is not valid XML document, give up!");
275                 return;
276             }
277             var status = $(data).find("status");
278             if (status.text() != "OK") {
279                 alert("service proxy auth response status: " + status.text() + ", give up!");
280                 return;
281             }
282
283             log("Service proxy auth successfully done");
284             mkws.authenticated = true;
285             runAutoSearches();
286         });
287     }
288
289
290     function runAutoSearches() {
291         log("running auto searches");
292
293         for (var teamName in mkws.teams) {
294             mkws.teams[teamName].runAutoSearch();
295         }
296     }
297
298
299     $(document).ready(function() {
300         defaultMkwsConfig();
301
302         if (mkws_config.query_width < 5 || mkws_config.query_width > 150) {
303             log("Reset query width: " + mkws_config.query_width);
304             mkws_config.query_width = 50;
305         }
306
307         for (var key in mkws_config) {
308             if (mkws_config.hasOwnProperty(key)) {
309                 if (key.match(/^language_/)) {
310                     var lang = key.replace(/^language_/, "");
311                     // Copy custom languages into list
312                     mkws.locale_lang[lang] = mkws_config[key];
313                     log("Added locally configured language '" + lang + "'");
314                 }
315             }
316         }
317
318         if (mkws_config.responsive_design_width) {
319             // Responsive web design - change layout on the fly based on
320             // current screen width. Required for mobile devices.
321             $(window).resize(resizePage);
322             // initial check after page load
323             $(document).ready(resizePage);
324         }
325
326         // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
327         if (mkws_config.pazpar2_url.match(/^\/\//)) {
328             mkws_config.pazpar2_url = document.location.protocol + mkws_config.pazpar2_url;
329             log("adjust protocol independent links: " + mkws_config.pazpar2_url);
330         }
331
332         // Backwards compatibility: set new magic class names on any
333         // elements that have the old magic IDs.
334         var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
335                     "Results", "Records", "Targets", "Ranking",
336                     "Termlists", "Stat", "MOTD" ];
337         for (var i = 0; i < ids.length; i++) {
338             var id = 'mkws' + ids[i];
339             var node = $('#' + id);
340             if (node.attr('id')) {
341                 node.addClass(id);
342                 log("added magic class to '" + node.attr('id') + "'");
343             }
344         }
345
346         // For all MKWS-classed nodes that don't have a team
347         // specified, set the team to AUTO.
348         $('[class^="mkws"],[class*=" mkws"]').each(function () {
349             if (!this.className.match(/mkwsTeam_/)) {
350                 log("adding AUTO team to node with class '" + this.className + "'");
351                 $(this).addClass('mkwsTeam_AUTO');
352             }
353         });
354
355         // Find all nodes with an MKWS class, and determine their team from
356         // the mkwsTeam_* class. Make all team objects.
357         var then = $.now();
358         $('[class^="mkws"],[class*=" mkws"]').each(function () {
359             handleNodeWithTeam(this, function(tname, type) {
360                 if (!mkws.teams[tname]) {
361                     mkws.teams[tname] = team(j, tname);
362                     log("Made MKWS team '" + tname + "'");
363                 }
364             });
365         });
366         // Second pass: make the individual widget objects. This has
367         // to be done separately, and after the team-creation, since
368         // that sometimes makes new widget nodes (e.g. creating
369         // mkwsTermlists inside mkwsResults.
370         $('[class^="mkws"],[class*=" mkws"]').each(function () {
371             handleNodeWithTeam(this, function(tname, type) {
372                 var myTeam = mkws.teams[tname];
373                 var myWidget = widget(j, myTeam, type, this);
374             });
375         });
376         var now = $.now();
377         log("Walking MKWS nodes took " + (now-then) + " ms");
378
379         if (mkws_config.use_service_proxy) {
380             authenticateSession(mkws_config.service_proxy_auth,
381                                 mkws_config.service_proxy_auth_domain,
382                                 mkws_config.pazpar2_url);
383         } else {
384             // raw pp2
385             runAutoSearches();
386         }
387     });
388 })(jQuery);