Use md-author if present instead of md-title-responsibility. Swap title-remainder...
[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-remainder"] !== undefined) {
157                   html.push('<a href="#">' + hit["md-title-remainder"] + ' </a> ');
158               if (hit["md-author"] != undefined) {
159                   html.push('<a href="#">'+hit["md-author"]+'</a> ');
160               }
161               else if (hit["md-title-responsibility"] !== undefined) {
162                   html.push('<a href="#">'+hit["md-title-responsibility"]+'</a> ');
163               }
164         }
165         if (hit.recid == curDetRecId) {
166             html.push(renderDetails_iphone(curDetRecData));
167         }
168         html.push('</div>');
169     }
170     replaceHtml(results, html.join(''));
171 }
172
173 function my_onstat(data) {
174     var stat = document.getElementById("stat");
175     if (stat == null)
176         return;
177     
178     stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
179                         + data.activeclients
180                         + '/' + data.clients + ' -- </span>'
181                         + '<span>Retrieved records: ' + data.records
182                         + '/' + data.hits + ' :.</span>';
183 }
184
185 function showhide(newtab) {
186     var showtermlist = false;
187     if (newtab != null)
188         tab = newtab;
189     
190     if (tab == "recordview") {
191         document.getElementById("recordview").style.display = '';
192     }
193     else 
194         document.getElementById("recordview").style.display = 'none';
195
196     if (tab == "xtargets") {
197         document.getElementById("term_xtargets").style.display = '';
198         showtermlist = true;
199     }
200     else
201         document.getElementById("term_xtargets").style.display = 'none';
202
203     if (tab == "subjects") {
204         document.getElementById("term_subjects").style.display = '';
205         showtermlist = true;
206     }
207     else
208         document.getElementById("term_subjects").style.display = 'none';
209
210     if (tab == "authors") {
211         document.getElementById("term_authors").style.display = '';
212         showtermlist = true;
213     }
214     else
215         document.getElementById("term_authors").style.display = 'none';
216
217     if (showtermlist == false) 
218         document.getElementById("termlist").style.display = 'none';
219     else 
220         document.getElementById("termlist").style.display = '';
221
222     var tabDiv = document.getElementById("loginDiv");
223     if (tab == "login") {
224         tabDiv.style.display = '';
225     }
226     else {
227         tabDiv.style.display = 'none';
228     }
229 }
230
231 function my_onterm(data) {
232     var termlists = [];
233     
234     termlists.push('<div id="term_xtargets" >');
235     termlists.push('<h4 class="termtitle">Sources</h4>');
236     termlists.push('<ul>');
237     termlists.push('<li><a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
238     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
239         termlists.push('<li><a href="#" target_id='+data.xtargets[i].id
240             + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">' 
241             + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
242     }
243     termlists.push('</ul>');
244     termlists.push('</div>');
245      
246     termlists.push('<div id="term_subjects" >');
247     termlists.push('<h4>Subjects</h4>');
248     termlists.push('<ul>');
249     termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
250     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
251         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">' 
252                        + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
253     }
254     termlists.push('</ul>');
255     termlists.push('</div>');
256             
257     termlists.push('<div id="term_authors" >');
258     termlists.push('<h4 class="termtitle">Authors</h4>');
259     termlists.push('<ul>');
260     termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All<a></li>');
261     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
262         termlists.push('<li><a href="#" onclick="limitQuery(\'au\', \'' + data.author[i].name +'\');return false;">' 
263                             + data.author[i].name 
264                             + '  (' 
265                             + data.author[i].freq 
266                             + ')</a></li>');
267     }
268     termlists.push('</ul>');
269     termlists.push('</div>');
270     var termlist = document.getElementById("termlist");
271     replaceHtml(termlist, termlists.join(''));
272     showhide();
273 }
274
275 var termlist = {};
276 function my_onterm_iphone(data) {
277     my_onterm(data);
278     var targets = "reset_xt|All\n";
279     
280     for (var i = 0; i < data.xtargets.length; i++ ) {
281         
282         targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
283     }
284     termlist["xtargets"] = targets;
285     var subjects = "reset_su|All\n";
286     for (var i = 0; i < data.subject.length; i++ ) {
287         subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
288     }
289     termlist["subjects"] = subjects;
290     var authors = "reset_au|All\n";
291     for (var i = 0; i < data.author.length; i++ ) {
292         authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
293     }
294     termlist["authors"] = authors;
295     callback.send("termlist", "refresh");
296 }
297
298 function getTargets() {
299         return termlist['xtargets'];
300 }
301
302 function getSubjects() {
303         return termlist['subjects'];
304 }
305
306 function getAuthors() {
307         return termlist['authors'];
308 }
309
310 function my_onrecord(data) {
311     // FIXME: record is async!!
312     clearTimeout(my_paz.recordTimer);
313     // in case on_show was faster to redraw element
314     var detRecordDiv = document.getElementById('det_'+data.recid);
315     if (detRecordDiv) return;
316     curDetRecData = data;
317     var recordDiv = document.getElementById('recdiv_'+curDetRecData.recid);
318     var html = renderDetails_iphone(curDetRecData);
319     recordDiv.innerHTML += html;
320 }
321
322 function my_onrecord_iphone(data) {
323     my_onrecord(data);
324     callback.send("record", data.recid, data, data.xtargets[i].freq);
325 }
326
327
328 function my_onbytarget(data) {
329     var targetDiv = document.getElementById("bytarget");
330     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
331         +'<td>Records</td><td>State</td></tr></thead><tbody>';
332     
333     for (var i = 0; i < data.length; i++ ) {
334         table += "<tr><td>" + data[i].id +
335             "</td><td>" + data[i].hits +
336             "</td><td>" + data[i].diagnostic +
337             "</td><td>" + data[i].records +
338             "</td><td>" + data[i].state + "</td></tr>";
339     }
340
341     table += '</tbody></table>';
342     targetDiv.innerHTML = table;
343 }
344
345 ////////////////////////////////////////////////////////////////////////////////
346 ////////////////////////////////////////////////////////////////////////////////
347
348 // wait until the DOM is ready
349 function domReady () 
350
351     document.search.onsubmit = onFormSubmitEventHandler;
352     document.search.query.value = '';
353     document.select.sort.onchange = onSelectDdChange;
354     document.select.perpage.onchange = onSelectDdChange;
355     if (document.location.search.match("inApp=true")) 
356         applicationMode(true);
357     else
358         applicationMode(false);
359 }
360  
361 function applicationMode(newmode) 
362 {
363     var searchdiv = document.getElementById("searchForm");
364     if (newmode)
365         inApp = newmode;
366     if (inApp) {
367         document.getElementById("heading").style.display="none";
368         searchdiv.style.display = 'none';
369     }
370     else { 
371         
372         document.getElementById("nav").style.display="";
373         document.getElementById("normal").style.display="inline";
374         document.getElementById("normal").style.visibility="";
375         searchdiv.style.display = '';
376         document.search.onsubmit = onFormSubmit;
377     }
378     callback.init();
379 }
380 // when search button pressed
381 function onFormSubmitEventHandler() 
382 {
383     resetPage();
384     document.getElementById("logo").style.display = 'none';
385     loadSelect();
386     triggerSearch();
387     submitted = true;
388     return true;
389 }
390
391 function onSelectDdChange()
392 {
393     if (!submitted) return false;
394     resetPage();
395     loadSelect();
396     my_paz.show(0, recPerPage, curSort);
397     return false;
398 }
399
400 function resetPage()
401 {
402     curPage = 1;
403     totalRec = 0;
404 }
405
406 function triggerSearch ()
407 {
408     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter);
409 /*
410     , startWith,
411         {
412            "limit" : getFacets() 
413         }
414         );
415 */
416 }
417
418 function loadSelect ()
419 {
420     curSort = document.select.sort.value;
421     recPerPage = document.select.perpage.value;
422 }
423
424 // limit the query after clicking the facet
425 function limitQuery(field, value)
426 {
427   var newQuery = ' and ' + field + '="' + value + '"';
428   querys[field] += newQuery;
429   document.search.query.value += newQuery;
430   onFormSubmitEventHandler();
431   showhide("recordview");
432 }
433
434 // limit the query after clicking the facet
435 function removeQuery (field, value) {
436         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
437     onFormSubmitEventHandler();
438     showhide("recordview");
439 }
440
441 // limit the query after clicking the facet
442 function limitOrResetQuery (field, value, selected) {
443         if (field == 'reset_su' || field == 'reset_au') {
444                 var reset_field = field.substring(6);
445                 document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
446                 querys[reset_field] = '';
447             onFormSubmitEventHandler();
448             showhide("recordview");
449         }
450         else 
451                 limitQuery(field, value);
452         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
453 }
454
455 // limit by target functions
456 function limitTarget (id, name)
457 {
458     curFilter = 'pz:id=' + id;
459     resetPage();
460     loadSelect();
461     triggerSearch();
462     showhide("recordview");
463     return false;
464 }
465
466 function delimitTarget ()
467 {
468     curFilter = 'ALL'; 
469     resetPage();
470     loadSelect();
471     triggerSearch();
472     return false;
473 }
474
475 function limitOrResetTarget(id, name) {
476         if (id == 'reset_xt') {
477                 delimitTarget();
478         }
479         else {
480                 limitTarget(id,name);
481         }
482 }
483
484 function drawPager (pagerDiv)
485 {
486     //client indexes pages from 1 but pz2 from 0
487     var onsides = 6;
488     var pages = Math.ceil(totalRec / recPerPage);
489     
490     var firstClkbl = ( curPage - onsides > 0 ) 
491         ? curPage - onsides
492         : 1;
493
494     var lastClkbl = firstClkbl + 2*onsides < pages
495         ? firstClkbl + 2*onsides
496         : pages;
497
498     var prev = '<span id="prev">&#60;&#60; Prev</span><b> | </b>';
499     if (curPage > 1)
500         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
501         +'&#60;&#60; Prev</a><b> | </b>';
502
503     var middle = '';
504     for(var i = firstClkbl; i <= lastClkbl; i++) {
505         var numLabel = i;
506         if(i == curPage)
507             numLabel = '<b>' + i + '</b>';
508
509         middle += '<a href="#" onclick="showPage(' + i + ')"> '
510             + numLabel + ' </a>';
511     }
512     
513     var next = '<b> | </b><span id="next">Next &#62;&#62;</span>';
514     if (pages - curPage > 0)
515     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
516         +'Next &#62;&#62;</a>';
517
518     predots = '';
519     if (firstClkbl > 1)
520         predots = '...';
521
522     postdots = '';
523     if (lastClkbl < pages)
524         postdots = '...';
525
526     pagerDiv.innerHTML += '<div style="float: none">' 
527         + prev + predots + middle + postdots + next + '</div><hr/>';
528 }
529
530 function showPage (pageNum)
531 {
532     curPage = pageNum;
533     my_paz.showPage( curPage - 1 );
534 }
535
536 // simple paging functions
537
538 function pagerNext() {
539     if ( totalRec - recPerPage*curPage > 0) {
540         my_paz.showNext();
541         curPage++;
542     }
543 }
544
545 function pagerPrev() {
546     if ( my_paz.showPrev() != false )
547         curPage--;
548 }
549
550 // swithing view between targets and records
551
552 function switchView(view) {
553     
554     var targets = document.getElementById('targetview');
555     var records = document.getElementById('recordview');
556     
557     switch(view) {
558         case 'targetview':
559             targets.style.display = "block";            
560             records.style.display = "none";
561             break;
562         case 'recordview':
563             targets.style.display = "none";            
564             records.style.display = "block";
565             break;
566         default:
567             alert('Unknown view.');
568     }
569 }
570
571 // detailed record drawing
572 function showDetails (prefixRecId) {
573     var recId = prefixRecId.replace('rec_', '');
574     var oldRecId = curDetRecId;
575     curDetRecId = recId;
576     
577     // remove current detailed view if any
578     var detRecordDiv = document.getElementById('det_'+oldRecId);
579     //alert("oldRecId: " + oldRecId + " " + detRecordDiv != null); 
580     // lovin DOM!
581     if (detRecordDiv)
582       detRecordDiv.parentNode.removeChild(detRecordDiv);
583
584     // if the same clicked, just hide
585     if (recId == oldRecId) {
586         curDetRecId = '';
587         curDetRecData = null;
588         return;
589     }
590     // request the record
591     my_paz.record(recId);
592 }
593
594 function replaceHtml(el, html) {
595   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
596   /*@cc_on // Pure innerHTML is slightly faster in IE
597     oldEl.innerHTML = html;
598     return oldEl;
599     @*/
600   var newEl = oldEl.cloneNode(false);
601   newEl.innerHTML = html;
602   oldEl.parentNode.replaceChild(newEl, oldEl);
603   /* Since we just removed the old element from the DOM, return a reference
604      to the new element, which can be used to restore variable references. */
605   return newEl;
606 };
607
608 function renderDetails(data, marker)
609 {
610     var details = '<div class="details" id="det_'+data.recid+'"><table>';
611     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
612     if (data["md-title"] != undefined) {
613         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
614         if (data["md-title-remainder"] !== undefined) {
615               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
616         }
617         if (data["md-author"] !== undefined) {
618               details += ' <span><i>'+ data["md-auhtor"] +'</i></span>';
619         }
620           details += '</td></tr>';
621     }
622     if (data["md-date"] != undefined)
623         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
624     if (data["md-author"] != undefined)
625         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
626     if (data["md-electronic-url"] != undefined)
627         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>';
628     if (data["location"][0]["md-subject"] != undefined)
629         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
630     if (data["location"][0]["@name"] != undefined)
631         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
632     details += '</table></div>';
633     return details;
634 }
635
636 function renderLine(title, value) {
637     if (value != undefined)
638         return '<li><h3>' + title + '</h3> <big>' + value + '</big></li>';
639     return '';
640 }
641
642 function renderLineURL(title, URL, display) {
643     if (URL != undefined)
644         return '<li><h3>' + title + '</h3> <a href="' + URL + '" target="_blank">' + display + '</a></li>';
645     return '';
646 }
647
648 function renderLineEmail(dtitle, email, display) {
649     if (email != undefined)
650         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
651     return '';
652 }
653
654 function renderDetails_iphone(data, marker)
655 {
656         //return renderDetails(data,marker);
657
658     if (!data) 
659         return ""; 
660     var details = '<div class="details" id="det_'+data.recid+'" >'
661 /*
662     details = '<div id="header" id="det_'+data.recid+'">' 
663         + '<h1>Detailed Info</h1>' 
664         + '<a id="backbutton" href="hidedetail(\'det_' + data.recid + '\')">Back</a>' 
665         + '</div>';
666 */
667     if (marker) 
668         details += '<h4>'+ marker + '</h4>'; 
669     details += '<ul class="field">';
670     if (data["md-title"] != undefined) {
671         details += '<li><h3>Title</h3> <big> ' + data["md-title"];
672         if (data["md-title-remainder"] !== undefined) {
673               details += ' ' + data["md-title-remainder"] + ' ';
674         }
675         if (data["md-author"] !== undefined) {
676               details += '<i>'+ data["md-author"] +'</i>';
677         } else if (data["md-title-responsibility"] !== undefined) {
678               details += '<i>'+ data["md-title-responsibility"] +'</i>';
679         }
680         details += '</big>'
681         details += '</li>'
682     }
683     details 
684         +=renderLine('Date',    data["md-date"])
685         + renderLine('Author',  data["md-author"])
686         + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
687         + renderLine('Subject', data["location"][0]["md-subject"]);
688     
689     if (data["location"][0]["@name"] != undefined)
690         details += renderLine('Location', data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")");
691     details += '</ul></div>';
692     return details;
693 }
694
695 //EOF