Add a new function renderDetails_iphone
[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') {
13     usesessions = false;
14     pazpar2path = '/service-proxy/';
15     showResponseType = 'json';
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     // navi
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 }
286  
287 function applicationMode(newmode) 
288 {
289         var searchdiv = document.getElementById("searchForm");
290         var navi = document.getElementById("navi");
291         if (newmode)
292                 inApp = newmode;
293         if (inApp) {
294         document.getElementById("heading").style.display="none";
295         searchdiv.style.display = 'none';
296         navi.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     loadSelect();
309     triggerSearch();
310     submitted = true;
311     return false;
312 }
313
314 function onSelectDdChange()
315 {
316     if (!submitted) return false;
317     resetPage();
318     loadSelect();
319     my_paz.show(0, recPerPage, curSort);
320     return false;
321 }
322
323 function resetPage()
324 {
325     curPage = 1;
326     totalRec = 0;
327 }
328
329 function triggerSearch ()
330 {
331     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter);
332 }
333
334 function loadSelect ()
335 {
336     curSort = document.select.sort.value;
337     recPerPage = document.select.perpage.value;
338 }
339
340 // limit the query after clicking the facet
341 function limitQuery(field, value)
342 {
343         var newQuery = ' and ' + field + '="' + value + '"';
344         querys[field] += newQuery;
345     document.search.query.value += newQuery;
346     onFormSubmitEventHandler();
347     showhide("recordview");
348 }
349
350 //limit the query after clicking the facet
351 function removeQuery (field, value) {
352         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
353     onFormSubmitEventHandler();
354     showhide("recordview");
355 }
356
357 //limit the query after clicking the facet
358 function limitOrResetQuery (field, value, selected) {
359         if (field == 'reset_su' || field == 'reset_au') {
360                 var reset_field = field.substring(6);
361                 document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
362                 querys[reset_field] = '';
363             onFormSubmitEventHandler();
364             showhide("recordview");
365         }
366         else 
367                 limitQuery(field, value);
368         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
369 }
370
371 // limit by target functions
372 function limitTarget (id, name)
373 {
374     var navi = document.getElementById('navi');
375     navi.innerHTML = 
376         'Source: <a class="crossout" href="#" onclick="delimitTarget();return false;">'
377         + name + '</a>';
378     navi.innerHTML += '<hr/>';
379     curFilter = 'pz:id=' + id;
380     resetPage();
381     loadSelect();
382     triggerSearch();
383     showhide("recordview");
384     return false;
385 }
386
387 function delimitTarget ()
388 {
389     var navi = document.getElementById('navi');
390     navi.innerHTML = '';
391     curFilter = null; 
392     resetPage();
393     loadSelect();
394     triggerSearch();
395     return false;
396 }
397
398 function limitOrResetTarget(id, name) {
399         if (id == 'reset_xt') {
400                 delimitTarget();
401         }
402         else {
403                 limitTarget(id,name);
404         }
405 }
406
407 function drawPager (pagerDiv)
408 {
409     //client indexes pages from 1 but pz2 from 0
410     var onsides = 6;
411     var pages = Math.ceil(totalRec / recPerPage);
412     
413     var firstClkbl = ( curPage - onsides > 0 ) 
414         ? curPage - onsides
415         : 1;
416
417     var lastClkbl = firstClkbl + 2*onsides < pages
418         ? firstClkbl + 2*onsides
419         : pages;
420
421     var prev = '<span id="prev">&#60;&#60; Prev</span><b> | </b>';
422     if (curPage > 1)
423         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
424         +'&#60;&#60; Prev</a><b> | </b>';
425
426     var middle = '';
427     for(var i = firstClkbl; i <= lastClkbl; i++) {
428         var numLabel = i;
429         if(i == curPage)
430             numLabel = '<b>' + i + '</b>';
431
432         middle += '<a href="#" onclick="showPage(' + i + ')"> '
433             + numLabel + ' </a>';
434     }
435     
436     var next = '<b> | </b><span id="next">Next &#62;&#62;</span>';
437     if (pages - curPage > 0)
438     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
439         +'Next &#62;&#62;</a>';
440
441     predots = '';
442     if (firstClkbl > 1)
443         predots = '...';
444
445     postdots = '';
446     if (lastClkbl < pages)
447         postdots = '...';
448
449     pagerDiv.innerHTML += '<div style="float: none">' 
450         + prev + predots + middle + postdots + next + '</div><hr/>';
451 }
452
453 function showPage (pageNum)
454 {
455     curPage = pageNum;
456     my_paz.showPage( curPage - 1 );
457 }
458
459 // simple paging functions
460
461 function pagerNext() {
462     if ( totalRec - recPerPage*curPage > 0) {
463         my_paz.showNext();
464         curPage++;
465     }
466 }
467
468 function pagerPrev() {
469     if ( my_paz.showPrev() != false )
470         curPage--;
471 }
472
473 // swithing view between targets and records
474
475 function switchView(view) {
476     
477     var targets = document.getElementById('targetview');
478     var records = document.getElementById('recordview');
479     
480     switch(view) {
481         case 'targetview':
482             targets.style.display = "block";            
483             records.style.display = "none";
484             break;
485         case 'recordview':
486             targets.style.display = "none";            
487             records.style.display = "block";
488             break;
489         default:
490             alert('Unknown view.');
491     }
492 }
493
494 // detailed record drawing
495 function showDetails (prefixRecId) {
496     var recId = prefixRecId.replace('rec_', '');
497     var oldRecId = curDetRecId;
498     curDetRecId = recId;
499     
500     // remove current detailed view if any
501     var detRecordDiv = document.getElementById('det_'+oldRecId);
502     // lovin DOM!
503     if (detRecordDiv)
504       detRecordDiv.parentNode.removeChild(detRecordDiv);
505
506     // if the same clicked, just hide
507     if (recId == oldRecId) {
508         curDetRecId = '';
509         curDetRecData = null;
510         return;
511     }
512     // request the record
513     my_paz.record(recId);
514 }
515
516 function replaceHtml(el, html) {
517   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
518   /*@cc_on // Pure innerHTML is slightly faster in IE
519     oldEl.innerHTML = html;
520     return oldEl;
521     @*/
522   var newEl = oldEl.cloneNode(false);
523   newEl.innerHTML = html;
524   oldEl.parentNode.replaceChild(newEl, oldEl);
525   /* Since we just removed the old element from the DOM, return a reference
526      to the new element, which can be used to restore variable references. */
527   return newEl;
528 };
529
530 function renderDetails(data, marker)
531 {
532     var details = '<div class="details" id="det_'+data.recid+'"><table>';
533     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
534     if (data["md-title"] != undefined) {
535         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
536         if (data["md-title-remainder"] !== undefined) {
537               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
538         }
539         if (data["md-title-responsibility"] !== undefined) {
540               details += ' <span><i>'+ data["md-title-responsibility"] +'</i></span>';
541         }
542           details += '</td></tr>';
543     }
544     if (data["md-date"] != undefined)
545         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
546     if (data["md-author"] != undefined)
547         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
548     if (data["md-electronic-url"] != undefined)
549         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>';
550     if (data["location"][0]["md-subject"] != undefined)
551         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
552     if (data["location"][0]["@name"] != undefined)
553         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
554     details += '</table></div>';
555     return details;
556 }
557
558 function renderLine(title, value) {
559     if (value != undefined)
560         return '<li><h3>' + title + '</h3> <big>' + value + '<big></li>';
561     return '';
562 }
563
564 function renderLineURL(title, URL, display) {
565     if (URL != undefined)
566         return '<li><h3>' + title + '</h3> <a href="' + URL + '" target="_blank">' + display + '</a></li>';
567     return '';
568 }
569
570 function renderLineEmail(dtitle, email, display) {
571     if (email != undefined)
572         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
573     return '';
574 }
575
576 function renderDetails_iphone(data, marker)
577 {
578         //return renderDetails(data,marker);
579         
580     var details = '<div id="det_'+data.recid+'">';
581     if (marker) 
582         details += '<h4>'+ marker + '</h4>'; 
583     details += '<ul class="field">';
584     if (data["md-title"] != undefined) {
585         details += '<li><h3>Title</h3> <big> ' + data["md-title"];
586         if (data["md-title-remainder"] !== undefined) {
587               details += '<span>' + data["md-title-remainder"] + ' </span>';
588         }
589         if (data["md-title-responsibility"] !== undefined) {
590               details += ' <span><i>'+ data["md-title-responsibility"] +'</i></span>';
591         }
592         details += '</big>'
593         details += '</li>'
594     }
595     details 
596         +=renderLine('Date',    data["md-date"])
597         + renderLine('Author',  data["md-author"])
598         + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
599         + renderLine('Subject', data["location"][0]["md-subject"]);
600     
601     if (data["location"][0]["@name"] != undefined)
602         renderLine(details, 'Location', data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")");
603     details += '</ul>';
604     return details;
605 }
606
607 //EOF