3 ** pz2.js - pazpar2's javascript client library.
6 //since explorer is flawed
8 window.Node = new Object();
10 Node.ATTRIBUTE_NODE = 2;
12 Node.CDATA_SECTION_NODE = 4;
13 Node.ENTITY_REFERENCE_NODE = 5;
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;
23 // prevent execution of more than once
24 if(typeof window.pz2 == "undefined") {
25 window.undefined = window.undefined;
27 var pz2 = function ( paramArray )
30 // at least one callback required
32 throw new Error("Pz2.js: Array with parameters has to be supplied.");
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;
40 this.pz2String = "/pazpar2/search.pz2";
41 this.useSessions = true;
43 this.stylesheet = paramArray.detailstylesheet || null;
44 //load stylesheet if required in async mode
45 if( this.stylesheet ) {
47 var request = new pzHttpRequest( this.stylesheet );
48 request.get( {}, function ( doc ) { context.xslDoc = doc; } );
51 this.errorHandler = paramArray.errorhandler || null;
52 this.showResponseType = paramArray.showResponseType || "xml";
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;
64 this.termKeys = paramArray.termlist || "subject";
66 // some configurational stuff
67 this.keepAlive = 50000;
69 if ( paramArray.keepAlive < this.keepAlive )
70 this.keepAlive = paramArray.keepAlive;
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;
81 this.currentSort = "relevance";
84 this.currentStart = 0;
85 // currentNum can be overwritten in show
88 // last full record retrieved
89 this.currRecID = null;
92 this.currQuery = null;
94 //current raw record offset
95 this.currRecOffset = null;
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;
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;
119 // active clients, updated by stat and show
120 // might be an issue since bytarget will poll accordingly
121 this.activeClients = 1;
123 // if in proxy mode no need to init
124 if (paramArray.usesessions != undefined) {
125 this.useSessions = paramArray.usesessions;
126 this.initStatusOK = true;
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);
133 this.version = paramArray.version || null;
138 //error handler for async error throws
139 throwError: function (errMsg, errCode)
141 var err = new Error(errMsg);
142 if (errCode) err.code = errCode;
144 if (this.errorHandler) {
145 this.errorHandler(err);
152 // stop activity by clearing tiemouts
155 clearTimeout(this.statTimer);
156 clearTimeout(this.showTimer);
157 clearTimeout(this.termTimer);
158 clearTimeout(this.bytargetTimer);
161 // reset status variables
164 if ( this.useSessions ) {
165 this.sessionID = null;
166 this.initStatusOK = false;
167 this.pingStatusOK = false;
168 clearTimeout(this.pingTimer);
170 this.searchStatusOK = false;
173 if ( this.resetCallback )
174 this.resetCallback(this.windowid);
177 init: function (sessionId, serviceId)
181 // session id as a param
182 if (sessionId && this.useSessions ) {
183 this.initStatusOK = true;
184 this.sessionID = sessionId;
186 // old school direct pazpar2 init
187 } else if (this.useSessions) {
189 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
190 var opts = {'command' : 'init'};
191 if (serviceId) opts.service = serviceId;
195 if ( data.getElementsByTagName("status")[0]
196 .childNodes[0].nodeValue == "OK" ) {
197 if ( data.getElementsByTagName("protocol")[0]
198 .childNodes[0].nodeValue
199 != context.suppProtoVer )
201 "Server's protocol not supported by the client"
203 context.initStatusOK = true;
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;
217 if ( context.initCallback )
218 context.initCallback(context.windowid);
221 context.throwError('Init failed. Malformed WS resonse.',
225 // when through proxy no need to init
227 this.initStatusOK = true;
230 // no need to ping explicitly
233 // pinging only makes sense when using pazpar2 directly
234 if( !this.initStatusOK || !this.useSessions )
236 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
240 clearTimeout(context.pingTimer);
242 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
244 { "command": "ping", "session": this.sessionID, "windowid" : context.windowid },
246 if ( data.getElementsByTagName("status")[0]
247 .childNodes[0].nodeValue == "OK" ) {
248 context.pingStatusOK = true;
258 context.throwError('Ping failed. Malformed WS resonse.',
263 search: function (query, num, sort, filter, showfrom, addParamsArr)
265 clearTimeout(this.statTimer);
266 clearTimeout(this.showTimer);
267 clearTimeout(this.termTimer);
268 clearTimeout(this.bytargetTimer);
270 this.showCounter = 0;
271 this.termCounter = 0;
272 this.bytargetCounter = 0;
273 this.statCounter = 0;
274 this.activeClients = 1;
277 if( !this.initStatusOK )
278 throw new Error('Pz2.js: session not initialized.');
280 if( query !== undefined )
281 this.currQuery = query;
283 throw new Error("Pz2.js: no query supplied to the search command.");
285 if ( showfrom !== undefined )
286 var start = showfrom;
292 "query": this.currQuery,
293 "session": this.sessionID,
294 "windowid" : this.windowid
297 if( sort !== undefined ) {
298 this.currentSort = sort;
299 searchParams["sort"] = sort;
301 if (filter !== undefined) searchParams["filter"] = filter;
302 if (this.mergekey) searchParams["mergekey"] = this.mergekey;
303 if (this.rank) searchParams["rank"] = this.rank;
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];
314 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
318 if ( data.getElementsByTagName("status")[0]
319 .childNodes[0].nodeValue == "OK" ) {
320 context.searchStatusOK = true;
322 context.show(start, num, sort);
323 if (context.statCallback)
325 if (context.termlistCallback)
327 if (context.bytargetCallback)
331 context.throwError('Search failed. Malformed WS resonse.',
338 if( !this.initStatusOK )
339 throw new Error('Pz2.js: session not initialized.');
341 // if called explicitly takes precedence
342 clearTimeout(this.statTimer);
345 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
347 { "command": "stat", "session": this.sessionID, "windowid" : context.windowid },
349 if ( data.getElementsByTagName("stat") ) {
351 Number( data.getElementsByTagName("activeclients")[0]
352 .childNodes[0].nodeValue );
353 context.activeClients = activeClients;
355 var stat = Element_parseChildNodes(data.documentElement);
357 context.statCounter++;
358 var delay = context.statTime
359 + context.statCounter * context.dumpFactor;
361 if ( activeClients > 0 )
369 context.statCallback(stat, context.windowid);
372 context.throwError('Stat failed. Malformed WS resonse.',
377 show: function(start, num, sort, query_state)
379 if( !this.searchStatusOK && this.useSessions )
381 'Pz2.js: show command has to be preceded with a search command.'
384 // if called explicitly takes precedence
385 clearTimeout(this.showTimer);
387 if( sort !== undefined )
388 this.currentSort = sort;
389 if( start !== undefined )
390 this.currentStart = Number( start );
391 if( num !== undefined )
392 this.currentNum = Number( num );
395 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
396 var requestParameters =
399 "session": this.sessionID,
400 "start": this.currentStart,
401 "num": this.currentNum,
402 "sort": this.currentSort,
404 "type": this.showResponseType,
405 "windowid" : this.windowid
408 requestParameters["query-state"] = query_state;
409 if (this.version && this.version > 0)
410 requestParameters["version"] = this.version;
413 function(data, type) {
415 var activeClients = 0;
416 if (type === "json") {
418 activeClients = Number(data.activeclients[0]);
419 show.activeclients = activeClients;
420 show.merged = Number(data.merged[0]);
421 show.total = Number(data.total[0]);
422 show.start = Number(data.start[0]);
423 show.num = Number(data.num[0]);
424 show.hits = data.hit;
425 } else if (data.getElementsByTagName("status")[0]
426 .childNodes[0].nodeValue == "OK") {
427 // first parse the status data send along with records
428 // this is strictly bound to the format
430 Number(data.getElementsByTagName("activeclients")[0]
431 .childNodes[0].nodeValue);
433 "activeclients": activeClients,
435 Number( data.getElementsByTagName("merged")[0]
436 .childNodes[0].nodeValue ),
438 Number( data.getElementsByTagName("total")[0]
439 .childNodes[0].nodeValue ),
441 Number( data.getElementsByTagName("start")[0]
442 .childNodes[0].nodeValue ),
444 Number( data.getElementsByTagName("num")[0]
445 .childNodes[0].nodeValue ),
448 // parse all the first-level nodes for all <hit> tags
449 var hits = data.getElementsByTagName("hit");
450 for (i = 0; i < hits.length; i++)
451 show.hits[i] = Element_parseChildNodes(hits[i]);
453 context.throwError('Show failed. Malformed WS resonse.',
457 var approxNode = data.getElementsByTagName("approximation");
458 if (approxNode && approxNode[0] && approxNode[0].childNodes[0] && approxNode[0].childNodes[0].nodeValue)
459 show['approximation'] =
460 Number( approxNode[0].childNodes[0].nodeValue);
463 data.getElementsByTagName("")
464 context.activeClients = activeClients;
465 context.showCounter++;
466 var delay = context.showTime;
467 if (context.showCounter > context.showFastCount)
468 delay += context.showCounter * context.dumpFactor;
469 if ( activeClients > 0 )
470 context.showTimer = setTimeout(
475 context.showCallback(show, context.windowid);
479 record: function(id, offset, syntax, handler)
481 // we may call record with no previous search if in proxy mode
482 if(!this.searchStatusOK && this.useSessions)
484 'Pz2.js: record command has to be preceded with a search command.'
487 if( id !== undefined )
492 "session": this.sessionID,
493 "id": this.currRecID,
494 "windowid" : this.windowid
497 this.currRecOffset = null;
498 if (offset != undefined) {
499 recordParams["offset"] = offset;
500 this.currRecOffset = offset;
503 if (syntax != undefined)
504 recordParams['syntax'] = syntax;
506 //overwrite default callback id needed
507 var callback = this.recordCallback;
508 var args = undefined;
509 if (handler != undefined) {
510 callback = handler['callback'];
511 args = handler['args'];
515 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
523 if (context.currRecOffset !== null) {
524 record = new Array();
525 record['xmlDoc'] = data;
526 record['offset'] = context.currRecOffset;
527 callback(record, args, context.windowid);
529 } else if ( recordNode =
530 data.getElementsByTagName("record")[0] ) {
531 // if stylesheet was fetched do not parse the response
532 if ( context.xslDoc ) {
533 record = new Array();
534 record['xmlDoc'] = data;
535 record['xslDoc'] = context.xslDoc;
537 recordNode.getElementsByTagName("recid")[0]
538 .firstChild.nodeValue;
541 record = Element_parseChildNodes(recordNode);
544 Number( data.getElementsByTagName("activeclients")[0]
545 .childNodes[0].nodeValue );
546 context.activeClients = activeClients;
547 context.recordCounter++;
548 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
549 if ( activeClients > 0 )
550 context.recordTimer =
553 context.record(id, offset, syntax, handler);
557 callback(record, args, context.windowid);
560 context.throwError('Record failed. Malformed WS resonse.',
568 if( !this.searchStatusOK && this.useSessions )
570 'Pz2.js: termlist command has to be preceded with a search command.'
573 // if called explicitly takes precedence
574 clearTimeout(this.termTimer);
577 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
580 "command": "termlist",
581 "session": this.sessionID,
582 "name": this.termKeys,
583 "windowid" : this.windowid,
584 "version" : this.version
588 if ( data.getElementsByTagName("termlist") ) {
590 Number( data.getElementsByTagName("activeclients")[0]
591 .childNodes[0].nodeValue );
592 context.activeClients = activeClients;
593 var termList = { "activeclients": activeClients };
594 var termLists = data.getElementsByTagName("list");
596 for (i = 0; i < termLists.length; i++) {
597 var listName = termLists[i].getAttribute('name');
598 termList[listName] = new Array();
599 var terms = termLists[i].getElementsByTagName('term');
600 //for each term in the list
601 for (j = 0; j < terms.length; j++) {
604 (terms[j].getElementsByTagName("name")[0]
606 ? terms[j].getElementsByTagName("name")[0]
607 .childNodes[0].nodeValue
611 .getElementsByTagName("frequency")[0]
612 .childNodes[0].nodeValue || 'ERROR'
615 // Only for xtargets: id, records, filtered
617 terms[j].getElementsByTagName("id");
618 if(terms[j].getElementsByTagName("id").length)
620 termIdNode[0].childNodes[0].nodeValue;
621 termList[listName][j] = term;
623 var recordsNode = terms[j].getElementsByTagName("records");
624 if (recordsNode && recordsNode.length)
625 term["records"] = recordsNode[0].childNodes[0].nodeValue;
627 var filteredNode = terms[j].getElementsByTagName("filtered");
628 if (filteredNode && filteredNode.length)
629 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
634 context.termCounter++;
635 var delay = context.termTime
636 + context.termCounter * context.dumpFactor;
637 if ( activeClients > 0 )
646 context.termlistCallback(termList, context.windowid);
649 context.throwError('Termlist failed. Malformed WS resonse.',
657 if( !this.initStatusOK && this.useSessions )
659 'Pz2.js: bytarget command has to be preceded with a search command.'
662 // no need to continue
663 if( !this.searchStatusOK )
666 // if called explicitly takes precedence
667 clearTimeout(this.bytargetTimer);
670 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
673 "command": "bytarget",
674 "session": this.sessionID,
676 "windowid" : this.windowid,
677 "version" : this.version
680 if ( data.getElementsByTagName("status")[0]
681 .childNodes[0].nodeValue == "OK" ) {
682 var targetNodes = data.getElementsByTagName("target");
683 var bytarget = new Array();
684 for ( i = 0; i < targetNodes.length; i++) {
685 bytarget[i] = new Array();
686 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
687 if ( targetNodes[i].childNodes[j].nodeType
688 == Node.ELEMENT_NODE ) {
690 targetNodes[i].childNodes[j].nodeName;
691 if (targetNodes[i].childNodes[j].firstChild != null)
693 var nodeText = targetNodes[i].childNodes[j]
694 .firstChild.nodeValue;
695 bytarget[i][nodeName] = nodeText;
698 bytarget[i][nodeName] = "";
704 if (bytarget[i]["state"]=="Client_Disconnected") {
705 bytarget[i]["hits"] = "Error";
706 } else if (bytarget[i]["state"]=="Client_Error") {
707 bytarget[i]["hits"] = "Error";
708 } else if (bytarget[i]["state"]=="Client_Working") {
709 bytarget[i]["hits"] = "...";
711 if (bytarget[i].diagnostic == "1") {
712 bytarget[i].diagnostic = "Permanent system error";
713 } else if (bytarget[i].diagnostic == "2") {
714 bytarget[i].diagnostic = "Temporary system error";
716 var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
717 if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
718 var suggestions = targetsSuggestions[0];
719 bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
723 context.bytargetCounter++;
724 var delay = context.bytargetTime
725 + context.bytargetCounter * context.dumpFactor;
726 if ( context.activeClients > 0 )
727 context.bytargetTimer =
735 context.bytargetCallback(bytarget, context.windowid);
738 context.throwError('Bytarget failed. Malformed WS resonse.',
744 // just for testing, probably shouldn't be here
745 showNext: function(page)
747 var step = page || 1;
748 this.show( ( step * this.currentNum ) + this.currentStart );
751 showPrev: function(page)
753 if (this.currentStart == 0 )
755 var step = page || 1;
756 var newStart = this.currentStart - (step * this.currentNum );
757 this.show( newStart > 0 ? newStart : 0 );
760 showPage: function(pageNum)
762 //var page = pageNum || 1;
763 this.show(pageNum * this.currentNum);
768 ********************************************************************************
769 ** AJAX HELPER CLASS ***********************************************************
770 ********************************************************************************
772 var pzHttpRequest = function (url, errorHandler, cookieDomain, windowId) {
773 this.maxUrlLength = 2048;
776 this.errorHandler = errorHandler || null;
778 this.requestHeaders = {};
780 this.domainRegex = /https?:\/\/([^:/]+).*/;
781 this.cookieDomain = cookieDomain || null;
782 this.windowId = windowId || window.name;
784 var xhr = new XMLHttpRequest();
785 var domain = this._getDomainFromUrl(url);
786 if ("withCredentials" in xhr) {
787 // XHR for Chrome/Firefox/Opera/Safari.
788 } else if (domain && this._isCrossDomain(domain) &&
789 typeof XDomainRequest != "undefined") {
790 // use XDR (IE7/8) when no other way
791 xhr = new XDomainRequest();
794 // CORS not supported.
800 pzHttpRequest.prototype =
802 safeGet: function ( params, callback )
804 var encodedParams = this.encodeParams(params);
805 var url = this._urlAppendParams(encodedParams);
806 if (url.length >= this.maxUrlLength) {
807 this.requestHeaders["Content-Type"]
808 = "application/x-www-form-urlencoded";
809 this._send( 'POST', this.url, encodedParams, callback );
811 this._send( 'GET', url, '', callback );
815 get: function ( params, callback )
817 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
821 post: function ( params, data, callback )
823 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
830 this.request.open( 'GET', this.url, this.async );
831 this.request.send('');
832 if ( this.request.status == 200 )
833 return this.request.responseXML;
836 encodeParams: function (params)
840 for (var key in params) {
841 if (params[key] != null) {
842 encoded += sep + key + '=' + encodeURIComponent(params[key]);
849 _getDomainFromUrl: function (url)
851 if (this.cookieDomain) return this.cookieDomain; //explicit cookie domain
852 var m = this.domainRegex.exec(url);
853 return (m && m.length > 1) ? m[1] : null;
856 _strEndsWith: function (str, suffix)
858 return str.indexOf(suffix, str.length - suffix.length) !== -1;
861 _isCrossDomain: function (domain)
863 if (this.cookieDomain) return true; //assume xdomain is cookie domain set
864 return !this._strEndsWith(domain, document.domain);
867 getCookie: function (sKey) {
868 return decodeURI(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"
869 + encodeURI(sKey).replace(/[\-\.\+\*]/g, "\\$&")
870 + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
873 setCookie: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
874 if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
879 switch (vEnd.constructor) {
881 sExpires = vEnd === Infinity
882 ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT"
883 : "; max-age=" + vEnd;
886 sExpires = "; expires=" + vEnd;
889 sExpires = "; expires=" + vEnd.toGMTString();
893 document.cookie = encodeURI(sKey) + "=" + encodeURI(sValue)
895 + (sDomain ? "; domain=" + sDomain : "")
896 + (sPath ? "; path=" + sPath : "")
897 + (bSecure ? "; secure" : "");
901 _send: function ( type, url, data, callback)
904 this.callback = callback;
906 //we never do withCredentials, so if it's CORS and we have
907 //session cookie, resend it
908 var domain = this._getDomainFromUrl(url);
909 if (domain && this._isCrossDomain(domain) &&
910 this.getCookie(domain+":"+this.windowId+":SESSID")) {
912 var sessparam = ';jsessionid=' + this.getCookie(domain+":"+this.windowId+":SESSID");
913 var q = url.indexOf('?');
917 url = url.substring(0, q) + sessparam + url.substring(q);
920 this.request.open( type, url, this.async );
922 //setting headers is only allowed with XHR
923 for (var key in this.requestHeaders)
924 this.request.setRequestHeader(key, this.requestHeaders[key]);
927 this.request.onload = function () {
929 context.request.status = 200;
930 context.request.readyState = 4;
932 context._handleResponse(url);
934 this.request.onerror = function () {
936 context.request.status = 417; //not really, but what can we do
937 context.request.readyState = 4;
939 context._handleResponse(url);
942 this.request.onreadystatechange = function () {
943 context._handleResponse(url); /// url used ONLY for error reporting
946 this.request.send(data);
949 _urlAppendParams: function (encodedParams)
952 return this.url + "?" + encodedParams;
957 _handleResponse: function (requestUrl)
959 if ( this.request.readyState == 4 ) {
960 // pick up appplication errors first
962 // xdomainreq does not have responseXML
964 if (this.request.contentType.match(/\/xml/)){
965 var dom = new ActiveXObject('Microsoft.XMLDOM');
967 dom.loadXML(this.request.responseText);
968 this.request.responseXML = dom;
970 this.request.responseXML = null;
973 if (this.request.responseXML &&
974 (errNode = this.request.responseXML.documentElement)
975 && errNode.nodeName == 'error') {
976 var errMsg = errNode.getAttribute("msg");
977 var errCode = errNode.getAttribute("code");
979 if (errNode.childNodes.length)
980 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
982 var err = new Error(errMsg + errAddInfo);
985 if (this.errorHandler) {
986 this.errorHandler(err);
992 else if (this.request.status == 200 &&
993 this.request.responseXML === null) {
994 if (this.request.responseText !== null) {
997 var text = this.request.responseText;
998 if (typeof window.JSON == "undefined") {
999 json = eval("(" + text + ")");
1002 json = JSON.parse(text);
1006 this.callback(json, "json");
1008 var err = new Error("XML/Text response is empty but no error " +
1009 "for " + requestUrl);
1011 if (this.errorHandler) {
1012 this.errorHandler(err);
1017 } else if (this.request.status == 200) {
1018 //set cookie manually only if cross-domain
1019 var domain = this._getDomainFromUrl(requestUrl);
1020 if (domain && this._isCrossDomain(domain)) {
1021 var jsessionId = this.request.responseXML
1022 .documentElement.getAttribute('jsessionId');
1024 this.setCookie(domain+":"+this.windowId+":SESSID", jsessionId);
1026 this.callback(this.request.responseXML);
1028 var err = new Error("HTTP response not OK: "
1029 + this.request.status + " - "
1030 + this.request.statusText );
1031 err.code = '00' + this.request.status;
1032 if (this.errorHandler) {
1033 this.errorHandler(err);
1044 ********************************************************************************
1045 ** XML HELPER FUNCTIONS ********************************************************
1046 ********************************************************************************
1051 if ( window.ActiveXObject) {
1052 var DOMDoc = document;
1054 var DOMDoc = Document.prototype;
1057 DOMDoc.newXmlDoc = function ( root )
1061 if (document.implementation && document.implementation.createDocument) {
1062 doc = document.implementation.createDocument('', root, null);
1063 } else if ( window.ActiveXObject ) {
1064 doc = new ActiveXObject("MSXML2.DOMDocument");
1065 doc.loadXML('<' + root + '/>');
1067 throw new Error ('No XML support in this browser');
1074 DOMDoc.parseXmlFromString = function ( xmlString )
1078 if ( window.DOMParser ) {
1079 var parser = new DOMParser();
1080 doc = parser.parseFromString( xmlString, "text/xml");
1081 } else if ( window.ActiveXObject ) {
1082 doc = new ActiveXObject("MSXML2.DOMDocument");
1083 doc.loadXML( xmlString );
1085 throw new Error ("No XML parsing support in this browser.");
1091 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
1093 if ( window.XSLTProcessor ) {
1094 var proc = new XSLTProcessor();
1095 proc.importStylesheet( xslDoc );
1096 return proc.transformToDocument(xmlDoc);
1097 } else if ( window.ActiveXObject ) {
1098 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
1100 alert( 'Unable to perform XSLT transformation in this browser' );
1106 Element_removeFromDoc = function (DOM_Element)
1108 DOM_Element.parentNode.removeChild(DOM_Element);
1111 Element_emptyChildren = function (DOM_Element)
1113 while( DOM_Element.firstChild ) {
1114 DOM_Element.removeChild( DOM_Element.firstChild )
1118 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1120 if ( window.XSLTProcessor ) {
1121 var proc = new XSLTProcessor();
1122 proc.importStylesheet( xslDoc );
1123 var docFrag = false;
1124 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1125 DOM_Element.appendChild(docFrag);
1126 } else if ( window.ActiveXObject ) {
1127 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1129 alert( 'Unable to perform XSLT transformation in this browser' );
1133 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1135 var node = DOM_Element.ownerDocument.createElement(tagName);
1136 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1138 DOM_Element.appendChild(node);
1139 node.appendChild(text);
1144 Element_setTextContent = function ( DOM_Element, textContent )
1146 if (typeof DOM_Element.textContent !== "undefined") {
1147 DOM_Element.textContent = textContent;
1148 } else if (typeof DOM_Element.innerText !== "undefined" ) {
1149 DOM_Element.innerText = textContent;
1151 throw new Error("Cannot set text content of the node, no such method.");
1155 Element_getTextContent = function (DOM_Element)
1157 if ( typeof DOM_Element.textContent != 'undefined' ) {
1158 return DOM_Element.textContent;
1159 } else if (typeof DOM_Element.text != 'undefined') {
1160 return DOM_Element.text;
1162 throw new Error("Cannot get text content of the node, no such method.");
1166 Element_parseChildNodes = function (node)
1169 var hasChildElems = false;
1170 var textContent = '';
1172 if (node.hasChildNodes()) {
1173 var children = node.childNodes;
1174 for (var i = 0; i < children.length; i++) {
1175 var child = children[i];
1176 switch (child.nodeType) {
1177 case Node.ELEMENT_NODE:
1178 hasChildElems = true;
1179 var nodeName = child.nodeName;
1180 if (!(nodeName in parsed))
1181 parsed[nodeName] = [];
1182 parsed[nodeName].push(Element_parseChildNodes(child));
1184 case Node.TEXT_NODE:
1185 textContent += child.nodeValue;
1187 case Node.CDATA_SECTION_NODE:
1188 textContent += child.nodeValue;
1194 var attrs = node.attributes;
1195 for (var i = 0; i < attrs.length; i++) {
1196 hasChildElems = true;
1197 var attrName = '@' + attrs[i].nodeName;
1198 var attrValue = attrs[i].nodeValue;
1199 parsed[attrName] = attrValue;
1202 // if no nested elements/attrs set value to text
1204 parsed['#text'] = textContent;
1206 parsed = textContent;
1211 /* do not remove trailing bracket */