1 /* A very simple client that shows a basic usage of the pz2.js
4 // create a parameters array and pass it to the pz2's constructor
5 // then register the form submit event with the pz2.search function
6 // autoInit is set to true on default
7 var usesessions = false;
8 var pazpar2path = '/service-proxy/';
9 var showResponseType = '';
10 // Facet configuration
11 var querys = {'su': '', 'au': '', 'xt': ''};
12 var query_client_server = {'su': 'subject', 'au': 'author', 'xt': 'xtargets'};
13 var querys_server = {};
15 // Fail to get JSON working stabil.
16 var showResponseType = 'xml';
18 var imageHelper = new ImageHelper();
20 if (document.location.hash == '#pazpar2' || document.location.search.match("useproxy=false")) {
22 pazpar2path = '/pazpar2/search.pz2';
23 showResponseType = 'xml';
26 my_paz = new pz2( { "onshow": my_onshow,
27 // "showtime": 2000, //each timer (show, stat, term, bytarget) can be specified this way
28 "pazpar2path": pazpar2path,
31 "onterm": my_onterm_iphone,
32 "termlist": "xtargets,subject,author",
34 "usesessions" : usesessions,
35 "showResponseType": showResponseType,
36 "onrecord": my_onrecord,
37 "errorhandler" : my_onerror}
42 var recToShowPageSize = 20;
43 var recToShow = recToShowPageSize;
47 var curDetRecData = null;
48 var curSort = 'relevance';
49 var curFilter = 'ALL';
50 var submitted = false;
54 var tab = "recordview";
60 // pz2.js event handlers:
62 function my_onerror(error) {
65 case "8": alert("No resources were selected for the search"); break;
66 // target not configured, this is a pazpar2 bug
67 // but for now simply research
78 auth.check(loggedIn, login);
81 alert("Unhandled error: " + error.code);
82 throw error; // display error in JavaScript console
86 function loginFormSubmit() {
87 triedUser = document.loginForm.username.value;
88 triedPass = document.loginForm.password.value;
89 auth.login( {"username": triedUser,
90 "password": triedPass},
94 function handleKeyPress(e)
98 key = window.event.keyCode;
102 if(key == 13 || key == 10)
104 button = document.getElementById('button');
114 function authCb(authData) {
115 if (!authData.loginFailed) {
120 if (authData.loggedIn == true) {
121 showhide("recordview");
125 function logOutClick() {
126 auth.logOut(authCb, authCb);
129 function loggedOut() {
130 var login = document.getElementById("login");
131 login.innerHTML = 'Login';
134 function loggingOutFailed() {
135 alert("Logging out failed");
143 auth.logOut(loggedOut, loggingOutFailed, true);
146 function logInOrOut() {
147 var loginElement = document.getElementById("login");
148 if (loginElement.innerHTML == 'Login')
153 function loggedIn() {
154 var login = document.getElementById("login");
155 login.innerHTML = 'Logout';
156 document.getElementById("log").innerHTML = login.innerHTML;
159 function auth_check() {
160 auth.check(loggedIn, login);
165 // Pz2.js event handlers:
167 function my_oninit() {
172 function showMoreRecords() {
174 recToShow += recToShowPageSize;
175 for ( ; i < recToShow && i < recPerPage; i++) {
176 var element = document.getElementById(recIDs[i]);
178 element.style.display = '';
180 if (i == recPerPage) {
181 var element = document.getElementById('recdiv_END');
183 element.style.display = 'none';
187 function hideRecords() {
188 for ( var i = 0; i < recToShow; i++) {
189 var element = document.getElementById(recIDs[i]);
190 if (element && recIDs != curDetRecId)
191 element.style.display = 'none';
193 var element = document.getElementById('recdiv_END');
195 element.style.display = 'none';
198 function showRecords() {
199 for (var i = 0 ; i < recToShow && i < recPerPage; i++) {
200 var element = document.getElementById(recIDs[i]);
202 element.style.display = '';
204 var element = document.getElementById('recdiv_END');
207 element.style.display = 'none';
209 element.style.display = '';
216 function my_onshow(data) {
217 totalRec = data.merged;
219 var pager = document.getElementById("pager");
220 pager.innerHTML = "";
222 pager.innerHTML +='<div class="status">Displaying: '
223 + (data.start + 1) + ' to ' + (data.start + data.num) +
224 ' of ' + data.merged + ' (found: '
225 + data.total + ')</div>';
227 var results = document.getElementById("results");
230 if (data.hits == undefined)
233 for (var i = 0; i < data.hits.length; i++) {
234 var hit = data.hits[i];
235 var recDivID = "recdiv_" + hit.recid;
236 recIDs[i] = recDivID;
239 style = ' style="display:none" ';
240 html.push('<li class="img" id="' + recDivID + '" ' + style + '>' );
241 html.push('<a class="img" href="#' + i + '" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;" >');
243 var useThumbnails = hit["md-use_thumbnails"];
244 var thumburls = hit["md-thumburl"];
245 if (thumburls && (useThumbnails == undefined || useThumbnails == "1")) {
246 var thumbnailtag = imageHelper.getImageTagByRecId(hit.recid,"md-thumburl", 60, "S");
247 html.push(thumbnailtag);
249 if (hit["md-isbn"] != undefined) {
250 var coverimagetag = imageHelper.getImageTagByRecId(hit.recid, "md-isbn", 60, "S");
251 if (coverimagetag.length>0) {
252 html.push(coverimagetag);
260 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
261 html.push(hit["md-title"]);
264 if (hit["md-title-remainder"] != undefined) {
265 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
266 html.push(hit["md-title-remainder"]);
270 if (hit["md-author"] != undefined) {
271 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
272 html.push(hit["md-author"]);
276 else if (hit["md-title-responsibility"] != undefined) {
277 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
278 html.push(hit["md-title-responsibility"]);
282 for (var idx = lines ; idx < 2 ; idx++) {
283 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
288 if (hit.recid == curDetRecId) {
289 html.push(renderDetails_iphone(curDetRecData));
294 if (data.activeclients == 0)
295 document.getElementById("loading").style.display = 'none';
297 // set up "More..." if needed.
298 style = 'display:none';
299 if (recToShow < recPerPage) {
300 style = 'display:block';
302 html.push('<li class="img" id="recdiv_END" style="' + style + '"><a onclick="showMoreRecords()">More...</a></li>');
304 replaceHtml(results, html.join(''));
307 function my_onstat(data) {
308 var stat = document.getElementById("stat");
312 stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
314 + '/' + data.clients + ' -- </span>'
315 + '<span>Retrieved records: ' + data.records
316 + '/' + data.hits + ' :.</span>';
319 function showhide(newtab, hash) {
320 var showtermlist = false;
324 if (tab == "recordview") {
325 document.getElementById("recordview").style.display = '';
326 if (hash != undefined)
327 document.location.hash = hash;
330 document.getElementById("recordview").style.display = 'none';
332 if (tab == "xtargets") {
333 document.getElementById("term_xtargets").style.display = '';
337 document.getElementById("term_xtargets").style.display = 'none';
339 if (tab == "subjects") {
340 document.getElementById("term_subjects").style.display = '';
344 document.getElementById("term_subjects").style.display = 'none';
346 if (tab == "authors") {
347 document.getElementById("term_authors").style.display = '';
351 document.getElementById("term_authors").style.display = 'none';
353 if (tab == "detailview") {
354 document.getElementById("detailview").style.display = '';
357 document.getElementById("detailview").style.display = 'none';
358 var element = document.getElementById("rec_" + curDetRecId);
359 if (element != undefined)
360 element.scrollIntoView();
363 if (showtermlist == false)
364 document.getElementById("termlist").style.display = 'none';
366 document.getElementById("termlist").style.display = '';
368 var tabDiv = document.getElementById("loginDiv");
369 if (tab == "login") {
370 tabDiv.style.display = '';
373 tabDiv.style.display = 'none';
377 function my_onterm(data) {
380 termlists.push('<div id="term_xtargets" >');
381 termlists.push('<h4 class="termtitle">Sources</h4>');
382 termlists.push('<ul class="termlist">');
383 termlists.push('<li> <a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
384 for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
385 termlists.push('<li class="termlist"><a href="#" target_id='+data.xtargets[i].id
386 + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">'
387 + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
389 termlists.push('</ul>');
390 termlists.push('</div>');
392 termlists.push('<div id="term_subjects" >');
393 termlists.push('<h4>Subjects</h4>');
394 termlists.push('<ul class="termlist">');
395 termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
396 for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
397 termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">'
398 + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
400 termlists.push('</ul>');
401 termlists.push('</div>');
403 termlists.push('<div id="term_authors" >');
404 termlists.push('<h4 class="termtitle">Authors</h4>');
405 termlists.push('<ul class="termlist">');
406 termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All</a></li>');
407 for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
408 termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'au\', \'' + data.author[i].name +'\');return false;">'
409 + data.author[i].name
411 + data.author[i].freq
414 termlists.push('</ul>');
415 termlists.push('</div>');
416 var termlist = document.getElementById("termlist");
417 replaceHtml(termlist, termlists.join(''));
422 function my_onterm_iphone(data) {
424 var targets = "reset_xt|All\n";
426 for (var i = 0; i < data.xtargets.length; i++ ) {
428 targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
430 termlist["xtargets"] = targets;
431 var subjects = "reset_su|All\n";
432 for (var i = 0; i < data.subject.length; i++ ) {
433 subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
435 termlist["subjects"] = subjects;
436 var authors = "reset_au|All\n";
437 for (var i = 0; i < data.author.length; i++ ) {
438 authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
440 termlist["authors"] = authors;
441 callback.send("termlist", "refresh");
444 function getTargets() {
445 return termlist['xtargets'];
448 function getSubjects() {
449 return termlist['subjects'];
452 function getAuthors() {
453 return termlist['authors'];
456 function my_onrecord(data) {
458 // FIXME: record is async!!
459 clearTimeout(my_paz.recordTimer);
460 // in case on_show was faster to redraw element
461 var detailRecordDiv = document.getElementById('detailrecord');
462 if (!detailRecordDiv)
464 curDetRecData = data;
465 var html = renderDetails_iphone(curDetRecData);
466 detailRecordDiv.innerHTML = html;
467 showhide('detailview');
468 document.getElementById("loading").style.display = 'none';
471 function my_onrecord_iphone(data) {
473 callback.send("record", data.recid, data, data.xtargets[i].freq);
477 function my_onbytarget(data) {
478 var targetDiv = document.getElementById("bytarget");
479 var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
480 +'<td>Records</td><td>State</td></tr></thead><tbody>';
482 for (var i = 0; i < data.length; i++ ) {
483 table += "<tr><td>" + data[i].id +
484 "</td><td>" + data[i].hits +
485 "</td><td>" + data[i].diagnostic +
486 "</td><td>" + data[i].records +
487 "</td><td>" + data[i].state + "</td></tr>";
490 table += '</tbody></table>';
491 targetDiv.innerHTML = table;
494 ////////////////////////////////////////////////////////////////////////////////
495 ////////////////////////////////////////////////////////////////////////////////
497 // wait until the DOM is ready
500 document.search.onsubmit = onFormSubmitEventHandler;
501 document.search.query.value = '';
502 document.select.sort.onchange = onSelectDdChange;
503 document.select.perpage.onchange = onSelectDdChange;
504 if (document.location.search.match("inApp=true"))
505 applicationMode(true);
507 applicationMode(false);
509 var params = parseQueryString(window.location.search);
511 document.search.query.value = params.query;
512 onFormSubmitEventHandler();
516 function applicationMode(newmode)
518 var searchdiv = document.getElementById("searchForm");
522 document.getElementById("heading").style.display="none";
523 searchdiv.style.display = 'none';
527 document.getElementById("nav").style.display="";
528 document.getElementById("normal").style.display="inline";
529 document.getElementById("normal").style.visibility="";
530 searchdiv.style.display = '';
531 document.search.onsubmit = onFormSubmit;
535 // when search button pressed
536 function onFormSubmitEventHandler()
539 document.getElementById("logo").style.display = 'none';
546 function onSelectDdChange()
548 if (!submitted) return false;
551 my_paz.show(0, recPerPage, curSort);
561 function getFacets() {
563 for (var key in querys_server) {
564 if (result.length > 0)
566 result += querys_server[key];
571 function triggerSearch ()
573 // Restore to initial page size
574 recToShow = recToShowPageSize;
575 document.getElementById("loading").style.display = 'inline';
576 my_paz.search(document.search.query.value, recPerPage, curSort, curFilter, undefined,
578 "limit" : getFacets()
581 showhide("recordview");
584 function loadSelect ()
586 curSort = document.select.sort.value;
587 recPerPage = document.select.perpage.value;
590 // limit the query after clicking the facet
591 function limitQuery(field, value)
593 var newQuery = ' and ' + field + '="' + value + '"';
594 querys[field] += newQuery;
595 document.search.query.value += newQuery;
596 onFormSubmitEventHandler();
597 showhide("recordview");
600 // limit the query after clicking the facet
601 function limitQueryServer(field, value)
603 // Check for client field usage
604 var fieldname = query_client_server[field];
608 var newQuery = fieldname + '=' + value.replace(",", "\\,").replace("|", "\\,");
609 // Does it already exists?
610 if (querys_server[fieldname])
611 querys_server[fieldname] += "," + newQuery;
613 querys_server[fieldname] = newQuery;
614 // document.search.query.value += newQuery;
615 onFormSubmitEventHandler();
616 showhide("recordview");
621 // limit the query after clicking the facet
622 function removeQuery (field, value) {
623 document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
624 onFormSubmitEventHandler();
625 showhide("recordview");
628 // limit the query after clicking the facet
629 function limitOrResetQuery (field, value, selected) {
631 limitOrResetQueryServer(field,value, selected);
634 if (field == 'reset_su' || field == 'reset_au') {
635 var reset_field = field.substring(6);
636 document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
637 querys[reset_field] = '';
638 onFormSubmitEventHandler();
639 showhide("recordview");
642 limitQuery(field, value);
643 //alert("limitOrResetQuerry: query after: " + document.search.query.value);
646 // limit the query after clicking the facet
647 function limitOrResetQueryServer (field, value, selected) {
648 if (field.substring(0,6) == 'reset_') {
649 var clientname = field.substring(6);
650 var fieldname = query_client_server[clientname];
652 fieldname = clientname;
653 delete querys_server[fieldname];
654 onFormSubmitEventHandler();
655 showhide("recordview");
658 limitQueryServer(field, value);
659 //alert("limitOrResetQuerry: query after: " + document.search.query.value);
665 // limit by target functions
666 function limitTarget (id, name)
668 curFilter = 'pz:id=' + id;
675 function delimitTarget ()
684 function limitOrResetTarget(id, name) {
685 if (id == 'reset_xt') {
689 limitTarget(id,name);
693 function drawPager (pagerDiv)
695 //client indexes pages from 1 but pz2 from 0
697 var pages = Math.ceil(totalRec / recPerPage);
699 var firstClkbl = ( curPage - onsides > 0 )
703 var lastClkbl = firstClkbl + 2*onsides < pages
704 ? firstClkbl + 2*onsides
707 var prev = '<span id="prev">Prev</span><b> | </b>';
709 var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
710 +'Prev</a><b> | </b>';
713 for(var i = firstClkbl; i <= lastClkbl; i++) {
716 numLabel = '<b>' + i + '</b>';
718 middle += '<a href="#" onclick="showPage(' + i + ')"> '
719 + numLabel + ' </a>';
722 var next = '<b> | </b><span id="next">Next</span>';
723 if (pages - curPage > 0)
724 var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
732 if (lastClkbl < pages)
735 pagerDiv.innerHTML += '<div class="pager">'
736 + prev + predots + middle + postdots + next + '</div>';
739 function showPage (pageNum)
742 my_paz.showPage( curPage - 1 );
745 // simple paging functions
747 function pagerNext() {
748 if ( totalRec - recPerPage*curPage > 0) {
754 function pagerPrev() {
755 if ( my_paz.showPrev() != false )
759 // swithing view between targets and records
761 function switchView(view) {
763 var targets = document.getElementById('targetview');
764 var records = document.getElementById('recordview');
768 targets.style.display = "block";
769 records.style.display = "none";
772 targets.style.display = "none";
773 records.style.display = "block";
776 alert('Unknown view.');
780 // detailed record drawing
781 function showDetails (prefixRecId) {
782 var recId = prefixRecId.replace('rec_', '');
783 var oldRecId = curDetRecId;
786 // if the same clicked, just show it again
787 if (recId == oldRecId) {
788 showhide('detailview');
791 // request the record
792 document.getElementById("loading").style.display = 'inline';
793 my_paz.record(recId);
796 function replaceHtml(el, html) {
797 var oldEl = typeof el === "string" ? document.getElementById(el) : el;
798 /*@cc_on // Pure innerHTML is slightly faster in IE
799 oldEl.innerHTML = html;
802 var newEl = oldEl.cloneNode(false);
803 newEl.innerHTML = html;
804 oldEl.parentNode.replaceChild(newEl, oldEl);
805 /* Since we just removed the old element from the DOM, return a reference
806 to the new element, which can be used to restore variable references. */
810 function renderDetails(data, marker)
812 var details = '<div class="details" id="det_'+data.recid+'"><table>';
813 if (marker) details += '<tr><td>'+ marker + '</td></tr>';
814 if (data["md-title"] != undefined) {
815 details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
816 if (data["md-title-remainder"] != undefined) {
817 details += ' : <span>' + data["md-title-remainder"] + ' </span>';
819 if (data["md-author"] != undefined) {
820 details += ' <span><i>'+ data["md-auhtor"] +'</i></span>';
822 details += '</td></tr>';
824 if (data["md-date"] != undefined)
825 details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
826 if (data["md-author"] != undefined)
827 details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
828 if (data["md-electronic-url"] != undefined)
829 details += '<tr><td><b>URL</b></td><td><b>:</b> <a href="' + data["md-electronic-url"] + '" target="_blank">' + data["md-electronic-url"] + '</a>' + '</td></tr>';
830 if (data["location"][0]["md-subject"] != undefined)
831 details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
832 if (data["location"][0]["@name"] != undefined)
833 details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
834 details += '</table></div>';
838 var default_tag = 'big';
839 function renderLine(title, value, tag) {
840 if (tag == undefined)
842 if (value != undefined)
843 return '<li><h3>' + title + '</h3><' + tag + '>' + value + '</' + tag + '></li>';
847 function renderLines(title, values, name, tag) {
848 if (tag == undefined)
851 if (values != undefined && values.length)
852 for (var idx = 0 ; idx < values.length ; idx++)
853 if (values[idx][name] != undefined )
854 result += values[idx][name] + ' ';
856 result = '<li><h3>' + title + '</h3><' + tag + '>' + result + '</' + tag + '></li>';
860 // Values is a array of locations.
862 function renderLinesURL(title, values, name, url, tag) {
863 if (tag == undefined)
866 result = '<li><h3>' + title + '</h3><' + tag + ' style="display: inline-block;">';
867 if (values != undefined && values.length) {
868 for (var idx = 0 ; idx < values.length ; idx++) {
869 var url = choose_url(values[idx], auth.proxyUrl);
871 result += '<a target="_blank" href="' + url + '">' + values[idx][name] + '</a><br>';
873 result += values[idx][name] + '<br>';
876 result += '</' + tag + '></li>';
880 function renderLineURL(title, URL, display) {
881 if (URL != undefined)
882 return '<li><h3>' + title + '</h3><a href="' + URL + '" target="_blank">' + display + '</a></li>';
886 function renderLineEmail(dtitle, email, display) {
887 if (email != undefined)
888 return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
893 function find_prioritized(values) {
894 for (var index = 0; index < values.length; index++) {
895 if (values[index] != undefined)
896 return values[index];
901 function renderDetails_iphone(data, marker)
903 //return renderDetails(data,marker);
907 var details = '<div class="details" id="det_'+data.recid+'" >'
909 details += '<h4>'+ marker + '</h4>';
910 details += '<ul class="field" >';
913 if (data["md-title"] != undefined) {
914 title += data["md-title"];
915 if (data["md-title-remainder"] != undefined) {
916 title += '<br><i>' + data["md-title-remainder"] + '</i>';
919 details += renderLine('Title', title);
921 var author = find_prioritized(
924 data["md-title-responsibility"]
928 var coverimagetag = imageHelper.getImageTagByRecId(data.recid, "md-isbn", undefined, "M");
930 +=renderLine('Date', data["md-date"])
931 + renderLine('Author', data["md-author"])
932 // + renderLineURL('URL', data["md-electronic-url"], data["md-electronic-url"])
933 + renderLine('Description', data["md-description"])
934 // + renderLines('Subjects', data["location"], "md-subject")
937 details += renderLinesURL('Location', data["location"], "@name", "md-url_recipe");
938 details += '<li><a href="#" onclick="showhide(\'recordview\')" style="font-size: 18px;margin-left: 10px;">Back</a></li>';
939 if (coverimagetag.length>0) {
940 details += renderLine(' ', coverimagetag);
943 details += '</ul></div>';