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
74 //window.location = "login.html";
77 alert("Unhandled error: " + error.code);
78 throw error; // display error in JavaScript console
82 function loginFormSubmit() {
83 triedUser = document.loginForm.username.value;
84 triedPass = document.loginForm.password.value;
85 auth.login( {"username": triedUser,
86 "password": triedPass},
90 function handleKeyPress(e)
94 key = window.event.keyCode;
98 if(key == 13 || key == 10)
100 button = document.getElementById('button');
110 function authCb(authData) {
111 if (!authData.loginFailed) {
116 if (authData.loggedIn == true) {
117 showhide("recordview");
121 function logOutClick() {
122 auth.logOut(authCb, authCb);
125 function loggedOut() {
126 var login = document.getElementById("login");
127 login.innerHTML = 'Login';
130 function loggingOutFailed() {
131 alert("Logging out failed");
139 auth.logOut(loggedOut, loggingOutFailed, true);
142 function logInOrOut() {
143 var loginElement = document.getElementById("login");
144 if (loginElement.innerHTML == 'Login')
149 function loggedIn() {
150 var login = document.getElementById("login");
151 login.innerHTML = 'Logout';
152 document.getElementById("log").innerHTML = login.innerHTML;
155 function auth_check() {
156 auth.check(loggedIn, login);
161 // Pz2.js event handlers:
163 function my_oninit() {
168 function showMoreRecords() {
170 recToShow += recToShowPageSize;
171 for ( ; i < recToShow && i < recPerPage; i++) {
172 var element = document.getElementById(recIDs[i]);
174 element.style.display = '';
176 if (i == recPerPage) {
177 var element = document.getElementById('recdiv_END');
179 element.style.display = 'none';
183 function hideRecords() {
184 for ( var i = 0; i < recToShow; i++) {
185 var element = document.getElementById(recIDs[i]);
186 if (element && recIDs != curDetRecId)
187 element.style.display = 'none';
189 var element = document.getElementById('recdiv_END');
191 element.style.display = 'none';
194 function showRecords() {
195 for (var i = 0 ; i < recToShow && i < recPerPage; i++) {
196 var element = document.getElementById(recIDs[i]);
198 element.style.display = '';
200 var element = document.getElementById('recdiv_END');
203 element.style.display = 'none';
205 element.style.display = '';
212 function my_onshow(data) {
213 totalRec = data.merged;
215 var pager = document.getElementById("pager");
216 pager.innerHTML = "";
218 pager.innerHTML +='<div class="status">Displaying: '
219 + (data.start + 1) + ' to ' + (data.start + data.num) +
220 ' of ' + data.merged + ' (found: '
221 + data.total + ')</div>';
223 var results = document.getElementById("results");
226 if (data.hits == undefined)
229 for (var i = 0; i < data.hits.length; i++) {
230 var hit = data.hits[i];
231 var recDivID = "recdiv_" + hit.recid;
232 recIDs[i] = recDivID;
235 style = ' style="display:none" ';
236 html.push('<li class="img" id="' + recDivID + '" ' + style + '>' );
237 html.push('<a class="img" href="#' + i + '" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;" >');
239 var useThumbnails = hit["md-use_thumbnails"];
240 var thumburls = hit["md-thumburl"];
241 if (thumburls && (useThumbnails == undefined || useThumbnails == "1")) {
242 var thumbnailtag = imageHelper.getImageTagByRecId(hit.recid,"md-thumburl", 60, "S");
243 html.push(thumbnailtag);
245 if (hit["md-isbn"] != undefined) {
246 var coverimagetag = imageHelper.getImageTagByRecId(hit.recid, "md-isbn", 60, "S");
247 if (coverimagetag.length>0) {
248 html.push(coverimagetag);
256 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
257 html.push(hit["md-title"]);
260 if (hit["md-title-remainder"] != undefined) {
261 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
262 html.push(hit["md-title-remainder"]);
266 if (hit["md-author"] != undefined) {
267 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
268 html.push(hit["md-author"]);
272 else if (hit["md-title-responsibility"] != undefined) {
273 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
274 html.push(hit["md-title-responsibility"]);
278 for (var idx = lines ; idx < 2 ; idx++) {
279 html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
284 if (hit.recid == curDetRecId) {
285 html.push(renderDetails_iphone(curDetRecData));
290 if (data.activeclients == 0)
291 document.getElementById("loading").style.display = 'none';
293 // set up "More..." if needed.
294 style = 'display:none';
295 if (recToShow < recPerPage) {
296 style = 'display:block';
298 html.push('<li class="img" id="recdiv_END" style="' + style + '"><a onclick="showMoreRecords()">More...</a></li>');
300 replaceHtml(results, html.join(''));
303 function my_onstat(data) {
304 var stat = document.getElementById("stat");
308 stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
310 + '/' + data.clients + ' -- </span>'
311 + '<span>Retrieved records: ' + data.records
312 + '/' + data.hits + ' :.</span>';
315 function showhide(newtab, hash) {
316 var showtermlist = false;
320 if (tab == "recordview") {
321 document.getElementById("recordview").style.display = '';
322 if (hash != undefined)
323 document.location.hash = hash;
326 document.getElementById("recordview").style.display = 'none';
328 if (tab == "xtargets") {
329 document.getElementById("term_xtargets").style.display = '';
333 document.getElementById("term_xtargets").style.display = 'none';
335 if (tab == "subjects") {
336 document.getElementById("term_subjects").style.display = '';
340 document.getElementById("term_subjects").style.display = 'none';
342 if (tab == "authors") {
343 document.getElementById("term_authors").style.display = '';
347 document.getElementById("term_authors").style.display = 'none';
349 if (tab == "detailview") {
350 document.getElementById("detailview").style.display = '';
353 document.getElementById("detailview").style.display = 'none';
354 var element = document.getElementById("rec_" + curDetRecId);
355 if (element != undefined)
356 element.scrollIntoView();
359 if (showtermlist == false)
360 document.getElementById("termlist").style.display = 'none';
362 document.getElementById("termlist").style.display = '';
364 var tabDiv = document.getElementById("loginDiv");
365 if (tab == "login") {
366 tabDiv.style.display = '';
369 tabDiv.style.display = 'none';
373 function my_onterm(data) {
376 termlists.push('<div id="term_xtargets" >');
377 termlists.push('<h4 class="termtitle">Sources</h4>');
378 termlists.push('<ul class="termlist">');
379 termlists.push('<li> <a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
380 for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
381 termlists.push('<li class="termlist"><a href="#" target_id='+data.xtargets[i].id
382 + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">'
383 + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
385 termlists.push('</ul>');
386 termlists.push('</div>');
388 termlists.push('<div id="term_subjects" >');
389 termlists.push('<h4>Subjects</h4>');
390 termlists.push('<ul class="termlist">');
391 termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
392 for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
393 termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">'
394 + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
396 termlists.push('</ul>');
397 termlists.push('</div>');
399 termlists.push('<div id="term_authors" >');
400 termlists.push('<h4 class="termtitle">Authors</h4>');
401 termlists.push('<ul class="termlist">');
402 termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All</a></li>');
403 for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
404 termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'au\', \'' + data.author[i].name +'\');return false;">'
405 + data.author[i].name
407 + data.author[i].freq
410 termlists.push('</ul>');
411 termlists.push('</div>');
412 var termlist = document.getElementById("termlist");
413 replaceHtml(termlist, termlists.join(''));
418 function my_onterm_iphone(data) {
420 var targets = "reset_xt|All\n";
422 for (var i = 0; i < data.xtargets.length; i++ ) {
424 targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
426 termlist["xtargets"] = targets;
427 var subjects = "reset_su|All\n";
428 for (var i = 0; i < data.subject.length; i++ ) {
429 subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
431 termlist["subjects"] = subjects;
432 var authors = "reset_au|All\n";
433 for (var i = 0; i < data.author.length; i++ ) {
434 authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
436 termlist["authors"] = authors;
437 callback.send("termlist", "refresh");
440 function getTargets() {
441 return termlist['xtargets'];
444 function getSubjects() {
445 return termlist['subjects'];
448 function getAuthors() {
449 return termlist['authors'];
452 function my_onrecord(data) {
454 // FIXME: record is async!!
455 clearTimeout(my_paz.recordTimer);
456 // in case on_show was faster to redraw element
457 var detailRecordDiv = document.getElementById('detailrecord');
458 if (!detailRecordDiv)
460 curDetRecData = data;
461 var html = renderDetails_iphone(curDetRecData);
462 detailRecordDiv.innerHTML = html;
463 showhide('detailview');
464 document.getElementById("loading").style.display = 'none';
467 function my_onrecord_iphone(data) {
469 callback.send("record", data.recid, data, data.xtargets[i].freq);
473 function my_onbytarget(data) {
474 var targetDiv = document.getElementById("bytarget");
475 var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
476 +'<td>Records</td><td>State</td></tr></thead><tbody>';
478 for (var i = 0; i < data.length; i++ ) {
479 table += "<tr><td>" + data[i].id +
480 "</td><td>" + data[i].hits +
481 "</td><td>" + data[i].diagnostic +
482 "</td><td>" + data[i].records +
483 "</td><td>" + data[i].state + "</td></tr>";
486 table += '</tbody></table>';
487 targetDiv.innerHTML = table;
490 ////////////////////////////////////////////////////////////////////////////////
491 ////////////////////////////////////////////////////////////////////////////////
493 // wait until the DOM is ready
496 document.search.onsubmit = onFormSubmitEventHandler;
497 document.search.query.value = '';
498 document.select.sort.onchange = onSelectDdChange;
499 document.select.perpage.onchange = onSelectDdChange;
500 if (document.location.search.match("inApp=true"))
501 applicationMode(true);
503 applicationMode(false);
505 var params = parseQueryString(window.location.search);
507 document.search.query.value = params.query;
508 onFormSubmitEventHandler();
512 function applicationMode(newmode)
514 var searchdiv = document.getElementById("searchForm");
518 document.getElementById("heading").style.display="none";
519 searchdiv.style.display = 'none';
523 document.getElementById("nav").style.display="";
524 document.getElementById("normal").style.display="inline";
525 document.getElementById("normal").style.visibility="";
526 searchdiv.style.display = '';
527 document.search.onsubmit = onFormSubmit;
531 // when search button pressed
532 function onFormSubmitEventHandler()
535 document.getElementById("logo").style.display = 'none';
542 function onSelectDdChange()
544 if (!submitted) return false;
547 my_paz.show(0, recPerPage, curSort);
557 function getFacets() {
559 for (var key in querys_server) {
560 if (result.length > 0)
562 result += querys_server[key];
567 function triggerSearch ()
569 // Restore to initial page size
570 recToShow = recToShowPageSize;
571 document.getElementById("loading").style.display = 'inline';
572 my_paz.search(document.search.query.value, recPerPage, curSort, curFilter, undefined,
574 "limit" : getFacets()
577 showhide("recordview");
580 function loadSelect ()
582 curSort = document.select.sort.value;
583 recPerPage = document.select.perpage.value;
586 // limit the query after clicking the facet
587 function limitQuery(field, value)
589 var newQuery = ' and ' + field + '="' + value + '"';
590 querys[field] += newQuery;
591 document.search.query.value += newQuery;
592 onFormSubmitEventHandler();
593 showhide("recordview");
596 // limit the query after clicking the facet
597 function limitQueryServer(field, value)
599 // Check for client field usage
600 var fieldname = query_client_server[field];
604 var newQuery = fieldname + '=' + value.replace(",", "\\,").replace("|", "\\,");
605 // Does it already exists?
606 if (querys_server[fieldname])
607 querys_server[fieldname] += "," + newQuery;
609 querys_server[fieldname] = newQuery;
610 // document.search.query.value += newQuery;
611 onFormSubmitEventHandler();
612 showhide("recordview");
617 // limit the query after clicking the facet
618 function removeQuery (field, value) {
619 document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
620 onFormSubmitEventHandler();
621 showhide("recordview");
624 // limit the query after clicking the facet
625 function limitOrResetQuery (field, value, selected) {
627 limitOrResetQueryServer(field,value, selected);
630 if (field == 'reset_su' || field == 'reset_au') {
631 var reset_field = field.substring(6);
632 document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
633 querys[reset_field] = '';
634 onFormSubmitEventHandler();
635 showhide("recordview");
638 limitQuery(field, value);
639 //alert("limitOrResetQuerry: query after: " + document.search.query.value);
642 // limit the query after clicking the facet
643 function limitOrResetQueryServer (field, value, selected) {
644 if (field.substring(0,6) == 'reset_') {
645 var clientname = field.substring(6);
646 var fieldname = query_client_server[clientname];
648 fieldname = clientname;
649 delete querys_server[fieldname];
650 onFormSubmitEventHandler();
651 showhide("recordview");
654 limitQueryServer(field, value);
655 //alert("limitOrResetQuerry: query after: " + document.search.query.value);
661 // limit by target functions
662 function limitTarget (id, name)
664 curFilter = 'pz:id=' + id;
671 function delimitTarget ()
680 function limitOrResetTarget(id, name) {
681 if (id == 'reset_xt') {
685 limitTarget(id,name);
689 function drawPager (pagerDiv)
691 //client indexes pages from 1 but pz2 from 0
693 var pages = Math.ceil(totalRec / recPerPage);
695 var firstClkbl = ( curPage - onsides > 0 )
699 var lastClkbl = firstClkbl + 2*onsides < pages
700 ? firstClkbl + 2*onsides
703 var prev = '<span id="prev">Prev</span><b> | </b>';
705 var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
706 +'Prev</a><b> | </b>';
709 for(var i = firstClkbl; i <= lastClkbl; i++) {
712 numLabel = '<b>' + i + '</b>';
714 middle += '<a href="#" onclick="showPage(' + i + ')"> '
715 + numLabel + ' </a>';
718 var next = '<b> | </b><span id="next">Next</span>';
719 if (pages - curPage > 0)
720 var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
728 if (lastClkbl < pages)
731 pagerDiv.innerHTML += '<div class="pager">'
732 + prev + predots + middle + postdots + next + '</div>';
735 function showPage (pageNum)
738 my_paz.showPage( curPage - 1 );
741 // simple paging functions
743 function pagerNext() {
744 if ( totalRec - recPerPage*curPage > 0) {
750 function pagerPrev() {
751 if ( my_paz.showPrev() != false )
755 // swithing view between targets and records
757 function switchView(view) {
759 var targets = document.getElementById('targetview');
760 var records = document.getElementById('recordview');
764 targets.style.display = "block";
765 records.style.display = "none";
768 targets.style.display = "none";
769 records.style.display = "block";
772 alert('Unknown view.');
776 // detailed record drawing
777 function showDetails (prefixRecId) {
778 var recId = prefixRecId.replace('rec_', '');
779 var oldRecId = curDetRecId;
782 // if the same clicked, just show it again
783 if (recId == oldRecId) {
784 showhide('detailview');
787 // request the record
788 document.getElementById("loading").style.display = 'inline';
789 my_paz.record(recId);
792 function replaceHtml(el, html) {
793 var oldEl = typeof el === "string" ? document.getElementById(el) : el;
794 /*@cc_on // Pure innerHTML is slightly faster in IE
795 oldEl.innerHTML = html;
798 var newEl = oldEl.cloneNode(false);
799 newEl.innerHTML = html;
800 oldEl.parentNode.replaceChild(newEl, oldEl);
801 /* Since we just removed the old element from the DOM, return a reference
802 to the new element, which can be used to restore variable references. */
806 function renderDetails(data, marker)
808 var details = '<div class="details" id="det_'+data.recid+'"><table>';
809 if (marker) details += '<tr><td>'+ marker + '</td></tr>';
810 if (data["md-title"] != undefined) {
811 details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
812 if (data["md-title-remainder"] != undefined) {
813 details += ' : <span>' + data["md-title-remainder"] + ' </span>';
815 if (data["md-author"] != undefined) {
816 details += ' <span><i>'+ data["md-auhtor"] +'</i></span>';
818 details += '</td></tr>';
820 if (data["md-date"] != undefined)
821 details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
822 if (data["md-author"] != undefined)
823 details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
824 if (data["md-electronic-url"] != undefined)
825 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>';
826 if (data["location"][0]["md-subject"] != undefined)
827 details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
828 if (data["location"][0]["@name"] != undefined)
829 details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
830 details += '</table></div>';
834 var default_tag = 'big';
835 function renderLine(title, value, tag) {
836 if (tag == undefined)
838 if (value != undefined)
839 return '<li><h3>' + title + '</h3><' + tag + '>' + value + '</' + tag + '></li>';
843 function renderLines(title, values, name, tag) {
844 if (tag == undefined)
847 if (values != undefined && values.length)
848 for (var idx = 0 ; idx < values.length ; idx++)
849 if (values[idx][name] != undefined )
850 result += values[idx][name] + ' ';
852 result = '<li><h3>' + title + '</h3><' + tag + '>' + result + '</' + tag + '></li>';
856 // Values is a array of locations.
858 function renderLinesURL(title, values, name, url, tag) {
859 if (tag == undefined)
862 result = '<li><h3>' + title + '</h3><' + tag + ' style="display: inline-block;">';
863 if (values != undefined && values.length) {
864 for (var idx = 0 ; idx < values.length ; idx++) {
865 var url = choose_url(values[idx], auth.proxyUrl);
867 result += '<a target="_blank" href="' + url + '">' + values[idx][name] + '</a><br>';
869 result += values[idx][name] + '<br>';
872 result += '</' + tag + '></li>';
876 function renderLineURL(title, URL, display) {
877 if (URL != undefined)
878 return '<li><h3>' + title + '</h3><a href="' + URL + '" target="_blank">' + display + '</a></li>';
882 function renderLineEmail(dtitle, email, display) {
883 if (email != undefined)
884 return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
889 function find_prioritized(values) {
890 for (var index = 0; index < values.length; index++) {
891 if (values[index] != undefined)
892 return values[index];
897 function renderDetails_iphone(data, marker)
899 //return renderDetails(data,marker);
903 var details = '<div class="details" id="det_'+data.recid+'" >'
905 details += '<h4>'+ marker + '</h4>';
906 details += '<ul class="field" >';
909 if (data["md-title"] != undefined) {
910 title += data["md-title"];
911 if (data["md-title-remainder"] != undefined) {
912 title += '<br><i>' + data["md-title-remainder"] + '</i>';
915 details += renderLine('Title', title);
917 var author = find_prioritized(
920 data["md-title-responsibility"]
924 var coverimagetag = imageHelper.getImageTagByRecId(data.recid, "md-isbn", undefined, "M");
926 +=renderLine('Date', data["md-date"])
927 + renderLine('Author', data["md-author"])
928 // + renderLineURL('URL', data["md-electronic-url"], data["md-electronic-url"])
929 + renderLine('Description', data["md-description"])
930 // + renderLines('Subjects', data["location"], "md-subject")
933 details += renderLinesURL('Location', data["location"], "@name", "md-url_recipe");
934 details += '<li><a href="#" onclick="showhide(\'recordview\')" style="font-size: 18px;">Back</a></li>';
935 if (coverimagetag.length>0) {
936 details += renderLine(' ', coverimagetag);
939 details += '</ul></div>';