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