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