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