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 debug("adding class 'foo' to node " + node);
411 mkws.handle_node_with_team(node, function(tname) {
412 $(node).submit(onFormSubmitEventHandler);
416 document.mkwsSearchForm.mkwsQuery.value = '';
417 if (document.mkwsSelect) {
418 if (document.mkwsSelect.mkwsSort)
419 document.mkwsSelect.mkwsSort.onchange = onSelectDdChange;
420 if (document.mkwsSelect.mkwsPerpage)
421 document.mkwsSelect.mkwsPerpage.onchange = onSelectDdChange;
426 // when search button pressed
427 function onFormSubmitEventHandler()
429 that.newSearch(document.mkwsSearchForm.mkwsQuery.value);
434 that.newSearch = function(query, sort, targets, windowid)
436 debug("newSearch: " + query);
438 if (mkws_config.use_service_proxy && !mkws.authenticated) {
439 alert("searching before authentication");
444 redraw_navi(); // ### should use windowid
445 resetPage(); // ### the globals it resents should be indexed by windowid
446 loadSelect(); // ### should use windowid
447 triggerSearch(query, sort, targets, windowid);
448 mkws.switchView('records'); // In case it's configured to start off as hidden
453 function onSelectDdChange()
455 if (!m_submitted) return false;
458 m_paz.show(0, m_recPerPage, m_sort);
470 function triggerSearch (query, sort, targets, windowid)
475 // Re-use previous query/sort if new ones are not specified
483 // ### should support multiple |-separated targets
484 m_filters.push({ id: targets, name: targets });
487 for (var i in m_filters) {
488 var filter = m_filters[i];
492 if (filter.id.match(/^[a-z:]+[=~]/)) {
493 debug("filter '" + filter.id + "' already begins with SETTING OP");
495 filter.id = 'pz:id=' + filter.id;
497 pp2filter += filter.id;
501 pp2limit += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
507 params.limit = pp2limit;
510 params.windowid = windowid;
512 debug("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
514 m_paz.search(m_query, m_recPerPage, m_sort, pp2filter, undefined, params);
518 function loadSelect ()
520 if (document.mkwsSelect) {
521 if (document.mkwsSelect.mkwsSort)
522 m_sort = document.mkwsSelect.mkwsSort.value;
523 if (document.mkwsSelect.mkwsPerpage)
524 m_recPerPage = document.mkwsSelect.mkwsPerpage.value;
529 // limit the query after clicking the facet
530 mkws.limitQuery = function (field, value)
532 debug("limitQuery(field=" + field + ", value=" + value + ")");
533 m_filters.push({ field: field, value: value });
542 // limit by target functions
543 mkws.limitTarget = function (id, name)
545 debug("limitTarget(id=" + id + ", name=" + name + ")");
546 m_filters.push({ id: id, name: name });
555 mkws.delimitQuery = function (field, value)
557 debug("delimitQuery(field=" + field + ", value=" + value + ")");
559 for (var i in m_filters) {
560 var filter = m_filters[i];
562 field == filter.field &&
563 value == filter.value) {
564 debug("delimitTarget() removing filter " + $.toJSON(filter));
566 debug("delimitTarget() keeping filter " + $.toJSON(filter));
567 newFilters.push(filter);
570 m_filters = newFilters;
580 mkws.delimitTarget = function (id)
582 debug("delimitTarget(id=" + id + ")");
584 for (var i in m_filters) {
585 var filter = m_filters[i];
587 debug("delimitTarget() removing filter " + $.toJSON(filter));
589 debug("delimitTarget() keeping filter " + $.toJSON(filter));
590 newFilters.push(filter);
593 m_filters = newFilters;
603 function redraw_navi ()
605 var navi = document.getElementById('mkwsNavi');
609 for (var i in m_filters) {
613 var filter = m_filters[i];
615 text += 'Source: <a class="crossout" href="#" onclick="mkws.delimitTarget(' +
616 "'" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
618 text += filter.field + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(' +
619 "'" + filter.field + "', '" + filter.value + "'" +
620 ');return false;">' + filter.value + '</a>';
624 navi.innerHTML = text;
628 function drawPager (pagerDiv)
630 //client indexes pages from 1 but pz2 from 0
632 var pages = Math.ceil(m_totalRec / m_recPerPage);
634 var firstClkbl = (m_curPage - onsides > 0)
635 ? m_curPage - onsides
638 var lastClkbl = firstClkbl + 2*onsides < pages
639 ? firstClkbl + 2*onsides
642 var prev = '<span id="mkwsPrev"><< ' + M('Prev') + '</span><b> | </b>';
644 prev = '<a href="#" id="mkwsPrev" onclick="mkws.pagerPrev();">'
645 +'<< ' + M('Prev') + '</a><b> | </b>';
648 for(var i = firstClkbl; i <= lastClkbl; i++) {
651 numLabel = '<b>' + i + '</b>';
653 middle += '<a href="#" onclick="mkws.showPage(' + i + ')"> '
654 + numLabel + ' </a>';
657 var next = '<b> | </b><span id="mkwsNext">' + M('Next') + ' >></span>';
658 if (pages - m_curPage > 0)
659 next = '<b> | </b><a href="#" id="mkwsNext" onclick="mkws.pagerNext()">'
660 + M('Next') + ' >></a>';
667 if (lastClkbl < pages)
670 pagerDiv.innerHTML += '<div style="float: clear">'
671 + prev + predots + middle + postdots + next + '</div>';
675 mkws.showPage = function (pageNum)
678 m_paz.showPage(m_curPage - 1);
682 // simple paging functions
683 mkws.pagerNext = function () {
684 if (m_totalRec - m_recPerPage*m_curPage > 0) {
691 mkws.pagerPrev = function () {
692 if (m_paz.showPrev() != false)
697 // switching view between targets and records
698 mkws.switchView = function(view) {
699 debug("switchView: " + view);
701 var targets = document.getElementById('mkwsTargets');
702 var results = document.getElementById('mkwsResults') ||
703 document.getElementById('mkwsRecords');
704 var blanket = document.getElementById('mkwsBlanket');
705 var motd = document.getElementById('mkwsMOTD');
709 if (targets) targets.style.display = "block";
710 if (results) results.style.display = "none";
711 if (blanket) blanket.style.display = "none";
712 if (motd) motd.style.display = "none";
715 if (targets) targets.style.display = "none";
716 if (results) results.style.display = "block";
717 if (blanket) blanket.style.display = "block";
718 if (motd) motd.style.display = "none";
721 if (targets) targets.style.display = "none";
722 if (results) results.style.display = "none";
723 if (blanket) blanket.style.display = "none";
724 if (motd) motd.style.display = "none";
727 alert("Unknown view '" + view + "'");
732 // detailed record drawing
733 that.showDetails = function (prefixRecId) {
734 var recId = prefixRecId.replace('mkwsRec_', '');
735 var oldRecId = m_curDetRecId;
736 m_curDetRecId = recId;
738 // remove current detailed view if any
739 var detRecordDiv = document.getElementById('mkwsDet_'+oldRecId);
742 detRecordDiv.parentNode.removeChild(detRecordDiv);
744 // if the same clicked, just hide
745 if (recId == oldRecId) {
747 m_curDetRecData = null;
750 // request the record
755 function renderDetails(data, marker)
757 var template = loadTemplate("Record");
758 var details = template(data);
759 return '<div class="details" id="mkwsDet_' + data.recid + '">' + details + '</div>';
763 function loadTemplate(name)
765 var template = mkws['template' + name];
767 if (template === undefined) {
768 var source = $("#mkwsTemplate" + name).html();
770 source = defaultTemplate(name);
773 template = Handlebars.compile(source);
774 debug("compiled template '" + name + "'");
775 mkws['template' + name] = template;
782 function defaultTemplate(name)
784 if (name === 'Record') {
788 <th>{{translate "Title"}}</th>\
791 {{#if md-title-remainder}}\
792 ({{md-title-remainder}})\
794 {{#if md-title-responsibility}}\
795 <i>{{md-title-responsibility}}</i>\
801 <th>{{translate "Date"}}</th>\
802 <td>{{md-date}}</td>\
807 <th>{{translate "Author"}}</th>\
808 <td>{{md-author}}</td>\
811 {{#if md-electronic-url}}\
813 <th>{{translate "URL"}}</th>\
815 {{#each md-electronic-url}}\
816 <a href="{{this}}">{{this}}</a><br/>\
821 {{#if-any location having="md-subject"}}\
823 <th>{{translate "Subject"}}</th>\
825 {{#first location having="md-subject"}}\
834 <th>{{translate "Locations"}}</th>\
836 {{#commaList location}}\
837 {{attr "@name"}}{{/commaList}}\
842 } else if (name === "Summary") {
844 <a href="#" id="{{_id}}" onclick="{{_onclick}}">\
847 {{#if md-title-remainder}}\
848 <span>{{md-title-remainder}}</span>\
850 {{#if md-title-responsibility}}\
851 <span><i>{{md-title-responsibility}}</i></span>\
856 var s = "There is no default '" + name +"' template!";
863 * All the HTML stuff to render the search forms and
866 function mkws_html_all() {
868 if (mkws_config.show_lang)
871 // For some reason, doing this programmatically results in
872 // document.mkwsSearchForm.mkwsQuery being undefined, hence the raw HTML.
873 debug("HTML search form");
874 $('.mkwsSearch').each(function (i, obj) {
876 mkws.handle_node_with_team(node, function(tname) {
878 <form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + tname + '" action="" >\
879 <input id="mkwsQuery" class="mkwsQuery mkwsTeam_' + tname + '" type="text" size="' + mkws_config.query_width + '" />\
880 <input id="mkwsButton" class="mkwsButton mkwsTeam_' + tname + '" type="submit" value="' + M('Search') + '" />\
885 debug("HTML records");
886 // If the application has an #mkwsResults, populate it in the
887 // usual way. If not, assume that it's a smarter application that
888 // defines its own subcomponents:
894 if ($("#mkwsResults").length) {
895 $("#mkwsResults").html('\
896 <table width="100%" border="0" cellpadding="6" cellspacing="0">\
898 <td id="mkwsTermlistContainer1" class="mkwsTermlistContainer1 mkwsTeam_AUTO" width="250" valign="top">\
899 <div id="mkwsTermlists" class="mkwsTermlists mkwsTeam_AUTO"></div>\
901 <td id="mkwsMOTDContainer" valign="top">\
902 <div id="mkwsRanking" class="mkwsRanking mkwsTeam_AUTO"></div>\
903 <div id="mkwsPager" class="mkwsPager mkwsTeam_AUTO"></div>\
904 <div id="mkwsNavi" class="mkwsNavi mkwsTeam_AUTO"></div>\
905 <div id="mkwsRecords" class="mkwsRecords mkwsTeam_AUTO"></div>\
910 <div id="mkwsTermlistContainer2" class="mkwsTermlistContainer2 mkwsTeam_AUTO"></div>\
916 if ($("#mkwsRanking").length) {
917 var ranking_data = '';
918 ranking_data += '<form name="mkwsSelect" id="mkwsSelect" action="" >';
919 if (mkws_config.show_sort) {
920 ranking_data += M('Sort by') + ' ' + mkws_html_sort() + ' ';
922 if (mkws_config.show_perpage) {
923 ranking_data += M('and show') + ' ' + mkws_html_perpage() + ' ' + M('per page') + '.';
925 ranking_data += '</form>';
927 $("#mkwsRanking").html(ranking_data);
932 if (mkws_config.responsive_design_width) {
933 // Responsive web design - change layout on the fly based on
934 // current screen width. Required for mobile devices.
935 $(window).resize(function(e) { mkws_resize_page() });
936 // initial check after page load
937 $(document).ready(function() { mkws_resize_page() });
942 // on first page, hide the termlist
943 $(document).ready(function() { $("#mkwsTermlists").hide(); });
944 var motd = document.getElementById("mkwsMOTD");
945 var container = document.getElementById("mkwsMOTDContainer");
946 if (motd && container) {
947 // Move the MOTD from the provided element down into the container
948 motd.parentNode.removeChild(motd);
949 container.appendChild(motd);
954 // implement $.parseQuerystring() for parsing URL parameters
955 function parseQuerystring() {
957 var qs = window.location.search.replace('?', '');
958 var pairs = qs.split('&');
959 $.each(pairs, function(i, v){
960 var pair = v.split('=');
961 nvpair[pair[0]] = pair[1];
967 function mkws_set_lang() {
968 var lang = parseQuerystring().lang || mkws_config.lang;
969 if (!lang || !mkws.locale_lang[lang]) {
970 mkws_config.lang = ""
972 mkws_config.lang = lang;
975 debug("Locale language: " + (mkws_config.lang ? mkws_config.lang : "none"));
976 return mkws_config.lang;
980 function mkws_html_switch() {
981 debug("HTML switch");
983 $("#mkwsSwitch").append($('<a href="#" id="mkwsSwitch_records" onclick="mkws.switchView(\'records\')">' + M('Records') + '</a>'));
984 $("#mkwsSwitch").append($("<span/>", { text: " | " }));
985 $("#mkwsSwitch").append($('<a href="#" id="mkwsSwitch_targets" onclick="mkws.switchView(\'targets\')">' + M('Targets') + '</a>'));
987 debug("HTML targets");
988 $("#mkwsTargets").html('\
989 <div id="mkwsBytarget" class="mkwsBytarget mkwsTeam_AUTO">\
990 No information available yet.\
992 $("#mkwsTargets").css("display", "none");
996 function mkws_html_sort() {
997 debug("HTML sort, m_sort = '" + m_sort + "'");
998 var sort_html = '<select name="mkwsSort" id="mkwsSort">';
1000 for(var i = 0; i < mkws_config.sort_options.length; i++) {
1001 var opt = mkws_config.sort_options[i];
1003 var val = opt.length == 1 ? opt[0] : opt[1];
1005 sort_html += '<option value="' + key + '"';
1006 if (m_sort == key || m_sort == val) {
1007 sort_html += ' selected="selected"';
1009 sort_html += '>' + M(val) + '</option>';
1011 sort_html += '</select>';
1017 function mkws_html_perpage() {
1018 debug("HTML perpage");
1019 var perpage_html = '<select name="mkwsPerpage" id="mkwsPerpage">';
1021 for(var i = 0; i < mkws_config.perpage_options.length; i++) {
1022 var key = mkws_config.perpage_options[i];
1024 perpage_html += '<option value="' + key + '"';
1025 if (key == mkws_config.perpage_default) {
1026 perpage_html += ' selected="selected"';
1028 perpage_html += '>' + key + '</option>';
1030 perpage_html += '</select>';
1032 return perpage_html;
1036 /* create locale language menu */
1037 function mkws_html_lang() {
1038 var lang_default = "en";
1039 var lang = mkws_config.lang || lang_default;
1042 /* display a list of configured languages, or all */
1043 var lang_options = mkws_config.lang_options || [];
1045 for (var i = 0; i < lang_options.length; i++) {
1046 hash[lang_options[i]] = 1;
1049 for (var k in mkws.locale_lang) {
1050 if (hash[k] == 1 || lang_options.length == 0)
1055 if (lang_options.length == 0 || hash[lang_default] == 1)
1056 list.push(lang_default);
1058 debug("Language menu for: " + list.join(", "));
1062 for(var i = 0; i < list.length; i++) {
1069 data += ' <span>' + l + '</span> ';
1071 data += ' <a href="?lang=' + l + '">' + l + '</a> '
1075 $("#mkwsLang").html(data);
1079 function mkws_resize_page () {
1080 var list = ["mkwsSwitch"];
1082 var width = mkws_config.responsive_design_width;
1083 var parentId = $("#mkwsTermlists").parent().attr('id');
1085 if ($(window).width() <= width &&
1086 parentId === "mkwsTermlistContainer1") {
1087 debug("changing from wide to narrow: " + $(window).width());
1088 $("#mkwsTermlists").appendTo($("#mkwsTermlistContainer2"));
1089 $("#mkwsTermlistContainer1").hide();
1090 $("#mkwsTermlistContainer2").show();
1091 for(var i = 0; i < list.length; i++) {
1092 $("#" + list[i]).hide();
1094 } else if ($(window).width() > width &&
1095 parentId === "mkwsTermlistContainer2") {
1096 debug("changing from narrow to wide: " + $(window).width());
1097 $("#mkwsTermlists").appendTo($("#mkwsTermlistContainer1"));
1098 $("#mkwsTermlistContainer1").show();
1099 $("#mkwsTermlistContainer2").hide();
1100 for(var i = 0; i < list.length; i++) {
1101 $("#" + list[i]).show();
1109 var lang = mkws_config.lang;
1111 if (!lang || !mkws.locale_lang[lang])
1114 return mkws.locale_lang[lang][word] || word;
1116 mkws.M = M; // so the Handlebars helper can use it
1126 mkws_config.error = e.message;
1127 // alert(e.message);
1131 // Bizarrely, 'that' is just an empty hash. All its state is in
1132 // the closure variables defined earlier in this function.
1138 * implement jQuery plugin $.pazpar2({})
1140 function _mkws_jquery_plugin ($) {
1141 var debug_level = 1;
1143 function debug (string) {
1147 if (typeof console === "undefined" || typeof console.log === "undefined")
1150 console.log("jquery.pazpar2: " + string);
1153 function init_popup(obj) {
1154 var config = obj ? obj : {};
1156 var height = config.height || 760;
1157 var width = config.width || 880;
1158 var id_button = config.id_button || "input#mkwsButton";
1159 var id_popup = config.id_popup || "#mkwsPopup";
1161 debug("popup height: " + height + ", width: " + width);
1163 // make sure that jquery-ui was loaded afte jQuery core lib, e.g.:
1164 // <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
1166 debug("Error: jquery-ui.js is missing, did you include it after jQuery core in the HTML file?");
1170 $(id_popup).dialog({
1171 closeOnEscape: true,
1178 Cancel: function() {
1179 $(this).dialog("close");
1182 close: function() { }
1188 $(id_popup).dialog("open");
1194 // service-proxy or pazpar2
1195 pazpar2: function(config) {
1196 var id_popup = config.id_popup || "#mkwsPopup";
1197 id_popup = id_popup.replace(/^#/, "");
1201 <div id="mkwsSwitch"></div>\
1202 <div id="mkwsLang"></div>\
1203 <div id="mkwsSearch"></div>\
1204 <div id="mkwsResults"></div>\
1205 <div id="mkwsTargets"></div>\
1206 <div id="mkwsStat"></div>';
1210 <style type="text/css">\
1211 #mkwsTermlists div.facet {\
1221 <table width="100%" border="0">\
1224 <div id="mkwsSwitch"></div>\
1225 <div id="mkwsLang"></div>\
1226 <div id="mkwsSearch"></div>\
1231 <div style="height:500px; overflow: auto">\
1232 <div id="mkwsPager"></div>\
1233 <div id="mkwsNavi"></div>\
1234 <div id="mkwsRecords"></div>\
1235 <div id="mkwsTargets"></div>\
1236 <div id="mkwsRanking"></div>\
1242 <div style="height:300px; overflow: hidden">\
1243 <div id="mkwsTermlists"></div>\
1249 <div id="mkwsStat"></div>\
1255 <div id="mkwsSearch"></div>\
1256 <div id="' + id_popup + '">\
1257 <div id="mkwsSwitch"></div>\
1258 <div id="mkwsLang"></div>\
1259 <div id="mkwsResults"></div>\
1260 <div id="mkwsTargets"></div>\
1261 <div id="mkwsStat"></div>\
1264 if (config && config.layout == 'div') {
1265 debug("jquery plugin layout: div");
1266 document.write(div);
1267 } else if (config && config.layout == 'popup') {
1268 debug("jquery plugin layout: popup with id: " + id_popup);
1269 document.write(popup);
1270 $(document).ready(function() { init_popup(config); });
1272 debug("jquery plugin layout: table");
1273 document.write(table);
1280 // wrapper to call team() after page load
1283 if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
1289 // enable before page load, so we could call it before mkws() runs
1290 _mkws_jquery_plugin(j);
1292 $(document).ready(function() {
1293 log("on load ready");
1294 default_mkws_config();
1296 // Backwards compatibility: set new magic class names on any
1297 // elements that have the old magic IDs.
1298 var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
1299 "Results", "Records", "Targets", "Ranking",
1300 "Termlists", "Stat" ];
1301 for (var i = 0; i < ids.length; i++) {
1302 var id = 'mkws' + ids[i];
1303 var node = $('#' + id);
1304 if (node.attr('id')) {
1305 node.addClass(id + " mkwsTeam_AUTO");
1306 log("added magic classes to '" + node.attr('id') + "'");
1310 // Find all nodes with class (NOT id) mkwsRecords, and
1311 // determine their team from the mkwsTeam_* class. So:
1312 // <div class="mkwsRecords mkwsTeam_foo"/>
1313 $('.mkwsSearch, .mkwsResults, .mkwsRecords, .mkwsTermlists').each(function () {
1315 mkws.handle_node_with_team(node, function(tname) {
1316 if (mkws.teams[tname]) {
1317 log("MKWS team '" + tname + "' already exists, skipping");
1319 mkws.teams[tname] = team(j, tname);
1320 log("Made MKWS team '" + tname + "'");
1325 if (mkws_config.use_service_proxy) {
1326 authenticate_session(mkws_config.service_proxy_auth,
1327 mkws_config.service_proxy_auth_domain,
1328 mkws_config.pazpar2_url);
1331 run_auto_searches();
1336 mkws.handle_node_with_team = function(node, callback) {
1337 var classes = node.className;
1338 var list = classes.split(/\s+/)
1340 for (var i = 0; i < list.length; i++) {
1341 var cname = list[i];
1342 if (cname.match(/^mkwsTeam_/)) {
1343 tname = cname.replace(/^mkwsTeam_/, '');
1352 mkws.showDetails = function (prefixRecId, tname) {
1353 mkws.teams[tname].showDetails(prefixRecId);
1357 function default_mkws_config() {
1358 /* default mkws config */
1359 var config_default = {
1360 use_service_proxy: true,
1361 pazpar2_url: "//mkws.indexdata.com/service-proxy/",
1362 service_proxy_auth: "//mkws.indexdata.com/service-proxy-auth",
1364 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
1365 perpage_options: [10, 20, 30, 50],
1366 sort_default: "relevance",
1367 perpage_default: 20,
1369 show_lang: true, /* show/hide language menu */
1370 show_sort: true, /* show/hide sort menu */
1371 show_perpage: true, /* show/hide perpage menu */
1372 lang_options: [], /* display languages links for given languages, [] for all */
1373 facets: ["sources", "subjects", "authors"], /* display facets, in this order, [] for none */
1374 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
1375 debug_level: 1, /* debug level for development: 0..2 */
1380 /* Set global debug_level flag early so that debug() works */
1381 if (typeof mkws_config.debug_level !== 'undefined') {
1382 mkws.debug_level = mkws_config.debug_level;
1383 } else if (typeof config_default.debug_level !== 'undefined') {
1384 mkws.debug_level = config_default.debug_level;
1387 // make sure the mkws_config is a valid hash
1388 if (!$.isPlainObject(mkws_config)) {
1389 debug("ERROR: mkws_config is not an JS object, ignore it....");
1393 /* override standard config values by function parameters */
1394 for (var k in config_default) {
1395 if (typeof mkws_config[k] === 'undefined')
1396 mkws_config[k] = config_default[k];
1397 //debug("Set config: " + k + ' => ' + mkws_config[k]);
1403 * Run service-proxy authentication in background (after page load).
1404 * The username/password is configured in the apache config file
1407 function authenticate_session(auth_url, auth_domain, pp2_url) {
1408 console.log("Run service proxy auth URL: " + auth_url);
1411 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
1412 console.log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
1415 var request = new pzHttpRequest(auth_url, function(err) {
1416 alert("HTTP call for authentication failed: " + err)
1420 request.get(null, function(data) {
1421 if (!$.isXMLDoc(data)) {
1422 alert("service proxy auth response document is not valid XML document, give up!");
1425 var status = $(data).find("status");
1426 if (status.text() != "OK") {
1427 alert("service proxy auth repsonse status: " + status.text() + ", give up!");
1431 console.log("Service proxy auth successfully done");
1432 mkws.authenticated = true;
1433 run_auto_searches();
1438 function run_auto_searches() {
1439 console.log("running auto searches");
1441 for (var teamName in mkws.teams) {
1442 // ### should check mkwsTermlist as well, for facet-only teams
1443 var node = $('.mkwsRecords.mkwsTeam_' + teamName);
1444 var query = node.attr('autosearch');
1445 console.log("teamName '" + teamName + "', node=" + node + ", class='" + node.className + "', query=" + query);
1448 var sort = node.attr('sort');
1449 var targets = node.attr('targets');
1450 var s = "running auto search: '" + query + "'";
1451 if (teamName) s += " [teamName '" + teamName + "']";
1452 if (sort) s += " sorted by '" + sort + "'";
1453 if (targets) s += " in targets '" + targets + "'";
1455 var team = mkws.teams[teamName];
1456 console.log($.toJSON(team));
1457 team.newSearch(query, sort, targets, teamName);