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