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