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