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