Reset ping timer when reset command is called
[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                     }
664                     
665                     context.bytargetCounter++;
666                     var delay = context.bytargetTime 
667                         + context.bytargetCounter * context.dumpFactor;
668                     if ( context.activeClients > 0 )
669                         context.bytargetTimer = 
670                             setTimeout(
671                                 function () {
672                                     context.bytarget();
673                                 }, 
674                                 delay
675                             );
676
677                     context.bytargetCallback(bytarget);
678                 }
679                 else
680                     context.throwError('Bytarget failed. Malformed WS resonse.',
681                                         117);
682             }
683         );
684     },
685     
686     // just for testing, probably shouldn't be here
687     showNext: function(page)
688     {
689         var step = page || 1;
690         this.show( ( step * this.currentNum ) + this.currentStart );     
691     },
692
693     showPrev: function(page)
694     {
695         if (this.currentStart == 0 )
696             return false;
697         var step = page || 1;
698         var newStart = this.currentStart - (step * this.currentNum );
699         this.show( newStart > 0 ? newStart : 0 );
700     },
701
702     showPage: function(pageNum)
703     {
704         //var page = pageNum || 1;
705         this.show(pageNum * this.currentNum);
706     }
707 };
708
709 /*
710 ********************************************************************************
711 ** AJAX HELPER CLASS ***********************************************************
712 ********************************************************************************
713 */
714 var pzHttpRequest = function ( url, errorHandler ) {
715         this.maxUrlLength = 2048;
716         this.request = null;
717         this.url = url;
718         this.errorHandler = errorHandler || null;
719         this.async = true;
720         this.requestHeaders = {};
721         
722         if ( window.XMLHttpRequest ) {
723             this.request = new XMLHttpRequest();
724         } else if ( window.ActiveXObject ) {
725             try {
726                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
727             } catch (err) {
728                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
729             }
730         }
731 };
732
733
734 pzHttpRequest.prototype = 
735 {
736     safeGet: function ( params, callback )
737     {
738         var encodedParams =  this.encodeParams(params);
739         var url = this._urlAppendParams(encodedParams);
740         if (url.length >= this.maxUrlLength) {
741             this.requestHeaders["Content-Type"]
742                 = "application/x-www-form-urlencoded";
743             this._send( 'POST', this.url, encodedParams, callback );
744         } else {
745             this._send( 'GET', url, '', callback );
746         }
747     },
748
749     get: function ( params, callback ) 
750     {
751         this._send( 'GET', this._urlAppendParams(this.encodeParams(params)), 
752             '', callback );
753     },
754
755     post: function ( params, data, callback )
756     {
757         this._send( 'POST', this._urlAppendParams(this.encodeParams(params)), 
758             data, callback );
759     },
760
761     load: function ()
762     {
763         this.async = false;
764         this.request.open( 'GET', this.url, this.async );
765         this.request.send('');
766         if ( this.request.status == 200 )
767             return this.request.responseXML;
768     },
769
770     encodeParams: function (params)
771     {
772         var sep = "";
773         var encoded = "";
774         for (var key in params) {
775             if (params[key] != null) {
776                 encoded += sep + key + '=' + encodeURIComponent(params[key]);
777                 sep = '&';
778             }
779         }
780         return encoded;
781     },
782
783     _send: function ( type, url, data, callback)
784     {
785         var context = this;
786         this.callback = callback;
787         this.async = true;
788         this.request.open( type, url, this.async );
789         for (var key in this.requestHeaders)
790             this.request.setRequestHeader(key, this.requestHeaders[key]);
791         this.request.onreadystatechange = function () {
792             context._handleResponse(url); /// url used ONLY for error reporting
793         }
794         this.request.send(data);
795     },
796
797     _urlAppendParams: function (encodedParams)
798     {
799         if (encodedParams)
800             return this.url + "?" + encodedParams;
801         else
802             return this.url;
803     },
804
805     _handleResponse: function (savedUrlForErrorReporting)
806     {
807         if ( this.request.readyState == 4 ) { 
808             // pick up appplication errors first
809             var errNode = null;
810             if (this.request.responseXML &&
811                 (errNode = this.request.responseXML.documentElement)
812                 && errNode.nodeName == 'error') {
813                 var errMsg = errNode.getAttribute("msg");
814                 var errCode = errNode.getAttribute("code");
815                 var errAddInfo = '';
816                 if (errNode.childNodes.length)
817                     errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
818                            
819                 var err = new Error(errMsg + errAddInfo);
820                 err.code = errCode;
821             
822                 if (this.errorHandler) {
823                     this.errorHandler(err);
824                 }
825                 else {
826                     throw err;
827                 }
828             } else if (this.request.status == 200 && 
829                        this.request.responseXML == null) {
830               if (this.request.responseText != null) {
831                 //assume JSON
832                 
833                 var json = null; 
834                 var text = this.request.responseText;
835                 if (typeof window.JSON == "undefined") 
836                     json = eval("(" + text + ")");
837                 else { 
838                     try {
839                         json = JSON.parse(text);
840                     }
841                     catch (e) {
842                         // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
843                         /* DEBUG only works in mk2-mobile
844                         if (document.getElementById("log")) 
845                             document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
846                         */
847                         try {
848                             json = eval("(" + text + ")");
849                         }
850                         catch (e) {
851                             /* DEBUG only works in mk2-mobile
852                             if (document.getElementById("log")) 
853                                 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
854                             */
855                         }
856                     }
857                 } 
858                 this.callback(json, "json");
859               } else {
860                 var err = new Error("XML response is empty but no error " +
861                                     "for " + savedUrlForErrorReporting);
862                 err.code = -1;
863                 if (this.errorHandler) {
864                     this.errorHandler(err);
865                 } else {
866                     throw err;
867                 }
868               }
869             } else if (this.request.status == 200) {
870                 this.callback(this.request.responseXML);
871             } else {
872                 var err = new Error("HTTP response not OK: " 
873                             + this.request.status + " - " 
874                             + this.request.statusText );
875                 err.code = '00' + this.request.status;        
876                 if (this.errorHandler) {
877                     this.errorHandler(err);
878                 }
879                 else {
880                     throw err;
881                 }
882             }
883         }
884     }
885 };
886
887 /*
888 ********************************************************************************
889 ** XML HELPER FUNCTIONS ********************************************************
890 ********************************************************************************
891 */
892
893 // DOMDocument
894
895 if ( window.ActiveXObject) {
896     var DOMDoc = document;
897 } else {
898     var DOMDoc = Document.prototype;
899 }
900
901 DOMDoc.newXmlDoc = function ( root )
902 {
903     var doc;
904
905     if (document.implementation && document.implementation.createDocument) {
906         doc = document.implementation.createDocument('', root, null);
907     } else if ( window.ActiveXObject ) {
908         doc = new ActiveXObject("MSXML2.DOMDocument");
909         doc.loadXML('<' + root + '/>');
910     } else {
911         throw new Error ('No XML support in this browser');
912     }
913
914     return doc;
915 }
916
917    
918 DOMDoc.parseXmlFromString = function ( xmlString ) 
919 {
920     var doc;
921
922     if ( window.DOMParser ) {
923         var parser = new DOMParser();
924         doc = parser.parseFromString( xmlString, "text/xml");
925     } else if ( window.ActiveXObject ) {
926         doc = new ActiveXObject("MSXML2.DOMDocument");
927         doc.loadXML( xmlString );
928     } else {
929         throw new Error ("No XML parsing support in this browser.");
930     }
931
932     return doc;
933 }
934
935 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
936 {
937     if ( window.XSLTProcessor ) {
938         var proc = new XSLTProcessor();
939         proc.importStylesheet( xslDoc );
940         return proc.transformToDocument(xmlDoc);
941     } else if ( window.ActiveXObject ) {
942         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
943     } else {
944         alert( 'Unable to perform XSLT transformation in this browser' );
945     }
946 }
947  
948 // DOMElement
949
950 Element_removeFromDoc = function (DOM_Element)
951 {
952     DOM_Element.parentNode.removeChild(DOM_Element);
953 }
954
955 Element_emptyChildren = function (DOM_Element)
956 {
957     while( DOM_Element.firstChild ) {
958         DOM_Element.removeChild( DOM_Element.firstChild )
959     }
960 }
961
962 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
963 {
964     if ( window.XSLTProcessor ) {
965         var proc = new XSLTProcessor();
966         proc.importStylesheet( xslDoc );
967         var docFrag = false;
968         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
969         DOM_Element.appendChild(docFrag);
970     } else if ( window.ActiveXObject ) {
971         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
972     } else {
973         alert( 'Unable to perform XSLT transformation in this browser' );
974     }
975 }
976  
977 Element_appendTextNode = function (DOM_Element, tagName, textContent )
978 {
979     var node = DOM_Element.ownerDocument.createElement(tagName);
980     var text = DOM_Element.ownerDocument.createTextNode(textContent);
981
982     DOM_Element.appendChild(node);
983     node.appendChild(text);
984
985     return node;
986 }
987
988 Element_setTextContent = function ( DOM_Element, textContent )
989 {
990     if (typeof DOM_Element.textContent !== "undefined") {
991         DOM_Element.textContent = textContent;
992     } else if (typeof DOM_Element.innerText !== "undefined" ) {
993         DOM_Element.innerText = textContent;
994     } else {
995         throw new Error("Cannot set text content of the node, no such method.");
996     }
997 }
998
999 Element_getTextContent = function (DOM_Element)
1000 {
1001     if ( typeof DOM_Element.textContent != 'undefined' ) {
1002         return DOM_Element.textContent;
1003     } else if (typeof DOM_Element.text != 'undefined') {
1004         return DOM_Element.text;
1005     } else {
1006         throw new Error("Cannot get text content of the node, no such method.");
1007     }
1008 }
1009
1010 Element_parseChildNodes = function (node)
1011 {
1012     var parsed = {};
1013     var hasChildElems = false;
1014
1015     if (node.hasChildNodes()) {
1016         var children = node.childNodes;
1017         for (var i = 0; i < children.length; i++) {
1018             var child = children[i];
1019             if (child.nodeType == Node.ELEMENT_NODE) {
1020                 hasChildElems = true;
1021                 var nodeName = child.nodeName; 
1022                 if (!(nodeName in parsed))
1023                     parsed[nodeName] = [];
1024                 parsed[nodeName].push(Element_parseChildNodes(child));
1025             }
1026         }
1027     }
1028
1029     var attrs = node.attributes;
1030     for (var i = 0; i < attrs.length; i++) {
1031         var attrName = '@' + attrs[i].nodeName;
1032         var attrValue = attrs[i].nodeValue;
1033         parsed[attrName] = attrValue;
1034     }
1035
1036     // if no nested elements, get text content
1037     if (node.hasChildNodes() && !hasChildElems) {
1038         if (node.attributes.length) 
1039             parsed['#text'] = node.firstChild.nodeValue;
1040         else
1041             parsed = node.firstChild.nodeValue;
1042     }
1043     
1044     return parsed;
1045 }
1046
1047 /* do not remove trailing bracket */
1048 }