Logon methods. default filter is now ALL
[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, false);
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, false);
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                 searchdiv.style.display = '';
368                 document.search.onsubmit = onFormSubmit;
369         }
370         callback.init();
371 }
372 // when search button pressed
373 function onFormSubmitEventHandler() 
374 {
375     resetPage();
376     document.getElementById("logo").style.display = 'none';
377     loadSelect();
378     triggerSearch();
379     submitted = true;
380     return true;
381 }
382
383 function onSelectDdChange()
384 {
385     if (!submitted) return false;
386     resetPage();
387     loadSelect();
388     my_paz.show(0, recPerPage, curSort);
389     return false;
390 }
391
392 function resetPage()
393 {
394     curPage = 1;
395     totalRec = 0;
396 }
397
398 function triggerSearch ()
399 {
400     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter);
401 }
402
403 function loadSelect ()
404 {
405     curSort = document.select.sort.value;
406     recPerPage = document.select.perpage.value;
407 }
408
409 // limit the query after clicking the facet
410 function limitQuery(field, value)
411 {
412         var newQuery = ' and ' + field + '="' + value + '"';
413         querys[field] += newQuery;
414     document.search.query.value += newQuery;
415     onFormSubmitEventHandler();
416     showhide("recordview");
417 }
418
419 //limit the query after clicking the facet
420 function removeQuery (field, value) {
421         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
422     onFormSubmitEventHandler();
423     showhide("recordview");
424 }
425
426 //limit the query after clicking the facet
427 function limitOrResetQuery (field, value, selected) {
428         if (field == 'reset_su' || field == 'reset_au') {
429                 var reset_field = field.substring(6);
430                 document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
431                 querys[reset_field] = '';
432             onFormSubmitEventHandler();
433             showhide("recordview");
434         }
435         else 
436                 limitQuery(field, value);
437         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
438 }
439
440 // limit by target functions
441 function limitTarget (id, name)
442 {
443     curFilter = 'pz:id=' + id;
444     resetPage();
445     loadSelect();
446     triggerSearch();
447     showhide("recordview");
448     return false;
449 }
450
451 function delimitTarget ()
452 {
453     curFilter = 'ALL'; 
454     resetPage();
455     loadSelect();
456     triggerSearch();
457     return false;
458 }
459
460 function limitOrResetTarget(id, name) {
461         if (id == 'reset_xt') {
462                 delimitTarget();
463         }
464         else {
465                 limitTarget(id,name);
466         }
467 }
468
469 function drawPager (pagerDiv)
470 {
471     //client indexes pages from 1 but pz2 from 0
472     var onsides = 6;
473     var pages = Math.ceil(totalRec / recPerPage);
474     
475     var firstClkbl = ( curPage - onsides > 0 ) 
476         ? curPage - onsides
477         : 1;
478
479     var lastClkbl = firstClkbl + 2*onsides < pages
480         ? firstClkbl + 2*onsides
481         : pages;
482
483     var prev = '<span id="prev">&#60;&#60; Prev</span><b> | </b>';
484     if (curPage > 1)
485         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
486         +'&#60;&#60; Prev</a><b> | </b>';
487
488     var middle = '';
489     for(var i = firstClkbl; i <= lastClkbl; i++) {
490         var numLabel = i;
491         if(i == curPage)
492             numLabel = '<b>' + i + '</b>';
493
494         middle += '<a href="#" onclick="showPage(' + i + ')"> '
495             + numLabel + ' </a>';
496     }
497     
498     var next = '<b> | </b><span id="next">Next &#62;&#62;</span>';
499     if (pages - curPage > 0)
500     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
501         +'Next &#62;&#62;</a>';
502
503     predots = '';
504     if (firstClkbl > 1)
505         predots = '...';
506
507     postdots = '';
508     if (lastClkbl < pages)
509         postdots = '...';
510
511     pagerDiv.innerHTML += '<div style="float: none">' 
512         + prev + predots + middle + postdots + next + '</div><hr/>';
513 }
514
515 function showPage (pageNum)
516 {
517     curPage = pageNum;
518     my_paz.showPage( curPage - 1 );
519 }
520
521 // simple paging functions
522
523 function pagerNext() {
524     if ( totalRec - recPerPage*curPage > 0) {
525         my_paz.showNext();
526         curPage++;
527     }
528 }
529
530 function pagerPrev() {
531     if ( my_paz.showPrev() != false )
532         curPage--;
533 }
534
535 // swithing view between targets and records
536
537 function switchView(view) {
538     
539     var targets = document.getElementById('targetview');
540     var records = document.getElementById('recordview');
541     
542     switch(view) {
543         case 'targetview':
544             targets.style.display = "block";            
545             records.style.display = "none";
546             break;
547         case 'recordview':
548             targets.style.display = "none";            
549             records.style.display = "block";
550             break;
551         default:
552             alert('Unknown view.');
553     }
554 }
555
556 // detailed record drawing
557 function showDetails (prefixRecId) {
558     var recId = prefixRecId.replace('rec_', '');
559     var oldRecId = curDetRecId;
560     curDetRecId = recId;
561     
562     // remove current detailed view if any
563     var detRecordDiv = document.getElementById('det_'+oldRecId);
564     //alert("oldRecId: " + oldRecId + " " + detRecordDiv != null); 
565     // lovin DOM!
566     if (detRecordDiv)
567       detRecordDiv.parentNode.removeChild(detRecordDiv);
568
569     // if the same clicked, just hide
570     if (recId == oldRecId) {
571         curDetRecId = '';
572         curDetRecData = null;
573         return;
574     }
575     // request the record
576     my_paz.record(recId);
577 }
578
579 function replaceHtml(el, html) {
580   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
581   /*@cc_on // Pure innerHTML is slightly faster in IE
582     oldEl.innerHTML = html;
583     return oldEl;
584     @*/
585   var newEl = oldEl.cloneNode(false);
586   newEl.innerHTML = html;
587   oldEl.parentNode.replaceChild(newEl, oldEl);
588   /* Since we just removed the old element from the DOM, return a reference
589      to the new element, which can be used to restore variable references. */
590   return newEl;
591 };
592
593 function renderDetails(data, marker)
594 {
595     var details = '<div class="details" id="det_'+data.recid+'"><table>';
596     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
597     if (data["md-title"] != undefined) {
598         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
599         if (data["md-title-remainder"] !== undefined) {
600               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
601         }
602         if (data["md-title-responsibility"] !== undefined) {
603               details += ' <span><i>'+ data["md-title-responsibility"] +'</i></span>';
604         }
605           details += '</td></tr>';
606     }
607     if (data["md-date"] != undefined)
608         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
609     if (data["md-author"] != undefined)
610         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
611     if (data["md-electronic-url"] != undefined)
612         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>';
613     if (data["location"][0]["md-subject"] != undefined)
614         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
615     if (data["location"][0]["@name"] != undefined)
616         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
617     details += '</table></div>';
618     return details;
619 }
620
621 function renderLine(title, value) {
622     if (value != undefined)
623         return '<li><h3>' + title + '</h3> <big>' + value + '</big></li>';
624     return '';
625 }
626
627 function renderLineURL(title, URL, display) {
628     if (URL != undefined)
629         return '<li><h3>' + title + '</h3> <a href="' + URL + '" target="_blank">' + display + '</a></li>';
630     return '';
631 }
632
633 function renderLineEmail(dtitle, email, display) {
634     if (email != undefined)
635         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
636     return '';
637 }
638
639 function renderDetails_iphone(data, marker)
640 {
641         //return renderDetails(data,marker);
642
643
644     var details = '<div class="details" id="det_'+data.recid+'" >'
645 /*
646     details = '<div id="header" id="det_'+data.recid+'">' 
647         + '<h1>Detailed Info</h1>' 
648         + '<a id="backbutton" href="hidedetail(\'det_' + data.recid + '\')">Back</a>' 
649         + '</div>';
650 */
651     if (marker) 
652         details += '<h4>'+ marker + '</h4>'; 
653     details += '<ul class="field">';
654     if (data["md-title"] != undefined) {
655         details += '<li><h3>Title</h3> <big> ' + data["md-title"];
656         if (data["md-title-remainder"] !== undefined) {
657               details += ' ' + data["md-title-remainder"] + ' ';
658         }
659         if (data["md-title-responsibility"] !== undefined) {
660               details += '<i>'+ data["md-title-responsibility"] +'</i>';
661         }
662         details += '</big>'
663         details += '</li>'
664     }
665     details 
666         +=renderLine('Date',    data["md-date"])
667         + renderLine('Author',  data["md-author"])
668         + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
669         + renderLine('Subject', data["location"][0]["md-subject"]);
670     
671     if (data["location"][0]["@name"] != undefined)
672         details += renderLine('Location', data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")");
673     details += '</ul></div>';
674     return details;
675 }
676
677 //EOF