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