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