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