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