e2335da5678ec9fbaaed44617ddb34a56109520b
[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         if (this.version && this.version > 0)
399             requestParameters["version"] = this.version;
400         request.safeGet(
401           requestParameters,
402           function(data, type) {
403             var show = null;
404             var activeClients = 0;
405             if (type === "json") {
406               show = {};
407               activeClients = Number(data.activeclients[0]);
408               show.activeclients = activeClients;
409               show.merged = Number(data.merged[0]);
410               show.total = Number(data.total[0]);
411               show.start = Number(data.start[0]);
412               show.num = Number(data.num[0]);
413               show.hits = data.hit;
414             } else if (data.getElementsByTagName("status")[0]
415                   .childNodes[0].nodeValue == "OK") {
416                 // first parse the status data send along with records
417                 // this is strictly bound to the format
418                 activeClients = 
419                   Number(data.getElementsByTagName("activeclients")[0]
420                       .childNodes[0].nodeValue);
421                 show = {
422                   "activeclients": activeClients,
423                   "merged": 
424                     Number( data.getElementsByTagName("merged")[0]
425                         .childNodes[0].nodeValue ),
426                   "total": 
427                     Number( data.getElementsByTagName("total")[0]
428                         .childNodes[0].nodeValue ),
429                   "start": 
430                     Number( data.getElementsByTagName("start")[0]
431                         .childNodes[0].nodeValue ),
432                   "num": 
433                     Number( data.getElementsByTagName("num")[0]
434                         .childNodes[0].nodeValue ),
435                   "hits": []
436                 };
437                 // parse all the first-level nodes for all <hit> tags
438                 var hits = data.getElementsByTagName("hit");
439                 for (i = 0; i < hits.length; i++)
440                   show.hits[i] = Element_parseChildNodes(hits[i]);
441             } else {
442               context.throwError('Show failed. Malformed WS resonse.',
443                   114);
444             };
445             var approxNode = data.getElementsByTagName("approximation");
446             if (approxNode)
447                 show['approximation'] = 
448                   Number( approxNode[0].childNodes[0].nodeValue);
449               
450
451               data.getElementsByTagName("")
452             context.activeClients = activeClients; 
453             context.showCounter++;
454             var delay = context.showTime;
455             if (context.showCounter > context.showFastCount)
456               delay += context.showCounter * context.dumpFactor;
457             if ( activeClients > 0 )
458               context.showTimer = setTimeout(
459                 function () {
460                   context.show();
461                 }, 
462                 delay);
463             context.showCallback(show);
464           }
465         );
466     },
467     record: function(id, offset, syntax, handler)
468     {
469         // we may call record with no previous search if in proxy mode
470         if(!this.searchStatusOK && this.useSessions)
471            throw new Error(
472             'Pz2.js: record command has to be preceded with a search command.'
473             );
474         
475         if( id !== undefined )
476             this.currRecID = id;
477         
478         var recordParams = { 
479             "command": "record", 
480             "session": this.sessionID,
481             "id": this.currRecID,
482             "windowid" : window.name
483         };
484         
485         this.currRecOffset = null;
486         if (offset != undefined) {
487             recordParams["offset"] = offset;
488             this.currRecOffset = offset;
489         }
490
491         if (syntax != undefined)
492             recordParams['syntax'] = syntax;
493
494         //overwrite default callback id needed
495         var callback = this.recordCallback;
496         var args = undefined;
497         if (handler != undefined) {
498             callback = handler['callback'];
499             args = handler['args'];
500         }
501         
502         var context = this;
503         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
504
505         request.safeGet(
506             recordParams,
507             function(data) {
508                 var recordNode;
509                 var record;                                
510                 //raw record
511                 if (context.currRecOffset !== null) {
512                     record = new Array();
513                     record['xmlDoc'] = data;
514                     record['offset'] = context.currRecOffset;
515                     callback(record, args);
516                 //pz2 record
517                 } else if ( recordNode = 
518                     data.getElementsByTagName("record")[0] ) {
519                     // if stylesheet was fetched do not parse the response
520                     if ( context.xslDoc ) {
521                         record = new Array();
522                         record['xmlDoc'] = data;
523                         record['xslDoc'] = context.xslDoc;
524                         record['recid'] = 
525                             recordNode.getElementsByTagName("recid")[0]
526                                 .firstChild.nodeValue;
527                     //parse record
528                     } else {
529                         record = Element_parseChildNodes(recordNode);
530                     }    
531                     var activeClients = 
532                        Number( data.getElementsByTagName("activeclients")[0]
533                                 .childNodes[0].nodeValue );
534                     context.activeClients = activeClients; 
535                     context.recordCounter++;
536                     var delay = context.recordTime + context.recordCounter * context.dumpFactor;
537                     if ( activeClients > 0 )
538                         context.recordTimer = 
539                            setTimeout ( 
540                                function() {
541                                   context.record(id, offset, syntax, handler);
542                                   },
543                                   delay
544                                );                                    
545                     callback(record, args);
546                 }
547                 else
548                     context.throwError('Record failed. Malformed WS resonse.',
549                                         115);
550             }
551         );
552     },
553
554     termlist: function()
555     {
556         if( !this.searchStatusOK && this.useSessions )
557             throw new Error(
558             'Pz2.js: termlist command has to be preceded with a search command.'
559             );
560
561         // if called explicitly takes precedence
562         clearTimeout(this.termTimer);
563         
564         var context = this;
565         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
566         request.safeGet(
567             { 
568                 "command": "termlist", 
569                 "session": this.sessionID, 
570                 "name": this.termKeys,
571                 "windowid" : window.name, 
572                 "version" : this.version
573         
574             },
575             function(data) {
576                 if ( data.getElementsByTagName("termlist") ) {
577                     var activeClients = 
578                         Number( data.getElementsByTagName("activeclients")[0]
579                                     .childNodes[0].nodeValue );
580                     context.activeClients = activeClients;
581                     var termList = { "activeclients":  activeClients };
582                     var termLists = data.getElementsByTagName("list");
583                     //for each termlist
584                     for (i = 0; i < termLists.length; i++) {
585                         var listName = termLists[i].getAttribute('name');
586                         termList[listName] = new Array();
587                         var terms = termLists[i].getElementsByTagName('term');
588                         //for each term in the list
589                         for (j = 0; j < terms.length; j++) { 
590                             var term = {
591                                 "name": 
592                                     (terms[j].getElementsByTagName("name")[0]
593                                         .childNodes.length 
594                                     ? terms[j].getElementsByTagName("name")[0]
595                                         .childNodes[0].nodeValue
596                                     : 'ERROR'),
597                                 "freq": 
598                                     terms[j]
599                                     .getElementsByTagName("frequency")[0]
600                                     .childNodes[0].nodeValue || 'ERROR'
601                             };
602
603                             // Only for xtargets: id, records, filtered
604                             var termIdNode = 
605                                 terms[j].getElementsByTagName("id");
606                             if(terms[j].getElementsByTagName("id").length)
607                                 term["id"] = 
608                                     termIdNode[0].childNodes[0].nodeValue;
609                             termList[listName][j] = term;
610
611                             var recordsNode  = terms[j].getElementsByTagName("records");
612                             if (recordsNode && recordsNode.length)
613                                 term["records"] = recordsNode[0].childNodes[0].nodeValue;
614                               
615                             var filteredNode  = terms[j].getElementsByTagName("filtered");
616                             if (filteredNode && filteredNode.length)
617                                 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
618                               
619                         }
620                     }
621
622                     context.termCounter++;
623                     var delay = context.termTime 
624                         + context.termCounter * context.dumpFactor;
625                     if ( activeClients > 0 )
626                         context.termTimer = 
627                             setTimeout(
628                                 function () {
629                                     context.termlist();
630                                 }, 
631                                 delay
632                             );
633                    
634                    context.termlistCallback(termList);
635                 }
636                 else
637                     context.throwError('Termlist failed. Malformed WS resonse.',
638                                         116);
639             }
640         );
641
642     },
643     bytarget: function()
644     {
645         if( !this.initStatusOK && this.useSessions )
646             throw new Error(
647             'Pz2.js: bytarget command has to be preceded with a search command.'
648             );
649         
650         // no need to continue
651         if( !this.searchStatusOK )
652             return;
653
654         // if called explicitly takes precedence
655         clearTimeout(this.bytargetTimer);
656         
657         var context = this;
658         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
659         request.safeGet(
660             { 
661                 "command": "bytarget", 
662                 "session": this.sessionID, 
663                 "block": 1,
664                 "windowid" : window.name,
665                 "version" : this.version
666             },
667             function(data) {
668                 if ( data.getElementsByTagName("status")[0]
669                         .childNodes[0].nodeValue == "OK" ) {
670                     var targetNodes = data.getElementsByTagName("target");
671                     var bytarget = new Array();
672                     for ( i = 0; i < targetNodes.length; i++) {
673                         bytarget[i] = new Array();
674                         for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
675                             if ( targetNodes[i].childNodes[j].nodeType 
676                                 == Node.ELEMENT_NODE ) {
677                                 var nodeName = 
678                                     targetNodes[i].childNodes[j].nodeName;
679                                 if (targetNodes[i].childNodes[j].firstChild != null) 
680                                 {
681                                     var nodeText = targetNodes[i].childNodes[j]
682                                         .firstChild.nodeValue;
683                                     bytarget[i][nodeName] = nodeText;
684                                 }
685                                 else { 
686                                     bytarget[i][nodeName] = "";  
687                                 }
688
689
690                             }
691                         }
692                         if (bytarget[i]["state"]=="Client_Disconnected") {
693                           bytarget[i]["hits"] = "Error";
694                         } else if (bytarget[i]["state"]=="Client_Error") {
695                           bytarget[i]["hits"] = "Error";                          
696                         } else if (bytarget[i]["state"]=="Client_Working") {
697                           bytarget[i]["hits"] = "...";
698                         }
699                         if (bytarget[i].diagnostic == "1") {
700                           bytarget[i].diagnostic = "Permanent system error";
701                         } else if (bytarget[i].diagnostic == "2") {
702                           bytarget[i].diagnostic = "Temporary system error";
703                         } 
704                         var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
705                         if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
706                           var suggestions = targetsSuggestions[0];
707                           bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
708                         }
709                     }
710                     
711                     context.bytargetCounter++;
712                     var delay = context.bytargetTime 
713                         + context.bytargetCounter * context.dumpFactor;
714                     if ( context.activeClients > 0 )
715                         context.bytargetTimer = 
716                             setTimeout(
717                                 function () {
718                                     context.bytarget();
719                                 }, 
720                                 delay
721                             );
722
723                     context.bytargetCallback(bytarget);
724                 }
725                 else
726                     context.throwError('Bytarget failed. Malformed WS resonse.',
727                                         117);
728             }
729         );
730     },
731     
732     // just for testing, probably shouldn't be here
733     showNext: function(page)
734     {
735         var step = page || 1;
736         this.show( ( step * this.currentNum ) + this.currentStart );     
737     },
738
739     showPrev: function(page)
740     {
741         if (this.currentStart == 0 )
742             return false;
743         var step = page || 1;
744         var newStart = this.currentStart - (step * this.currentNum );
745         this.show( newStart > 0 ? newStart : 0 );
746     },
747
748     showPage: function(pageNum)
749     {
750         //var page = pageNum || 1;
751         this.show(pageNum * this.currentNum);
752     }
753 };
754
755 /*
756 ********************************************************************************
757 ** AJAX HELPER CLASS ***********************************************************
758 ********************************************************************************
759 */
760 var pzHttpRequest = function ( url, errorHandler ) {
761         this.maxUrlLength = 2048;
762         this.request = null;
763         this.url = url;
764         this.errorHandler = errorHandler || null;
765         this.async = true;
766         this.requestHeaders = {};
767         
768         if ( window.XMLHttpRequest ) {
769             this.request = new XMLHttpRequest();
770         } else if ( window.ActiveXObject ) {
771             try {
772                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
773             } catch (err) {
774                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
775             }
776         }
777 };
778
779
780 pzHttpRequest.prototype = 
781 {
782     safeGet: function ( params, callback )
783     {
784         var encodedParams =  this.encodeParams(params);
785         var url = this._urlAppendParams(encodedParams);
786         if (url.length >= this.maxUrlLength) {
787             this.requestHeaders["Content-Type"]
788                 = "application/x-www-form-urlencoded";
789             this._send( 'POST', this.url, encodedParams, callback );
790         } else {
791             this._send( 'GET', url, '', callback );
792         }
793     },
794
795     get: function ( params, callback ) 
796     {
797         this._send( 'GET', this._urlAppendParams(this.encodeParams(params)), 
798             '', callback );
799     },
800
801     post: function ( params, data, callback )
802     {
803         this._send( 'POST', this._urlAppendParams(this.encodeParams(params)), 
804             data, callback );
805     },
806
807     load: function ()
808     {
809         this.async = false;
810         this.request.open( 'GET', this.url, this.async );
811         this.request.send('');
812         if ( this.request.status == 200 )
813             return this.request.responseXML;
814     },
815
816     encodeParams: function (params)
817     {
818         var sep = "";
819         var encoded = "";
820         for (var key in params) {
821             if (params[key] != null) {
822                 encoded += sep + key + '=' + encodeURIComponent(params[key]);
823                 sep = '&';
824             }
825         }
826         return encoded;
827     },
828
829     _send: function ( type, url, data, callback)
830     {
831         var context = this;
832         this.callback = callback;
833         this.async = true;
834         this.request.open( type, url, this.async );
835         for (var key in this.requestHeaders)
836             this.request.setRequestHeader(key, this.requestHeaders[key]);
837         this.request.onreadystatechange = function () {
838             context._handleResponse(url); /// url used ONLY for error reporting
839         }
840         this.request.send(data);
841     },
842
843     _urlAppendParams: function (encodedParams)
844     {
845         if (encodedParams)
846             return this.url + "?" + encodedParams;
847         else
848             return this.url;
849     },
850
851     _handleResponse: function (savedUrlForErrorReporting)
852     {
853         if ( this.request.readyState == 4 ) { 
854             // pick up appplication errors first
855             var errNode = null;
856             if (this.request.responseXML &&
857                 (errNode = this.request.responseXML.documentElement)
858                 && errNode.nodeName == 'error') {
859                 var errMsg = errNode.getAttribute("msg");
860                 var errCode = errNode.getAttribute("code");
861                 var errAddInfo = '';
862                 if (errNode.childNodes.length)
863                     errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
864                            
865                 var err = new Error(errMsg + errAddInfo);
866                 err.code = errCode;
867             
868                 if (this.errorHandler) {
869                     this.errorHandler(err);
870                 }
871                 else {
872                     throw err;
873                 }
874             } else if (this.request.status == 200 && 
875                        this.request.responseXML == null) {
876               if (this.request.responseText != null) {
877                 //assume JSON
878                 
879                 var json = null; 
880                 var text = this.request.responseText;
881                 if (typeof window.JSON == "undefined") 
882                     json = eval("(" + text + ")");
883                 else { 
884                     try {
885                         json = JSON.parse(text);
886                     }
887                     catch (e) {
888                         // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
889                         /* DEBUG only works in mk2-mobile
890                         if (document.getElementById("log")) 
891                             document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
892                         */
893                         try {
894                             json = eval("(" + text + ")");
895                         }
896                         catch (e) {
897                             /* DEBUG only works in mk2-mobile
898                             if (document.getElementById("log")) 
899                                 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
900                             */
901                         }
902                     }
903                 } 
904                 this.callback(json, "json");
905               } else {
906                 var err = new Error("XML response is empty but no error " +
907                                     "for " + savedUrlForErrorReporting);
908                 err.code = -1;
909                 if (this.errorHandler) {
910                     this.errorHandler(err);
911                 } else {
912                     throw err;
913                 }
914               }
915             } else if (this.request.status == 200) {
916                 this.callback(this.request.responseXML);
917             } else {
918                 var err = new Error("HTTP response not OK: " 
919                             + this.request.status + " - " 
920                             + this.request.statusText );
921                 err.code = '00' + this.request.status;        
922                 if (this.errorHandler) {
923                     this.errorHandler(err);
924                 }
925                 else {
926                     throw err;
927                 }
928             }
929         }
930     }
931 };
932
933 /*
934 ********************************************************************************
935 ** XML HELPER FUNCTIONS ********************************************************
936 ********************************************************************************
937 */
938
939 // DOMDocument
940
941 if ( window.ActiveXObject) {
942     var DOMDoc = document;
943 } else {
944     var DOMDoc = Document.prototype;
945 }
946
947 DOMDoc.newXmlDoc = function ( root )
948 {
949     var doc;
950
951     if (document.implementation && document.implementation.createDocument) {
952         doc = document.implementation.createDocument('', root, null);
953     } else if ( window.ActiveXObject ) {
954         doc = new ActiveXObject("MSXML2.DOMDocument");
955         doc.loadXML('<' + root + '/>');
956     } else {
957         throw new Error ('No XML support in this browser');
958     }
959
960     return doc;
961 }
962
963    
964 DOMDoc.parseXmlFromString = function ( xmlString ) 
965 {
966     var doc;
967
968     if ( window.DOMParser ) {
969         var parser = new DOMParser();
970         doc = parser.parseFromString( xmlString, "text/xml");
971     } else if ( window.ActiveXObject ) {
972         doc = new ActiveXObject("MSXML2.DOMDocument");
973         doc.loadXML( xmlString );
974     } else {
975         throw new Error ("No XML parsing support in this browser.");
976     }
977
978     return doc;
979 }
980
981 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
982 {
983     if ( window.XSLTProcessor ) {
984         var proc = new XSLTProcessor();
985         proc.importStylesheet( xslDoc );
986         return proc.transformToDocument(xmlDoc);
987     } else if ( window.ActiveXObject ) {
988         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
989     } else {
990         alert( 'Unable to perform XSLT transformation in this browser' );
991     }
992 }
993  
994 // DOMElement
995
996 Element_removeFromDoc = function (DOM_Element)
997 {
998     DOM_Element.parentNode.removeChild(DOM_Element);
999 }
1000
1001 Element_emptyChildren = function (DOM_Element)
1002 {
1003     while( DOM_Element.firstChild ) {
1004         DOM_Element.removeChild( DOM_Element.firstChild )
1005     }
1006 }
1007
1008 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1009 {
1010     if ( window.XSLTProcessor ) {
1011         var proc = new XSLTProcessor();
1012         proc.importStylesheet( xslDoc );
1013         var docFrag = false;
1014         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1015         DOM_Element.appendChild(docFrag);
1016     } else if ( window.ActiveXObject ) {
1017         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1018     } else {
1019         alert( 'Unable to perform XSLT transformation in this browser' );
1020     }
1021 }
1022  
1023 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1024 {
1025     var node = DOM_Element.ownerDocument.createElement(tagName);
1026     var text = DOM_Element.ownerDocument.createTextNode(textContent);
1027
1028     DOM_Element.appendChild(node);
1029     node.appendChild(text);
1030
1031     return node;
1032 }
1033
1034 Element_setTextContent = function ( DOM_Element, textContent )
1035 {
1036     if (typeof DOM_Element.textContent !== "undefined") {
1037         DOM_Element.textContent = textContent;
1038     } else if (typeof DOM_Element.innerText !== "undefined" ) {
1039         DOM_Element.innerText = textContent;
1040     } else {
1041         throw new Error("Cannot set text content of the node, no such method.");
1042     }
1043 }
1044
1045 Element_getTextContent = function (DOM_Element)
1046 {
1047     if ( typeof DOM_Element.textContent != 'undefined' ) {
1048         return DOM_Element.textContent;
1049     } else if (typeof DOM_Element.text != 'undefined') {
1050         return DOM_Element.text;
1051     } else {
1052         throw new Error("Cannot get text content of the node, no such method.");
1053     }
1054 }
1055
1056 Element_parseChildNodes = function (node)
1057 {
1058     var parsed = {};
1059     var hasChildElems = false;
1060
1061     if (node.hasChildNodes()) {
1062         var children = node.childNodes;
1063         for (var i = 0; i < children.length; i++) {
1064             var child = children[i];
1065             if (child.nodeType == Node.ELEMENT_NODE) {
1066                 hasChildElems = true;
1067                 var nodeName = child.nodeName; 
1068                 if (!(nodeName in parsed))
1069                     parsed[nodeName] = [];
1070                 parsed[nodeName].push(Element_parseChildNodes(child));
1071             }
1072         }
1073     }
1074
1075     var attrs = node.attributes;
1076     for (var i = 0; i < attrs.length; i++) {
1077         var attrName = '@' + attrs[i].nodeName;
1078         var attrValue = attrs[i].nodeValue;
1079         parsed[attrName] = attrValue;
1080     }
1081
1082     // if no nested elements, get text content
1083     if (node.hasChildNodes() && !hasChildElems) {
1084         if (node.attributes.length) 
1085             parsed['#text'] = node.firstChild.nodeValue;
1086         else
1087             parsed = node.firstChild.nodeValue;
1088     }
1089     
1090     return parsed;
1091 }
1092
1093 /* do not remove trailing bracket */
1094 }