2 ** $Id: pz2.js,v 1.62 2007-10-02 12:09:40 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: Array with parameters has to be suplied.");
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 )
182 "Server's protocol not supported by the client"
184 context.initStatusOK = true;
186 data.getElementsByTagName("session")[0]
187 .childNodes[0].nodeValue;
196 context.throwError('Init failed. Malformed WS resonse.',
200 // when through proxy no need to init
202 this.initStatusOK = true;
205 // no need to ping explicitly
208 // pinging only makes sense when using pazpar2 directly
209 if( !this.initStatusOK || !this.useSessions )
211 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
214 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
216 { "command": "ping", "session": this.sessionID },
218 if ( data.getElementsByTagName("status")[0]
219 .childNodes[0].nodeValue == "OK" ) {
220 context.pingStatusOK = true;
229 context.throwError('Ping failed. Malformed WS resonse.',
234 search: function (query, num, sort, filter, showfrom)
236 clearTimeout(this.statTimer);
237 clearTimeout(this.showTimer);
238 clearTimeout(this.termTimer);
239 clearTimeout(this.bytargetTimer);
241 this.showCounter = 0;
242 this.termCounter = 0;
243 this.bytargetCounter = 0;
244 this.statCounter = 0;
247 if( !this.initStatusOK )
248 throw new Error('Pz2.js: session not initialized.');
250 if( query !== undefined )
251 this.currQuery = query;
253 throw new Error("Pz2.js: no query supplied to the search command.");
255 if ( showfrom !== undefined )
256 var start = showfrom;
262 "query": this.currQuery,
263 "session": this.sessionID
266 if (filter !== undefined)
267 searchParams["filter"] = filter;
270 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
274 if ( data.getElementsByTagName("status")[0]
275 .childNodes[0].nodeValue == "OK" ) {
276 context.searchStatusOK = true;
278 context.show(start, num, sort);
279 if ( context.statCallback )
281 if ( context.termlistCallback )
283 if ( context.bytargetCallback )
287 context.throwError('Search failed. Malformed WS resonse.',
294 if( !this.initStatusOK )
295 throw new Error('Pz2.js: session not initialized.');
297 // if called explicitly takes precedence
298 clearTimeout(this.statTimer);
301 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
303 { "command": "stat", "session": this.sessionID },
305 if ( data.getElementsByTagName("stat") ) {
307 Number( data.getElementsByTagName("activeclients")[0]
308 .childNodes[0].nodeValue );
309 context.activeClients = activeClients;
311 "activeclients": activeClients,
313 Number( data.getElementsByTagName("hits")[0]
314 .childNodes[0].nodeValue ),
316 Number( data.getElementsByTagName("records")[0]
317 .childNodes[0].nodeValue ),
319 Number( data.getElementsByTagName("clients")[0]
320 .childNodes[0].nodeValue ),
322 Number( data.getElementsByTagName("initializing")[0]
323 .childNodes[0].nodeValue ),
325 Number( data.getElementsByTagName("searching")[0]
326 .childNodes[0].nodeValue ),
328 Number( data.getElementsByTagName("presenting")[0]
329 .childNodes[0].nodeValue ),
331 Number( data.getElementsByTagName("idle")[0]
332 .childNodes[0].nodeValue ),
334 Number( data.getElementsByTagName("failed")[0]
335 .childNodes[0].nodeValue ),
337 Number( data.getElementsByTagName("error")[0]
338 .childNodes[0].nodeValue )
341 context.statCounter++;
342 var delay = context.statTime
343 + context.statCounter * context.dumpFactor;
345 if ( activeClients > 0 )
353 context.statCallback(stat);
356 context.throwError('Stat failed. Malformed WS resonse.',
361 show: function(start, num, sort)
363 if( !this.searchStatusOK && this.useSessions )
365 'Pz2.js: show command has to be preceded with a search command.'
368 // if called explicitly takes precedence
369 clearTimeout(this.showTimer);
371 if( sort !== undefined )
372 this.currentSort = sort;
373 if( start !== undefined )
374 this.currentStart = Number( start );
375 if( num !== undefined )
376 this.currentNum = Number( num );
379 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
383 "session": this.sessionID,
384 "start": this.currentStart,
385 "num": this.currentNum,
386 "sort": this.currentSort,
390 if ( data.getElementsByTagName("status")[0]
391 .childNodes[0].nodeValue == "OK" ) {
392 // first parse the status data send along with records
393 // this is strictly bound to the format
395 Number( data.getElementsByTagName("activeclients")[0]
396 .childNodes[0].nodeValue );
397 context.activeClients = activeClients;
399 "activeclients": activeClients,
401 Number( data.getElementsByTagName("merged")[0]
402 .childNodes[0].nodeValue ),
404 Number( data.getElementsByTagName("total")[0]
405 .childNodes[0].nodeValue ),
407 Number( data.getElementsByTagName("start")[0]
408 .childNodes[0].nodeValue ),
410 Number( data.getElementsByTagName("num")[0]
411 .childNodes[0].nodeValue ),
414 // parse all the first-level nodes for all <hit> tags
415 var hits = data.getElementsByTagName("hit");
416 var hit = new Array();
417 for (i = 0; i < hits.length; i++) {
418 show.hits[i] = new Array();
419 show.hits[i]['location'] = new Array();
420 for ( j = 0; j < hits[i].childNodes.length; j++) {
422 if ( hits[i].childNodes[j].nodeType
423 == Node.ELEMENT_NODE ) {
424 if (hits[i].childNodes[j].nodeName
426 var locNode = hits[i].childNodes[j];
427 var id = locNode.getAttribute('id');
428 show.hits[i]['location'][id] = {
429 "id": locNode.getAttribute("id"),
430 "name": locNode.getAttribute("name")
435 hits[i].childNodes[j].nodeName;
436 var nodeText = 'ERROR'
437 if ( hits[i].childNodes[j].firstChild )
439 hits[i].childNodes[j]
440 .firstChild.nodeValue;
441 show.hits[i][nodeName] = nodeText;
446 context.showCounter++;
447 var delay = context.showTime;
448 if (context.showCounter > context.showFastCount)
449 delay += context.showCounter * context.dumpFactor;
450 if ( activeClients > 0 )
451 context.showTimer = setTimeout(
457 context.showCallback(show);
460 context.throwError('Show failed. Malformed WS resonse.',
465 record: function(id, offset, params)
467 // we may call record with no previous search if in proxy mode
468 if( !this.searchStatusOK && this.useSessions)
470 'Pz2.js: record command has to be preceded with a search command.'
472 if ( params == undefined )
475 if ( params.callback != undefined ) {
476 callback = params.callback;
478 callback = this.recordCallback;
482 if ( params['handle'] == undefined )
485 handle = params['handle'];
487 if( id !== undefined )
491 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
493 var recordParams = { "command": "record",
494 "session": this.sessionID,
495 "id": this.currRecID };
497 if (offset !== undefined) {
498 recordParams["offset"] = offset;
501 if (params.syntax != undefined) {
502 recordParams['syntax'] = params.syntax;
505 this.currRecOffset = offset;
511 var record = new Array();
512 record['xmlDoc'] = data;
513 if (context.currRecOffset !== undefined) {
514 record['offset'] = context.currRecOffset;
515 callback(record, handle);
516 } else if ( recordNode =
517 data.getElementsByTagName("record")[0] ) {
518 // if stylesheet was fetched do not parse the response
519 if ( context.xslDoc ) {
521 recordNode.getElementsByTagName("recid")[0]
522 .firstChild.nodeValue;
526 for ( i = 0; i < recordNode.childNodes.length; i++) {
527 if ( recordNode.childNodes[i].nodeType
529 && recordNode.childNodes[i].nodeName
532 recordNode.childNodes[i].nodeName;
534 recordNode.childNodes[i]
535 .firstChild.nodeValue;
536 record[nodeName] = nodeText;
539 // the location might be empty!!
541 recordNode.getElementsByTagName("location");
542 record["location"] = new Array();
543 for ( i = 0; i < locationNodes.length; i++ ) {
544 record["location"][i] = {
545 "id": locationNodes[i].getAttribute("id"),
546 "name": locationNodes[i].getAttribute("name")
550 j < locationNodes[i].childNodes.length;
552 if ( locationNodes[i].childNodes[j].nodeType
553 == Node.ELEMENT_NODE ) {
555 locationNodes[i].childNodes[j].nodeName;
557 if (locationNodes[i].childNodes[j]
560 locationNodes[i].childNodes[j]
561 .firstChild.nodeValue;
562 record["location"][i][nodeName] = nodeText;
568 callback(record, handle);
571 context.throwError('Record failed. Malformed WS resonse.',
579 if( !this.searchStatusOK && this.useSessions )
581 'Pz2.js: termlist command has to be preceded with a search command.'
584 // if called explicitly takes precedence
585 clearTimeout(this.termTimer);
588 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
591 "command": "termlist",
592 "session": this.sessionID,
593 "name": this.termKeys
596 if ( data.getElementsByTagName("termlist") ) {
598 Number( data.getElementsByTagName("activeclients")[0]
599 .childNodes[0].nodeValue );
600 context.activeClients = activeClients;
601 var termList = { "activeclients": activeClients };
602 var termLists = data.getElementsByTagName("list");
604 for (i = 0; i < termLists.length; i++) {
605 var listName = termLists[i].getAttribute('name');
606 termList[listName] = new Array();
607 var terms = termLists[i].getElementsByTagName('term');
608 //for each term in the list
609 for (j = 0; j < terms.length; j++) {
612 (terms[j].getElementsByTagName("name")[0]
614 ? terms[j].getElementsByTagName("name")[0]
615 .childNodes[0].nodeValue
619 .getElementsByTagName("frequency")[0]
620 .childNodes[0].nodeValue || 'ERROR'
624 terms[j].getElementsByTagName("id");
625 if(terms[j].getElementsByTagName("id").length)
627 termIdNode[0].childNodes[0].nodeValue;
628 termList[listName][j] = term;
632 context.termCounter++;
633 var delay = context.termTime
634 + context.termCounter * context.dumpFactor;
635 if ( activeClients > 0 )
644 context.termlistCallback(termList);
647 context.throwError('Termlist failed. Malformed WS resonse.',
655 if( !this.initStatusOK && this.useSessions )
657 'Pz2.js: bytarget command has to be preceded with a search command.'
660 // no need to continue
661 if( !this.searchStatusOK )
664 // if called explicitly takes precedence
665 clearTimeout(this.bytargetTimer);
668 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
670 { "command": "bytarget", "session": this.sessionID },
672 if ( data.getElementsByTagName("status")[0]
673 .childNodes[0].nodeValue == "OK" ) {
674 var targetNodes = data.getElementsByTagName("target");
675 var bytarget = new Array();
676 for ( i = 0; i < targetNodes.length; i++) {
677 bytarget[i] = new Array();
678 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
679 if ( targetNodes[i].childNodes[j].nodeType
680 == Node.ELEMENT_NODE ) {
682 targetNodes[i].childNodes[j].nodeName;
684 targetNodes[i].childNodes[j]
685 .firstChild.nodeValue;
686 bytarget[i][nodeName] = nodeText;
691 context.bytargetCounter++;
692 var delay = context.bytargetTime
693 + context.bytargetCounter * context.dumpFactor;
694 if ( context.activeClients > 0 )
695 context.bytargetTimer =
703 context.bytargetCallback(bytarget);
706 context.throwError('Bytarget failed. Malformed WS resonse.',
712 // just for testing, probably shouldn't be here
713 showNext: function(page)
715 var step = page || 1;
716 this.show( ( step * this.currentNum ) + this.currentStart );
719 showPrev: function(page)
721 if (this.currentStart == 0 )
723 var step = page || 1;
724 var newStart = this.currentStart - (step * this.currentNum );
725 this.show( newStart > 0 ? newStart : 0 );
728 showPage: function(pageNum)
730 //var page = pageNum || 1;
731 this.show(pageNum * this.currentNum);
736 ********************************************************************************
737 ** AJAX HELPER CLASS ***********************************************************
738 ********************************************************************************
740 var pzHttpRequest = function ( url, errorHandler ) {
743 this.errorHandler = errorHandler || null;
746 if ( window.XMLHttpRequest ) {
747 this.request = new XMLHttpRequest();
748 } else if ( window.ActiveXObject ) {
750 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
752 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
757 pzHttpRequest.prototype =
759 get: function ( params, callback )
761 this._send( 'GET', params, '', callback );
764 post: function ( params, data, callback )
766 this._send( 'POST', params, data, callback );
772 this.request.open( 'GET', this.url, this.async );
773 this.request.send('');
774 if ( this.request.status == 200 )
775 return this.request.responseXML;
778 _send: function ( type, params, data, callback )
780 this.callback = callback;
783 this.request.open( type, this._urlAppendParams(params), this.async );
784 this.request.onreadystatechange = function () {
785 context._handleResponse();
787 this.request.send(data);
790 _urlAppendParams: function (params)
792 var getUrl = this.url;
796 for (var key in el) {
797 if (el[key] != null) {
798 getUrl += sep + key + '=' + encodeURIComponent(el[key]);
805 _handleResponse: function ()
807 if ( this.request.readyState == 4 ) {
808 // pick up pazpr2 errors first
809 if ( this.request.responseXML
810 && this.request.responseXML.documentElement.nodeName == 'error'
811 && this.request.responseXML.getElementsByTagName("error")
814 if ( this.request.responseXML.getElementsByTagName("error")[0]
817 this.request.responseXML
818 .getElementsByTagName("error")[0]
819 .childNodes[0].nodeValue;
821 this.request.responseXML.getElementsByTagName("error")[0]
822 .getAttribute("msg");
824 this.request.responseXML.getElementsByTagName("error")[0]
825 .getAttribute("code");
827 var err = new Error(errMsg + errAddInfo);
830 if (this.errorHandler) {
831 this.errorHandler(err);
836 } else if ( this.request.status == 200 ) {
837 this.callback( this.request.responseXML );
839 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: "
840 + this.request.status + " Info: "
841 + this.request.statusText );
844 if (this.errorHandler) {
845 this.errorHandler(err);
856 ********************************************************************************
857 ** XML HELPER FUNCTIONS ********************************************************
858 ********************************************************************************
863 if ( window.ActiveXObject) {
864 var DOMDoc = document;
866 var DOMDoc = Document.prototype;
869 DOMDoc.newXmlDoc = function ( root )
873 if (document.implementation && document.implementation.createDocument) {
874 doc = document.implementation.createDocument('', root, null);
875 } else if ( window.ActiveXObject ) {
876 doc = new ActiveXObject("MSXML2.DOMDocument");
877 doc.loadXML('<' + root + '/>');
879 throw new Error ('No XML support in this browser');
886 DOMDoc.parseXmlFromString = function ( xmlString )
890 if ( window.DOMParser ) {
891 var parser = new DOMParser();
892 doc = parser.parseFromString( xmlString, "text/xml");
893 } else if ( window.ActiveXObject ) {
894 doc = new ActiveXObject("MSXML2.DOMDocument");
895 doc.loadXML( xmlString );
897 throw new Error ("No XML parsing support in this browser.");
903 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
905 if ( window.XSLTProcessor ) {
906 var proc = new XSLTProcessor();
907 proc.importStylesheet( xslDoc );
908 return proc.transformToDocument(xmlDoc);
909 } else if ( window.ActiveXObject ) {
910 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
912 alert( 'Unable to perform XSLT transformation in this browser' );
918 Element_removeFromDoc = function (DOM_Element)
920 DOM_Element.parentNode.removeChild(DOM_Element);
923 Element_emptyChildren = function (DOM_Element)
925 while( DOM_Element.firstChild ) {
926 DOM_Element.removeChild( DOM_Element.firstChild )
930 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
932 if ( window.XSLTProcessor ) {
933 var proc = new XSLTProcessor();
934 proc.importStylesheet( xslDoc );
936 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
937 DOM_Element.appendChild(docFrag);
938 } else if ( window.ActiveXObject ) {
939 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
941 alert( 'Unable to perform XSLT transformation in this browser' );
945 Element_appendTextNode = function (DOM_Element, tagName, textContent )
947 var node = DOM_Element.ownerDocument.createElement(tagName);
948 var text = DOM_Element.ownerDocument.createTextNode(textContent);
950 DOM_Element.appendChild(node);
951 node.appendChild(text);
956 Element_setTextContent = function ( DOM_Element, textContent )
958 if (typeof DOM_Element.textContent !== "undefined") {
959 DOM_Element.textContent = textContent;
960 } else if (typeof DOM_Element.innerText !== "undefined" ) {
961 DOM_Element.innerText = textContent;
963 throw new Error("Cannot set text content of the node, no such method.");
967 Element_getTextContent = function (DOM_Element)
969 if ( typeof DOM_Element.textContent != 'undefined' ) {
970 return DOM_Element.textContent;
971 } else if (typeof DOM_Element.text != 'undefined') {
972 return DOM_Element.text;
974 throw new Error("Cannot get text content of the node, no such method.");
978 /* do not remove trailing bracket */