2 ** $Id: pz2.js,v 1.61 2007-10-02 11:47:50 jakub Exp $
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: An array with parameters has to be suplied when instantiating a class");
34 //supported pazpar2's protocol version
35 this.suppProtoVer = '1';
36 if (typeof paramArray.pazpar2path != "undefined")
37 this.pz2String = paramArray.pazpar2path;
39 this.pz2String = "/pazpar2/search.pz2";
40 this.useSessions = true;
42 this.stylesheet = paramArray.detailstylesheet || null;
43 //load stylesheet if required in async mode
44 if( this.stylesheet ) {
46 var request = new pzHttpRequest( this.stylesheet );
47 request.get( {}, function ( doc ) { context.xslDoc = doc; } );
50 this.errorHandler = paramArray.errorhandler || null;
53 this.statCallback = paramArray.onstat || null;
54 this.showCallback = paramArray.onshow || null;
55 this.termlistCallback = paramArray.onterm || null;
56 this.recordCallback = paramArray.onrecord || null;
57 this.bytargetCallback = paramArray.onbytarget || null;
58 this.resetCallback = paramArray.onreset || null;
61 this.termKeys = paramArray.termlist || "subject";
63 // some configurational stuff
64 this.keepAlive = 50000;
66 if ( paramArray.keepAlive < this.keepAlive )
67 this.keepAlive = paramArray.keepAlive;
69 this.sessionID = null;
70 this.initStatusOK = false;
71 this.pingStatusOK = false;
72 this.searchStatusOK = false;
75 this.currentSort = "relevance";
78 this.currentStart = 0;
81 // last full record retrieved
82 this.currRecID = null;
85 this.currQuery = null;
88 this.statTime = paramArray.stattime || 1000;
89 this.statTimer = null;
90 this.termTime = paramArray.termtime || 1000;
91 this.termTimer = null;
92 this.showTime = paramArray.showtime || 1000;
93 this.showTimer = null;
94 this.showFastCount = 4;
95 this.bytargetTime = paramArray.bytargettime || 1000;
96 this.bytargetTimer = null;
98 // counters for each command and applied delay
99 this.dumpFactor = 500;
100 this.showCounter = 0;
101 this.termCounter = 0;
102 this.statCounter = 0;
103 this.bytargetCounter = 0;
105 // active clients, updated by stat and show
106 // might be an issue since bytarget will poll accordingly
107 this.activeClients = 1;
109 // if in proxy mode no need to init
110 if (paramArray.usesessions != undefined) {
111 this.useSessions = paramArray.usesessions;
112 this.initStatusOK = true;
114 // else, auto init session or wait for a user init?
115 if (this.useSessions && paramArray.autoInit !== false) {
122 //error handler for async error throws
123 throwError: function (errMsg, errCode)
125 var err = new Error(errMsg);
126 if (errCode) err.code = errCode;
128 if (this.errorHandler) {
129 this.errorHandler(err);
136 // stop activity by clearing tiemouts
139 clearTimeout(this.statTimer);
140 clearTimeout(this.showTimer);
141 clearTimeout(this.termTimer);
142 clearTimeout(this.bytargetTimer);
145 // reset status variables
148 if ( this.useSessions ) {
149 this.sessionID = null;
150 this.initStatusOK = false;
151 this.pingStatusOK = false;
153 this.searchStatusOK = false;
156 if ( this.resetCallback )
157 this.resetCallback();
160 init: function ( sessionId )
164 // session id as a param
165 if ( sessionId != undefined && this.useSessions ) {
166 this.initStatusOK = true;
167 this.sessionID = sessionId;
169 // old school direct pazpar2 init
170 } else if (this.useSessions) {
172 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
174 { "command": "init" },
176 if ( data.getElementsByTagName("status")[0]
177 .childNodes[0].nodeValue == "OK" ) {
178 if ( data.getElementsByTagName("protocol")[0]
179 .childNodes[0].nodeValue
180 != context.suppProtoVer )
181 throw new Error("Server's protocol not supported by the client");
182 context.initStatusOK = true;
184 data.getElementsByTagName("session")[0]
185 .childNodes[0].nodeValue;
194 context.throwError('Init failed. Malformed WS resonse.',
198 // when through proxy no need to init
200 this.initStatusOK = true;
203 // no need to ping explicitly
206 // pinging only makes sense when using pazpar2 directly
207 if( !this.initStatusOK || !this.useSessions )
208 throw new Error('Pz2.js: Ping not allowed (proxy mode) or session not initialized.');
209 // session is not initialized code here
212 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
214 { "command": "ping", "session": this.sessionID },
216 if ( data.getElementsByTagName("status")[0]
217 .childNodes[0].nodeValue == "OK" ) {
218 context.pingStatusOK = true;
227 context.throwError('Ping failed. Malformed WS resonse.',
232 search: function (query, num, sort, filter, showfrom)
234 clearTimeout(this.statTimer);
235 clearTimeout(this.showTimer);
236 clearTimeout(this.termTimer);
237 clearTimeout(this.bytargetTimer);
239 this.showCounter = 0;
240 this.termCounter = 0;
241 this.bytargetCounter = 0;
242 this.statCounter = 0;
245 if( !this.initStatusOK )
246 throw new Error('Pz2.js: session not initialized.');
248 if( query !== undefined )
249 this.currQuery = query;
251 throw new Error("Pz2.js: no query supplied to the search command.");
253 if ( showfrom !== undefined )
254 var start = showfrom;
260 "query": this.currQuery,
261 "session": this.sessionID
264 if (filter !== undefined)
265 searchParams["filter"] = filter;
268 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
272 if ( data.getElementsByTagName("status")[0]
273 .childNodes[0].nodeValue == "OK" ) {
274 context.searchStatusOK = true;
276 context.show(start, num, sort);
277 if ( context.statCallback )
279 if ( context.termlistCallback )
281 if ( context.bytargetCallback )
285 context.throwError('Search failed. Malformed WS resonse.',
292 if( !this.initStatusOK )
293 throw new Error('Pz2.js: session not initialized.');
295 // if called explicitly takes precedence
296 clearTimeout(this.statTimer);
299 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
301 { "command": "stat", "session": this.sessionID },
303 if ( data.getElementsByTagName("stat") ) {
305 Number( data.getElementsByTagName("activeclients")[0]
306 .childNodes[0].nodeValue );
307 context.activeClients = activeClients;
309 "activeclients": activeClients,
311 Number( data.getElementsByTagName("hits")[0]
312 .childNodes[0].nodeValue ),
314 Number( data.getElementsByTagName("records")[0]
315 .childNodes[0].nodeValue ),
317 Number( data.getElementsByTagName("clients")[0]
318 .childNodes[0].nodeValue ),
320 Number( data.getElementsByTagName("initializing")[0]
321 .childNodes[0].nodeValue ),
323 Number( data.getElementsByTagName("searching")[0]
324 .childNodes[0].nodeValue ),
326 Number( data.getElementsByTagName("presenting")[0]
327 .childNodes[0].nodeValue ),
329 Number( data.getElementsByTagName("idle")[0]
330 .childNodes[0].nodeValue ),
332 Number( data.getElementsByTagName("failed")[0]
333 .childNodes[0].nodeValue ),
335 Number( data.getElementsByTagName("error")[0]
336 .childNodes[0].nodeValue )
339 context.statCounter++;
340 var delay = context.statTime
341 + context.statCounter * context.dumpFactor;
343 if ( activeClients > 0 )
351 context.statCallback(stat);
354 context.throwError('Stat failed. Malformed WS resonse.',
359 show: function(start, num, sort)
361 if( !this.searchStatusOK && this.useSessions )
362 throw new Error('Pz2.js: show command has to be preceded with a search command.');
364 // if called explicitly takes precedence
365 clearTimeout(this.showTimer);
367 if( sort !== undefined )
368 this.currentSort = sort;
369 if( start !== undefined )
370 this.currentStart = Number( start );
371 if( num !== undefined )
372 this.currentNum = Number( num );
375 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
379 "session": this.sessionID,
380 "start": this.currentStart,
381 "num": this.currentNum,
382 "sort": this.currentSort,
386 if ( data.getElementsByTagName("status")[0]
387 .childNodes[0].nodeValue == "OK" ) {
388 // first parse the status data send along with records
389 // this is strictly bound to the format
391 Number( data.getElementsByTagName("activeclients")[0]
392 .childNodes[0].nodeValue );
393 context.activeClients = activeClients;
395 "activeclients": activeClients,
397 Number( data.getElementsByTagName("merged")[0]
398 .childNodes[0].nodeValue ),
400 Number( data.getElementsByTagName("total")[0]
401 .childNodes[0].nodeValue ),
403 Number( data.getElementsByTagName("start")[0]
404 .childNodes[0].nodeValue ),
406 Number( data.getElementsByTagName("num")[0]
407 .childNodes[0].nodeValue ),
410 // parse all the first-level nodes for all <hit> tags
411 var hits = data.getElementsByTagName("hit");
412 var hit = new Array();
413 for (i = 0; i < hits.length; i++) {
414 show.hits[i] = new Array();
415 show.hits[i]['location'] = new Array();
416 for ( j = 0; j < hits[i].childNodes.length; j++) {
418 if ( hits[i].childNodes[j].nodeType
419 == Node.ELEMENT_NODE ) {
420 if (hits[i].childNodes[j].nodeName
422 var locNode = hits[i].childNodes[j];
423 var id = locNode.getAttribute('id');
424 show.hits[i]['location'][id] = {
425 "id": locNode.getAttribute("id"),
426 "name": locNode.getAttribute("name")
431 hits[i].childNodes[j].nodeName;
432 var nodeText = 'ERROR'
433 if ( hits[i].childNodes[j].firstChild )
435 hits[i].childNodes[j]
436 .firstChild.nodeValue;
437 show.hits[i][nodeName] = nodeText;
442 context.showCounter++;
443 var delay = context.showTime;
444 if (context.showCounter > context.showFastCount)
445 delay += context.showCounter * context.dumpFactor;
446 if ( activeClients > 0 )
447 context.showTimer = setTimeout(
453 context.showCallback(show);
456 context.throwError('Show failed. Malformed WS resonse.',
461 record: function(id, offset, params)
463 // we may call record with no previous search if in proxy mode
464 if( !this.searchStatusOK && this.useSessions)
466 'Pz2.js: record command has to be preceded with a search command.'
468 if ( params == undefined )
471 if ( params.callback != undefined ) {
472 callback = params.callback;
474 callback = this.recordCallback;
478 if ( params['handle'] == undefined )
481 handle = params['handle'];
483 if( id !== undefined )
487 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
489 var recordParams = { "command": "record",
490 "session": this.sessionID,
491 "id": this.currRecID };
493 if (offset !== undefined) {
494 recordParams["offset"] = offset;
497 if (params.syntax != undefined) {
498 recordParams['syntax'] = params.syntax;
501 this.currRecOffset = offset;
507 var record = new Array();
508 record['xmlDoc'] = data;
509 if (context.currRecOffset !== undefined) {
510 record['offset'] = context.currRecOffset;
511 callback(record, handle);
512 } else if ( recordNode =
513 data.getElementsByTagName("record")[0] ) {
514 // if stylesheet was fetched do not parse the response
515 if ( context.xslDoc ) {
517 recordNode.getElementsByTagName("recid")[0]
518 .firstChild.nodeValue;
522 for ( i = 0; i < recordNode.childNodes.length; i++) {
523 if ( recordNode.childNodes[i].nodeType
525 && recordNode.childNodes[i].nodeName
528 recordNode.childNodes[i].nodeName;
530 recordNode.childNodes[i]
531 .firstChild.nodeValue;
532 record[nodeName] = nodeText;
535 // the location might be empty!!
537 recordNode.getElementsByTagName("location");
538 record["location"] = new Array();
539 for ( i = 0; i < locationNodes.length; i++ ) {
540 record["location"][i] = {
541 "id": locationNodes[i].getAttribute("id"),
542 "name": locationNodes[i].getAttribute("name")
545 for ( j = 0; j < locationNodes[i].childNodes.length; j++) {
546 if ( locationNodes[i].childNodes[j].nodeType
547 == Node.ELEMENT_NODE ) {
549 locationNodes[i].childNodes[j].nodeName;
551 if (locationNodes[i].childNodes[j]
554 locationNodes[i].childNodes[j]
555 .firstChild.nodeValue;
556 record["location"][i][nodeName] = nodeText;
562 callback(record, handle);
565 context.throwError('Record failed. Malformed WS resonse.',
573 if( !this.searchStatusOK && this.useSessions )
574 throw new Error('Pz2.js: termlist command has to be preceded with a search command.');
576 // if called explicitly takes precedence
577 clearTimeout(this.termTimer);
580 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
583 "command": "termlist",
584 "session": this.sessionID,
585 "name": this.termKeys
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'
616 terms[j].getElementsByTagName("id");
617 if(terms[j].getElementsByTagName("id").length)
619 termIdNode[0].childNodes[0].nodeValue;
620 termList[listName][j] = term;
624 context.termCounter++;
625 var delay = context.termTime
626 + context.termCounter * context.dumpFactor;
627 if ( activeClients > 0 )
636 context.termlistCallback(termList);
639 context.throwError('Termlist failed. Malformed WS resonse.',
647 if( !this.initStatusOK && this.useSessions )
648 throw new Error('Pz2.js: bytarget command has to be preceded with a search command.');
650 // no need to continue
651 if( !this.searchStatusOK )
654 // if called explicitly takes precedence
655 clearTimeout(this.bytargetTimer);
658 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
660 { "command": "bytarget", "session": this.sessionID },
662 if ( data.getElementsByTagName("status")[0]
663 .childNodes[0].nodeValue == "OK" ) {
664 var targetNodes = data.getElementsByTagName("target");
665 var bytarget = new Array();
666 for ( i = 0; i < targetNodes.length; i++) {
667 bytarget[i] = new Array();
668 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
669 if ( targetNodes[i].childNodes[j].nodeType
670 == Node.ELEMENT_NODE ) {
672 targetNodes[i].childNodes[j].nodeName;
674 targetNodes[i].childNodes[j]
675 .firstChild.nodeValue;
676 bytarget[i][nodeName] = nodeText;
681 context.bytargetCounter++;
682 var delay = context.bytargetTime
683 + context.bytargetCounter * context.dumpFactor;
684 if ( context.activeClients > 0 )
685 context.bytargetTimer =
693 context.bytargetCallback(bytarget);
696 context.throwError('Bytarget failed. Malformed WS resonse.',
702 // just for testing, probably shouldn't be here
703 showNext: function(page)
705 var step = page || 1;
706 this.show( ( step * this.currentNum ) + this.currentStart );
709 showPrev: function(page)
711 if (this.currentStart == 0 )
713 var step = page || 1;
714 var newStart = this.currentStart - (step * this.currentNum );
715 this.show( newStart > 0 ? newStart : 0 );
718 showPage: function(pageNum)
720 //var page = pageNum || 1;
721 this.show(pageNum * this.currentNum);
726 ********************************************************************************
727 ** AJAX HELPER CLASS ***********************************************************
728 ********************************************************************************
730 var pzHttpRequest = function ( url, errorHandler ) {
733 this.errorHandler = errorHandler || null;
736 if ( window.XMLHttpRequest ) {
737 this.request = new XMLHttpRequest();
738 } else if ( window.ActiveXObject ) {
740 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
742 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
747 pzHttpRequest.prototype =
749 get: function ( params, callback )
751 this._send( 'GET', params, '', callback );
754 post: function ( params, data, callback )
756 this._send( 'POST', params, data, callback );
762 this.request.open( 'GET', this.url, this.async );
763 this.request.send('');
764 if ( this.request.status == 200 )
765 return this.request.responseXML;
768 _send: function ( type, params, data, callback )
770 this.callback = callback;
773 this.request.open( type, this._urlAppendParams(params), this.async );
774 this.request.onreadystatechange = function () {
775 context._handleResponse();
777 this.request.send(data);
780 _urlAppendParams: function (params)
782 var getUrl = this.url;
786 for (var key in el) {
787 if (el[key] != null) {
788 getUrl += sep + key + '=' + encodeURIComponent(el[key]);
795 _handleResponse: function ()
797 if ( this.request.readyState == 4 ) {
798 // pick up pazpr2 errors first
799 if ( this.request.responseXML
800 && this.request.responseXML.documentElement.nodeName == 'error'
801 && this.request.responseXML.getElementsByTagName("error").length ) {
803 if ( this.request.responseXML.getElementsByTagName("error")[0].childNodes.length )
804 errAddInfo = ': ' + this.request.responseXML.getElementsByTagName("error")[0].childNodes[0].nodeValue;
805 var errMsg = this.request.responseXML.getElementsByTagName("error")[0].getAttribute("msg");
806 var errCode = this.request.responseXML.getElementsByTagName("error")[0].getAttribute("code");
808 var err = new Error(errMsg + errAddInfo);
811 if (this.errorHandler) {
812 this.errorHandler(err);
817 } else if ( this.request.status == 200 ) {
818 this.callback( this.request.responseXML );
820 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: "
821 + this.request.status + " Info: "
822 + this.request.statusText );
825 if (this.errorHandler) {
826 this.errorHandler(err);
837 *********************************************************************************
838 ** XML HELPER CLASS ************************************************************
839 *********************************************************************************
844 if ( window.ActiveXObject) {
845 var DOMDoc = document;
847 var DOMDoc = Document.prototype;
850 DOMDoc.newXmlDoc = function ( root )
854 if (document.implementation && document.implementation.createDocument) {
855 doc = document.implementation.createDocument('', root, null);
856 } else if ( window.ActiveXObject ) {
857 doc = new ActiveXObject("MSXML2.DOMDocument");
858 doc.loadXML('<' + root + '/>');
860 throw new Error ('No XML support in this browser');
867 DOMDoc.parseXmlFromString = function ( xmlString )
871 if ( window.DOMParser ) {
872 var parser = new DOMParser();
873 doc = parser.parseFromString( xmlString, "text/xml");
874 } else if ( window.ActiveXObject ) {
875 doc = new ActiveXObject("MSXML2.DOMDocument");
876 doc.loadXML( xmlString );
878 throw new Error ("No XML parsing support in this browser.");
884 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
886 if ( window.XSLTProcessor ) {
887 var proc = new XSLTProcessor();
888 proc.importStylesheet( xslDoc );
889 return proc.transformToDocument(xmlDoc);
890 } else if ( window.ActiveXObject ) {
891 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
893 alert( 'Unable to perform XSLT transformation in this browser' );
899 Element_removeFromDoc = function (DOM_Element)
901 DOM_Element.parentNode.removeChild(DOM_Element);
904 Element_emptyChildren = function (DOM_Element)
906 while( DOM_Element.firstChild ) {
907 DOM_Element.removeChild( DOM_Element.firstChild )
911 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
913 if ( window.XSLTProcessor ) {
914 var proc = new XSLTProcessor();
915 proc.importStylesheet( xslDoc );
917 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
918 DOM_Element.appendChild(docFrag);
919 } else if ( window.ActiveXObject ) {
920 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
922 alert( 'Unable to perform XSLT transformation in this browser' );
926 Element_appendTextNode = function (DOM_Element, tagName, textContent )
928 var node = DOM_Element.ownerDocument.createElement(tagName);
929 var text = DOM_Element.ownerDocument.createTextNode(textContent);
931 DOM_Element.appendChild(node);
932 node.appendChild(text);
937 Element_setTextContent = function ( DOM_Element, textContent )
939 if (typeof DOM_Element.textContent !== "undefined") {
940 DOM_Element.textContent = textContent;
941 } else if (typeof DOM_Element.innerText !== "undefined" ) {
942 DOM_Element.innerText = textContent;
944 throw new Error("Cannot set text content of the node, no such method.");
948 Element_getTextContent = function (DOM_Element)
950 if ( typeof DOM_Element.textContent != 'undefined' ) {
951 return DOM_Element.textContent;
952 } else if (typeof DOM_Element.text != 'undefined') {
953 return DOM_Element.text;
955 throw new Error("Cannot get text content of the node, no such method.");