Mobile Browser/iPhone App friendly demo
[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 if (document.location.hash == '#useproxy') {
11     usesessions = false;
12     pazpar2path = '/service-proxy/';
13     showResponseType = 'json';
14 }
15
16 my_paz = new pz2( { "onshow": my_onshow,
17                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
18                     "pazpar2path": pazpar2path,
19                     "oninit": my_oninit,
20                     "onstat": my_onstat,
21                     "onterm": my_onterm_iphone,
22                     "termlist": "xtargets,subject,author",
23                     "onbytarget": my_onbytarget,
24                             "usesessions" : usesessions,
25                     "showResponseType": showResponseType,
26                     "onrecord": my_onrecord } );
27 // some state vars
28 var curPage = 1;
29 var recPerPage = 20;
30 var totalRec = 0;
31 var curDetRecId = '';
32 var curDetRecData = null;
33 var curSort = 'relevance';
34 var curFilter = null;
35 var submitted = false;
36 var SourceMax = 16;
37 var SubjectMax = 10;
38 var AuthorMax = 10;
39 var tab = "recordview"; 
40 var inApp = false;
41
42
43 //
44 // pz2.js event handlers:
45 //
46 function my_oninit() {
47     my_paz.stat();
48     my_paz.bytarget();
49 }
50
51 function my_onshow(data) {
52     totalRec = data.merged;
53     // move it out
54     var pager = document.getElementById("pager");
55     pager.innerHTML = "";
56     pager.innerHTML +='<hr/><div style="float: right">Displaying: ' 
57                     + (data.start + 1) + ' to ' + (data.start + data.num) +
58                      ' of ' + data.merged + ' (found: ' 
59                      + data.total + ')</div>';
60     drawPager(pager);
61     // navi
62     var results = document.getElementById("results");
63   
64     var html = [];
65     for (var i = 0; i < data.hits.length; i++) {
66         var hit = data.hits[i];
67               html.push('<li id="recdiv_'+hit.recid+'" >'
68            /* +'<span>'+ (i + 1 + recPerPage * (curPage - 1)) +'. </span>' */
69             +'<a href="#" id="rec_'+hit.recid
70             +'" onclick="showDetails(this.id);return false;">' 
71             + hit["md-title"] +'</a> '); 
72               if (hit["md-title-responsibility"] !== undefined) {
73             html.push('<a href="#">'+hit["md-title-responsibility"]+'</a> ');
74               if (hit["md-title-remainder"] !== undefined) {
75                 html.push('<a href="#">' + hit["md-title-remainder"] + ' </a> ');
76               }
77         }
78         if (hit.recid == curDetRecId) {
79             html.push(renderDetails(curDetRecData));
80         }
81         html.push('</div>');
82     }
83     replaceHtml(results, html.join(''));
84 }
85
86 function my_onstat(data) {
87     var stat = document.getElementById("stat");
88     if (stat == null)
89         return;
90     
91     stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
92                         + data.activeclients
93                         + '/' + data.clients + ' -- </span>'
94                         + '<span>Retrieved records: ' + data.records
95                         + '/' + data.hits + ' :.</span>';
96 }
97
98 function showhide(newtab) {
99         var showtermlist = false;
100         if (newtab != null)
101                 tab = newtab;
102
103         if (tab == "recordview") {
104                 document.getElementById("recordview").style.display = '';
105         }
106         else 
107                 document.getElementById("recordview").style.display = 'none';
108
109         if (tab == "xtargets") {
110                 document.getElementById("term_xtargets").style.display = '';
111                 showtermlist = true;
112         }
113         else
114                 document.getElementById("term_xtargets").style.display = 'none';
115         if (tab == "subjects") {
116                 document.getElementById("term_subjects").style.display = '';
117                 showtermlist = true;
118         }
119         else
120                 document.getElementById("term_subjects").style.display = 'none';
121         if (tab == "authors") {
122                 document.getElementById("term_authors").style.display = '';
123                 showtermlist = true;
124         }
125         else
126                 document.getElementById("term_authors").style.display = 'none';
127
128         if (showtermlist == false) 
129                 document.getElementById("termlist").style.display = 'none';
130         else 
131                 document.getElementById("termlist").style.display = '';
132 }
133
134 function my_onterm(data) {
135     var termlists = [];
136     
137     termlists.push('<div id="term_xtargets" >');
138     termlists.push('<div class="termtitle">.::Sources</div>');
139     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
140         termlists.push('<a href="#" target_id='+data.xtargets[i].id
141             + ' onclick="limitTarget(this.getAttribute(\'target_id\'), this.firstChild.nodeValue);return false;">' + data.xtargets[i].name 
142         + ' </a><span> (' + data.xtargets[i].freq + ')</span><br/>');
143     }
144     termlists.push('</div>');
145      
146     termlists.push('<div id="term_subjects" >');
147     termlists.push('<div id="subjects" class="termtitle">.::Subjects</div>');
148     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
149         termlists.push('<a href="#" onclick="limitQuery(\'su\', this.firstChild.nodeValue);return false;">' + data.subject[i].name + '</a><span>  (' 
150               + data.subject[i].freq + ')</span><br/>');
151     }
152     termlists.push('</div>');
153             
154     termlists.push('<div id="term_authors" >');
155     termlists.push('<div class="termtitle">.::Authors</div>');
156     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
157         termlists.push('<a href="#" onclick="limitQuery(\'au\', this.firstChild.nodeValue);return false;">' 
158                             + data.author[i].name 
159                             + ' </a><span> (' 
160                             + data.author[i].freq 
161                             + ')</span><br/>');
162     }
163     termlists.push('</div>');
164     var termlist = document.getElementById("termlist");
165     replaceHtml(termlist, termlists.join(''));
166     var d;
167 /*
168     for (d in ("xtargets", "subjects", "authors")) {
169         alert(d);
170         if (tab == d)
171                 document.getElementById("term_" + d).style.display = '';
172         else 
173                 document.getElementById("term_" +d ).style.display = 'none';
174     }
175 */
176     showhide();
177 }
178
179 function serialize(array) {
180         var t = typeof (obj);
181         if (t != "object" || obj === null) {
182                 // simple data type
183                 return String(obj);
184         } else {
185                 // recurse array or object
186                 var n, v, json = [], arr = (obj && obj.constructor == Array);
187                 for (n in obj) {
188                         v = obj[n];
189                         t = typeof (v);
190                         if (t == "string")
191                                 v = '"' + v + '"';
192                         else if (t == "object" && v !== null)
193                                 v = JSON.stringify(v);
194                         json.push((arr ? "" : '"' + n + '":') + String(v));
195                 }
196                 return (arr ? "" : "") + String(json) + (arr ? "]" : "}");
197         }
198 }
199
200 var termlist = {};
201 function my_onterm_iphone(data) {
202     my_onterm(data);
203     var targets = "";
204     for (var i = 0; i < data.xtargets.length; i++ ) {
205         
206         targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
207     }
208     termlist["xtargets"] = targets;
209     var subjects = "";
210     for (var i = 0; i < data.subject.length; i++ ) {
211         subjects = subjects + "-" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
212     }
213     termlist["subjects"] = subjects;
214     var authors = "";
215     for (var i = 0; i < data.author.length; i++ ) {
216         authors = authors + "-" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
217     }
218     termlist["authors"] = authors;
219     //document.getElementById("log").innerHTML = targets + "\n" + subjects + "\n" + authors;
220     callback.send("termlist", "refresh");
221 }
222
223 function getTargets() {
224         return termlist['xtargets'];
225 }
226
227 function getSubjects() {
228         return termlist['subjects'];
229 }
230
231 function getAuthors() {
232         return termlist['authors'];
233 }
234
235 function my_onrecord(data) {
236     // FIXME: record is async!!
237     clearTimeout(my_paz.recordTimer);
238     // in case on_show was faster to redraw element
239     var detRecordDiv = document.getElementById('det_'+data.recid);
240     if (detRecordDiv) return;
241     curDetRecData = data;
242     var recordDiv = document.getElementById('recdiv_'+curDetRecData.recid);
243     var html = renderDetails(curDetRecData);
244     recordDiv.innerHTML += html;
245 }
246
247 function my_onrecord_iphone(data) {
248     my_onrecord(data);
249     callback.send("record", data.recid, data, data.xtargets[i].freq);
250 }
251
252
253 function my_onbytarget(data) {
254     var targetDiv = document.getElementById("bytarget");
255     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
256         +'<td>Records</td><td>State</td></tr></thead><tbody>';
257     
258     for (var i = 0; i < data.length; i++ ) {
259         table += "<tr><td>" + data[i].id +
260             "</td><td>" + data[i].hits +
261             "</td><td>" + data[i].diagnostic +
262             "</td><td>" + data[i].records +
263             "</td><td>" + data[i].state + "</td></tr>";
264     }
265
266     table += '</tbody></table>';
267     targetDiv.innerHTML = table;
268 }
269
270 ////////////////////////////////////////////////////////////////////////////////
271 ////////////////////////////////////////////////////////////////////////////////
272
273 // wait until the DOM is ready
274 function domReady () 
275
276     document.search.onsubmit = onFormSubmitEventHandler;
277     document.search.query.value = '';
278     document.select.sort.onchange = onSelectDdChange;
279     document.select.perpage.onchange = onSelectDdChange;
280     if (!inApp)
281         document.getElementById("heading").style.display="";
282 }
283
284 // when search button pressed
285 function onFormSubmitEventHandler() 
286 {
287     resetPage();
288     loadSelect();
289     triggerSearch();
290     submitted = true;
291     return false;
292 }
293
294 function onSelectDdChange()
295 {
296     if (!submitted) return false;
297     resetPage();
298     loadSelect();
299     my_paz.show(0, recPerPage, curSort);
300     return false;
301 }
302
303 function resetPage()
304 {
305     curPage = 1;
306     totalRec = 0;
307 }
308
309 function triggerSearch ()
310 {
311     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter);
312 }
313
314 function loadSelect ()
315 {
316     curSort = document.select.sort.value;
317     recPerPage = document.select.perpage.value;
318 }
319
320 // limit the query after clicking the facet
321 function limitQuery (field, value)
322 {
323     document.search.query.value += ' and ' + field + '="' + value + '"';
324     onFormSubmitEventHandler();
325     showhide("recordview");
326 }
327
328 // limit by target functions
329 function limitTarget (id, name)
330 {
331     var navi = document.getElementById('navi');
332     navi.innerHTML = 
333         'Source: <a class="crossout" href="#" onclick="delimitTarget();return false;">'
334         + name + '</a>';
335     navi.innerHTML += '<hr/>';
336     curFilter = 'pz:id=' + id;
337     resetPage();
338     loadSelect();
339     triggerSearch();
340     showhide("recordview");
341     return false;
342 }
343
344 function delimitTarget ()
345 {
346     var navi = document.getElementById('navi');
347     navi.innerHTML = '';
348     curFilter = null; 
349     resetPage();
350     loadSelect();
351     triggerSearch();
352     return false;
353 }
354
355 function drawPager (pagerDiv)
356 {
357     //client indexes pages from 1 but pz2 from 0
358     var onsides = 6;
359     var pages = Math.ceil(totalRec / recPerPage);
360     
361     var firstClkbl = ( curPage - onsides > 0 ) 
362         ? curPage - onsides
363         : 1;
364
365     var lastClkbl = firstClkbl + 2*onsides < pages
366         ? firstClkbl + 2*onsides
367         : pages;
368
369     var prev = '<span id="prev">&#60;&#60; Prev</span><b> | </b>';
370     if (curPage > 1)
371         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
372         +'&#60;&#60; Prev</a><b> | </b>';
373
374     var middle = '';
375     for(var i = firstClkbl; i <= lastClkbl; i++) {
376         var numLabel = i;
377         if(i == curPage)
378             numLabel = '<b>' + i + '</b>';
379
380         middle += '<a href="#" onclick="showPage(' + i + ')"> '
381             + numLabel + ' </a>';
382     }
383     
384     var next = '<b> | </b><span id="next">Next &#62;&#62;</span>';
385     if (pages - curPage > 0)
386     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
387         +'Next &#62;&#62;</a>';
388
389     predots = '';
390     if (firstClkbl > 1)
391         predots = '...';
392
393     postdots = '';
394     if (lastClkbl < pages)
395         postdots = '...';
396
397     pagerDiv.innerHTML += '<div style="float: clear">' 
398         + prev + predots + middle + postdots + next + '</div><hr/>';
399 }
400
401 function showPage (pageNum)
402 {
403     curPage = pageNum;
404     my_paz.showPage( curPage - 1 );
405 }
406
407 // simple paging functions
408
409 function pagerNext() {
410     if ( totalRec - recPerPage*curPage > 0) {
411         my_paz.showNext();
412         curPage++;
413     }
414 }
415
416 function pagerPrev() {
417     if ( my_paz.showPrev() != false )
418         curPage--;
419 }
420
421 // swithing view between targets and records
422
423 function switchView(view) {
424     
425     var targets = document.getElementById('targetview');
426     var records = document.getElementById('recordview');
427     
428     switch(view) {
429         case 'targetview':
430             targets.style.display = "block";            
431             records.style.display = "none";
432             break;
433         case 'recordview':
434             targets.style.display = "none";            
435             records.style.display = "block";
436             break;
437         default:
438             alert('Unknown view.');
439     }
440 }
441
442 // detailed record drawing
443 function showDetails (prefixRecId) {
444     var recId = prefixRecId.replace('rec_', '');
445     var oldRecId = curDetRecId;
446     curDetRecId = recId;
447     
448     // remove current detailed view if any
449     var detRecordDiv = document.getElementById('det_'+oldRecId);
450     // lovin DOM!
451     if (detRecordDiv)
452       detRecordDiv.parentNode.removeChild(detRecordDiv);
453
454     // if the same clicked, just hide
455     if (recId == oldRecId) {
456         curDetRecId = '';
457         curDetRecData = null;
458         return;
459     }
460     // request the record
461     my_paz.record(recId);
462 }
463
464 function replaceHtml(el, html) {
465   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
466   /*@cc_on // Pure innerHTML is slightly faster in IE
467     oldEl.innerHTML = html;
468     return oldEl;
469     @*/
470   var newEl = oldEl.cloneNode(false);
471   newEl.innerHTML = html;
472   oldEl.parentNode.replaceChild(newEl, oldEl);
473   /* Since we just removed the old element from the DOM, return a reference
474      to the new element, which can be used to restore variable references. */
475   return newEl;
476 };
477
478 function renderDetails(data, marker)
479 {
480     var details = '<div class="details" id="det_'+data.recid+'"><table>';
481     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
482     if (data["md-title"] != undefined) {
483         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
484         if (data["md-title-remainder"] !== undefined) {
485               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
486         }
487         if (data["md-title-responsibility"] !== undefined) {
488               details += ' <span><i>'+ data["md-title-responsibility"] +'</i></span>';
489         }
490           details += '</td></tr>';
491     }
492     if (data["md-date"] != undefined)
493         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
494     if (data["md-author"] != undefined)
495         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
496     if (data["md-electronic-url"] != undefined)
497         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>';
498     if (data["location"][0]["md-subject"] != undefined)
499         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
500     if (data["location"][0]["@name"] != undefined)
501         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
502     details += '</table></div>';
503     return details;
504 }
505  //EOF