1 /*! MKWS, the MasterKey Widget Set.
2 * Copyright (C) 2013-2014 Index Data
3 * See the file LICENSE for details
6 "use strict"; // HTML5: disable for debug_level >= 2
10 Handlebars.registerHelper('json', function(obj) {
15 Handlebars.registerHelper('translate', function(s) {
20 // We need {{attr '@name'}} because Handlebars can't parse {{@name}}
21 Handlebars.registerHelper('attr', function(attrName) {
22 return this[attrName];
27 * Use as follows: {{#if-any NAME1 having="NAME2"}}
28 * Applicable when NAME1 is the name of an array
29 * The guarded code runs only if at least one element of the NAME1
30 * array has a subelement called NAME2.
32 Handlebars.registerHelper('if-any', function(items, options) {
33 var having = options.hash.having;
34 for (var i in items) {
36 if (!having || item[having]) {
37 return options.fn(this);
44 Handlebars.registerHelper('first', function(items, options) {
45 var having = options.hash.having;
46 for (var i in items) {
48 if (!having || item[having]) {
49 return options.fn(item);
56 Handlebars.registerHelper('commaList', function(items, options) {
59 for (var i in items) {
60 if (i > 0) out += ", ";
61 out += options.fn(items[i])
69 // Set up global mkws object. Contains truly global state such as SP
70 // authentication, and a hash of team objects, indexed by windowid.
74 debug_level: 1, // Will be overridden from mkws_config, but
75 // initial value allows jQuery popup to use logging.
76 paz: undefined, // will be set up during initialisation
81 "Subjects": "Schlagwörter",
82 "Sources": "Daten und Quellen",
83 "source": "datenquelle",
84 "Termlists": "Termlisten",
86 "Prev": "Zurück",
88 "Sort by": "Sortieren nach",
89 "and show": "und zeige",
90 "per page": "pro Seite",
91 "Displaying": "Zeige",
99 "Subject": "Schlagwort",
100 "subject": "schlagwort",
102 "Records": "Datensätze",
103 "Targets": "Datenbanken",
109 "Authors": "Forfattere",
113 "Termlists": "Termlists",
114 "Next": "Næste",
116 "Search": "Søg",
117 "Sort by": "Sorter efter",
118 "and show": "og vis",
119 "per page": "per side",
120 "Displaying": "Viser",
125 "Author": "Forfatter",
126 "author": "forfatter",
128 "Subject": "Emneord",
129 "subject": "emneord",
130 "Location": "Lokation",
140 // Define empty mkws_config for simple applications that don't define it.
141 if (mkws_config == null || typeof mkws_config != 'object') {
142 var mkws_config = {};
146 // Factory function for team objects. As much as possible, this uses
147 // only member variables (prefixed "m_") and inner functions with
148 // private scope. Some functions are visibl as member-functions to be
149 // called from outside code -- specifically, from generated
150 // HTML. These functions are that.switchView(), showDetails(),
151 // limitTarget(), limitQuery(), delimitTarget(), delimitQuery(),
152 // pagerPrev(), pagerNext(), showPage().
154 function team($, teamName) {
156 var m_teamName = teamName;
157 var m_submitted = false;
158 var m_query; // initially undefined
159 var m_sort; // will be set below
160 var m_perpage; // will be set below
164 var m_curDetRecId = '';
165 var m_curDetRecData = null;
167 // Timestamps for logging
171 var m_paz; // will be initialised below
174 var debug = function (s) {
176 var timestamp = ((now - m_debug_time.start)/1000).toFixed(3) + " (+" + ((now - m_debug_time.last)/1000).toFixed(3) + ") "
177 m_debug_time.last = now;
179 mkws.debug(m_teamName + ": " + timestamp + s);
182 debug("start running MKWS");
184 m_sort = mkws_config.sort_default;
185 debug("copied mkws_config.sort_default '" + mkws_config.sort_default + "' to m_sort");
187 if (mkws_config.query_width < 5 || mkws_config.query_width > 150) {
188 debug("Reset query width: " + mkws_config.query_width);
189 mkws_config.query_width = 50;
192 for (var key in mkws_config) {
193 if (mkws_config.hasOwnProperty(key)) {
194 if (key.match(/^language_/)) {
195 var lang = key.replace(/^language_/, "");
196 // Copy custom languages into list
197 mkws.locale_lang[lang] = mkws_config[key];
198 debug("Added locally configured language '" + lang + "'");
203 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
204 if (mkws_config.pazpar2_url.match(/^\/\//)) {
205 mkws_config.pazpar2_url = document.location.protocol + mkws_config.pazpar2_url;
206 debug("adjust protocol independent links: " + mkws_config.pazpar2_url);
209 debug("Create main pz2 object");
210 // create a parameters array and pass it to the pz2's constructor
211 // then register the form submit event with the pz2.search function
212 // autoInit is set to true on default
213 m_paz = new pz2({ "onshow": my_onshow,
214 "windowid": teamName,
215 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
216 "pazpar2path": mkws_config.pazpar2_url,
219 "onterm": (mkws_config.facets.length ? my_onterm : undefined),
220 "termlist": mkws_config.facets.join(','),
221 "onbytarget": my_onbytarget,
222 "usesessions" : mkws_config.use_service_proxy ? false : true,
223 "showResponseType": '', // or "json" (for debugging?)
224 "onrecord": my_onrecord });
226 if (!isNaN(parseInt(mkws_config.perpage_default))) {
227 m_perpage = parseInt(mkws_config.perpage_default);
232 // pz2.js event handlers:
234 function my_oninit(teamName) {
241 function my_onshow(data, teamName) {
243 m_totalRec = data.merged;
245 var pager = $(".mkwsPager.mkwsTeam_" + m_teamName);
247 pager.html(drawPager(data))
250 var results = $(".mkwsRecords.mkwsTeam_" + m_teamName);
255 for (var i = 0; i < data.hits.length; i++) {
256 var hit = data.hits[i];
257 html.push('<div class="record" id="mkwsRecdiv_' + teamName + '_' + hit.recid + '" >',
260 if (hit.recid == m_curDetRecId) {
262 html.push(renderDetails(m_curDetRecData));
265 results.html(html.join(''));
269 function renderSummary(hit)
271 var template = loadTemplate("Summary");
272 hit._id = "mkwsRec_" + hit.recid;
273 hit._onclick = "mkws.showDetails('" + m_teamName + "', this.id);return false;"
274 return template(hit);
278 function my_onstat(data, teamName) {
280 var stat = $('.mkwsStat.mkwsTeam_' + teamName);
281 if (stat.length === 0)
284 stat.html('<span class="head">' + M('Status info') + '</span>' +
286 '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
288 '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>');
292 function my_onterm(data, teamName) {
294 var node = $(".mkwsTermlists.mkwsTeam_" + teamName);
295 if (node.length == 0) return;
297 // no facets: this should never happen
298 if (!mkws_config.facets || mkws_config.facets.length == 0) {
299 alert("my_onterm called even though we have no facets: " + $.toJSON(data));
304 // display if we first got results
308 acc.push('<div class="title">' + M('Termlists') + '</div>');
309 var facets = mkws_config.facets;
311 for(var i = 0; i < facets.length; i++) {
312 if (facets[i] == "xtargets") {
313 add_single_facet(acc, "Sources", data.xtargets, 16, null);
314 } else if (facets[i] == "subject") {
315 add_single_facet(acc, "Subjects", data.subject, 10, "subject");
316 } else if (facets[i] == "author") {
317 add_single_facet(acc, "Authors", data.author, 10, "author");
319 alert("bad facet configuration: '" + facets[i] + "'");
323 node.html(acc.join(''));
327 function add_single_facet(acc, caption, data, max, pzIndex) {
328 acc.push('<div class="facet mkwsFacet' + caption + ' mkwsTeam_' + m_teamName + '">');
329 acc.push('<div class="termtitle">' + M(caption) + '</div>');
330 for (var i = 0; i < data.length && i < max; i++) {
331 acc.push('<div class="term">');
332 acc.push('<a href="#" ');
335 // Special case: target selection
336 acc.push('target_id='+data[i].id+' ');
337 if (!target_filtered(data[i].id)) {
338 action = 'mkws.limitTarget(\'' + m_teamName + '\', this.getAttribute(\'target_id\'),this.firstChild.nodeValue)';
341 action = 'mkws.limitQuery(\'' + m_teamName + '\', \'' + pzIndex + '\', this.firstChild.nodeValue)';
343 acc.push('onclick="' + action + ';return false;">' + data[i].name + '</a>'
344 + ' <span>' + data[i].freq + '</span>');
351 function target_filtered(id) {
352 for (var i = 0; i < m_filters.length; i++) {
353 if (m_filters[i].id === id ||
354 m_filters[i].id === 'pz:id=' + id) {
362 function my_onrecord(data, args, teamName) {
363 debug("record: teamName=" + teamName + ", m_teamName=" + m_teamName);
364 // FIXME: record is async!!
365 clearTimeout(m_paz.recordTimer);
366 // in case on_show was faster to redraw element
367 var detRecordDiv = document.getElementById('mkwsDet_' + teamName + '_' + data.recid);
368 if (detRecordDiv) return;
369 m_curDetRecData = data;
370 var recordDiv = document.getElementById('mkwsRecdiv_' + teamName + '_' + m_curDetRecData.recid);
371 var html = renderDetails(m_curDetRecData);
372 recordDiv.innerHTML += html;
376 function my_onbytarget(data, teamName) {
378 var targetDiv = $('.mkwsBytarget.mkwsTeam_' + teamName);
383 var table ='<table><thead><tr>' +
384 '<td>' + M('Target ID') + '</td>' +
385 '<td>' + M('Hits') + '</td>' +
386 '<td>' + M('Diags') + '</td>' +
387 '<td>' + M('Records') + '</td>' +
388 '<td>' + M('State') + '</td>' +
389 '</tr></thead><tbody>';
391 for (var i = 0; i < data.length; i++) {
392 table += "<tr><td>" + data[i].id +
393 "</td><td>" + data[i].hits +
394 "</td><td>" + data[i].diagnostic +
395 "</td><td>" + data[i].records +
396 "</td><td>" + data[i].state + "</td></tr>";
399 table += '</tbody></table>';
400 targetDiv.html(table);
403 ////////////////////////////////////////////////////////////////////////////////
404 ////////////////////////////////////////////////////////////////////////////////
407 // when search button pressed
408 function onFormSubmitEventHandler()
410 mkws.handle_node_with_team(this, function (tname) {
411 var val = $('.mkwsQuery.mkwsTeam_' + tname).val();
412 mkws.teams[tname].newSearch(val);
419 that.newSearch = function(query, sort, targets, windowid)
421 debug("newSearch: " + query);
423 if (mkws_config.use_service_proxy && !mkws.authenticated) {
424 alert("searching before authentication");
432 triggerSearch(query, sort, targets, windowid);
433 that.switchView('records'); // In case it's configured to start off as hidden
438 function onSelectDdChange()
440 if (!m_submitted) return false;
443 m_paz.show(0, m_perpage, m_sort);
455 function triggerSearch (query, sort, targets, windowid)
460 // Re-use previous query/sort if new ones are not specified
468 // ### should support multiple |-separated targets
469 m_filters.push({ id: targets, name: targets });
472 for (var i in m_filters) {
473 var filter = m_filters[i];
477 if (filter.id.match(/^[a-z:]+[=~]/)) {
478 debug("filter '" + filter.id + "' already begins with SETTING OP");
480 filter.id = 'pz:id=' + filter.id;
482 pp2filter += filter.id;
486 pp2limit += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
492 params.limit = pp2limit;
495 params.windowid = windowid;
497 debug("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
499 m_paz.search(m_query, m_perpage, m_sort, pp2filter, undefined, params);
503 function loadSelect ()
505 var node = $('.mkwsSort.mkwsTeam_' + m_teamName);
506 if (node.length && node.val() != m_sort) {
507 debug("changing m_sort from " + m_sort + " to " + node.val());
510 node = $('.mkwsPerpage.mkwsTeam_' + m_teamName);
511 if (node.length && node.val() != m_perpage) {
512 debug("changing m_perpage from " + m_perpage + " to " + node.val());
513 m_perpage = node.val();
518 // limit by target functions
519 that.limitTarget = function (id, name)
521 debug("limitTarget(id=" + id + ", name=" + name + ")");
522 m_filters.push({ id: id, name: name });
531 // limit the query after clicking the facet
532 that.limitQuery = function (field, value)
534 debug("limitQuery(field=" + field + ", value=" + value + ")");
535 m_filters.push({ field: field, value: value });
544 that.delimitTarget = function (id)
546 debug("delimitTarget(id=" + id + ")");
548 for (var i in m_filters) {
549 var filter = m_filters[i];
551 debug("delimitTarget() removing filter " + $.toJSON(filter));
553 debug("delimitTarget() keeping filter " + $.toJSON(filter));
554 newFilters.push(filter);
557 m_filters = newFilters;
567 that.delimitQuery = function (field, value)
569 debug("delimitQuery(field=" + field + ", value=" + value + ")");
571 for (var i in m_filters) {
572 var filter = m_filters[i];
574 field == filter.field &&
575 value == filter.value) {
576 debug("delimitQuery() removing filter " + $.toJSON(filter));
578 debug("delimitQuery() keeping filter " + $.toJSON(filter));
579 newFilters.push(filter);
582 m_filters = newFilters;
592 function redraw_navi ()
594 var navi = $('.mkwsNavi.mkwsTeam_' + m_teamName);
598 for (var i in m_filters) {
602 var filter = m_filters[i];
604 text += M('source') + ': <a class="crossout" href="#" onclick="mkws.delimitTarget(\'' + m_teamName +
605 "', '" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
607 text += M(filter.field) + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(\'' + m_teamName +
608 "', '" + filter.field + "', '" + filter.value + "'" +
609 ');return false;">' + filter.value + '</a>';
617 function drawPager (data)
619 var s = '<div style="float: right">' + M('Displaying') + ': '
620 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
621 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
622 + data.total + ')</div>';
624 //client indexes pages from 1 but pz2 from 0
626 var pages = Math.ceil(m_totalRec / m_perpage);
628 var firstClkbl = (m_curPage - onsides > 0)
629 ? m_curPage - onsides
632 var lastClkbl = firstClkbl + 2*onsides < pages
633 ? firstClkbl + 2*onsides
636 var prev = '<span class="mkwsPrev"><< ' + M('Prev') + '</span><b> | </b>';
638 prev = '<a href="#" class="mkwsPrev" onclick="mkws.pagerPrev(\'' + m_teamName + '\');">'
639 +'<< ' + M('Prev') + '</a><b> | </b>';
642 for(var i = firstClkbl; i <= lastClkbl; i++) {
645 numLabel = '<b>' + i + '</b>';
647 middle += '<a href="#" onclick="mkws.showPage(\'' + m_teamName + '\', ' + i + ')"> '
648 + numLabel + ' </a>';
651 var next = '<b> | </b><span class="mkwsNext">' + M('Next') + ' >></span>';
652 if (pages - m_curPage > 0)
653 next = '<b> | </b><a href="#" class="mkwsNext" onclick="mkws.pagerNext(\'' + m_teamName + '\')">'
654 + M('Next') + ' >></a>';
661 if (lastClkbl < pages)
664 s += '<div style="float: clear">'
665 + prev + predots + middle + postdots + next + '</div>';
671 that.showPage = function (pageNum)
674 m_paz.showPage(m_curPage - 1);
678 // simple paging functions
679 that.pagerNext = function () {
680 if (m_totalRec - m_perpage*m_curPage > 0) {
687 that.pagerPrev = function () {
688 if (m_paz.showPrev() != false)
693 // switching view between targets and records
694 that.switchView = function(view) {
695 var targets = $('.mkwsTargets.mkwsTeam_' + m_teamName);
696 var results = $('.mkwsResults.mkwsTeam_' + m_teamName + ',.mkwsRecords.mkwsTeam_' + m_teamName);
697 var blanket = $('.mkwsBlanket.mkwsTeam_' + m_teamName);
698 var motd = $('.mkwsMOTD.mkwsTeam_' + m_teamName);
702 if (targets) targets.css('display', 'block');
703 if (results) results.css('display', 'none');
704 if (blanket) blanket.css('display', 'none');
705 if (motd) motd.css('display', 'none');
708 if (targets) targets.css('display', 'none');
709 if (results) results.css('display', 'block');
710 if (blanket) blanket.css('display', 'block');
711 if (motd) motd.css('display', 'none');
714 alert("mkws.switchView(" + m_teamName + ", 'none') shouldn't happen");
715 if (targets) targets.css('display', 'none');
716 if (results) results.css('display', 'none');
717 if (blanket) blanket.css('display', 'none');
718 if (motd) motd.css('display', 'none');
721 alert("Unknown view '" + view + "'");
726 // detailed record drawing
727 that.showDetails = function (prefixRecId) {
728 var recId = prefixRecId.replace('mkwsRec_', '');
729 var oldRecId = m_curDetRecId;
730 m_curDetRecId = recId;
732 // remove current detailed view if any
733 var detRecordDiv = document.getElementById('mkwsDet_' + m_teamName + '_' + oldRecId);
736 detRecordDiv.parentNode.removeChild(detRecordDiv);
738 // if the same clicked, just hide
739 if (recId == oldRecId) {
741 m_curDetRecData = null;
744 // request the record
745 debug("showDetails() requesting record '" + recId + "'");
750 function renderDetails(data, marker)
752 var template = loadTemplate("Record");
753 var details = template(data);
754 return '<div class="details" id="mkwsDet_' + m_teamName + '_' + data.recid + '">' + details + '</div>';
758 function loadTemplate(name)
760 var template = mkws['template' + name];
762 if (template === undefined) {
763 var source = $("#mkwsTemplate" + name).html();
765 source = defaultTemplate(name);
768 template = Handlebars.compile(source);
769 debug("compiled template '" + name + "'");
770 mkws['template' + name] = template;
777 function defaultTemplate(name)
779 if (name === 'Record') {
783 <th>{{translate "Title"}}</th>\
786 {{#if md-title-remainder}}\
787 ({{md-title-remainder}})\
789 {{#if md-title-responsibility}}\
790 <i>{{md-title-responsibility}}</i>\
796 <th>{{translate "Date"}}</th>\
797 <td>{{md-date}}</td>\
802 <th>{{translate "Author"}}</th>\
803 <td>{{md-author}}</td>\
806 {{#if md-electronic-url}}\
808 <th>{{translate "URL"}}</th>\
810 {{#each md-electronic-url}}\
811 <a href="{{this}}">{{this}}</a><br/>\
816 {{#if-any location having="md-subject"}}\
818 <th>{{translate "Subject"}}</th>\
820 {{#first location having="md-subject"}}\
829 <th>{{translate "Locations"}}</th>\
831 {{#commaList location}}\
832 {{attr "@name"}}{{/commaList}}\
837 } else if (name === "Summary") {
839 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
842 {{#if md-title-remainder}}\
843 <span>{{md-title-remainder}}</span>\
845 {{#if md-title-responsibility}}\
846 <span><i>{{md-title-responsibility}}</i></span>\
851 var s = "There is no default '" + name +"' template!";
858 * All the HTML stuff to render the search forms and
861 function mkws_html_all() {
863 if (mkws_config.show_lang)
866 debug("HTML search form");
867 // ### There is only one match here by design: fix not to bother looping
868 $('.mkwsSearch.mkwsTeam_' + m_teamName).each(function (i, obj) {
870 mkws.handle_node_with_team(node, function(tname) {
872 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + tname + '" action="" >\
873 <input class="mkwsQuery mkwsTeam_' + tname + '" type="text" size="' + mkws_config.query_width + '" />\
874 <input class="mkwsButton mkwsTeam_' + tname + '" type="submit" value="' + M('Search') + '" />\
879 debug("HTML records");
880 // If the team has a .mkwsResults, populate it in the usual
881 // way. If not, assume that it's a smarter application that
882 // defines its own subcomponents, some or all of the
889 if ($(".mkwsResults.mkwsTeam_" + m_teamName).length) {
890 $(".mkwsResults.mkwsTeam_" + m_teamName).html('\
891 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
893 <td class="mkwsTermlistContainer1 mkwsTeam_' + m_teamName + '" width="250" valign="top">\
894 <div class="mkwsTermlists mkwsTeam_' + m_teamName + '"></div>\
896 <td class="mkwsMOTDContainer mkwsTeam_' + m_teamName + '" valign="top">\
897 <div class="mkwsRanking mkwsTeam_' + m_teamName + '"></div>\
898 <div class="mkwsPager mkwsTeam_' + m_teamName + '"></div>\
899 <div class="mkwsNavi mkwsTeam_' + m_teamName + '"></div>\
900 <div class="mkwsRecords mkwsTeam_' + m_teamName + '"></div>\
905 <div class="mkwsTermlistContainer2 mkwsTeam_' + m_teamName + '"></div>\
911 var node = $(".mkwsRanking.mkwsTeam_" + m_teamName);
913 var ranking_data = '';
914 ranking_data += '<form name="mkwsSelect" class="mkwsSelect mkwsTeam_' + m_teamName + '" action="" >';
915 if (mkws_config.show_sort) {
916 ranking_data += M('Sort by') + ' ' + mkws_html_sort() + ' ';
918 if (mkws_config.show_perpage) {
919 ranking_data += M('and show') + ' ' + mkws_html_perpage() + ' ' + M('per page') + '.';
921 ranking_data += '</form>';
923 node.html(ranking_data);
928 // ### Should not be in the team code, since window size is global
929 if (mkws_config.responsive_design_width) {
930 // Responsive web design - change layout on the fly based on
931 // current screen width. Required for mobile devices.
932 $(window).resize(function(e) { mkws.resize_page() });
933 // initial check after page load
934 $(document).ready(function() { mkws.resize_page() });
937 $('.mkwsSearchForm.mkwsTeam_' + m_teamName).each(function (i, obj) {
938 debug("adding search-forms for team '" + m_teamName + "'");
940 mkws.handle_node_with_team(node, function(tname) {
941 debug("adding search-form '" + tname + "' for team '" + m_teamName + "'");
942 $(node).submit(onFormSubmitEventHandler);
946 node = $('.mkwsSort.mkwsTeam_' + m_teamName);
948 node.change(onSelectDdChange);
949 node = $('.mkwsPerpage.mkwsTeam_' + m_teamName);
951 node.change(onSelectDdChange);
953 // on first page, hide the termlist
954 $(document).ready(function() { $(".mkwsTermlists.mkwsTeam_" + m_teamName).hide(); });
955 var motd = $(".mkwsMOTD.mkwsTeam_" + m_teamName);
956 var container = $(".mkwsMOTDContainer.mkwsTeam_" + m_teamName);
957 if (motd.length && container.length) {
958 // Move the MOTD from the provided element down into the container
959 motd.appendTo(container);
964 // implement $.parseQuerystring() for parsing URL parameters
965 function parseQuerystring() {
967 var qs = window.location.search.replace('?', '');
968 var pairs = qs.split('&');
969 $.each(pairs, function(i, v){
970 var pair = v.split('=');
971 nvpair[pair[0]] = pair[1];
977 function mkws_set_lang() {
978 var lang = parseQuerystring().lang || mkws_config.lang;
979 if (!lang || !mkws.locale_lang[lang]) {
980 mkws_config.lang = ""
982 mkws_config.lang = lang;
985 debug("Locale language: " + (mkws_config.lang ? mkws_config.lang : "none"));
986 return mkws_config.lang;
990 function mkws_html_switch() {
991 debug("HTML switch for team " + m_teamName);
993 var node = $(".mkwsSwitch.mkwsTeam_" + m_teamName);
994 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'records\')">' + M('Records') + '</a>'));
995 node.append($("<span/>", { text: " | " }));
996 node.append($('<a href="#" onclick="mkws.switchView(\'' + m_teamName + '\', \'targets\')">' + M('Targets') + '</a>'));
998 debug("HTML targets");
999 var node = $(".mkwsTargets.mkwsTeam_" + m_teamName);
1001 <div class="mkwsBytarget mkwsTeam_' + m_teamName + '">\
1002 No information available yet.\
1004 node.css("display", "none");
1008 function mkws_html_sort() {
1009 debug("HTML sort, m_sort = '" + m_sort + "'");
1010 var sort_html = '<select class="mkwsSort mkwsTeam_' + m_teamName + '">';
1012 for(var i = 0; i < mkws_config.sort_options.length; i++) {
1013 var opt = mkws_config.sort_options[i];
1015 var val = opt.length == 1 ? opt[0] : opt[1];
1017 sort_html += '<option value="' + key + '"';
1018 if (m_sort == key || m_sort == val) {
1019 sort_html += ' selected="selected"';
1021 sort_html += '>' + M(val) + '</option>';
1023 sort_html += '</select>';
1029 function mkws_html_perpage() {
1030 debug("HTML perpage, m_perpage = " + m_perpage);
1031 var perpage_html = '<select class="mkwsPerpage mkwsTeam_' + m_teamName + '">';
1033 for(var i = 0; i < mkws_config.perpage_options.length; i++) {
1034 var key = mkws_config.perpage_options[i];
1036 perpage_html += '<option value="' + key + '"';
1037 if (key == m_perpage) {
1038 perpage_html += ' selected="selected"';
1040 perpage_html += '>' + key + '</option>';
1042 perpage_html += '</select>';
1044 return perpage_html;
1048 /* create locale language menu */
1049 function mkws_html_lang() {
1050 var lang_default = "en";
1051 var lang = mkws_config.lang || lang_default;
1054 /* display a list of configured languages, or all */
1055 var lang_options = mkws_config.lang_options || [];
1056 var toBeIncluded = {};
1057 for (var i = 0; i < lang_options.length; i++) {
1058 toBeIncluded[lang_options[i]] = true;
1061 for (var k in mkws.locale_lang) {
1062 if (toBeIncluded[k] || lang_options.length == 0)
1067 if (lang_options.length == 0 || toBeIncluded[lang_default])
1068 list.push(lang_default);
1070 debug("Language menu for: " + list.join(", "));
1074 for(var i = 0; i < list.length; i++) {
1081 data += ' <span>' + l + '</span> ';
1083 data += ' <a href="?lang=' + l + '">' + l + '</a> '
1087 $(".mkwsLang.mkwsTeam_" + m_teamName).html(data);
1093 var lang = mkws_config.lang;
1095 if (!lang || !mkws.locale_lang[lang])
1098 return mkws.locale_lang[lang][word] || word;
1100 mkws.M = M; // so the Handlebars helper can use it
1110 mkws_config.error = e.message;
1111 // alert(e.message);
1115 // Bizarrely, 'that' is just an empty hash. All its state is in
1116 // the closure variables defined earlier in this function.
1121 // wrapper to call team() after page load
1123 mkws.debug = function (string) {
1124 if (!mkws.debug_level)
1127 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
1131 // you need to disable use strict at the top of the file!!!
1132 if (mkws.debug_level >= 3) {
1133 console.log(arguments.callee.caller);
1134 } else if (mkws.debug_level >= 2) {
1135 console.log(">>> called from function " + arguments.callee.caller.name + ' <<<');
1137 console.log(string);
1139 var debug = mkws.debug;
1142 mkws.handle_node_with_team = function(node, callback) {
1143 var classes = node.className;
1144 var list = classes.split(/\s+/)
1146 for (var i = 0; i < list.length; i++) {
1147 var cname = list[i];
1148 if (cname.match(/^mkwsTeam_/)) {
1149 tname = cname.replace(/^mkwsTeam_/, '');
1156 mkws.resize_page = function () {
1157 var list = ["mkwsSwitch", "mkwsLang"];
1159 var width = mkws_config.responsive_design_width;
1160 var parent = $(".mkwsTermlists").parent();
1162 if ($(window).width() <= width &&
1163 parent.hasClass("mkwsTermlistContainer1")) {
1164 debug("changing from wide to narrow: " + $(window).width());
1165 $(".mkwsTermlistContainer1").hide();
1166 $(".mkwsTermlistContainer2").show();
1167 for (var tname in mkws.teams) {
1168 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer2.mkwsTeam_" + tname));
1169 for(var i = 0; i < list.length; i++) {
1170 $("." + list[i] + ".mkwsTeam_" + tname).hide();
1173 } else if ($(window).width() > width &&
1174 parent.hasClass("mkwsTermlistContainer2")) {
1175 debug("changing from narrow to wide: " + $(window).width());
1176 $(".mkwsTermlistContainer1").show();
1177 $(".mkwsTermlistContainer2").hide();
1178 for (var tname in mkws.teams) {
1179 $(".mkwsTermlists.mkwsTeam_" + tname).appendTo($(".mkwsTermlistContainer1.mkwsTeam_" + tname));
1180 for(var i = 0; i < list.length; i++) {
1181 $("." + list[i] + ".mkwsTeam_" + tname).show();
1188 mkws.switchView = function(tname, view) {
1189 mkws.teams[tname].switchView(view);
1192 mkws.showDetails = function (tname, prefixRecId) {
1193 mkws.teams[tname].showDetails(prefixRecId);
1196 mkws.limitTarget = function (tname, id, name) {
1197 mkws.teams[tname].limitTarget(id, name);
1200 mkws.limitQuery = function (tname, field, value) {
1201 mkws.teams[tname].limitQuery(field, value);
1204 mkws.delimitTarget = function (tname, id) {
1205 mkws.teams[tname].delimitTarget(id);
1208 mkws.delimitQuery = function (tname, field, value) {
1209 mkws.teams[tname].delimitQuery(field, value);
1212 mkws.showPage = function (tname, pageNum) {
1213 mkws.teams[tname].showPage(pageNum);
1216 mkws.pagerPrev = function (tname) {
1217 mkws.teams[tname].pagerPrev();
1220 mkws.pagerNext = function (tname) {
1221 mkws.teams[tname].pagerNext();
1225 function default_mkws_config() {
1226 /* default mkws config */
1227 var config_default = {
1228 use_service_proxy: true,
1229 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
1230 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
1232 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
1233 perpage_options: [10, 20, 30, 50],
1234 sort_default: "relevance",
1235 perpage_default: 20,
1237 show_lang: true, /* show/hide language menu */
1238 show_sort: true, /* show/hide sort menu */
1239 show_perpage: true, /* show/hide perpage menu */
1240 lang_options: [], /* display languages links for given languages, [] for all */
1241 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
1242 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
1243 debug_level: 1, /* debug level for development: 0..2 */
1248 /* Set global debug_level flag early so that debug() works */
1249 if (typeof mkws_config.debug_level !== 'undefined') {
1250 mkws.debug_level = mkws_config.debug_level;
1251 } else if (typeof config_default.debug_level !== 'undefined') {
1252 mkws.debug_level = config_default.debug_level;
1255 // make sure the mkws_config is a valid hash
1256 if (!$.isPlainObject(mkws_config)) {
1257 debug("ERROR: mkws_config is not an JS object, ignore it....");
1261 /* override standard config values by function parameters */
1262 for (var k in config_default) {
1263 if (typeof mkws_config[k] === 'undefined')
1264 mkws_config[k] = config_default[k];
1265 //debug("Set config: " + k + ' => ' + mkws_config[k]);
1271 * Run service-proxy authentication in background (after page load).
1272 * The username/password is configured in the apache config file
1275 function authenticate_session(auth_url, auth_domain, pp2_url) {
1276 debug("Run service proxy auth URL: " + auth_url);
1279 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
1280 debug("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
1283 var request = new pzHttpRequest(auth_url, function(err) {
1284 alert("HTTP call for authentication failed: " + err)
1288 request.get(null, function(data) {
1289 if (!$.isXMLDoc(data)) {
1290 alert("service proxy auth response document is not valid XML document, give up!");
1293 var status = $(data).find("status");
1294 if (status.text() != "OK") {
1295 alert("service proxy auth repsonse status: " + status.text() + ", give up!");
1299 debug("Service proxy auth successfully done");
1300 mkws.authenticated = true;
1301 run_auto_searches();
1306 function run_auto_searches() {
1307 debug("running auto searches");
1309 for (var teamName in mkws.teams) {
1310 // ### should check mkwsTermlist as well, for facet-only teams
1311 var node = $('.mkwsRecords.mkwsTeam_' + teamName);
1312 var query = node.attr('autosearch');
1313 if (query.match(/^!param!/)) {
1314 var param = query.replace(/^!param!/, '');
1315 query = getParameterByName(param);
1316 debug("obtained query '" + query + "' from param '" + param + "'");
1318 alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
1321 debug("teamName '" + teamName + "', node=" + node + ", class='" + node.className + "', query=" + query);
1324 var sort = node.attr('sort');
1325 var targets = node.attr('targets');
1326 var s = "running auto search: '" + query + "'";
1327 if (teamName) s += " [teamName '" + teamName + "']";
1328 if (sort) s += " sorted by '" + sort + "'";
1329 if (targets) s += " in targets '" + targets + "'";
1331 var team = mkws.teams[teamName];
1332 debug($.toJSON(team));
1333 team.newSearch(query, sort, targets, teamName);
1339 // This function is taken from a StackOverflow answer
1340 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
1341 function getParameterByName(name) {
1342 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
1343 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
1344 results = regex.exec(location.search);
1345 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
1349 $(document).ready(function() {
1350 debug("on load ready");
1351 default_mkws_config();
1353 // Backwards compatibility: set new magic class names on any
1354 // elements that have the old magic IDs.
1355 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
1356 "Results", "Records", "Targets", "Ranking",
1357 "Termlists", "Stat" ];
1358 for (var i = 0; i < ids.length; i++) {
1359 var id = 'mkws' + ids[i];
1360 var node = $('#' + id);
1361 if (node.attr('id')) {
1363 debug("added magic class to '" + node.attr('id') + "'");
1367 // For all MKWS-classed nodes that don't have a team
1368 // specified, set the team to AUTO.
1369 $('[class^="mkws"],[class*=" mkws"]').each(function () {
1370 if (!this.className.match(/mkwsTeam_/)) {
1371 debug("adding AUTO team to node with class '" + this.className + "'");
1372 $(this).addClass('mkwsTeam_AUTO');
1376 // Find all nodes with an class, and determine their team from
1377 // the mkwsTeam_* class. Make all team objects.
1378 $('[class^="mkws"],[class*=" mkws"]').each(function () {
1380 mkws.handle_node_with_team(node, function(tname) {
1381 if (!mkws.teams[tname]) {
1382 mkws.teams[tname] = team(j, tname);
1383 debug("Made MKWS team '" + tname + "'");
1388 if (mkws_config.use_service_proxy) {
1389 authenticate_session(mkws_config.service_proxy_auth,
1390 mkws_config.service_proxy_auth_domain,
1391 mkws_config.pazpar2_url);
1394 run_auto_searches();