Mv team-local getParameterByName function to mkws.getParameterByName
[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 mkws.log = function(string) {
82     if (!mkws.log_level)
83         return;
84
85     if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
86         return;
87     }
88
89     // you need to disable use strict at the top of the file!!!
90     if (mkws.log_level >= 3) {
91         console.log(arguments.callee.caller);
92     } else if (mkws.log_level >= 2) {
93         console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
94     }
95     console.log(string);
96 };
97
98
99 mkws.objectWithParent = function(parent) {
100     function thing() {} // Must be function so `prototype' works
101
102     thing.prototype = parent;
103     var res = new thing();
104     thing.prototype = null;
105     return res;
106 };
107
108
109 // This function is taken from a StackOverflow answer
110 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
111 mkws.getParameterByName = function(name) {
112     name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
113     var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
114         results = regex.exec(location.search);
115     return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
116 }
117
118
119 mkws.registerWidgetType = function(name, fn) {
120     mkws.widgetType2function[name] = fn;
121     mkws.log("registered widget-type '" + name + "'");
122 };
123
124 mkws.promotionFunction = function(name) {
125     return mkws.widgetType2function[name];
126 };
127
128
129 mkws.setMkwsConfig = function(overrides) {
130     // Set global log_level flag early so that mkws.log() works
131     // Fall back to old "debug_level" setting for backwards compatibility
132     var tmp = overrides.log_level;
133     if (typeof(tmp) === 'undefined') tmp = overrides.debug_level;
134     if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
135
136     var config_default = {
137         use_service_proxy: true,
138         pazpar2_url: "//mkws.indexdata.com/service-proxy/",
139         service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
140         lang: "",
141         sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
142         perpage_options: [10, 20, 30, 50],
143         sort_default: "relevance",
144         perpage_default: 20,
145         query_width: 50,
146         show_lang: true,        /* show/hide language menu */
147         show_sort: true,        /* show/hide sort menu */
148         show_perpage: true,     /* show/hide perpage menu */
149         lang_options: [],       /* display languages links for given languages, [] for all */
150         facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
151         responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
152         log_level: 1,     /* log level for development: 0..2 */
153
154         dummy: "dummy"
155     };
156
157     mkws.config = Object.create(config_default);
158     for (var k in overrides) {
159         mkws.config[k] = overrides[k];
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.
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 // wrapper to call team() after page load
205 (function(j) {
206     var log = mkws.log;
207
208     function handleNodeWithTeam(node, callback) {
209         // First branch for DOM objects; second branch for jQuery objects
210         var classes = node.className || node.attr('class');
211         if (!classes) {
212             // For some reason, if we try to proceed when classes is
213             // undefined, we don't get an error message, but this
214             // function and its callers, up several stack level,
215             // silently return. What a crock.
216             log("handleNodeWithTeam() called on node with no classes");
217             return;
218         }
219         var list = classes.split(/\s+/)
220         var teamName, type;
221
222         for (var i = 0; i < list.length; i++) {
223             var cname = list[i];
224             if (cname.match(/^mkwsTeam_/)) {
225                 teamName = cname.replace(/^mkwsTeam_/, '');
226             } else if (cname.match(/^mkws/)) {
227                 type = cname.replace(/^mkws/, '');
228             }
229         }
230         callback.call(node, teamName, type);
231     }
232
233
234     function resizePage() {
235         var list = ["mkwsSwitch", "mkwsLang"];
236
237         var width = mkws.config.responsive_design_width;
238         var parent = $(".mkwsTermlists").parent();
239
240         if ($(window).width() <= width &&
241             parent.hasClass("mkwsTermlistContainer1")) {
242             log("changing from wide to narrow: " + $(window).width());
243             $(".mkwsTermlistContainer1").hide();
244             $(".mkwsTermlistContainer2").show();
245             for (var tname in mkws.teams) {
246                 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer2.mkwsTeam_" + tname));
247                 for(var i = 0; i < list.length; i++) {
248                     $("." + list[i] + ".mkwsTeam_" + tname).hide();
249                 }
250             }
251         } else if ($(window).width() > width &&
252                    parent.hasClass("mkwsTermlistContainer2")) {
253             log("changing from narrow to wide: " + $(window).width());
254             $(".mkwsTermlistContainer1").show();
255             $(".mkwsTermlistContainer2").hide();
256             for (var tname in mkws.teams) {
257                 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer1.mkwsTeam_" + tname));
258                 for(var i = 0; i < list.length; i++) {
259                     $("." + list[i] + ".mkwsTeam_" + tname).show();
260                 }
261             }
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].queue("ready").publish();
312         }
313     }
314
315
316     // I don't understand why I need this copy, but I do: mkws_config
317     // is not visible inside the document.ready function, but the
318     // saved copy is.
319     var saved_config;
320     if (typeof mkws_config === 'undefined') {
321         log("setting empty config");
322         saved_config = {};
323     } else {
324         log("using config: " + $.toJSON(mkws_config));
325         saved_config = mkws_config;
326     }
327
328
329     $(document).ready(function() {
330         mkws.setMkwsConfig(saved_config);
331
332         for (var key in mkws.config) {
333             if (mkws.config.hasOwnProperty(key)) {
334                 if (key.match(/^language_/)) {
335                     var lang = key.replace(/^language_/, "");
336                     // Copy custom languages into list
337                     mkws.locale_lang[lang] = mkws.config[key];
338                     log("Added locally configured language '" + lang + "'");
339                 }
340             }
341         }
342
343         if (mkws.config.query_width < 5 || mkws.config.query_width > 150) {
344             log("Reset query width: " + mkws.config.query_width);
345             mkws.config.query_width = 50;
346         }
347
348         // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
349         if (mkws.config.pazpar2_url.match(/^\/\//)) {
350             mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
351             log("adjust protocol independent links: " + mkws.config.pazpar2_url);
352         }
353
354         if (mkws.config.responsive_design_width) {
355             // Responsive web design - change layout on the fly based on
356             // current screen width. Required for mobile devices.
357             $(window).resize(resizePage);
358             // initial check after page load
359             $(document).ready(resizePage);
360         }
361
362         // Backwards compatibility: set new magic class names on any
363         // elements that have the old magic IDs.
364         var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
365                     "Results", "Records", "Targets", "Ranking",
366                     "Termlists", "Stat", "MOTD" ];
367         for (var i = 0; i < ids.length; i++) {
368             var id = 'mkws' + ids[i];
369             var node = $('#' + id);
370             if (node.attr('id')) {
371                 node.addClass(id);
372                 log("added magic class to '" + node.attr('id') + "'");
373             }
374         }
375
376         // For all MKWS-classed nodes that don't have a team
377         // specified, set the team to AUTO.
378         $('[class^="mkws"],[class*=" mkws"]').each(function() {
379             if (!this.className.match(/mkwsTeam_/)) {
380                 log("adding AUTO team to node with class '" + this.className + "'");
381                 $(this).addClass('mkwsTeam_AUTO');
382             }
383         });
384
385         // Find all nodes with an MKWS class, and determine their team from
386         // the mkwsTeam_* class. Make all team objects.
387         var then = $.now();
388         $('[class^="mkws"],[class*=" mkws"]').each(function() {
389             handleNodeWithTeam(this, function(tname, type) {
390                 if (!mkws.teams[tname]) {
391                     mkws.teams[tname] = team(j, tname);
392                     log("Made MKWS team '" + tname + "'");
393                 }
394             });
395         });
396         // Second pass: make the individual widget objects. This has
397         // to be done separately, and after the team-creation, since
398         // that sometimes makes new widget nodes (e.g. creating
399         // mkwsTermlists inside mkwsResults.
400         $('[class^="mkws"],[class*=" mkws"]').each(function() {
401             handleNodeWithTeam(this, function(tname, type) {
402                 var myTeam = mkws.teams[tname];
403                 var myWidget = widget(j, myTeam, type, this);
404             });
405         });
406         var now = $.now();
407         log("Walking MKWS nodes took " + (now-then) + " ms");
408
409         if (mkws.config.use_service_proxy) {
410             authenticateSession(mkws.config.service_proxy_auth,
411                                 mkws.config.service_proxy_auth_domain,
412                                 mkws.config.pazpar2_url);
413         } else {
414             // raw pp2
415             runAutoSearches();
416         }
417     });
418 })(jQuery);