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