Debug HTTP 000 error. Moved domReady into loggedIn method.
[pazpar2-moved-to-github.git] / www / mobile / mobile_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 = false;
8 var pazpar2path = '/service-proxy/';
9 var showResponseType = '';
10 // Facet configuration
11 var querys = {'su': '', 'au': '', 'xt': ''};
12 var query_client_server = {'su': 'subject', 'au': 'author', 'xt': 'xtargets'};
13 var querys_server = {};
14 var useLimit = 1;
15 var state = new State();
16 // Fail to get JSON working stabil.
17 var showResponseType = 'xml';
18 //some state vars
19 state.curPage = 1;
20 state.recPerPage = 5;
21 var recToShowPageSize = 20;
22 var recToShow = recToShowPageSize;
23 var recIDs = {};
24 var totalRec = 0;
25 var curDetRecId = '';
26 var curDetRecData = null;
27 var curSort = 'relevance';
28 var curFilter = 'ALL';
29 var submitted = false;
30 var SourceMax = 16;
31 var SubjectMax = 10;
32 var AuthorMax = 10;
33 var tab = "recordview"; 
34
35 var triedPass = "";
36 var triedUser = "";
37
38 var previousOrientation = window.orientation || 0;
39
40
41 window.addEventListener("load",function() {
42   // Set a timeout...
43   setTimeout(function(){
44     // Hide the address bar!
45     window.scrollTo(0, 1);
46   }, 0);
47 });
48
49 function calcRecPerPage() {
50   state.width = window.innerWidth;
51   state.height = window.innerHeight;
52   return Math.max(Math.round((state.height - 88 - 40) / 60), 5) ; 
53 }
54
55 function checkOrientation() {
56     if(state.height != window.innerHeight){
57         var newPageSize = calcRecPerPage();
58         //alert("orient change: Dimension " + state.width + " " + state.height + " Old Rec/page " + state.recPerPage + " New: " + newPageSize);  
59         state.setRecPerPage(newPageSize);
60         my_paz.show(state.getStartWith(), state.getRecPerPage(), curSort);
61     }
62 };
63
64 state.setRecPerPage(calcRecPerPage());
65
66 window.addEventListener("resize", checkOrientation, false);
67 window.addEventListener("orientationchange", checkOrientation, false);
68
69 // (optional) Android doesn't always fire orientationChange on 180 degree turns
70 //setInterval(checkOrientation, 2000);
71
72 var imageHelper = new ImageHelper();
73
74 if (document.location.hash == '#pazpar2' || document.location.search.match("useproxy=false")) {
75     usesessions = true;
76     pazpar2path = '/pazpar2/search.pz2';
77     showResponseType = 'xml';
78 }
79
80 my_paz = new pz2( { "onshow": my_onshow,
81 //                    "showtime": 2000,            //each timer (show, stat, term, bytarget) can be specified this way
82                     "pazpar2path": pazpar2path,
83                     "oninit": my_oninit,
84                     "onstat": null,
85                     "onterm": my_onterm_iphone,
86                     "termlist": "xtargets,subject,author",
87                     "onbytarget": null,
88                     "usesessions" : usesessions,
89                     "showResponseType": showResponseType,
90                     "onrecord": my_onrecord,
91                     "errorhandler" : my_onerror} 
92 );
93
94 //
95 // pz2.js event handlers:
96 //
97 function my_onerror(error) {
98   alert("Unhandled error: " + error.code);
99     switch(error.code) {
100         // No targets!
101     case "8": alert("No resources were selected for the search"); break;
102         // target not configured, this is a pazpar2 bug
103         // but for now simply research
104     case "9": 
105         triggerSearch(); 
106         break;
107         
108         // Already blocked 
109     case "13": 
110         // ignore
111         break
112         // authentication
113     case "100" : 
114         auth.check(loggedIn, login);
115         break;
116     default: 
117         alert("Unhandled error: " + error.code);
118         throw error; // display error in JavaScript console
119     }
120 }
121
122 //FF has a bug and un-escaped location.hash, don't use it
123 function getRealHash() {
124   var i = window.location.href.indexOf('#');
125   return i > -1 ? window.location.href.substr(i) : "";
126 }
127
128 function loginFormSubmit() {
129     triedUser = document.loginForm.username.value;
130     triedPass = document.loginForm.password.value;
131     auth.login( {"username": triedUser,
132                 "password": triedPass},
133         authCb, authCb);
134 }
135
136 function handleKeyPress(e)  
137 {  
138   var key;  
139   if(window.event)  
140     key = window.event.keyCode;  
141   else  
142     key = e.which;  
143
144   if(key == 13 || key == 10)  
145   {  
146       button = document.getElementById('button');
147       button.focus();
148       button.click();
149
150       return false;  
151   }  
152   else  
153     return true;  
154 }  
155
156 function authCb(authData) {
157     if (!authData.loginFailed) {
158         triedUser = "";
159         triedPass = "";
160     }
161
162     if (authData.loggedIn == true) {        
163         showhide("recordview");
164     }
165 }
166
167 function logOutClick() {
168     auth.logOut(authCb, authCb);
169 }
170
171 function loggedOut() {
172     var login = document.getElementById("login");
173     login.innerHTML = 'Login';
174 }
175
176 function loggingOutFailed() {
177     alert("Logging out failed");
178 }
179
180 function login() {
181     showhide("login");
182 }
183
184 function logout() {
185     auth.logOut(loggedOut, loggingOutFailed, true);
186 }
187
188 function logInOrOut() {
189     var loginElement = document.getElementById("login");
190     if (loginElement.innerHTML == 'Login')
191         login();
192     else
193         logout();
194 }
195 function loggedIn() {
196     var login = document.getElementById("login");
197     login.innerHTML = 'Logout';
198     document.getElementById("log").innerHTML = login.innerHTML;
199     domReady();
200 }
201
202 function auth_check() {
203     auth.check(loggedIn, login);
204     //domReady();
205 }
206
207
208 function auth_check_item(methods) {
209   auth.check(itemMain, function () { window.location = "login.html" + window.location.search + "&page="+window.location.pathname;}, methods );
210 }
211
212 //when page loads
213 function itemMain() {
214   mk_showPage();
215   if (auth.styleCss && document.getElementById("stylesheet")) {
216       document.getElementById("stylesheet").href = auth.styleCss;
217   }
218
219   // parse HTTP GET params (!!!)
220   window.location.parameters = parseQueryString(window.location.search);
221   var params = window.location.parameters;
222   // query params used by optional record_facets.js
223   if (window.RecordFacets != undefined) {
224     this.recordFacets = new RecordFacets();
225     this.recordFacets.setRequestParams(params);
226   }
227   prefixRecId = params["prefixrecid"];
228   query_state = params["query_state"];
229   recQuery = params["recordquery"];    
230   // load templating components
231 /*
232   loadComponents();
233   renderComponent("authLogoComp", auth);
234   renderComponent("authInfoComp", auth);
235   renderComponent("infoComp",null);    
236   renderComponent("backToSearchComp",query_state);
237 */
238   my_paz = new pz2( {"pazpar2path": auth.servicePath,
239                              "usesessions" : usesessions,
240                      "errorhandler" : my_onerror,
241                      "onrecord" : my_onrecord
242   });
243   
244   // http params have highest priority
245   showDetails(prefixRecId,recQuery);
246 }
247
248
249 //
250 // Pz2.js event handlers:
251 //
252 function my_oninit() {
253     my_paz.stat();
254     my_paz.bytarget();
255 }
256
257 function showMoreRecords() {
258     var i = recToShow;
259     recToShow += recToShowPageSize;
260     for ( ; i < recToShow && i < state.recPerPage; i++) {
261         var element = document.getElementById(recIDs[i]);
262         if (element)
263             element.style.display = '';
264     }
265     if (i == state.recPerPage) {
266         var element = document.getElementById('recdiv_END');
267         if (element)
268             element.style.display = 'none';
269     }
270 }
271
272 function hideRecords() {
273     for ( var i = 0; i < recToShow; i++) {
274         var element = document.getElementById(recIDs[i]);
275         if (element && recIDs != curDetRecId)
276             element.style.display = 'none';
277     }
278     var element = document.getElementById('recdiv_END');
279     if (element)
280         element.style.display = 'none';
281 }
282
283 function showRecords() {
284     for (var i = 0 ; i < recToShow && i < state.recPerPage; i++) {
285         var element = document.getElementById(recIDs[i]);
286         if (element)
287             element.style.display = '';
288     }
289     var element = document.getElementById('recdiv_END');
290     if (element) {
291         if (i == state.recPerPage)
292             element.style.display = 'none';
293         else
294             element.style.display = '';
295     }
296 }
297
298 function my_onshow(data) {
299   hideLogo();
300   totalRec = data.merged;
301     // move it out
302     var pager = document.getElementById("pager");
303     pager.innerHTML = "";
304     drawPager(pager);
305     pager.innerHTML +='<div class="status">Displaying: ' 
306                     + (data.start + 1) + ' to ' + (data.start + data.num) +
307                      ' of ' + data.merged + ' (found: ' 
308                      + data.total + ')</div>';
309
310     var results = document.getElementById("results");
311     
312     var html = [];
313     if (data.hits == undefined) 
314         return ;
315     var style = '';
316     for (var i = 0; i < data.hits.length; i++) {
317         var hit = data.hits[i];
318         var recDivID = "recdiv_" + hit.recid; 
319         recIDs[i] = recDivID;
320         var lines = 0;
321         if (i == recToShow)
322             style = ' style="display:none" ';
323         html.push('<li class="img" id="' + recDivID + '" ' + style +  '>' );
324         html.push('<a class="img" href="#' + i + '" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;" >');
325         if (1) {
326             var useThumbnails = hit["md-use_thumbnails"];
327             var thumburls = hit["md-thumburl"];
328             if (thumburls && (useThumbnails == undefined || useThumbnails == "1")) {
329                 var thumbnailtag = imageHelper.getImageTagByRecId(hit.recid,"md-thumburl", 60, "S"); 
330                 html.push(thumbnailtag);
331             } else { 
332                 if (hit["md-isbn"] != undefined) { 
333                     var coverimagetag = imageHelper.getImageTagByRecId(hit.recid, "md-isbn", 60, "S"); 
334                     if (coverimagetag.length>0) { 
335                         html.push(coverimagetag);
336                     } else { 
337                         html.push("&nbsp;");
338                     }
339                 }
340             }
341         } 
342         html.push("</a>");
343         html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
344         html.push(hit["md-title"]); 
345         html.push("</a>");
346
347         if (hit["md-title-remainder"] != undefined) {
348             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
349             html.push(hit["md-title-remainder"]);
350             html.push("</a>");
351             lines++;
352         }
353         if (hit["md-author"] != undefined) {
354             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
355             html.push(hit["md-author"]);
356             html.push("</a>");
357             lines++;
358         }
359         else if (hit["md-title-responsibility"] != undefined) {
360             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
361             html.push(hit["md-title-responsibility"]);
362             html.push("</a>");
363             lines++;
364         }
365         for (var idx = lines ; idx < 2 ; idx++) {
366             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
367             html.push("&nbsp;");            
368             html.push("</a>");
369         }
370 /*      
371         html.push('<a href="go.html" id="rec_'+ hit.recid + '" >');
372         html.push("item page;");            
373         html.push("</a>");
374 */
375 /*
376         if (hit.recid == curDetRecId) {
377             html.push(renderDetails_iphone(curDetRecData));
378         }
379 */
380         html.push('</li>');
381     }
382     if (data.activeclients == 0)
383       finishLoading();
384 /*
385     // set up "More..." if needed. 
386     style = 'display:none';
387     if (recToShow < recPerPage) {
388         style = 'display:block';
389     }
390     html.push('<li class="img" id="recdiv_END" style="' + style + '"><a onclick="showMoreRecords()">More...</a></li>');     
391 */
392     replaceHtml(results, html.join(''));
393 }
394
395 function my_onstat(data) {
396     var stat = document.getElementById("stat");
397     if (stat == null)
398         return;
399     
400     stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
401                         + data.activeclients
402                         + '/' + data.clients + ' -- </span>'
403                         + '<span>Retrieved records: ' + data.records
404                         + '/' + data.hits + ' :.</span>';
405 }
406
407 function showhide(newtab, hash) {
408     var showtermlist = false;
409     if (newtab != null)
410         tab = newtab;
411     
412     if (tab == "recordview") {
413         document.getElementById("recordview").style.display = '';
414         if (hash != undefined)
415             document.location.hash = hash;
416     }
417     else 
418         document.getElementById("recordview").style.display = 'none';
419
420     if (tab == "xtargets") {
421         document.getElementById("term_xtargets").style.display = '';
422         showtermlist = true;
423     }
424     else
425         document.getElementById("term_xtargets").style.display = 'none';
426
427     if (tab == "subjects") {
428         document.getElementById("term_subjects").style.display = '';
429         showtermlist = true;
430     }
431     else
432         document.getElementById("term_subjects").style.display = 'none';
433
434     if (tab == "authors") {
435         document.getElementById("term_authors").style.display = '';
436         showtermlist = true;
437     }
438     else
439         document.getElementById("term_authors").style.display = 'none';
440
441     if (tab == "detailview") {
442         document.getElementById("detailview").style.display = '';
443     }
444     else {
445         document.getElementById("detailview").style.display = 'none';
446         var element = document.getElementById("rec_" + curDetRecId);
447         if (element != undefined)
448             element.scrollIntoView();
449
450     }
451     if (showtermlist == false) 
452         document.getElementById("termlist").style.display = 'none';
453     else 
454         document.getElementById("termlist").style.display = '';
455
456     var tabDiv = document.getElementById("loginDiv");
457     if (tab == "login") {
458         tabDiv.style.display = '';
459     }
460     else {
461         tabDiv.style.display = 'none';
462     }
463 }
464
465 function my_onterm(data) {
466     var termlists = [];
467     
468     termlists.push('<div id="term_xtargets" >');
469     termlists.push('<h4 class="termtitle">Sources</h4>');
470     termlists.push('<ul class="termlist">');
471     termlists.push('<li> <a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
472     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
473         termlists.push('<li class="termlist"><a href="#" target_id='+data.xtargets[i].id
474             + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">' 
475             + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
476     }
477     termlists.push('</ul>');
478     termlists.push('</div>');
479      
480     termlists.push('<div id="term_subjects" >');
481     termlists.push('<h4>Subjects</h4>');
482     termlists.push('<ul class="termlist">');
483     termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
484     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
485         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">' 
486                        + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
487     }
488     termlists.push('</ul>');
489     termlists.push('</div>');
490             
491     termlists.push('<div id="term_authors" >');
492     termlists.push('<h4 class="termtitle">Authors</h4>');
493     termlists.push('<ul class="termlist">');
494     termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All</a></li>');
495     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
496         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'au\', \'' + data.author[i].name +'\');return false;">' 
497                             + data.author[i].name 
498                             + '  (' 
499                             + data.author[i].freq 
500                             + ')</a></li>');
501     }
502     termlists.push('</ul>');
503     termlists.push('</div>');
504     var termlist = document.getElementById("termlist");
505     replaceHtml(termlist, termlists.join(''));
506     showhide();
507 }
508
509 var termlist = {};
510 function my_onterm_iphone(data) {
511     my_onterm(data);
512     var targets = "reset_xt|All\n";
513     
514     for (var i = 0; i < data.xtargets.length; i++ ) {
515         
516         targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
517     }
518     termlist["xtargets"] = targets;
519     var subjects = "reset_su|All\n";
520     for (var i = 0; i < data.subject.length; i++ ) {
521         subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
522     }
523     termlist["subjects"] = subjects;
524     var authors = "reset_au|All\n";
525     for (var i = 0; i < data.author.length; i++ ) {
526         authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
527     }
528     termlist["authors"] = authors;
529     callback.send("termlist", "refresh");
530 }
531
532 function getTargets() {
533         return termlist['xtargets'];
534 }
535
536 function getSubjects() {
537         return termlist['subjects'];
538 }
539
540 function getAuthors() {
541         return termlist['authors'];
542 }
543
544 function my_onrecord(data) {
545
546     // FIXME: record is async!!
547     clearTimeout(my_paz.recordTimer);
548     // in case on_show was faster to redraw element
549     var detailRecordDiv = document.getElementById('detailrecord');
550     if (!detailRecordDiv) 
551         return;
552     curDetRecData = data;
553     var html = renderDetails_iphone(curDetRecData);
554     detailRecordDiv.innerHTML = html;
555     showhide('detailview');
556     finishLoading();
557 }
558
559 function my_onrecord_iphone(data) {
560     my_onrecord(data);
561     callback.send("record", data.recid, data, data.xtargets[i].freq);
562 }
563
564
565 function my_onbytarget(data) {
566     var targetDiv = document.getElementById("bytarget");
567     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
568         +'<td>Records</td><td>State</td></tr></thead><tbody>';
569     
570     for (var i = 0; i < data.length; i++ ) {
571         table += "<tr><td>" + data[i].id +
572             "</td><td>" + data[i].hits +
573             "</td><td>" + data[i].diagnostic +
574             "</td><td>" + data[i].records +
575             "</td><td>" + data[i].state + "</td></tr>";
576     }
577
578     table += '</tbody></table>';
579     targetDiv.innerHTML = table;
580 }
581
582 ////////////////////////////////////////////////////////////////////////////////
583 ////////////////////////////////////////////////////////////////////////////////
584
585 // wait until the DOM is ready
586 function domReady () 
587
588     // document.search.onsubmit = onFormSubmitEventHandler;
589     document.search.query.value = '';
590     document.select.sort.onchange = onSelectDdChange;
591     document.select.perpage.onchange = onSelectDdChange;
592     if (document.location.search.match("inApp=true")) 
593         applicationMode(true);
594     else
595         applicationMode(false);
596
597     window.location.parameters = parseQueryString(window.location.search);
598     window.location.parametersMulti = parseQueryStringMulti(window.location.search);
599
600     // hash params have highest priority, than query params
601     var params = (window.location.hash && window.location.hash.length > 1)
602       ? parseQueryString(getRealHash())
603       : window.location.parameters;
604     var paramsMulti = window.location.parametersMulti;
605 /*
606     var params = parseQueryString(window.location.search);
607     if (params.query) {
608         document.search.query.value = params.query;
609         onFormSubmitEventHandler();
610     }
611     
612 */
613     controlRegister.loadControls();
614
615     //append settings to the 'state'
616     loadSettings(function (setts) {
617         state.setFallbackSettings(setts);
618         controlRegister.populateControls(setts);  // set controls from cookies
619         controlRegister.populateControls(params); // override from query string
620         stateChanged(params);        
621     });
622     
623 }
624  
625 function applicationMode(newmode) 
626 {
627     var searchdiv = document.getElementById("searchForm");
628     if (newmode)
629         inApp = newmode;
630     if (inApp) {
631         document.getElementById("heading").style.display="none";
632         searchdiv.style.display = 'none';
633     }
634     else { 
635         
636         document.getElementById("nav").style.display="";
637         document.getElementById("normal").style.display="inline";
638         document.getElementById("normal").style.visibility="";
639         searchdiv.style.display = '';
640         //document.search.onsubmit = onFormSubmit;
641     }
642     callback.init();
643 }
644 // when search button pressed
645 function onFormSubmitEventHandler() 
646 {
647     resetPage();
648     document.location.hash = "query=" + document.search.query.value;
649     //window.location.search = "query=" + document.search.query.value;
650     loadSelect();
651     triggerSearch();
652     submitted = true;
653     return true;
654 }
655
656 function onSelectDdChange()
657 {
658     if (!submitted) return false;
659     resetPage();
660     loadSelect();
661     my_paz.show(0, state.recPerPage, curSort);
662     return false;
663 }
664
665
666 function stateChanged(params) {
667   if (params == undefined) 
668         return;
669   if (params["query"]) {
670     // If this page was accessed with a query param, usually means
671     // new page refresh, but not always!
672     state.reset(); // to ensure it's clean and fallbacks are loaded
673     calcRecPerPage();
674     state.loadParams(params);
675   } else if (params["query_state"]) {
676           // If this page was accessed with a serialized State object
677     state.reset(); // to ensure it's clean and fallbacks are loaded
678     state.deserialize(String(params["query_state"]));
679   }
680   document.search.query.value = state.simpleQuery;        
681   document.select.sort.value = state.curSort;        
682   //document.select.perpage.value = state.recPerPage;
683   if (document.category && document.category.category_filter) {
684         document.category.category_filter.value = state.categoryFilter;
685   }
686   if (document.search.query.value != "")
687     triggerSearch();
688 }
689
690 function resetPage()
691 {
692   state.curPage = 1;    
693   totalRec = 0;     
694 }
695
696 function getFacets() {
697     var result = "";
698     for (var key in querys_server) {
699         if (result.length > 0)
700             result += ","
701         result += querys_server[key];
702     }
703     return result;
704 }
705
706 function triggerSearch ()
707 {
708     // Restore to initial page size. Old stuff
709     recToShow = recToShowPageSize;
710     
711     displayLoading();
712     my_paz.search(document.search.query.value, state.recPerPage, curSort, curFilter, undefined,
713         {
714            "limit" : getFacets() 
715         }
716         );
717     showhide("recordview");
718 }
719
720 function loadSelect ()
721 {
722     curSort = document.select.sort.value;
723     //state.recPerPage = document.select.perpage.value;
724 }
725
726 // limit the query after clicking the facet
727 function limitQuery(field, value)
728 {
729   var newQuery = ' and ' + field + '="' + value + '"';
730   querys[field] += newQuery;
731   document.search.query.value += newQuery;
732   onFormSubmitEventHandler();
733   showhide("recordview");
734 }
735
736 // limit the query after clicking the facet
737 function limitQueryServer(field, value)
738 {
739     // Check for client field usage
740     var fieldname = query_client_server[field];
741     if (!fieldname) 
742         fieldname = field;      
743     
744     var newQuery = fieldname + '=' + value.replace(",", "\\,").replace("|", "\\,");
745     // Does it already exists?
746     if (querys_server[fieldname]) 
747         querys_server[fieldname] += "," + newQuery;
748     else
749         querys_server[fieldname] = newQuery;
750 //  document.search.query.value += newQuery;
751   onFormSubmitEventHandler();
752   showhide("recordview");
753 }
754
755
756
757 // limit the query after clicking the facet
758 function removeQuery (field, value) {
759         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
760     onFormSubmitEventHandler();
761     showhide("recordview");
762 }
763
764 // limit the query after clicking the facet
765 function limitOrResetQuery (field, value, selected) {
766     if (useLimit) {
767         limitOrResetQueryServer(field,value, selected);
768         return ;
769     }
770     if (field == 'reset_su' || field == 'reset_au') {
771         var reset_field = field.substring(6);
772         document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
773         querys[reset_field] = '';
774         onFormSubmitEventHandler();
775         showhide("recordview");
776     }
777     else 
778         limitQuery(field, value);
779         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
780 }
781
782 // limit the query after clicking the facet
783 function limitOrResetQueryServer (field, value, selected) {
784     if (field.substring(0,6) == 'reset_') {
785         var clientname = field.substring(6);
786         var fieldname = query_client_server[clientname];
787         if (!fieldname) 
788             fieldname = clientname;     
789         delete querys_server[fieldname];
790         onFormSubmitEventHandler();
791         showhide("recordview");
792     }
793     else 
794         limitQueryServer(field, value);
795         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
796 }
797
798
799
800
801 // limit by target functions
802 function limitTarget (id, name)
803 {
804     curFilter = 'pz:id=' + id;
805     resetPage();
806     loadSelect();
807     triggerSearch();
808     return false;
809 }
810
811 function delimitTarget ()
812 {
813     curFilter = 'ALL'; 
814     resetPage();
815     loadSelect();
816     triggerSearch();
817     return false;
818 }
819
820 function limitOrResetTarget(id, name) {
821         if (id == 'reset_xt') {
822                 delimitTarget();
823         }
824         else {
825                 limitTarget(id,name);
826         }
827 }
828
829 function drawPager (pagerDiv)
830 {
831     //client indexes pages from 1 but pz2 from 0
832     var onsides = 2;
833     var pages = Math.ceil(totalRec / state.recPerPage);
834     
835     var firstClkbl = ( state.curPage - onsides > 0 ) 
836         ? state.curPage - onsides
837         : 1;
838
839     var lastClkbl = firstClkbl + 2*onsides < pages
840         ? firstClkbl + 2*onsides
841         : pages;
842
843     var prev = '<span id="prev">Prev</span><b> | </b>';
844     if (state.curPage > 1)
845         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
846         +'Prev</a><b> | </b>';
847
848     var middle = '';
849     for(var i = firstClkbl; i <= lastClkbl; i++) {
850         var numLabel = i;
851         if(i == state.curPage)
852             numLabel = '<b>' + i + '</b>';
853
854         middle += '<a href="#" onclick="showPage(' + i + ')"> '
855             + numLabel + ' </a>';
856     }
857     
858     var next = '<b> | </b><span id="next">Next</span>';
859     if (pages - state.curPage > 0)
860     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
861         +'Next</a>';
862
863     predots = '';
864     if (firstClkbl > 1)
865         predots = '...';
866
867     postdots = '';
868     if (lastClkbl < pages)
869         postdots = '...';
870
871     pagerDiv.innerHTML += '<div class="pager">' 
872         + prev + predots + middle + postdots + next + '</div>';
873 }
874
875 function showPage(pageNum)
876 {
877     //state.curPage = pageNum;
878     state.curPage = pageNum;
879     displayLoading();
880     my_paz.showPage( state.curPage - 1 );
881 }
882
883 // simple paging functions
884
885 function pagerNext() {
886     if ( totalRec - state.recPerPage*state.curPage > 0) {
887         displayLoading();
888         my_paz.showNext();
889         //curPage++;
890         state.curPage++;
891     }
892 }
893
894 function pagerPrev() {
895   if ( my_paz.showPrev() != false ) {
896     displayLoading();    
897     state.curPage--;
898     if (state.curPage <= 0)
899       throw "Zeo or negative current page"; 
900   }
901
902 }
903
904 // swithing view between targets and records
905
906 function switchView(view) {
907     
908     var targets = document.getElementById('targetview');
909     var records = document.getElementById('recordview');
910     
911     switch(view) {
912         case 'targetview':
913             targets.style.display = "block";            
914             records.style.display = "none";
915             break;
916         case 'recordview':
917             targets.style.display = "none";            
918             records.style.display = "block";
919             break;
920         default:
921             alert('Unknown view.');
922     }
923 }
924
925 function hideLogo() {
926   document.getElementById("logo").style.display = 'none';
927 }
928
929 function displayLoading() {
930   document.getElementById("loading").style.display = 'inline';
931 }
932
933 function finishLoading() {
934   document.getElementById("loading").style.display = 'none';
935 }
936
937
938 // detailed record drawing
939 function showDetails (prefixRecId) {
940     var recId = prefixRecId.replace('rec_', '');
941     var oldRecId = curDetRecId;
942     curDetRecId = recId;
943     
944     // if the same clicked, just show it again
945     if (recId == oldRecId) {
946         showhide('detailview');
947         return;
948     }
949     // request the record
950     displayLoading()
951     my_paz.record_with_query(recId, state.simpleQuery);
952 }
953
954 function replaceHtml(el, html) {
955   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
956   /*@cc_on // Pure innerHTML is slightly faster in IE
957     oldEl.innerHTML = html;
958     return oldEl;
959     @*/
960   var newEl = oldEl.cloneNode(false);
961   newEl.innerHTML = html;
962   oldEl.parentNode.replaceChild(newEl, oldEl);
963   /* Since we just removed the old element from the DOM, return a reference
964      to the new element, which can be used to restore variable references. */
965   return newEl;
966 };
967
968 function renderDetails(data, marker)
969 {
970     var details = '<div class="details" id="det_'+data.recid+'"><table>';
971     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
972     if (data["md-title"] != undefined) {
973         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
974         if (data["md-title-remainder"] != undefined) {
975               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
976         }
977         if (data["md-author"] != undefined) {
978               details += ' <span><i>'+ data["md-auhtor"] +'</i></span>';
979         }
980         details += '</td></tr>';
981     }
982     if (data["md-date"] != undefined)
983         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
984     if (data["md-author"] != undefined)
985         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
986     if (data["md-electronic-url"] != undefined)
987         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>';
988     if (data["location"][0]["md-subject"] != undefined)
989         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
990     if (data["location"][0]["@name"] != undefined)
991         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
992     details += '</table></div>';
993     return details;
994 }
995
996 var default_tag = 'big';
997 function renderLine(title, value, tag) {
998     if (tag == undefined)
999         tag = default_tag;
1000     if (value != undefined)
1001         return '<li><h3>' + title + '</h3><' + tag + '>' + value + '</' + tag + '></li>';
1002     return '';
1003 }
1004
1005 function renderLines(title, values, name, tag) {
1006     if (tag == undefined)
1007         tag = default_tag;
1008     var result = "";
1009     if (values != undefined && values.length)
1010         for (var idx = 0 ; idx < values.length ; idx++)
1011             if (values[idx][name] != undefined )
1012                 result += values[idx][name] + ' ';
1013     if (result != "") 
1014         result = '<li><h3>' + title + '</h3><' + tag + '>' + result + '</' + tag + '></li>';
1015     return result;
1016 }
1017
1018 // Values is a array of locations. 
1019
1020 function renderLinesURL(title, values, name, url, tag) {
1021     if (tag == undefined)
1022         tag = default_tag;
1023     var result = "";
1024     result = '<li><h3>' + title + '</h3><' + tag + ' style="display: inline-block;">';
1025     if (values != undefined && values.length) {
1026         for (var idx = 0 ; idx < values.length ; idx++) {
1027             var url = choose_url(values[idx], auth.proxyUrl);
1028             if (url != null)
1029                 result += '<a target="_blank" href="' + url + '">' + values[idx][name] + '</a><br>';
1030             else
1031                 result += values[idx][name] + '<br>';
1032         }
1033     }
1034     result += '</' + tag + '></li>';
1035     return result;
1036 }
1037
1038 function renderLineURL(title, URL, display) {
1039     if (URL != undefined)
1040         return '<li><h3>' + title + '</h3><a href="' + URL + '" target="_blank">' + display + '</a></li>';
1041     return '';
1042 }
1043
1044 function renderLineEmail(dtitle, email, display) {
1045     if (email != undefined)
1046         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
1047     return '';
1048 }
1049
1050
1051 function find_prioritized(values) {
1052     for (var index = 0; index < values.length; index++) {
1053         if (values[index] != undefined)
1054             return values[index];
1055     }
1056     return undefined;
1057 }
1058
1059 function renderDetails_iphone(data, marker)
1060 {
1061         //return renderDetails(data,marker);
1062
1063     if (!data) 
1064         return ""; 
1065     var details = '<div class="details" id="det_'+data.recid+'" >'
1066     if (marker) 
1067         details += '<h4>'+ marker + '</h4>'; 
1068     details += '<ul class="field" >';
1069
1070     var title  = '';
1071     if (data["md-title"] != undefined) {
1072         title +=  data["md-title"];
1073         if (data["md-title-remainder"] != undefined) {
1074             title += '<br><i>' + data["md-title-remainder"] + '</i>';
1075         }
1076     }
1077     details += renderLine('Title', title);
1078
1079     var author = find_prioritized(
1080         [
1081             data["md-author"],
1082             data["md-title-responsibility"]
1083         ]
1084     );
1085
1086     var coverimagetag = imageHelper.getImageTagByRecId(data.recid, "md-isbn", undefined, "M");
1087     details 
1088         +=renderLine('Date',    data["md-date"])
1089         + renderLine('Author',  data["md-author"])
1090 //      + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
1091         + renderLine('Description',     data["md-description"])
1092 //      + renderLines('Subjects', data["location"], "md-subject")
1093     ;
1094
1095     details += renderLinesURL('Location', data["location"], "@name", "md-url_recipe");
1096     details += '<li><a href="#" onclick="showhide(\'recordview\')" style="font-size: 18px;margin-left: 10px;">Back</a></li>';
1097     if (coverimagetag.length>0) {
1098         details += renderLine('&nbsp;', coverimagetag);
1099     }
1100
1101     details += '</ul></div>';
1102     return details;
1103 }
1104
1105 //EOF