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