Implement Limit parameter on search, e.g. server side facetting
[pazpar2-moved-to-github.git] / www / iphone / example_client.js
1 /* A very simple client that shows a basic usage of the pz2.js
2 */
3
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 = {};
14 var useLimit = 1;
15 // Fail to get JSON working stabil.
16 var showResponseType = 'xml';
17 if (document.location.hash == '#pazpar2' || document.location.search.match("useproxy=false")) {
18     usesessions = true;
19     pazpar2path = '/pazpar2/search.pz2';
20     showResponseType = 'xml';
21 }
22
23
24 my_paz = new pz2( { "onshow": my_onshow,
25                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
26                     "pazpar2path": pazpar2path,
27                     "oninit": my_oninit,
28                     "onstat": my_onstat,
29                     "onterm": my_onterm_iphone,
30                     "termlist": "xtargets,subject,author",
31                     "onbytarget": my_onbytarget,
32                     "usesessions" : usesessions,
33                     "showResponseType": showResponseType,
34                     "onrecord": my_onrecord } );
35 // some state vars
36 var curPage = 1;
37 var recPerPage = 20;
38 var totalRec = 0;
39 var curDetRecId = '';
40 var curDetRecData = null;
41 var curSort = 'relevance';
42 var curFilter = 'ALL';
43 var submitted = false;
44 var SourceMax = 16;
45 var SubjectMax = 10;
46 var AuthorMax = 10;
47 var tab = "recordview"; 
48
49 var triedPass = "";
50 var triedUser = "";
51
52 function loginFormSubmit() {
53     triedUser = document.loginForm.username.value;
54     triedPass = document.loginForm.password.value;
55     auth.login( {"username": triedUser,
56                 "password": triedPass},
57         authCb, authCb);
58 }
59
60 function handleKeyPress(e, formId, focusId)  
61 {  
62   var key;  
63   if(window.event)  
64     key = window.event.keyCode;  
65   else  
66     key = e.which;  
67
68   if(key == 13 || key == 10)  
69   {  
70       onFormSubmitEventHandler();
71       focusElement = document.getElementById(focusId);
72       if (focusElement)
73           focusElement.focus();  
74       return false;  
75   }  
76   else  
77     return true;  
78 }  
79
80 function authCb(authData) {
81     if (!authData.loginFailed) {
82         triedUser = "";
83         triedPass = "";
84     }
85
86     if (authData.loggedIn == true) {        
87         showhide("recordview");
88     }
89 }
90
91 function logOutClick() {
92     auth.logOut(authCb, authCb);
93 }
94
95 function loggedOut() {
96     var login = document.getElementById("login");
97     login.innerHTML = 'Login';
98 }
99
100 function loggingOutFailed() {
101     alert("Logging out failed");
102 }
103
104 function login() {
105     showhide("login");
106 }
107
108 function logout() {
109     auth.logOut(loggedOut, loggingOutFailed, true);
110 }
111
112 function logInOrOut() {
113     var loginElement = document.getElementById("login");
114     if (loginElement.innerHTML == 'Login')
115         login();
116     else
117         logout();
118 }
119 function loggedIn() {
120     var login = document.getElementById("login");
121     login.innerHTML = 'Logout(' + auth.displayName + ')';
122     document.getElementById("log").innerHTML = login.innerHTML;
123 }
124
125 function auth_check() {
126     auth.check(loggedIn, login);
127     domReady();
128 }
129
130 //
131 // Pz2.js event handlers:
132 //
133 function my_oninit() {
134     my_paz.stat();
135     my_paz.bytarget();
136 }
137
138 function my_onshow(data) {
139     totalRec = data.merged;
140     // move it out
141     var pager = document.getElementById("pager");
142     pager.innerHTML = "";
143     pager.innerHTML +='<hr/><div style="float: right">Displaying: ' 
144                     + (data.start + 1) + ' to ' + (data.start + data.num) +
145                      ' of ' + data.merged + ' (found: ' 
146                      + data.total + ')</div>';
147     drawPager(pager);
148
149     var results = document.getElementById("results");
150   
151     var html = [];
152     if (data.hits == undefined) 
153         return ; 
154     for (var i = 0; i < data.hits.length; i++) {
155         var hit = data.hits[i];
156               html.push('<li id="recdiv_'+hit.recid+'" >'
157            /* +'<span>'+ (i + 1 + recPerPage * (curPage - 1)) +'. </span>' */
158             +'<a href="#" id="rec_'+hit.recid
159             +'" onclick="showDetails(this.id);return false;">' 
160             + hit["md-title"] +'</a> '); 
161               if (hit["md-title-responsibility"] !== undefined) {
162             html.push('<a href="#">'+hit["md-title-responsibility"]+'</a> ');
163               if (hit["md-title-remainder"] !== undefined) {
164                 html.push('<a href="#">' + hit["md-title-remainder"] + ' </a> ');
165               }
166         }
167         if (hit.recid == curDetRecId) {
168             html.push(renderDetails_iphone(curDetRecData));
169         }
170         html.push('</div>');
171     }
172     replaceHtml(results, html.join(''));
173 }
174
175 function my_onstat(data) {
176     var stat = document.getElementById("stat");
177     if (stat == null)
178         return;
179     
180     stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
181                         + data.activeclients
182                         + '/' + data.clients + ' -- </span>'
183                         + '<span>Retrieved records: ' + data.records
184                         + '/' + data.hits + ' :.</span>';
185 }
186
187 function showhide(newtab) {
188     var showtermlist = false;
189     if (newtab != null)
190         tab = newtab;
191     
192     if (tab == "recordview") {
193         document.getElementById("recordview").style.display = '';
194     }
195     else 
196         document.getElementById("recordview").style.display = 'none';
197
198     if (tab == "xtargets") {
199         document.getElementById("term_xtargets").style.display = '';
200         showtermlist = true;
201     }
202     else
203         document.getElementById("term_xtargets").style.display = 'none';
204
205     if (tab == "subjects") {
206         document.getElementById("term_subjects").style.display = '';
207         showtermlist = true;
208     }
209     else
210         document.getElementById("term_subjects").style.display = 'none';
211
212     if (tab == "authors") {
213         document.getElementById("term_authors").style.display = '';
214         showtermlist = true;
215     }
216     else
217         document.getElementById("term_authors").style.display = 'none';
218
219     if (showtermlist == false) 
220         document.getElementById("termlist").style.display = 'none';
221     else 
222         document.getElementById("termlist").style.display = '';
223
224     var tabDiv = document.getElementById("loginDiv");
225     if (tab == "login") {
226         tabDiv.style.display = '';
227     }
228     else {
229         tabDiv.style.display = 'none';
230     }
231 }
232
233 function my_onterm(data) {
234     var termlists = [];
235     
236     termlists.push('<div id="term_xtargets" >');
237     termlists.push('<h4 class="termtitle">Sources</h4>');
238     termlists.push('<ul>');
239     termlists.push('<li><a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
240     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
241         termlists.push('<li><a href="#" target_id='+data.xtargets[i].id
242             + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">' 
243             + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
244     }
245     termlists.push('</ul>');
246     termlists.push('</div>');
247      
248     termlists.push('<div id="term_subjects" >');
249     termlists.push('<h4>Subjects</h4>');
250     termlists.push('<ul>');
251     termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
252     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
253         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">' 
254                        + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
255     }
256     termlists.push('</ul>');
257     termlists.push('</div>');
258             
259     termlists.push('<div id="term_authors" >');
260     termlists.push('<h4 class="termtitle">Authors</h4>');
261     termlists.push('<ul>');
262     termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All<a></li>');
263     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
264         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'au\', \'' + data.author[i].name +'\');return false;">' 
265                             + data.author[i].name 
266                             + '  (' 
267                             + data.author[i].freq 
268                             + ')</a></li>');
269     }
270     termlists.push('</ul>');
271     termlists.push('</div>');
272     var termlist = document.getElementById("termlist");
273     replaceHtml(termlist, termlists.join(''));
274     showhide();
275 }
276
277 var termlist = {};
278 function my_onterm_iphone(data) {
279     my_onterm(data);
280     var targets = "reset_xt|All\n";
281     
282     for (var i = 0; i < data.xtargets.length; i++ ) {
283         
284         targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
285     }
286     termlist["xtargets"] = targets;
287     var subjects = "reset_su|All\n";
288     for (var i = 0; i < data.subject.length; i++ ) {
289         subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
290     }
291     termlist["subjects"] = subjects;
292     var authors = "reset_au|All\n";
293     for (var i = 0; i < data.author.length; i++ ) {
294         authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
295     }
296     termlist["authors"] = authors;
297     callback.send("termlist", "refresh");
298 }
299
300 function getTargets() {
301         return termlist['xtargets'];
302 }
303
304 function getSubjects() {
305         return termlist['subjects'];
306 }
307
308 function getAuthors() {
309         return termlist['authors'];
310 }
311
312 function my_onrecord(data) {
313     // FIXME: record is async!!
314     clearTimeout(my_paz.recordTimer);
315     // in case on_show was faster to redraw element
316     var detRecordDiv = document.getElementById('det_'+data.recid);
317     if (detRecordDiv) return;
318     curDetRecData = data;
319     var recordDiv = document.getElementById('recdiv_'+curDetRecData.recid);
320     var html = renderDetails_iphone(curDetRecData);
321     recordDiv.innerHTML += html;
322 }
323
324 function my_onrecord_iphone(data) {
325     my_onrecord(data);
326     callback.send("record", data.recid, data, data.xtargets[i].freq);
327 }
328
329
330 function my_onbytarget(data) {
331     var targetDiv = document.getElementById("bytarget");
332     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
333         +'<td>Records</td><td>State</td></tr></thead><tbody>';
334     
335     for (var i = 0; i < data.length; i++ ) {
336         table += "<tr><td>" + data[i].id +
337             "</td><td>" + data[i].hits +
338             "</td><td>" + data[i].diagnostic +
339             "</td><td>" + data[i].records +
340             "</td><td>" + data[i].state + "</td></tr>";
341     }
342
343     table += '</tbody></table>';
344     targetDiv.innerHTML = table;
345 }
346
347 ////////////////////////////////////////////////////////////////////////////////
348 ////////////////////////////////////////////////////////////////////////////////
349
350 // wait until the DOM is ready
351 function domReady () 
352
353     document.search.onsubmit = onFormSubmitEventHandler;
354     document.search.query.value = '';
355     document.select.sort.onchange = onSelectDdChange;
356     document.select.perpage.onchange = onSelectDdChange;
357     if (document.location.search.match("inApp=true")) 
358         applicationMode(true);
359     else
360         applicationMode(false);
361 }
362  
363 function applicationMode(newmode) 
364 {
365     var searchdiv = document.getElementById("searchForm");
366     if (newmode)
367         inApp = newmode;
368     if (inApp) {
369         document.getElementById("heading").style.display="none";
370         searchdiv.style.display = 'none';
371     }
372     else { 
373         
374         document.getElementById("nav").style.display="";
375         document.getElementById("normal").style.display="inline";
376         document.getElementById("normal").style.visibility="";
377         searchdiv.style.display = '';
378         document.search.onsubmit = onFormSubmit;
379     }
380     callback.init();
381 }
382 // when search button pressed
383 function onFormSubmitEventHandler() 
384 {
385     resetPage();
386     document.getElementById("logo").style.display = 'none';
387     loadSelect();
388     triggerSearch();
389     submitted = true;
390     return true;
391 }
392
393 function onSelectDdChange()
394 {
395     if (!submitted) return false;
396     resetPage();
397     loadSelect();
398     my_paz.show(0, recPerPage, curSort);
399     return false;
400 }
401
402 function resetPage()
403 {
404     curPage = 1;
405     totalRec = 0;
406 }
407
408 function getFacets() {
409     var result = "";
410     for (var key in querys_server) {
411         if (result.length > 0)
412             result += ","
413         result += querys_server[key];
414     }
415     return result;
416 }
417
418 function triggerSearch ()
419 {
420     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter, undefined,
421         {
422            "limit" : getFacets() 
423         }
424         );
425 }
426
427 function loadSelect ()
428 {
429     curSort = document.select.sort.value;
430     recPerPage = document.select.perpage.value;
431 }
432
433 // limit the query after clicking the facet
434 function limitQuery(field, value)
435 {
436   var newQuery = ' and ' + field + '="' + value + '"';
437   querys[field] += newQuery;
438   document.search.query.value += newQuery;
439   onFormSubmitEventHandler();
440   showhide("recordview");
441 }
442
443 // limit the query after clicking the facet
444 function limitQueryServer(field, value)
445 {
446     // Check for client field usage
447     var fieldname = query_client_server[field];
448     if (!fieldname) 
449         fieldname = field;      
450     
451     var newQuery = fieldname + '=' + value.replace(",", "\\,").replace("|", "\\,");
452     // Does it already exists?
453     if (querys_server[fieldname]) 
454         querys_server[fieldname] += "," + newQuery;
455     else
456         querys_server[fieldname] = newQuery;
457 //  document.search.query.value += newQuery;
458   onFormSubmitEventHandler();
459   showhide("recordview");
460 }
461
462
463
464 // limit the query after clicking the facet
465 function removeQuery (field, value) {
466         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
467     onFormSubmitEventHandler();
468     showhide("recordview");
469 }
470
471 // limit the query after clicking the facet
472 function limitOrResetQuery (field, value, selected) {
473     if (useLimit) {
474         limitOrResetQueryServer(field,value, selected);
475         return ;
476     }
477     if (field == 'reset_su' || field == 'reset_au') {
478         var reset_field = field.substring(6);
479         document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
480         querys[reset_field] = '';
481         onFormSubmitEventHandler();
482         showhide("recordview");
483     }
484     else 
485         limitQuery(field, value);
486         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
487 }
488
489 // limit the query after clicking the facet
490 function limitOrResetQueryServer (field, value, selected) {
491     if (field.substring(0,6) == 'reset_') {
492         var clientname = field.substring(6);
493         var fieldname = query_client_server[clientname];
494         if (!fieldname) 
495             fieldname = clientname;     
496         delete querys_server[fieldname];
497         onFormSubmitEventHandler();
498         showhide("recordview");
499     }
500     else 
501         limitQueryServer(field, value);
502         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
503 }
504
505
506
507
508 // limit by target functions
509 function limitTarget (id, name)
510 {
511     curFilter = 'pz:id=' + id;
512     resetPage();
513     loadSelect();
514     triggerSearch();
515     showhide("recordview");
516     return false;
517 }
518
519 function delimitTarget ()
520 {
521     curFilter = 'ALL'; 
522     resetPage();
523     loadSelect();
524     triggerSearch();
525     return false;
526 }
527
528 function limitOrResetTarget(id, name) {
529         if (id == 'reset_xt') {
530                 delimitTarget();
531         }
532         else {
533                 limitTarget(id,name);
534         }
535 }
536
537 function drawPager (pagerDiv)
538 {
539     //client indexes pages from 1 but pz2 from 0
540     var onsides = 6;
541     var pages = Math.ceil(totalRec / recPerPage);
542     
543     var firstClkbl = ( curPage - onsides > 0 ) 
544         ? curPage - onsides
545         : 1;
546
547     var lastClkbl = firstClkbl + 2*onsides < pages
548         ? firstClkbl + 2*onsides
549         : pages;
550
551     var prev = '<span id="prev">&#60;&#60; Prev</span><b> | </b>';
552     if (curPage > 1)
553         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
554         +'&#60;&#60; Prev</a><b> | </b>';
555
556     var middle = '';
557     for(var i = firstClkbl; i <= lastClkbl; i++) {
558         var numLabel = i;
559         if(i == curPage)
560             numLabel = '<b>' + i + '</b>';
561
562         middle += '<a href="#" onclick="showPage(' + i + ')"> '
563             + numLabel + ' </a>';
564     }
565     
566     var next = '<b> | </b><span id="next">Next &#62;&#62;</span>';
567     if (pages - curPage > 0)
568     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
569         +'Next &#62;&#62;</a>';
570
571     predots = '';
572     if (firstClkbl > 1)
573         predots = '...';
574
575     postdots = '';
576     if (lastClkbl < pages)
577         postdots = '...';
578
579     pagerDiv.innerHTML += '<div style="float: none">' 
580         + prev + predots + middle + postdots + next + '</div><hr/>';
581 }
582
583 function showPage (pageNum)
584 {
585     curPage = pageNum;
586     my_paz.showPage( curPage - 1 );
587 }
588
589 // simple paging functions
590
591 function pagerNext() {
592     if ( totalRec - recPerPage*curPage > 0) {
593         my_paz.showNext();
594         curPage++;
595     }
596 }
597
598 function pagerPrev() {
599     if ( my_paz.showPrev() != false )
600         curPage--;
601 }
602
603 // swithing view between targets and records
604
605 function switchView(view) {
606     
607     var targets = document.getElementById('targetview');
608     var records = document.getElementById('recordview');
609     
610     switch(view) {
611         case 'targetview':
612             targets.style.display = "block";            
613             records.style.display = "none";
614             break;
615         case 'recordview':
616             targets.style.display = "none";            
617             records.style.display = "block";
618             break;
619         default:
620             alert('Unknown view.');
621     }
622 }
623
624 // detailed record drawing
625 function showDetails (prefixRecId) {
626     var recId = prefixRecId.replace('rec_', '');
627     var oldRecId = curDetRecId;
628     curDetRecId = recId;
629     
630     // remove current detailed view if any
631     var detRecordDiv = document.getElementById('det_'+oldRecId);
632     //alert("oldRecId: " + oldRecId + " " + detRecordDiv != null); 
633     // lovin DOM!
634     if (detRecordDiv)
635       detRecordDiv.parentNode.removeChild(detRecordDiv);
636
637     // if the same clicked, just hide
638     if (recId == oldRecId) {
639         curDetRecId = '';
640         curDetRecData = null;
641         return;
642     }
643     // request the record
644     my_paz.record(recId);
645 }
646
647 function replaceHtml(el, html) {
648   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
649   /*@cc_on // Pure innerHTML is slightly faster in IE
650     oldEl.innerHTML = html;
651     return oldEl;
652     @*/
653   var newEl = oldEl.cloneNode(false);
654   newEl.innerHTML = html;
655   oldEl.parentNode.replaceChild(newEl, oldEl);
656   /* Since we just removed the old element from the DOM, return a reference
657      to the new element, which can be used to restore variable references. */
658   return newEl;
659 };
660
661 function renderDetails(data, marker)
662 {
663     var details = '<div class="details" id="det_'+data.recid+'"><table>';
664     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
665     if (data["md-title"] != undefined) {
666         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
667         if (data["md-title-remainder"] !== undefined) {
668               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
669         }
670         if (data["md-title-responsibility"] !== undefined) {
671               details += ' <span><i>'+ data["md-title-responsibility"] +'</i></span>';
672         }
673           details += '</td></tr>';
674     }
675     if (data["md-date"] != undefined)
676         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
677     if (data["md-author"] != undefined)
678         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
679     if (data["md-electronic-url"] != undefined)
680         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>';
681     if (data["location"][0]["md-subject"] != undefined)
682         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
683     if (data["location"][0]["@name"] != undefined)
684         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
685     details += '</table></div>';
686     return details;
687 }
688
689 function renderLine(title, value) {
690     if (value != undefined)
691         return '<li><h3>' + title + '</h3> <big>' + value + '</big></li>';
692     return '';
693 }
694
695 function renderLineURL(title, URL, display) {
696     if (URL != undefined)
697         return '<li><h3>' + title + '</h3> <a href="' + URL + '" target="_blank">' + display + '</a></li>';
698     return '';
699 }
700
701 function renderLineEmail(dtitle, email, display) {
702     if (email != undefined)
703         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
704     return '';
705 }
706
707 function renderDetails_iphone(data, marker)
708 {
709         //return renderDetails(data,marker);
710
711     if (!data) 
712         return ""; 
713     var details = '<div class="details" id="det_'+data.recid+'" >'
714 /*
715     details = '<div id="header" id="det_'+data.recid+'">' 
716         + '<h1>Detailed Info</h1>' 
717         + '<a id="backbutton" href="hidedetail(\'det_' + data.recid + '\')">Back</a>' 
718         + '</div>';
719 */
720     if (marker) 
721         details += '<h4>'+ marker + '</h4>'; 
722     details += '<ul class="field">';
723     if (data["md-title"] != undefined) {
724         details += '<li><h3>Title</h3> <big> ' + data["md-title"];
725         if (data["md-title-remainder"] !== undefined) {
726               details += ' ' + data["md-title-remainder"] + ' ';
727         }
728         if (data["md-title-responsibility"] !== undefined) {
729               details += '<i>'+ data["md-title-responsibility"] +'</i>';
730         }
731         details += '</big>'
732         details += '</li>'
733     }
734     details 
735         +=renderLine('Date',    data["md-date"])
736         + renderLine('Author',  data["md-author"])
737         + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
738         + renderLine('Subject', data["location"][0]["md-subject"]);
739     
740     if (data["location"][0]["@name"] != undefined)
741         details += renderLine('Location', data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")");
742     details += '</ul></div>';
743     return details;
744 }
745
746 //EOF