1 /*! MKWS, the MasterKey Widget Set. Copyright (C) 2013-2014, Index Data */
3 "use strict"; // HTML5: disable for debug_level >= 2
7 Handlebars.registerHelper('json', function(obj) {
12 Handlebars.registerHelper('translate', function(s) {
17 // We need {{attr '@name'}} because Handlebars can't parse {{@name}}
18 Handlebars.registerHelper('attr', function(attrName) {
19 return this[attrName];
24 * Use as follows: {{#if-any NAME1 having="NAME2"}}
25 * Applicable when NAME1 is the name of an array
26 * The guarded code runs only if at least one element of the NAME1
27 * array has a subelement called NAME2.
29 Handlebars.registerHelper('if-any', function(items, options) {
30 var having = options.hash.having;
31 for (var i in items) {
33 if (!having || item[having]) {
34 return options.fn(this);
41 Handlebars.registerHelper('first', function(items, options) {
42 var having = options.hash.having;
43 for (var i in items) {
45 if (!having || item[having]) {
46 return options.fn(item);
53 Handlebars.registerHelper('commaList', function(items, options) {
56 for (var i in items) {
57 if (i > 0) out += ", ";
58 out += options.fn(items[i])
66 // Some functions are visible to be called from outside code, namely
67 // generated HTML: mkws.switchView(), showDetails(), limitTarget(),
68 // limitQuery(), delimitTarget(), delimitQuery(), pagerPrev(),
69 // pagerNext(), showPage(). Also mkws.M() is made available for the
70 // Handlebars helper 'translate'
73 // Set up global mkws object. Contains a hash of team objects,
74 // indexed by windowid.
77 debug_function: undefined, // will be set during initialisation
78 debug_level: undefined, // will be initialised from mkws_config
79 paz: undefined, // will be set up during initialisation
84 "Subjects": "Schlagwörter",
85 "Sources": "Daten und Quellen",
86 "Termlists": "Termlisten",
88 "Prev": "Zurück",
90 "Sort by": "Sortieren nach",
91 "and show": "und zeige",
92 "per page": "pro Seite",
93 "Displaying": "Zeige",
100 "Subject": "Schlagwort",
102 "Records": "Datensätze",
103 "Targets": "Datenbanken",
109 "Authors": "Forfattere",
112 "Termlists": "Termlists",
113 "Next": "Næste",
115 "Search": "Søg",
116 "Sort by": "Sorter efter",
117 "and show": "og vis",
118 "per page": "per side",
119 "Displaying": "Viser",
124 "Author": "Forfatter",
126 "Subject": "Emneord",
127 "Location": "Lokation",
137 // Define empty mkws_config for simple applications that don't define it.
138 if (mkws_config == null || typeof mkws_config != 'object') {
139 var mkws_config = {};
143 // wrapper for jQuery lib
144 function team($, teamName) {
146 var m_teamName = teamName;
147 var m_submitted = false;
148 var m_query; // initially undefined
149 var m_sort = 'relevance';
152 var m_recPerPage = 20;
154 var m_curDetRecId = '';
155 var m_curDetRecData = null;
157 // Timestamps for logging
161 var m_paz; // will be initialised below
164 // if (console && console.log) // disabled, will fail in IE8
165 // console.log("run team(" + (teamName ? teamName : "") + ")");
168 // Needs to be defined inside team() so it can see m_debug_time
169 // ### member access won't work: there is only one instance of this function
170 mkws.debug_function = function (string) {
171 if (!mkws.debug_level)
174 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
179 var timestamp = ((now - m_debug_time.start)/1000).toFixed(3) + " (+" + ((now - m_debug_time.last)/1000).toFixed(3) + ") "
180 m_debug_time.last = now;
182 // you need to disable use strict at the top of the file!!!
183 if (mkws.debug_level >= 3) {
184 console.log(timestamp + arguments.callee.caller);
185 } else if (mkws.debug_level >= 2) {
186 console.log(timestamp + ">>> called from function " + arguments.callee.caller.name + ' <<<');
188 console.log(timestamp + string);
190 var debug = mkws.debug_function; // local alias
191 debug("start running MKWS");
193 m_sort = mkws_config.sort_default;
194 debug("copied mkws_config.sort_default '" + mkws_config.sort_default + "' to m_sort");
196 if (mkws_config.query_width < 5 || mkws_config.query_width > 150) {
197 debug("Reset query width: " + mkws_config.query_width);
198 mkws_config.query_width = 50;
201 for (var key in mkws_config) {
202 if (mkws_config.hasOwnProperty(key)) {
203 if (key.match(/^language_/)) {
204 var lang = key.replace(/^language_/, "");
205 // Copy custom languages into list
206 mkws.locale_lang[lang] = mkws_config[key];
207 debug("Added locally configured language '" + lang + "'");
212 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
213 if (mkws_config.pazpar2_url.match(/^\/\//)) {
214 mkws_config.pazpar2_url = document.location.protocol + mkws_config.pazpar2_url;
215 debug("adjust protocol independent links: " + mkws_config.pazpar2_url);
218 debug("Create main pz2 object");
219 // create a parameters array and pass it to the pz2's constructor
220 // then register the form submit event with the pz2.search function
221 // autoInit is set to true on default
222 m_paz = new pz2({ "onshow": my_onshow,
223 "windowid": teamName,
224 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
225 "pazpar2path": mkws_config.pazpar2_url,
229 "termlist": "xtargets,subject,author",
230 "onbytarget": my_onbytarget,
231 "usesessions" : mkws_config.use_service_proxy ? false : true,
232 "showResponseType": '', // or "json" (for debugging?)
233 "onrecord": my_onrecord });
235 if (!isNaN(parseInt(mkws_config.perpage_default))) {
236 m_recPerPage = parseInt(mkws_config.perpage_default);
241 // pz2.js event handlers:
243 function my_oninit(teamName) {
244 debug("init for " + teamName);
250 function my_onshow(data, teamName) {
251 debug("show for " + teamName);
252 m_totalRec = data.merged;
254 var pager = document.getElementById("mkwsPager");
256 pager.innerHTML = "";
257 pager.innerHTML +='<div style="float: right">' + M('Displaying') + ': '
258 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
259 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
260 + data.total + ')</div>';
265 var results = $(".mkwsRecords.mkwsTeam_" + m_teamName);
268 for (var i = 0; i < data.hits.length; i++) {
269 var hit = data.hits[i];
270 html.push('<div class="record" id="mkwsRecdiv_' + hit.recid + '" >',
273 if (hit.recid == m_curDetRecId) {
274 html.push(renderDetails(m_curDetRecData));
277 results.html(html.join(''));
281 function renderSummary(hit)
283 var template = loadTemplate("Summary");
284 hit._id = "mkwsRec_" + hit.recid;
285 hit._onclick = "mkws.showDetails(this.id, '" + m_teamName + "');return false;"
286 return template(hit);
290 function my_onstat(data, teamName) {
291 debug("stat for " + teamName);
292 var stat = document.getElementById("mkwsStat");
296 stat.innerHTML = '<span class="head">' + M('Status info') + '</span>' +
298 '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
300 '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>';
304 function my_onterm(data, teamName) {
305 debug("term for " + teamName);
307 if (!mkws_config.facets || mkws_config.facets.length == 0) {
308 $("#mkwsTermlists").hide();
312 // display if we first got results
313 $("#mkwsTermlists").show();
316 acc.push('<div class="title">' + M('Termlists') + '</div>');
317 var facets = mkws_config.facets;
319 for(var i = 0; i < facets.length; i++) {
320 if (facets[i] == "sources") {
321 add_single_facet(acc, "Sources", data.xtargets, 16, null);
322 } else if (facets[i] == "subjects") {
323 add_single_facet(acc, "Subjects", data.subject, 10, "subject");
324 } else if (facets[i] == "authors") {
325 add_single_facet(acc, "Authors", data.author, 10, "author");
327 alert("bad facet configuration: '" + facets[i] + "'");
331 var termlist = $("#mkwsTermlists");
333 termlist.html(acc.join(''));
337 function add_single_facet(acc, caption, data, max, pzIndex) {
338 acc.push('<div class="facet" id="mkwsFacet' + caption + '">');
339 acc.push('<div class="termtitle">' + M(caption) + '</div>');
340 for (var i = 0; i < data.length && i < max; i++) {
341 acc.push('<div class="term">');
342 acc.push('<a href="#" ');
345 // Special case: target selection
346 acc.push('target_id='+data[i].id+' ');
347 action = 'mkws.limitTarget(this.getAttribute(\'target_id\'),this.firstChild.nodeValue)';
349 action = 'mkws.limitQuery(\'' + pzIndex + '\', this.firstChild.nodeValue)';
351 acc.push('onclick="' + action + ';return false;">' + data[i].name + '</a>'
352 + ' <span>' + data[i].freq + '</span>');
359 function my_onrecord(data, args, teamName) {
360 debug("record for " + teamName);
361 // FIXME: record is async!!
362 clearTimeout(m_paz.recordTimer);
363 // in case on_show was faster to redraw element
364 var detRecordDiv = document.getElementById('mkwsDet_'+data.recid);
365 if (detRecordDiv) return;
366 m_curDetRecData = data;
367 var recordDiv = document.getElementById('mkwsRecdiv_'+m_curDetRecData.recid);
368 var html = renderDetails(m_curDetRecData);
369 recordDiv.innerHTML += html;
373 function my_onbytarget(data, teamName) {
374 debug("target for " + teamName);
375 var targetDiv = document.getElementById("mkwsBytarget");
377 // No mkwsTargets div.
381 var table ='<table><thead><tr>' +
382 '<td>' + M('Target ID') + '</td>' +
383 '<td>' + M('Hits') + '</td>' +
384 '<td>' + M('Diags') + '</td>' +
385 '<td>' + M('Records') + '</td>' +
386 '<td>' + M('State') + '</td>' +
387 '</tr></thead><tbody>';
389 for (var i = 0; i < data.length; i++) {
390 table += "<tr><td>" + data[i].id +
391 "</td><td>" + data[i].hits +
392 "</td><td>" + data[i].diagnostic +
393 "</td><td>" + data[i].records +
394 "</td><td>" + data[i].state + "</td></tr>";
397 table += '</tbody></table>';
398 targetDiv.innerHTML = table;
401 ////////////////////////////////////////////////////////////////////////////////
402 ////////////////////////////////////////////////////////////////////////////////
405 // wait until the DOM is ready
408 $('.mkwsSearchForm').each(function (i, obj) {
410 mkws.handle_node_with_team(node, function(tname) {
411 $(node).submit(onFormSubmitEventHandler);
415 document.mkwsSearchForm.mkwsQuery.value = '';
416 if (document.mkwsSelect) {
417 if (document.mkwsSelect.mkwsSort)
418 document.mkwsSelect.mkwsSort.onchange = onSelectDdChange;
419 if (document.mkwsSelect.mkwsPerpage)
420 document.mkwsSelect.mkwsPerpage.onchange = onSelectDdChange;
425 // when search button pressed
426 function onFormSubmitEventHandler()
428 mkws.handle_node_with_team(this, function (tname) {
429 var val = $('.mkwsQuery.mkwsTeam_' + tname).val();
430 mkws.teams[tname].newSearch(val);
437 that.newSearch = function(query, sort, targets, windowid)
439 debug("newSearch: " + query);
441 if (mkws_config.use_service_proxy && !mkws.authenticated) {
442 alert("searching before authentication");
447 redraw_navi(); // ### should use windowid
448 resetPage(); // ### the globals it resents should be indexed by windowid
449 loadSelect(); // ### should use windowid
450 triggerSearch(query, sort, targets, windowid);
451 mkws.switchView('records'); // In case it's configured to start off as hidden
456 function onSelectDdChange()
458 if (!m_submitted) return false;
461 m_paz.show(0, m_recPerPage, m_sort);
473 function triggerSearch (query, sort, targets, windowid)
478 // Re-use previous query/sort if new ones are not specified
486 // ### should support multiple |-separated targets
487 m_filters.push({ id: targets, name: targets });
490 for (var i in m_filters) {
491 var filter = m_filters[i];
495 if (filter.id.match(/^[a-z:]+[=~]/)) {
496 debug("filter '" + filter.id + "' already begins with SETTING OP");
498 filter.id = 'pz:id=' + filter.id;
500 pp2filter += filter.id;
504 pp2limit += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
510 params.limit = pp2limit;
513 params.windowid = windowid;
515 debug("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
517 m_paz.search(m_query, m_recPerPage, m_sort, pp2filter, undefined, params);
521 function loadSelect ()
523 if (document.mkwsSelect) {
524 if (document.mkwsSelect.mkwsSort)
525 m_sort = document.mkwsSelect.mkwsSort.value;
526 if (document.mkwsSelect.mkwsPerpage)
527 m_recPerPage = document.mkwsSelect.mkwsPerpage.value;
532 // limit the query after clicking the facet
533 mkws.limitQuery = function (field, value)
535 debug("limitQuery(field=" + field + ", value=" + value + ")");
536 m_filters.push({ field: field, value: value });
545 // limit by target functions
546 mkws.limitTarget = function (id, name)
548 debug("limitTarget(id=" + id + ", name=" + name + ")");
549 m_filters.push({ id: id, name: name });
558 mkws.delimitQuery = function (field, value)
560 debug("delimitQuery(field=" + field + ", value=" + value + ")");
562 for (var i in m_filters) {
563 var filter = m_filters[i];
565 field == filter.field &&
566 value == filter.value) {
567 debug("delimitTarget() removing filter " + $.toJSON(filter));
569 debug("delimitTarget() keeping filter " + $.toJSON(filter));
570 newFilters.push(filter);
573 m_filters = newFilters;
583 mkws.delimitTarget = function (id)
585 debug("delimitTarget(id=" + id + ")");
587 for (var i in m_filters) {
588 var filter = m_filters[i];
590 debug("delimitTarget() removing filter " + $.toJSON(filter));
592 debug("delimitTarget() keeping filter " + $.toJSON(filter));
593 newFilters.push(filter);
596 m_filters = newFilters;
606 function redraw_navi ()
608 var navi = document.getElementById('mkwsNavi');
612 for (var i in m_filters) {
616 var filter = m_filters[i];
618 text += 'Source: <a class="crossout" href="#" onclick="mkws.delimitTarget(' +
619 "'" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
621 text += filter.field + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(' +
622 "'" + filter.field + "', '" + filter.value + "'" +
623 ');return false;">' + filter.value + '</a>';
627 navi.innerHTML = text;
631 function drawPager (pagerDiv)
633 //client indexes pages from 1 but pz2 from 0
635 var pages = Math.ceil(m_totalRec / m_recPerPage);
637 var firstClkbl = (m_curPage - onsides > 0)
638 ? m_curPage - onsides
641 var lastClkbl = firstClkbl + 2*onsides < pages
642 ? firstClkbl + 2*onsides
645 var prev = '<span id="mkwsPrev"><< ' + M('Prev') + '</span><b> | </b>';
647 prev = '<a href="#" id="mkwsPrev" onclick="mkws.pagerPrev();">'
648 +'<< ' + M('Prev') + '</a><b> | </b>';
651 for(var i = firstClkbl; i <= lastClkbl; i++) {
654 numLabel = '<b>' + i + '</b>';
656 middle += '<a href="#" onclick="mkws.showPage(' + i + ')"> '
657 + numLabel + ' </a>';
660 var next = '<b> | </b><span id="mkwsNext">' + M('Next') + ' >></span>';
661 if (pages - m_curPage > 0)
662 next = '<b> | </b><a href="#" id="mkwsNext" onclick="mkws.pagerNext()">'
663 + M('Next') + ' >></a>';
670 if (lastClkbl < pages)
673 pagerDiv.innerHTML += '<div style="float: clear">'
674 + prev + predots + middle + postdots + next + '</div>';
678 mkws.showPage = function (pageNum)
681 m_paz.showPage(m_curPage - 1);
685 // simple paging functions
686 mkws.pagerNext = function () {
687 if (m_totalRec - m_recPerPage*m_curPage > 0) {
694 mkws.pagerPrev = function () {
695 if (m_paz.showPrev() != false)
700 // switching view between targets and records
701 mkws.switchView = function(view) {
702 debug("switchView: " + view);
704 var targets = document.getElementById('mkwsTargets');
705 var results = document.getElementById('mkwsResults') ||
706 document.getElementById('mkwsRecords');
707 var blanket = document.getElementById('mkwsBlanket');
708 var motd = document.getElementById('mkwsMOTD');
712 if (targets) targets.style.display = "block";
713 if (results) results.style.display = "none";
714 if (blanket) blanket.style.display = "none";
715 if (motd) motd.style.display = "none";
718 if (targets) targets.style.display = "none";
719 if (results) results.style.display = "block";
720 if (blanket) blanket.style.display = "block";
721 if (motd) motd.style.display = "none";
724 if (targets) targets.style.display = "none";
725 if (results) results.style.display = "none";
726 if (blanket) blanket.style.display = "none";
727 if (motd) motd.style.display = "none";
730 alert("Unknown view '" + view + "'");
735 // detailed record drawing
736 that.showDetails = function (prefixRecId) {
737 var recId = prefixRecId.replace('mkwsRec_', '');
738 var oldRecId = m_curDetRecId;
739 m_curDetRecId = recId;
741 // remove current detailed view if any
742 var detRecordDiv = document.getElementById('mkwsDet_'+oldRecId);
745 detRecordDiv.parentNode.removeChild(detRecordDiv);
747 // if the same clicked, just hide
748 if (recId == oldRecId) {
750 m_curDetRecData = null;
753 // request the record
758 function renderDetails(data, marker)
760 var template = loadTemplate("Record");
761 var details = template(data);
762 return '<div class="details" id="mkwsDet_' + data.recid + '">' + details + '</div>';
766 function loadTemplate(name)
768 var template = mkws['template' + name];
770 if (template === undefined) {
771 var source = $("#mkwsTemplate" + name).html();
773 source = defaultTemplate(name);
776 template = Handlebars.compile(source);
777 debug("compiled template '" + name + "'");
778 mkws['template' + name] = template;
785 function defaultTemplate(name)
787 if (name === 'Record') {
791 <th>{{translate "Title"}}</th>\
794 {{#if md-title-remainder}}\
795 ({{md-title-remainder}})\
797 {{#if md-title-responsibility}}\
798 <i>{{md-title-responsibility}}</i>\
804 <th>{{translate "Date"}}</th>\
805 <td>{{md-date}}</td>\
810 <th>{{translate "Author"}}</th>\
811 <td>{{md-author}}</td>\
814 {{#if md-electronic-url}}\
816 <th>{{translate "URL"}}</th>\
818 {{#each md-electronic-url}}\
819 <a href="{{this}}">{{this}}</a><br/>\
824 {{#if-any location having="md-subject"}}\
826 <th>{{translate "Subject"}}</th>\
828 {{#first location having="md-subject"}}\
837 <th>{{translate "Locations"}}</th>\
839 {{#commaList location}}\
840 {{attr "@name"}}{{/commaList}}\
845 } else if (name === "Summary") {
847 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
850 {{#if md-title-remainder}}\
851 <span>{{md-title-remainder}}</span>\
853 {{#if md-title-responsibility}}\
854 <span><i>{{md-title-responsibility}}</i></span>\
859 var s = "There is no default '" + name +"' template!";
866 * All the HTML stuff to render the search forms and
869 function mkws_html_all() {
871 if (mkws_config.show_lang)
874 // For some reason, doing this programmatically results in
875 // document.mkwsSearchForm.mkwsQuery being undefined, hence the raw HTML.
876 debug("HTML search form");
877 $('.mkwsSearch').each(function (i, obj) {
879 mkws.handle_node_with_team(node, function(tname) {
881 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + tname + '" action="" >\
882 <input id="mkwsQuery" class="mkwsQuery mkwsTeam_' + tname + '" type="text" size="' + mkws_config.query_width + '" />\
883 <input id="mkwsButton" class="mkwsButton mkwsTeam_' + tname + '" type="submit" value="' + M('Search') + '" />\
888 debug("HTML records");
889 // If the application has an #mkwsResults, populate it in the
890 // usual way. If not, assume that it's a smarter application that
891 // defines its own subcomponents:
897 if ($("#mkwsResults").length) {
898 $("#mkwsResults").html('\
899 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
901 <td id="mkwsTermlistContainer1" class="mkwsTermlistContainer1 mkwsTeam_AUTO" width="250" valign="top">\
902 <div id="mkwsTermlists" class="mkwsTermlists mkwsTeam_AUTO"></div>\
904 <td id="mkwsMOTDContainer" valign="top">\
905 <div id="mkwsRanking" class="mkwsRanking mkwsTeam_AUTO"></div>\
906 <div id="mkwsPager" class="mkwsPager mkwsTeam_AUTO"></div>\
907 <div id="mkwsNavi" class="mkwsNavi mkwsTeam_AUTO"></div>\
908 <div id="mkwsRecords" class="mkwsRecords mkwsTeam_AUTO"></div>\
913 <div id="mkwsTermlistContainer2" class="mkwsTermlistContainer2 mkwsTeam_AUTO"></div>\
919 if ($("#mkwsRanking").length) {
920 var ranking_data = '';
921 ranking_data += '<form name="mkwsSelect" id="mkwsSelect" action="" >';
922 if (mkws_config.show_sort) {
923 ranking_data += M('Sort by') + ' ' + mkws_html_sort() + ' ';
925 if (mkws_config.show_perpage) {
926 ranking_data += M('and show') + ' ' + mkws_html_perpage() + ' ' + M('per page') + '.';
928 ranking_data += '</form>';
930 $("#mkwsRanking").html(ranking_data);
935 if (mkws_config.responsive_design_width) {
936 // Responsive web design - change layout on the fly based on
937 // current screen width. Required for mobile devices.
938 $(window).resize(function(e) { mkws_resize_page() });
939 // initial check after page load
940 $(document).ready(function() { mkws_resize_page() });
945 // on first page, hide the termlist
946 $(document).ready(function() { $("#mkwsTermlists").hide(); });
947 var motd = document.getElementById("mkwsMOTD");
948 var container = document.getElementById("mkwsMOTDContainer");
949 if (motd && container) {
950 // Move the MOTD from the provided element down into the container
951 motd.parentNode.removeChild(motd);
952 container.appendChild(motd);
957 // implement $.parseQuerystring() for parsing URL parameters
958 function parseQuerystring() {
960 var qs = window.location.search.replace('?', '');
961 var pairs = qs.split('&');
962 $.each(pairs, function(i, v){
963 var pair = v.split('=');
964 nvpair[pair[0]] = pair[1];
970 function mkws_set_lang() {
971 var lang = parseQuerystring().lang || mkws_config.lang;
972 if (!lang || !mkws.locale_lang[lang]) {
973 mkws_config.lang = ""
975 mkws_config.lang = lang;
978 debug("Locale language: " + (mkws_config.lang ? mkws_config.lang : "none"));
979 return mkws_config.lang;
983 function mkws_html_switch() {
984 debug("HTML switch");
986 $("#mkwsSwitch").append($('<a href="#" id="mkwsSwitch_records" onclick="mkws.switchView(\'records\')">' + M('Records') + '</a>'));
987 $("#mkwsSwitch").append($("<span/>", { text: " | " }));
988 $("#mkwsSwitch").append($('<a href="#" id="mkwsSwitch_targets" onclick="mkws.switchView(\'targets\')">' + M('Targets') + '</a>'));
990 debug("HTML targets");
991 $("#mkwsTargets").html('\
992 <div id="mkwsBytarget" class="mkwsBytarget mkwsTeam_AUTO">\
993 No information available yet.\
995 $("#mkwsTargets").css("display", "none");
999 function mkws_html_sort() {
1000 debug("HTML sort, m_sort = '" + m_sort + "'");
1001 var sort_html = '<select name="mkwsSort" id="mkwsSort">';
1003 for(var i = 0; i < mkws_config.sort_options.length; i++) {
1004 var opt = mkws_config.sort_options[i];
1006 var val = opt.length == 1 ? opt[0] : opt[1];
1008 sort_html += '<option value="' + key + '"';
1009 if (m_sort == key || m_sort == val) {
1010 sort_html += ' selected="selected"';
1012 sort_html += '>' + M(val) + '</option>';
1014 sort_html += '</select>';
1020 function mkws_html_perpage() {
1021 debug("HTML perpage");
1022 var perpage_html = '<select name="mkwsPerpage" id="mkwsPerpage">';
1024 for(var i = 0; i < mkws_config.perpage_options.length; i++) {
1025 var key = mkws_config.perpage_options[i];
1027 perpage_html += '<option value="' + key + '"';
1028 if (key == mkws_config.perpage_default) {
1029 perpage_html += ' selected="selected"';
1031 perpage_html += '>' + key + '</option>';
1033 perpage_html += '</select>';
1035 return perpage_html;
1039 /* create locale language menu */
1040 function mkws_html_lang() {
1041 var lang_default = "en";
1042 var lang = mkws_config.lang || lang_default;
1045 /* display a list of configured languages, or all */
1046 var lang_options = mkws_config.lang_options || [];
1048 for (var i = 0; i < lang_options.length; i++) {
1049 hash[lang_options[i]] = 1;
1052 for (var k in mkws.locale_lang) {
1053 if (hash[k] == 1 || lang_options.length == 0)
1058 if (lang_options.length == 0 || hash[lang_default] == 1)
1059 list.push(lang_default);
1061 debug("Language menu for: " + list.join(", "));
1065 for(var i = 0; i < list.length; i++) {
1072 data += ' <span>' + l + '</span> ';
1074 data += ' <a href="?lang=' + l + '">' + l + '</a> '
1078 $("#mkwsLang").html(data);
1082 function mkws_resize_page () {
1083 var list = ["mkwsSwitch"];
1085 var width = mkws_config.responsive_design_width;
1086 var parentId = $("#mkwsTermlists").parent().attr('id');
1088 if ($(window).width() <= width &&
1089 parentId === "mkwsTermlistContainer1") {
1090 debug("changing from wide to narrow: " + $(window).width());
1091 $("#mkwsTermlists").appendTo($("#mkwsTermlistContainer2"));
1092 $("#mkwsTermlistContainer1").hide();
1093 $("#mkwsTermlistContainer2").show();
1094 for(var i = 0; i < list.length; i++) {
1095 $("#" + list[i]).hide();
1097 } else if ($(window).width() > width &&
1098 parentId === "mkwsTermlistContainer2") {
1099 debug("changing from narrow to wide: " + $(window).width());
1100 $("#mkwsTermlists").appendTo($("#mkwsTermlistContainer1"));
1101 $("#mkwsTermlistContainer1").show();
1102 $("#mkwsTermlistContainer2").hide();
1103 for(var i = 0; i < list.length; i++) {
1104 $("#" + list[i]).show();
1112 var lang = mkws_config.lang;
1114 if (!lang || !mkws.locale_lang[lang])
1117 return mkws.locale_lang[lang][word] || word;
1119 mkws.M = M; // so the Handlebars helper can use it
1129 mkws_config.error = e.message;
1130 // alert(e.message);
1134 // Bizarrely, 'that' is just an empty hash. All its state is in
1135 // the closure variables defined earlier in this function.
1141 * implement jQuery plugin $.pazpar2({})
1143 function _mkws_jquery_plugin ($) {
1144 var debug_level = 1;
1146 function debug (string) {
1150 if (typeof console === "undefined" || typeof console.log === "undefined")
1153 console.log("jquery.pazpar2: " + string);
1156 function init_popup(obj) {
1157 var config = obj ? obj : {};
1159 var height = config.height || 760;
1160 var width = config.width || 880;
1161 var id_button = config.id_button || "input#mkwsButton";
1162 var id_popup = config.id_popup || "#mkwsPopup";
1164 debug("popup height: " + height + ", width: " + width);
1166 // make sure that jquery-ui was loaded afte jQuery core lib, e.g.:
1167 // <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
1169 debug("Error: jquery-ui.js is missing, did you include it after jQuery core in the HTML file?");
1173 $(id_popup).dialog({
1174 closeOnEscape: true,
1181 Cancel: function() {
1182 $(this).dialog("close");
1185 close: function() { }
1191 $(id_popup).dialog("open");
1197 // service-proxy or pazpar2
1198 pazpar2: function(config) {
1199 var id_popup = config.id_popup || "#mkwsPopup";
1200 id_popup = id_popup.replace(/^#/, "");
1204 <div id="mkwsSwitch"></div>\
1205 <div id="mkwsLang"></div>\
1206 <div id="mkwsSearch"></div>\
1207 <div id="mkwsResults"></div>\
1208 <div id="mkwsTargets"></div>\
1209 <div id="mkwsStat"></div>';
1213 <style type="text/css">\
1214 #mkwsTermlists div.facet {\
1224 <table width="100%" border="0">\
1227 <div id="mkwsSwitch"></div>\
1228 <div id="mkwsLang"></div>\
1229 <div id="mkwsSearch"></div>\
1234 <div style="height:500px; overflow: auto">\
1235 <div id="mkwsPager"></div>\
1236 <div id="mkwsNavi"></div>\
1237 <div id="mkwsRecords"></div>\
1238 <div id="mkwsTargets"></div>\
1239 <div id="mkwsRanking"></div>\
1245 <div style="height:300px; overflow: hidden">\
1246 <div id="mkwsTermlists"></div>\
1252 <div id="mkwsStat"></div>\
1258 <div id="mkwsSearch"></div>\
1259 <div id="' + id_popup + '">\
1260 <div id="mkwsSwitch"></div>\
1261 <div id="mkwsLang"></div>\
1262 <div id="mkwsResults"></div>\
1263 <div id="mkwsTargets"></div>\
1264 <div id="mkwsStat"></div>\
1267 if (config && config.layout == 'div') {
1268 debug("jquery plugin layout: div");
1269 document.write(div);
1270 } else if (config && config.layout == 'popup') {
1271 debug("jquery plugin layout: popup with id: " + id_popup);
1272 document.write(popup);
1273 $(document).ready(function() { init_popup(config); });
1275 debug("jquery plugin layout: table");
1276 document.write(table);
1283 // wrapper to call team() after page load
1286 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
1292 // enable before page load, so we could call it before mkws() runs
1293 _mkws_jquery_plugin(j);
1295 $(document).ready(function() {
1296 log("on load ready");
1297 default_mkws_config();
1299 // Backwards compatibility: set new magic class names on any
1300 // elements that have the old magic IDs.
1301 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
1302 "Results", "Records", "Targets", "Ranking",
1303 "Termlists", "Stat" ];
1304 for (var i = 0; i < ids.length; i++) {
1305 var id = 'mkws' + ids[i];
1306 var node = $('#' + id);
1307 if (node.attr('id')) {
1308 node.addClass(id + " mkwsTeam_AUTO");
1309 log("added magic classes to '" + node.attr('id') + "'");
1313 // Find all nodes with class (NOT id) mkwsRecords, and
1314 // determine their team from the mkwsTeam_* class. So:
1315 // <div class="mkwsRecords mkwsTeam_foo"/>
1316 $('.mkwsSearch, .mkwsResults, .mkwsRecords, .mkwsTermlists').each(function () {
1318 mkws.handle_node_with_team(node, function(tname) {
1319 if (mkws.teams[tname]) {
1320 log("MKWS team '" + tname + "' already exists, skipping");
1322 mkws.teams[tname] = team(j, tname);
1323 log("Made MKWS team '" + tname + "'");
1328 if (mkws_config.use_service_proxy) {
1329 authenticate_session(mkws_config.service_proxy_auth,
1330 mkws_config.service_proxy_auth_domain,
1331 mkws_config.pazpar2_url);
1334 run_auto_searches();
1339 mkws.handle_node_with_team = function(node, callback) {
1340 var classes = node.className;
1341 var list = classes.split(/\s+/)
1343 for (var i = 0; i < list.length; i++) {
1344 var cname = list[i];
1345 if (cname.match(/^mkwsTeam_/)) {
1346 tname = cname.replace(/^mkwsTeam_/, '');
1355 mkws.showDetails = function (prefixRecId, tname) {
1356 mkws.teams[tname].showDetails(prefixRecId);
1360 function default_mkws_config() {
1361 /* default mkws config */
1362 var config_default = {
1363 use_service_proxy: true,
1364 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
1365 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
1367 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
1368 perpage_options: [10, 20, 30, 50],
1369 sort_default: "relevance",
1370 perpage_default: 20,
1372 show_lang: true, /* show/hide language menu */
1373 show_sort: true, /* show/hide sort menu */
1374 show_perpage: true, /* show/hide perpage menu */
1375 lang_options: [], /* display languages links for given languages, [] for all */
1376 facets: ["sources", "subjects", "authors"], /* display facets, in this order, [] for none */
1377 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
1378 debug_level: 1, /* debug level for development: 0..2 */
1383 /* Set global debug_level flag early so that debug() works */
1384 if (typeof mkws_config.debug_level !== 'undefined') {
1385 mkws.debug_level = mkws_config.debug_level;
1386 } else if (typeof config_default.debug_level !== 'undefined') {
1387 mkws.debug_level = config_default.debug_level;
1390 // make sure the mkws_config is a valid hash
1391 if (!$.isPlainObject(mkws_config)) {
1392 debug("ERROR: mkws_config is not an JS object, ignore it....");
1396 /* override standard config values by function parameters */
1397 for (var k in config_default) {
1398 if (typeof mkws_config[k] === 'undefined')
1399 mkws_config[k] = config_default[k];
1400 //debug("Set config: " + k + ' => ' + mkws_config[k]);
1406 * Run service-proxy authentication in background (after page load).
1407 * The username/password is configured in the apache config file
1410 function authenticate_session(auth_url, auth_domain, pp2_url) {
1411 console.log("Run service proxy auth URL: " + auth_url);
1414 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
1415 console.log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
1418 var request = new pzHttpRequest(auth_url, function(err) {
1419 alert("HTTP call for authentication failed: " + err)
1423 request.get(null, function(data) {
1424 if (!$.isXMLDoc(data)) {
1425 alert("service proxy auth response document is not valid XML document, give up!");
1428 var status = $(data).find("status");
1429 if (status.text() != "OK") {
1430 alert("service proxy auth repsonse status: " + status.text() + ", give up!");
1434 console.log("Service proxy auth successfully done");
1435 mkws.authenticated = true;
1436 run_auto_searches();
1441 function run_auto_searches() {
1442 console.log("running auto searches");
1444 for (var teamName in mkws.teams) {
1445 // ### should check mkwsTermlist as well, for facet-only teams
1446 var node = $('.mkwsRecords.mkwsTeam_' + teamName);
1447 var query = node.attr('autosearch');
1448 console.log("teamName '" + teamName + "', node=" + node + ", class='" + node.className + "', query=" + query);
1451 var sort = node.attr('sort');
1452 var targets = node.attr('targets');
1453 var s = "running auto search: '" + query + "'";
1454 if (teamName) s += " [teamName '" + teamName + "']";
1455 if (sort) s += " sorted by '" + sort + "'";
1456 if (targets) s += " in targets '" + targets + "'";
1458 var team = mkws.teams[teamName];
1459 console.log($.toJSON(team));
1460 team.newSearch(query, sort, targets, teamName);