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