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