Refactoring.
[pazpar2-moved-to-github.git] / js / pz2.js
1 /*
2 ** $Id: pz2.js,v 1.62 2007-10-02 12:09:40 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                         for ( j = 0; j < hits[i].childNodes.length; j++) {
421                             var locCount = 0;
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'][id] = {
429                                         "id": locNode.getAttribute("id"),
430                                         "name": locNode.getAttribute("name")
431                                     };
432                                 }
433                                 else {
434                                     var nodeName = 
435                                         hits[i].childNodes[j].nodeName;
436                                     var nodeText = 'ERROR'
437                                     if ( hits[i].childNodes[j].firstChild )
438                                         nodeText = 
439                                             hits[i].childNodes[j]
440                                                 .firstChild.nodeValue;
441                                     show.hits[i][nodeName] = nodeText;
442                                 }
443                             }
444                         }
445                     }
446                     context.showCounter++;
447                     var delay = context.showTime;
448                     if (context.showCounter > context.showFastCount)
449                             delay += context.showCounter * context.dumpFactor;
450                     if ( activeClients > 0 )
451                         context.showTimer = setTimeout(
452                             function () {
453                                 context.show();
454                             }, 
455                             delay);
456
457                     context.showCallback(show);
458                 }
459                 else
460                     context.throwError('Show failed. Malformed WS resonse.',
461                                         114);
462             }
463         );
464     },
465     record: function(id, offset, params)
466     {
467         // we may call record with no previous search if in proxy mode
468         if( !this.searchStatusOK && this.useSessions)
469            throw new Error(
470             'Pz2.js: record command has to be preceded with a search command.'
471             ); 
472         if ( params == undefined )
473             params = {};
474
475         if ( params.callback != undefined ) {
476             callback = params.callback;
477         } else {
478             callback = this.recordCallback;
479         }
480         
481         // what is that?
482         if ( params['handle'] == undefined )
483             handle = {};
484         else
485             handle = params['handle'];
486
487         if( id !== undefined )
488             this.currRecID = id;
489         
490         var context = this;
491         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
492
493         var recordParams = { "command": "record", 
494                             "session": this.sessionID,
495                             "id": this.currRecID };
496         
497         if (offset !== undefined) {
498             recordParams["offset"] = offset;
499         }
500
501         if (params.syntax != undefined) {
502             recordParams['syntax'] = params.syntax;
503         }
504
505         this.currRecOffset = offset;
506
507         request.get(
508             recordParams,
509             function(data) {
510                 var recordNode;
511                 var record = new Array();
512                 record['xmlDoc'] = data;
513                 if (context.currRecOffset !== undefined) {
514                     record['offset'] = context.currRecOffset;
515                     callback(record, handle);
516                 } else if ( recordNode = 
517                     data.getElementsByTagName("record")[0] ) {
518                     // if stylesheet was fetched do not parse the response
519                     if ( context.xslDoc ) {
520                         record['recid'] = 
521                             recordNode.getElementsByTagName("recid")[0]
522                                 .firstChild.nodeValue;
523                         record['xslDoc'] = 
524                             context.xslDoc;
525                     } else {
526                         for ( i = 0; i < recordNode.childNodes.length; i++) {
527                             if ( recordNode.childNodes[i].nodeType 
528                                 == Node.ELEMENT_NODE
529                                 && recordNode.childNodes[i].nodeName 
530                                 != 'location' ) {
531                                 var nodeName = 
532                                     recordNode.childNodes[i].nodeName;
533                                 var nodeText = 
534                                     recordNode.childNodes[i]
535                                         .firstChild.nodeValue;
536                                 record[nodeName] = nodeText;                            
537                             }
538                         }
539                         // the location might be empty!!
540                         var locationNodes = 
541                             recordNode.getElementsByTagName("location");
542                         record["location"] = new Array();
543                         for ( i = 0; i < locationNodes.length; i++ ) {
544                             record["location"][i] = {
545                                 "id": locationNodes[i].getAttribute("id"),
546                                 "name": locationNodes[i].getAttribute("name")
547                             };
548                             
549                             for (j = 0; 
550                                 j < locationNodes[i].childNodes.length; 
551                                 j++) {
552                                 if ( locationNodes[i].childNodes[j].nodeType 
553                                     == Node.ELEMENT_NODE ) {
554                                     var nodeName = 
555                                         locationNodes[i].childNodes[j].nodeName;
556                                     var nodeText = '';
557                                     if (locationNodes[i].childNodes[j]
558                                             .firstChild)
559                                         nodeText = 
560                                             locationNodes[i].childNodes[j]
561                                                 .firstChild.nodeValue;
562                                     record["location"][i][nodeName] = nodeText;                            
563                                 }
564                             }
565                         }
566                     }
567                     
568                     callback(record, handle);
569                 }
570                 else
571                     context.throwError('Record failed. Malformed WS resonse.',
572                                         115);
573             }
574         );
575     },
576
577     termlist: function()
578     {
579         if( !this.searchStatusOK && this.useSessions )
580             throw new Error(
581             'Pz2.js: termlist command has to be preceded with a search command.'
582             );
583
584         // if called explicitly takes precedence
585         clearTimeout(this.termTimer);
586         
587         var context = this;
588         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
589         request.get(
590             { 
591                 "command": "termlist", 
592                 "session": this.sessionID, 
593                 "name": this.termKeys 
594             },
595             function(data) {
596                 if ( data.getElementsByTagName("termlist") ) {
597                     var activeClients = 
598                         Number( data.getElementsByTagName("activeclients")[0]
599                                     .childNodes[0].nodeValue );
600                     context.activeClients = activeClients;
601                     var termList = { "activeclients":  activeClients };
602                     var termLists = data.getElementsByTagName("list");
603                     //for each termlist
604                     for (i = 0; i < termLists.length; i++) {
605                         var listName = termLists[i].getAttribute('name');
606                         termList[listName] = new Array();
607                         var terms = termLists[i].getElementsByTagName('term');
608                         //for each term in the list
609                         for (j = 0; j < terms.length; j++) { 
610                             var term = {
611                                 "name": 
612                                     (terms[j].getElementsByTagName("name")[0]
613                                         .childNodes.length 
614                                     ? terms[j].getElementsByTagName("name")[0]
615                                         .childNodes[0].nodeValue
616                                     : 'ERROR'),
617                                 "freq": 
618                                     terms[j]
619                                     .getElementsByTagName("frequency")[0]
620                                     .childNodes[0].nodeValue || 'ERROR'
621                             };
622
623                             var termIdNode = 
624                                 terms[j].getElementsByTagName("id");
625                             if(terms[j].getElementsByTagName("id").length)
626                                 term["id"] = 
627                                     termIdNode[0].childNodes[0].nodeValue;
628                             termList[listName][j] = term;
629                         }
630                     }
631
632                     context.termCounter++;
633                     var delay = context.termTime 
634                         + context.termCounter * context.dumpFactor;
635                     if ( activeClients > 0 )
636                         context.termTimer = 
637                             setTimeout(
638                                 function () {
639                                     context.termlist();
640                                 }, 
641                                 delay
642                             );
643                    
644                    context.termlistCallback(termList);
645                 }
646                 else
647                     context.throwError('Termlist failed. Malformed WS resonse.',
648                                         116);
649             }
650         );
651
652     },
653     bytarget: function()
654     {
655         if( !this.initStatusOK && this.useSessions )
656             throw new Error(
657             'Pz2.js: bytarget command has to be preceded with a search command.'
658             );
659         
660         // no need to continue
661         if( !this.searchStatusOK )
662             return;
663
664         // if called explicitly takes precedence
665         clearTimeout(this.bytargetTimer);
666         
667         var context = this;
668         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
669         request.get(
670             { "command": "bytarget", "session": this.sessionID },
671             function(data) {
672                 if ( data.getElementsByTagName("status")[0]
673                         .childNodes[0].nodeValue == "OK" ) {
674                     var targetNodes = data.getElementsByTagName("target");
675                     var bytarget = new Array();
676                     for ( i = 0; i < targetNodes.length; i++) {
677                         bytarget[i] = new Array();
678                         for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
679                             if ( targetNodes[i].childNodes[j].nodeType 
680                                 == Node.ELEMENT_NODE ) {
681                                 var nodeName = 
682                                     targetNodes[i].childNodes[j].nodeName;
683                                 var nodeText = 
684                                     targetNodes[i].childNodes[j]
685                                         .firstChild.nodeValue;
686                                 bytarget[i][nodeName] = nodeText;
687                             }
688                         }
689                     }
690                     
691                     context.bytargetCounter++;
692                     var delay = context.bytargetTime 
693                         + context.bytargetCounter * context.dumpFactor;
694                     if ( context.activeClients > 0 )
695                         context.bytargetTimer = 
696                             setTimeout(
697                                 function () {
698                                     context.bytarget();
699                                 }, 
700                                 delay
701                             );
702
703                     context.bytargetCallback(bytarget);
704                 }
705                 else
706                     context.throwError('Bytarget failed. Malformed WS resonse.',
707                                         117);
708             }
709         );
710     },
711     
712     // just for testing, probably shouldn't be here
713     showNext: function(page)
714     {
715         var step = page || 1;
716         this.show( ( step * this.currentNum ) + this.currentStart );     
717     },
718
719     showPrev: function(page)
720     {
721         if (this.currentStart == 0 )
722             return false;
723         var step = page || 1;
724         var newStart = this.currentStart - (step * this.currentNum );
725         this.show( newStart > 0 ? newStart : 0 );
726     },
727
728     showPage: function(pageNum)
729     {
730         //var page = pageNum || 1;
731         this.show(pageNum * this.currentNum);
732     }
733 };
734
735 /*
736 ********************************************************************************
737 ** AJAX HELPER CLASS ***********************************************************
738 ********************************************************************************
739 */
740 var pzHttpRequest = function ( url, errorHandler ) {
741         this.request = null;
742         this.url = url;
743         this.errorHandler = errorHandler || null;
744         this.async = true;
745         
746         if ( window.XMLHttpRequest ) {
747             this.request = new XMLHttpRequest();
748         } else if ( window.ActiveXObject ) {
749             try {
750                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
751             } catch (err) {
752                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
753             }
754         }
755 };
756
757 pzHttpRequest.prototype = 
758 {
759     get: function ( params, callback ) 
760     {
761         this._send( 'GET', params, '', callback );
762     },
763
764     post: function ( params, data, callback )
765     {
766         this._send( 'POST', params, data, callback );
767     },
768
769     load: function ()
770     {
771         this.async = false;
772         this.request.open( 'GET', this.url, this.async );
773         this.request.send('');
774         if ( this.request.status == 200 )
775             return this.request.responseXML;
776     },
777
778     _send: function ( type, params, data, callback )
779     {
780         this.callback = callback;
781         var context = this;
782         this.async = true;
783         this.request.open( type, this._urlAppendParams(params), this.async );
784         this.request.onreadystatechange = function () {
785             context._handleResponse();
786         }
787         this.request.send(data);
788     },
789
790     _urlAppendParams: function (params)
791     {
792         var getUrl = this.url;
793
794         var sep = '?';
795         var el = params;
796         for (var key in el) {
797             if (el[key] != null) {
798                 getUrl += sep + key + '=' + encodeURIComponent(el[key]);
799                 sep = '&';
800             }
801         }
802         return getUrl;
803     },
804
805     _handleResponse: function ()
806     {
807         if ( this.request.readyState == 4 ) { 
808             // pick up pazpr2 errors first
809             if ( this.request.responseXML 
810                 && this.request.responseXML.documentElement.nodeName == 'error'
811                 && this.request.responseXML.getElementsByTagName("error")
812                     .length ) {
813                 var errAddInfo = '';
814                 if ( this.request.responseXML.getElementsByTagName("error")[0]
815                         .childNodes.length )
816                     errAddInfo = ': ' + 
817                         this.request.responseXML
818                             .getElementsByTagName("error")[0]
819                             .childNodes[0].nodeValue;
820                 var errMsg = 
821                     this.request.responseXML.getElementsByTagName("error")[0]
822                         .getAttribute("msg");
823                 var errCode = 
824                     this.request.responseXML.getElementsByTagName("error")[0]
825                         .getAttribute("code");
826             
827                 var err = new Error(errMsg + errAddInfo);
828                 err.code = errCode;
829             
830                 if (this.errorHandler) {
831                     this.errorHandler(err);
832                 }
833                 else {
834                     throw err;
835                 }
836             } else if ( this.request.status == 200 ) {
837                 this.callback( this.request.responseXML );
838             } else {
839                 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: " 
840                             + this.request.status + " Info: " 
841                             + this.request.statusText );
842                 err.code = 'HTTP';
843                 
844                 if (this.errorHandler) {
845                     this.errorHandler(err);
846                 }
847                 else {
848                     throw err;
849                 }
850             }
851         }
852     }
853 };
854
855 /*
856 ********************************************************************************
857 ** XML HELPER FUNCTIONS ********************************************************
858 ********************************************************************************
859 */
860
861 // DOMDocument
862
863 if ( window.ActiveXObject) {
864     var DOMDoc = document;
865 } else {
866     var DOMDoc = Document.prototype;
867 }
868
869 DOMDoc.newXmlDoc = function ( root )
870 {
871     var doc;
872
873     if (document.implementation && document.implementation.createDocument) {
874         doc = document.implementation.createDocument('', root, null);
875     } else if ( window.ActiveXObject ) {
876         doc = new ActiveXObject("MSXML2.DOMDocument");
877         doc.loadXML('<' + root + '/>');
878     } else {
879         throw new Error ('No XML support in this browser');
880     }
881
882     return doc;
883 }
884
885    
886 DOMDoc.parseXmlFromString = function ( xmlString ) 
887 {
888     var doc;
889
890     if ( window.DOMParser ) {
891         var parser = new DOMParser();
892         doc = parser.parseFromString( xmlString, "text/xml");
893     } else if ( window.ActiveXObject ) {
894         doc = new ActiveXObject("MSXML2.DOMDocument");
895         doc.loadXML( xmlString );
896     } else {
897         throw new Error ("No XML parsing support in this browser.");
898     }
899
900     return doc;
901 }
902
903 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
904 {
905     if ( window.XSLTProcessor ) {
906         var proc = new XSLTProcessor();
907         proc.importStylesheet( xslDoc );
908         return proc.transformToDocument(xmlDoc);
909     } else if ( window.ActiveXObject ) {
910         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
911     } else {
912         alert( 'Unable to perform XSLT transformation in this browser' );
913     }
914 }
915  
916 // DOMElement
917
918 Element_removeFromDoc = function (DOM_Element)
919 {
920     DOM_Element.parentNode.removeChild(DOM_Element);
921 }
922
923 Element_emptyChildren = function (DOM_Element)
924 {
925     while( DOM_Element.firstChild ) {
926         DOM_Element.removeChild( DOM_Element.firstChild )
927     }
928 }
929
930 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
931 {
932     if ( window.XSLTProcessor ) {
933         var proc = new XSLTProcessor();
934         proc.importStylesheet( xslDoc );
935         var docFrag = false;
936         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
937         DOM_Element.appendChild(docFrag);
938     } else if ( window.ActiveXObject ) {
939         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
940     } else {
941         alert( 'Unable to perform XSLT transformation in this browser' );
942     }
943 }
944  
945 Element_appendTextNode = function (DOM_Element, tagName, textContent )
946 {
947     var node = DOM_Element.ownerDocument.createElement(tagName);
948     var text = DOM_Element.ownerDocument.createTextNode(textContent);
949
950     DOM_Element.appendChild(node);
951     node.appendChild(text);
952
953     return node;
954 }
955
956 Element_setTextContent = function ( DOM_Element, textContent )
957 {
958     if (typeof DOM_Element.textContent !== "undefined") {
959         DOM_Element.textContent = textContent;
960     } else if (typeof DOM_Element.innerText !== "undefined" ) {
961         DOM_Element.innerText = textContent;
962     } else {
963         throw new Error("Cannot set text content of the node, no such method.");
964     }
965 }
966
967 Element_getTextContent = function (DOM_Element)
968 {
969     if ( typeof DOM_Element.textContent != 'undefined' ) {
970         return DOM_Element.textContent;
971     } else if (typeof DOM_Element.text != 'undefined') {
972         return DOM_Element.text;
973     } else {
974         throw new Error("Cannot get text content of the node, no such method.");
975     }
976 }
977
978 /* do not remove trailing bracket */
979 }