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