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