Show command output pasrsing: keeping location nodes in an array rather than hash.
[pazpar2-moved-to-github.git] / js / pz2.js
1 /*
2 ** $Id: pz2.js,v 1.63 2007-10-30 13:41:05 jakub Exp $
3 ** pz2.js - pazpar2's javascript client library.
4 */
5
6 //since explorer is flawed
7 if (!window['Node']) {
8     window.Node = new Object();
9     Node.ELEMENT_NODE = 1;
10     Node.ATTRIBUTE_NODE = 2;
11     Node.TEXT_NODE = 3;
12     Node.CDATA_SECTION_NODE = 4;
13     Node.ENTITY_REFERENCE_NODE = 5;
14     Node.ENTITY_NODE = 6;
15     Node.PROCESSING_INSTRUCTION_NODE = 7;
16     Node.COMMENT_NODE = 8;
17     Node.DOCUMENT_NODE = 9;
18     Node.DOCUMENT_TYPE_NODE = 10;
19     Node.DOCUMENT_FRAGMENT_NODE = 11;
20     Node.NOTATION_NODE = 12;
21 }
22
23 // prevent execution of more than once
24 if(typeof window.pz2 == "undefined") {
25 window.undefined = window.undefined;
26
27 var pz2 = function ( paramArray )
28 {
29     
30     // at least one callback required
31     if ( !paramArray )
32         throw new Error("Pz2.js: Array with parameters has to be suplied."); 
33
34     //supported pazpar2's protocol version
35     this.suppProtoVer = '1';
36     if (typeof paramArray.pazpar2path != "undefined")
37         this.pz2String = paramArray.pazpar2path;
38     else
39         this.pz2String = "/pazpar2/search.pz2";
40     this.useSessions = true;
41     
42     this.stylesheet = paramArray.detailstylesheet || null;
43     //load stylesheet if required in async mode
44     if( this.stylesheet ) {
45         var context = this;
46         var request = new pzHttpRequest( this.stylesheet );
47         request.get( {}, function ( doc ) { context.xslDoc = doc; } );
48     }
49     
50     this.errorHandler = paramArray.errorhandler || null;
51     
52     // function callbacks
53     this.statCallback = paramArray.onstat || null;
54     this.showCallback = paramArray.onshow || null;
55     this.termlistCallback = paramArray.onterm || null;
56     this.recordCallback = paramArray.onrecord || null;
57     this.bytargetCallback = paramArray.onbytarget || null;
58     this.resetCallback = paramArray.onreset || null;
59
60     // termlist keys
61     this.termKeys = paramArray.termlist || "subject";
62     
63     // some configurational stuff
64     this.keepAlive = 50000;
65     
66     if ( paramArray.keepAlive < this.keepAlive )
67         this.keepAlive = paramArray.keepAlive;
68
69     this.sessionID = null;
70     this.initStatusOK = false;
71     this.pingStatusOK = false;
72     this.searchStatusOK = false;
73     
74     // for sorting
75     this.currentSort = "relevance";
76
77     // where are we?
78     this.currentStart = 0;
79     this.currentNum = 20;
80
81     // last full record retrieved
82     this.currRecID = null;
83     
84     // current query
85     this.currQuery = null;
86
87     //timers
88     this.statTime = paramArray.stattime || 1000;
89     this.statTimer = null;
90     this.termTime = paramArray.termtime || 1000;
91     this.termTimer = null;
92     this.showTime = paramArray.showtime || 1000;
93     this.showTimer = null;
94     this.showFastCount = 4;
95     this.bytargetTime = paramArray.bytargettime || 1000;
96     this.bytargetTimer = null;
97
98     // counters for each command and applied delay
99     this.dumpFactor = 500;
100     this.showCounter = 0;
101     this.termCounter = 0;
102     this.statCounter = 0;
103     this.bytargetCounter = 0;
104
105     // active clients, updated by stat and show
106     // might be an issue since bytarget will poll accordingly
107     this.activeClients = 1;
108
109     // if in proxy mode no need to init
110     if (paramArray.usesessions != undefined) {
111          this.useSessions = paramArray.usesessions;
112         this.initStatusOK = true;
113     }
114     // else, auto init session or wait for a user init?
115     if (this.useSessions && paramArray.autoInit !== false) {
116         this.init();
117     }
118 };
119
120 pz2.prototype = 
121 {
122     //error handler for async error throws
123    throwError: function (errMsg, errCode)
124    {
125         var err = new Error(errMsg);
126         if (errCode) err.code = errCode;
127                 
128         if (this.errorHandler) {
129             this.errorHandler(err);
130         }
131         else {
132             throw err;
133         }
134    },
135
136     // stop activity by clearing tiemouts 
137    stop: function ()
138    {
139        clearTimeout(this.statTimer);
140        clearTimeout(this.showTimer);
141        clearTimeout(this.termTimer);
142        clearTimeout(this.bytargetTimer);
143     },
144     
145     // reset status variables
146     reset: function ()
147     {   
148         if ( this.useSessions ) {
149             this.sessionID = null;
150             this.initStatusOK = false;
151             this.pingStatusOK = false;
152         }
153         this.searchStatusOK = false;
154         this.stop();
155             
156         if ( this.resetCallback )
157                 this.resetCallback();
158     },
159
160     init: function ( sessionId ) 
161     {
162         this.reset();
163         
164         // session id as a param
165         if ( sessionId != undefined && this.useSessions ) {
166             this.initStatusOK = true;
167             this.sessionID = sessionId;
168             this.ping();
169         // old school direct pazpar2 init
170         } else if (this.useSessions) {
171             var context = this;
172             var request = new pzHttpRequest(this.pz2String, this.errorHandler);
173             request.get(
174                 { "command": "init" },
175                 function(data) {
176                     if ( data.getElementsByTagName("status")[0]
177                             .childNodes[0].nodeValue == "OK" ) {
178                         if ( data.getElementsByTagName("protocol")[0]
179                                 .childNodes[0].nodeValue 
180                             != context.suppProtoVer )
181                             throw new Error(
182                                 "Server's protocol not supported by the client"
183                             );
184                         context.initStatusOK = true;
185                         context.sessionID = 
186                             data.getElementsByTagName("session")[0]
187                                 .childNodes[0].nodeValue;
188                         setTimeout(
189                             function () {
190                                 context.ping();
191                             },
192                             context.keepAlive
193                         );
194                     }
195                     else
196                         context.throwError('Init failed. Malformed WS resonse.',
197                                             110);
198                 }
199             );
200         // when through proxy no need to init
201         } else {
202             this.initStatusOK = true;
203         }
204     },
205     // no need to ping explicitly
206     ping: function () 
207     {
208         // pinging only makes sense when using pazpar2 directly
209         if( !this.initStatusOK || !this.useSessions )
210             throw new Error(
211             'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
212             );
213         var context = this;
214         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
215         request.get(
216             { "command": "ping", "session": this.sessionID },
217             function(data) {
218                 if ( data.getElementsByTagName("status")[0]
219                         .childNodes[0].nodeValue == "OK" ) {
220                     context.pingStatusOK = true;
221                     setTimeout(
222                         function () {
223                             context.ping();
224                         }, 
225                         context.keepAlive
226                     );
227                 }
228                 else
229                     context.throwError('Ping failed. Malformed WS resonse.',
230                                         111);
231             }
232         );
233     },
234     search: function (query, num, sort, filter, showfrom)
235     {
236         clearTimeout(this.statTimer);
237         clearTimeout(this.showTimer);
238         clearTimeout(this.termTimer);
239         clearTimeout(this.bytargetTimer);
240         
241         this.showCounter = 0;
242         this.termCounter = 0;
243         this.bytargetCounter = 0;
244         this.statCounter = 0;
245         
246         // no proxy mode
247         if( !this.initStatusOK )
248             throw new Error('Pz2.js: session not initialized.');
249         
250         if( query !== undefined )
251             this.currQuery = query;
252         else
253             throw new Error("Pz2.js: no query supplied to the search command.");
254         
255         if ( showfrom !== undefined )
256             var start = showfrom;
257         else
258             var start = 0;
259
260         var searchParams = { 
261             "command": "search",
262             "query": this.currQuery, 
263             "session": this.sessionID 
264         };
265         
266         if (filter !== undefined)
267             searchParams["filter"] = filter;
268         
269         var context = this;
270         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
271         request.get(
272             searchParams,
273             function(data) {
274                 if ( data.getElementsByTagName("status")[0]
275                         .childNodes[0].nodeValue == "OK" ) {
276                     context.searchStatusOK = true;
277                     //piggyback search
278                     context.show(start, num, sort);
279                     if ( context.statCallback )
280                         context.stat();
281                     if ( context.termlistCallback )
282                         context.termlist();
283                     if ( context.bytargetCallback )
284                         context.bytarget();
285                 }
286                 else
287                     context.throwError('Search failed. Malformed WS resonse.',
288                                         112);
289             }
290         );
291     },
292     stat: function()
293     {
294         if( !this.initStatusOK )
295             throw new Error('Pz2.js: session not initialized.');
296         
297         // if called explicitly takes precedence
298         clearTimeout(this.statTimer);
299         
300         var context = this;
301         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
302         request.get(
303             { "command": "stat", "session": this.sessionID },
304             function(data) {
305                 if ( data.getElementsByTagName("stat") ) {
306                     var activeClients = 
307                         Number( data.getElementsByTagName("activeclients")[0]
308                                     .childNodes[0].nodeValue );
309                     context.activeClients = activeClients;
310                     var stat = {
311                         "activeclients": activeClients,
312                         "hits": 
313                             Number( data.getElementsByTagName("hits")[0]
314                                         .childNodes[0].nodeValue ),
315                         "records": 
316                             Number( data.getElementsByTagName("records")[0]
317                                         .childNodes[0].nodeValue ),
318                         "clients": 
319                             Number( data.getElementsByTagName("clients")[0]
320                                         .childNodes[0].nodeValue ),
321                         "initializing": 
322                             Number( data.getElementsByTagName("initializing")[0]
323                                         .childNodes[0].nodeValue ),
324                         "searching": 
325                             Number( data.getElementsByTagName("searching")[0]
326                                         .childNodes[0].nodeValue ),
327                         "presenting": 
328                             Number( data.getElementsByTagName("presenting")[0]
329                                         .childNodes[0].nodeValue ),
330                         "idle": 
331                             Number( data.getElementsByTagName("idle")[0]
332                                         .childNodes[0].nodeValue ),
333                         "failed": 
334                             Number( data.getElementsByTagName("failed")[0]
335                                         .childNodes[0].nodeValue ),
336                         "error": 
337                             Number( data.getElementsByTagName("error")[0]
338                                         .childNodes[0].nodeValue )
339                     };
340                     
341                     context.statCounter++;
342                     var delay = context.statTime 
343                         + context.statCounter * context.dumpFactor;
344                     
345                     if ( activeClients > 0 )
346                         context.statTimer = 
347                             setTimeout( 
348                                 function () {
349                                     context.stat();
350                                 },
351                                 delay
352                             );
353                     context.statCallback(stat);
354                 }
355                 else
356                     context.throwError('Stat failed. Malformed WS resonse.',
357                                         113);
358             }
359         );
360     },
361     show: function(start, num, sort)
362     {
363         if( !this.searchStatusOK && this.useSessions )
364             throw new Error(
365                 'Pz2.js: show command has to be preceded with a search command.'
366             );
367         
368         // if called explicitly takes precedence
369         clearTimeout(this.showTimer);
370         
371         if( sort !== undefined )
372             this.currentSort = sort;
373         if( start !== undefined )
374             this.currentStart = Number( start );
375         if( num !== undefined )
376             this.currentNum = Number( num );
377
378         var context = this;
379         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
380         request.get(
381             { 
382                 "command": "show", 
383                 "session": this.sessionID, 
384                 "start": this.currentStart,
385                 "num": this.currentNum, 
386                 "sort": this.currentSort, 
387                 "block": 1 
388             },
389             function(data) {
390                 if ( data.getElementsByTagName("status")[0]
391                         .childNodes[0].nodeValue == "OK" ) {
392                     // first parse the status data send along with records
393                     // this is strictly bound to the format
394                     var activeClients = 
395                         Number( data.getElementsByTagName("activeclients")[0]
396                                     .childNodes[0].nodeValue );
397                     context.activeClients = activeClients; 
398                     var show = {
399                         "activeclients": activeClients,
400                         "merged": 
401                             Number( data.getElementsByTagName("merged")[0]
402                                         .childNodes[0].nodeValue ),
403                         "total": 
404                             Number( data.getElementsByTagName("total")[0]
405                                         .childNodes[0].nodeValue ),
406                         "start": 
407                             Number( data.getElementsByTagName("start")[0]
408                                         .childNodes[0].nodeValue ),
409                         "num": 
410                             Number( data.getElementsByTagName("num")[0]
411                                         .childNodes[0].nodeValue ),
412                         "hits": []
413                     };
414                     // parse all the first-level nodes for all <hit> tags
415                     var hits = data.getElementsByTagName("hit");
416                     var hit = new Array();
417                     for (i = 0; i < hits.length; i++) {
418                         show.hits[i] = new Array();
419                         show.hits[i]['location'] = new Array();
420                         var locCount = 0;
421                         for ( j = 0; j < hits[i].childNodes.length; j++) {
422                             if ( hits[i].childNodes[j].nodeType 
423                                 == Node.ELEMENT_NODE ) {
424                                 if (hits[i].childNodes[j].nodeName 
425                                     == 'location') {
426                                     var locNode = hits[i].childNodes[j];
427                                     var id = locNode.getAttribute('id');
428                                     show.hits[i]['location'][locCount] = {
429                                         "id": locNode.getAttribute("id"),
430                                         "name": locNode.getAttribute("name")
431                                     };
432                                     locCount++;
433                                 }
434                                 else {
435                                     var nodeName = 
436                                         hits[i].childNodes[j].nodeName;
437                                     var nodeText = 'ERROR'
438                                     if ( hits[i].childNodes[j].firstChild )
439                                         nodeText = 
440                                             hits[i].childNodes[j]
441                                                 .firstChild.nodeValue;
442                                     show.hits[i][nodeName] = nodeText;
443                                 }
444                             }
445                         }
446                     }
447                     context.showCounter++;
448                     var delay = context.showTime;
449                     if (context.showCounter > context.showFastCount)
450                             delay += context.showCounter * context.dumpFactor;
451                     if ( activeClients > 0 )
452                         context.showTimer = setTimeout(
453                             function () {
454                                 context.show();
455                             }, 
456                             delay);
457
458                     context.showCallback(show);
459                 }
460                 else
461                     context.throwError('Show failed. Malformed WS resonse.',
462                                         114);
463             }
464         );
465     },
466     record: function(id, offset, params)
467     {
468         // we may call record with no previous search if in proxy mode
469         if( !this.searchStatusOK && this.useSessions)
470            throw new Error(
471             'Pz2.js: record command has to be preceded with a search command.'
472             ); 
473         if ( params == undefined )
474             params = {};
475
476         if ( params.callback != undefined ) {
477             callback = params.callback;
478         } else {
479             callback = this.recordCallback;
480         }
481         
482         // what is that?
483         if ( params['handle'] == undefined )
484             handle = {};
485         else
486             handle = params['handle'];
487
488         if( id !== undefined )
489             this.currRecID = id;
490         
491         var context = this;
492         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
493
494         var recordParams = { "command": "record", 
495                             "session": this.sessionID,
496                             "id": this.currRecID };
497         
498         if (offset !== undefined) {
499             recordParams["offset"] = offset;
500         }
501
502         if (params.syntax != undefined) {
503             recordParams['syntax'] = params.syntax;
504         }
505
506         this.currRecOffset = offset;
507
508         request.get(
509             recordParams,
510             function(data) {
511                 var recordNode;
512                 var record = new Array();
513                 record['xmlDoc'] = data;
514                 if (context.currRecOffset !== undefined) {
515                     record['offset'] = context.currRecOffset;
516                     callback(record, handle);
517                 } else if ( recordNode = 
518                     data.getElementsByTagName("record")[0] ) {
519                     // if stylesheet was fetched do not parse the response
520                     if ( context.xslDoc ) {
521                         record['recid'] = 
522                             recordNode.getElementsByTagName("recid")[0]
523                                 .firstChild.nodeValue;
524                         record['xslDoc'] = 
525                             context.xslDoc;
526                     } else {
527                         for ( i = 0; i < recordNode.childNodes.length; i++) {
528                             if ( recordNode.childNodes[i].nodeType 
529                                 == Node.ELEMENT_NODE
530                                 && recordNode.childNodes[i].nodeName 
531                                 != 'location' ) {
532                                 var nodeName = 
533                                     recordNode.childNodes[i].nodeName;
534                                 var nodeText = 
535                                     recordNode.childNodes[i]
536                                         .firstChild.nodeValue;
537                                 record[nodeName] = nodeText;                            
538                             }
539                         }
540                         // the location might be empty!!
541                         var locationNodes = 
542                             recordNode.getElementsByTagName("location");
543                         record["location"] = new Array();
544                         for ( i = 0; i < locationNodes.length; i++ ) {
545                             record["location"][i] = {
546                                 "id": locationNodes[i].getAttribute("id"),
547                                 "name": locationNodes[i].getAttribute("name")
548                             };
549                             
550                             for (j = 0; 
551                                 j < locationNodes[i].childNodes.length; 
552                                 j++) {
553                                 if ( locationNodes[i].childNodes[j].nodeType 
554                                     == Node.ELEMENT_NODE ) {
555                                     var nodeName = 
556                                         locationNodes[i].childNodes[j].nodeName;
557                                     var nodeText = '';
558                                     if (locationNodes[i].childNodes[j]
559                                             .firstChild)
560                                         nodeText = 
561                                             locationNodes[i].childNodes[j]
562                                                 .firstChild.nodeValue;
563                                     record["location"][i][nodeName] = nodeText;                            
564                                 }
565                             }
566                         }
567                     }
568                     
569                     callback(record, handle);
570                 }
571                 else
572                     context.throwError('Record failed. Malformed WS resonse.',
573                                         115);
574             }
575         );
576     },
577
578     termlist: function()
579     {
580         if( !this.searchStatusOK && this.useSessions )
581             throw new Error(
582             'Pz2.js: termlist command has to be preceded with a search command.'
583             );
584
585         // if called explicitly takes precedence
586         clearTimeout(this.termTimer);
587         
588         var context = this;
589         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
590         request.get(
591             { 
592                 "command": "termlist", 
593                 "session": this.sessionID, 
594                 "name": this.termKeys 
595             },
596             function(data) {
597                 if ( data.getElementsByTagName("termlist") ) {
598                     var activeClients = 
599                         Number( data.getElementsByTagName("activeclients")[0]
600                                     .childNodes[0].nodeValue );
601                     context.activeClients = activeClients;
602                     var termList = { "activeclients":  activeClients };
603                     var termLists = data.getElementsByTagName("list");
604                     //for each termlist
605                     for (i = 0; i < termLists.length; i++) {
606                         var listName = termLists[i].getAttribute('name');
607                         termList[listName] = new Array();
608                         var terms = termLists[i].getElementsByTagName('term');
609                         //for each term in the list
610                         for (j = 0; j < terms.length; j++) { 
611                             var term = {
612                                 "name": 
613                                     (terms[j].getElementsByTagName("name")[0]
614                                         .childNodes.length 
615                                     ? terms[j].getElementsByTagName("name")[0]
616                                         .childNodes[0].nodeValue
617                                     : 'ERROR'),
618                                 "freq": 
619                                     terms[j]
620                                     .getElementsByTagName("frequency")[0]
621                                     .childNodes[0].nodeValue || 'ERROR'
622                             };
623
624                             var termIdNode = 
625                                 terms[j].getElementsByTagName("id");
626                             if(terms[j].getElementsByTagName("id").length)
627                                 term["id"] = 
628                                     termIdNode[0].childNodes[0].nodeValue;
629                             termList[listName][j] = term;
630                         }
631                     }
632
633                     context.termCounter++;
634                     var delay = context.termTime 
635                         + context.termCounter * context.dumpFactor;
636                     if ( activeClients > 0 )
637                         context.termTimer = 
638                             setTimeout(
639                                 function () {
640                                     context.termlist();
641                                 }, 
642                                 delay
643                             );
644                    
645                    context.termlistCallback(termList);
646                 }
647                 else
648                     context.throwError('Termlist failed. Malformed WS resonse.',
649                                         116);
650             }
651         );
652
653     },
654     bytarget: function()
655     {
656         if( !this.initStatusOK && this.useSessions )
657             throw new Error(
658             'Pz2.js: bytarget command has to be preceded with a search command.'
659             );
660         
661         // no need to continue
662         if( !this.searchStatusOK )
663             return;
664
665         // if called explicitly takes precedence
666         clearTimeout(this.bytargetTimer);
667         
668         var context = this;
669         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
670         request.get(
671             { "command": "bytarget", "session": this.sessionID },
672             function(data) {
673                 if ( data.getElementsByTagName("status")[0]
674                         .childNodes[0].nodeValue == "OK" ) {
675                     var targetNodes = data.getElementsByTagName("target");
676                     var bytarget = new Array();
677                     for ( i = 0; i < targetNodes.length; i++) {
678                         bytarget[i] = new Array();
679                         for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
680                             if ( targetNodes[i].childNodes[j].nodeType 
681                                 == Node.ELEMENT_NODE ) {
682                                 var nodeName = 
683                                     targetNodes[i].childNodes[j].nodeName;
684                                 var nodeText = 
685                                     targetNodes[i].childNodes[j]
686                                         .firstChild.nodeValue;
687                                 bytarget[i][nodeName] = nodeText;
688                             }
689                         }
690                     }
691                     
692                     context.bytargetCounter++;
693                     var delay = context.bytargetTime 
694                         + context.bytargetCounter * context.dumpFactor;
695                     if ( context.activeClients > 0 )
696                         context.bytargetTimer = 
697                             setTimeout(
698                                 function () {
699                                     context.bytarget();
700                                 }, 
701                                 delay
702                             );
703
704                     context.bytargetCallback(bytarget);
705                 }
706                 else
707                     context.throwError('Bytarget failed. Malformed WS resonse.',
708                                         117);
709             }
710         );
711     },
712     
713     // just for testing, probably shouldn't be here
714     showNext: function(page)
715     {
716         var step = page || 1;
717         this.show( ( step * this.currentNum ) + this.currentStart );     
718     },
719
720     showPrev: function(page)
721     {
722         if (this.currentStart == 0 )
723             return false;
724         var step = page || 1;
725         var newStart = this.currentStart - (step * this.currentNum );
726         this.show( newStart > 0 ? newStart : 0 );
727     },
728
729     showPage: function(pageNum)
730     {
731         //var page = pageNum || 1;
732         this.show(pageNum * this.currentNum);
733     }
734 };
735
736 /*
737 ********************************************************************************
738 ** AJAX HELPER CLASS ***********************************************************
739 ********************************************************************************
740 */
741 var pzHttpRequest = function ( url, errorHandler ) {
742         this.request = null;
743         this.url = url;
744         this.errorHandler = errorHandler || null;
745         this.async = true;
746         
747         if ( window.XMLHttpRequest ) {
748             this.request = new XMLHttpRequest();
749         } else if ( window.ActiveXObject ) {
750             try {
751                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
752             } catch (err) {
753                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
754             }
755         }
756 };
757
758 pzHttpRequest.prototype = 
759 {
760     get: function ( params, callback ) 
761     {
762         this._send( 'GET', params, '', callback );
763     },
764
765     post: function ( params, data, callback )
766     {
767         this._send( 'POST', params, data, callback );
768     },
769
770     load: function ()
771     {
772         this.async = false;
773         this.request.open( 'GET', this.url, this.async );
774         this.request.send('');
775         if ( this.request.status == 200 )
776             return this.request.responseXML;
777     },
778
779     _send: function ( type, params, data, callback )
780     {
781         this.callback = callback;
782         var context = this;
783         this.async = true;
784         this.request.open( type, this._urlAppendParams(params), this.async );
785         this.request.onreadystatechange = function () {
786             context._handleResponse();
787         }
788         this.request.send(data);
789     },
790
791     _urlAppendParams: function (params)
792     {
793         var getUrl = this.url;
794
795         var sep = '?';
796         var el = params;
797         for (var key in el) {
798             if (el[key] != null) {
799                 getUrl += sep + key + '=' + encodeURIComponent(el[key]);
800                 sep = '&';
801             }
802         }
803         return getUrl;
804     },
805
806     _handleResponse: function ()
807     {
808         if ( this.request.readyState == 4 ) { 
809             // pick up pazpr2 errors first
810             if ( this.request.responseXML 
811                 && this.request.responseXML.documentElement.nodeName == 'error'
812                 && this.request.responseXML.getElementsByTagName("error")
813                     .length ) {
814                 var errAddInfo = '';
815                 if ( this.request.responseXML.getElementsByTagName("error")[0]
816                         .childNodes.length )
817                     errAddInfo = ': ' + 
818                         this.request.responseXML
819                             .getElementsByTagName("error")[0]
820                             .childNodes[0].nodeValue;
821                 var errMsg = 
822                     this.request.responseXML.getElementsByTagName("error")[0]
823                         .getAttribute("msg");
824                 var errCode = 
825                     this.request.responseXML.getElementsByTagName("error")[0]
826                         .getAttribute("code");
827             
828                 var err = new Error(errMsg + errAddInfo);
829                 err.code = errCode;
830             
831                 if (this.errorHandler) {
832                     this.errorHandler(err);
833                 }
834                 else {
835                     throw err;
836                 }
837             } else if ( this.request.status == 200 ) {
838                 this.callback( this.request.responseXML );
839             } else {
840                 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: " 
841                             + this.request.status + " Info: " 
842                             + this.request.statusText );
843                 err.code = 'HTTP';
844                 
845                 if (this.errorHandler) {
846                     this.errorHandler(err);
847                 }
848                 else {
849                     throw err;
850                 }
851             }
852         }
853     }
854 };
855
856 /*
857 ********************************************************************************
858 ** XML HELPER FUNCTIONS ********************************************************
859 ********************************************************************************
860 */
861
862 // DOMDocument
863
864 if ( window.ActiveXObject) {
865     var DOMDoc = document;
866 } else {
867     var DOMDoc = Document.prototype;
868 }
869
870 DOMDoc.newXmlDoc = function ( root )
871 {
872     var doc;
873
874     if (document.implementation && document.implementation.createDocument) {
875         doc = document.implementation.createDocument('', root, null);
876     } else if ( window.ActiveXObject ) {
877         doc = new ActiveXObject("MSXML2.DOMDocument");
878         doc.loadXML('<' + root + '/>');
879     } else {
880         throw new Error ('No XML support in this browser');
881     }
882
883     return doc;
884 }
885
886    
887 DOMDoc.parseXmlFromString = function ( xmlString ) 
888 {
889     var doc;
890
891     if ( window.DOMParser ) {
892         var parser = new DOMParser();
893         doc = parser.parseFromString( xmlString, "text/xml");
894     } else if ( window.ActiveXObject ) {
895         doc = new ActiveXObject("MSXML2.DOMDocument");
896         doc.loadXML( xmlString );
897     } else {
898         throw new Error ("No XML parsing support in this browser.");
899     }
900
901     return doc;
902 }
903
904 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
905 {
906     if ( window.XSLTProcessor ) {
907         var proc = new XSLTProcessor();
908         proc.importStylesheet( xslDoc );
909         return proc.transformToDocument(xmlDoc);
910     } else if ( window.ActiveXObject ) {
911         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
912     } else {
913         alert( 'Unable to perform XSLT transformation in this browser' );
914     }
915 }
916  
917 // DOMElement
918
919 Element_removeFromDoc = function (DOM_Element)
920 {
921     DOM_Element.parentNode.removeChild(DOM_Element);
922 }
923
924 Element_emptyChildren = function (DOM_Element)
925 {
926     while( DOM_Element.firstChild ) {
927         DOM_Element.removeChild( DOM_Element.firstChild )
928     }
929 }
930
931 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
932 {
933     if ( window.XSLTProcessor ) {
934         var proc = new XSLTProcessor();
935         proc.importStylesheet( xslDoc );
936         var docFrag = false;
937         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
938         DOM_Element.appendChild(docFrag);
939     } else if ( window.ActiveXObject ) {
940         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
941     } else {
942         alert( 'Unable to perform XSLT transformation in this browser' );
943     }
944 }
945  
946 Element_appendTextNode = function (DOM_Element, tagName, textContent )
947 {
948     var node = DOM_Element.ownerDocument.createElement(tagName);
949     var text = DOM_Element.ownerDocument.createTextNode(textContent);
950
951     DOM_Element.appendChild(node);
952     node.appendChild(text);
953
954     return node;
955 }
956
957 Element_setTextContent = function ( DOM_Element, textContent )
958 {
959     if (typeof DOM_Element.textContent !== "undefined") {
960         DOM_Element.textContent = textContent;
961     } else if (typeof DOM_Element.innerText !== "undefined" ) {
962         DOM_Element.innerText = textContent;
963     } else {
964         throw new Error("Cannot set text content of the node, no such method.");
965     }
966 }
967
968 Element_getTextContent = function (DOM_Element)
969 {
970     if ( typeof DOM_Element.textContent != 'undefined' ) {
971         return DOM_Element.textContent;
972     } else if (typeof DOM_Element.text != 'undefined') {
973         return DOM_Element.text;
974     } else {
975         throw new Error("Cannot get text content of the node, no such method.");
976     }
977 }
978
979 /* do not remove trailing bracket */
980 }