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