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