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