2 ** $Id: pz2.js,v 1.63 2007-10-30 13:41:05 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();
421 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'][locCount] = {
429 "id": locNode.getAttribute("id"),
430 "name": locNode.getAttribute("name")
436 hits[i].childNodes[j].nodeName;
437 var nodeText = 'ERROR'
438 if ( hits[i].childNodes[j].firstChild )
440 hits[i].childNodes[j]
441 .firstChild.nodeValue;
442 show.hits[i][nodeName] = nodeText;
447 context.showCounter++;
448 var delay = context.showTime;
449 if (context.showCounter > context.showFastCount)
450 delay += context.showCounter * context.dumpFactor;
451 if ( activeClients > 0 )
452 context.showTimer = setTimeout(
458 context.showCallback(show);
461 context.throwError('Show failed. Malformed WS resonse.',
466 record: function(id, offset, params)
468 // we may call record with no previous search if in proxy mode
469 if( !this.searchStatusOK && this.useSessions)
471 'Pz2.js: record command has to be preceded with a search command.'
473 if ( params == undefined )
476 if ( params.callback != undefined ) {
477 callback = params.callback;
479 callback = this.recordCallback;
483 if ( params['handle'] == undefined )
486 handle = params['handle'];
488 if( id !== undefined )
492 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
494 var recordParams = { "command": "record",
495 "session": this.sessionID,
496 "id": this.currRecID };
498 if (offset !== undefined) {
499 recordParams["offset"] = offset;
502 if (params.syntax != undefined) {
503 recordParams['syntax'] = params.syntax;
506 this.currRecOffset = offset;
512 var record = new Array();
513 record['xmlDoc'] = data;
514 if (context.currRecOffset !== undefined) {
515 record['offset'] = context.currRecOffset;
516 callback(record, handle);
517 } else if ( recordNode =
518 data.getElementsByTagName("record")[0] ) {
519 // if stylesheet was fetched do not parse the response
520 if ( context.xslDoc ) {
522 recordNode.getElementsByTagName("recid")[0]
523 .firstChild.nodeValue;
527 for ( i = 0; i < recordNode.childNodes.length; i++) {
528 if ( recordNode.childNodes[i].nodeType
530 && recordNode.childNodes[i].nodeName
533 recordNode.childNodes[i].nodeName;
535 recordNode.childNodes[i]
536 .firstChild.nodeValue;
537 record[nodeName] = nodeText;
540 // the location might be empty!!
542 recordNode.getElementsByTagName("location");
543 record["location"] = new Array();
544 for ( i = 0; i < locationNodes.length; i++ ) {
545 record["location"][i] = {
546 "id": locationNodes[i].getAttribute("id"),
547 "name": locationNodes[i].getAttribute("name")
551 j < locationNodes[i].childNodes.length;
553 if ( locationNodes[i].childNodes[j].nodeType
554 == Node.ELEMENT_NODE ) {
556 locationNodes[i].childNodes[j].nodeName;
558 if (locationNodes[i].childNodes[j]
561 locationNodes[i].childNodes[j]
562 .firstChild.nodeValue;
563 record["location"][i][nodeName] = nodeText;
569 callback(record, handle);
572 context.throwError('Record failed. Malformed WS resonse.',
580 if( !this.searchStatusOK && this.useSessions )
582 'Pz2.js: termlist command has to be preceded with a search command.'
585 // if called explicitly takes precedence
586 clearTimeout(this.termTimer);
589 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
592 "command": "termlist",
593 "session": this.sessionID,
594 "name": this.termKeys
597 if ( data.getElementsByTagName("termlist") ) {
599 Number( data.getElementsByTagName("activeclients")[0]
600 .childNodes[0].nodeValue );
601 context.activeClients = activeClients;
602 var termList = { "activeclients": activeClients };
603 var termLists = data.getElementsByTagName("list");
605 for (i = 0; i < termLists.length; i++) {
606 var listName = termLists[i].getAttribute('name');
607 termList[listName] = new Array();
608 var terms = termLists[i].getElementsByTagName('term');
609 //for each term in the list
610 for (j = 0; j < terms.length; j++) {
613 (terms[j].getElementsByTagName("name")[0]
615 ? terms[j].getElementsByTagName("name")[0]
616 .childNodes[0].nodeValue
620 .getElementsByTagName("frequency")[0]
621 .childNodes[0].nodeValue || 'ERROR'
625 terms[j].getElementsByTagName("id");
626 if(terms[j].getElementsByTagName("id").length)
628 termIdNode[0].childNodes[0].nodeValue;
629 termList[listName][j] = term;
633 context.termCounter++;
634 var delay = context.termTime
635 + context.termCounter * context.dumpFactor;
636 if ( activeClients > 0 )
645 context.termlistCallback(termList);
648 context.throwError('Termlist failed. Malformed WS resonse.',
656 if( !this.initStatusOK && this.useSessions )
658 'Pz2.js: bytarget command has to be preceded with a search command.'
661 // no need to continue
662 if( !this.searchStatusOK )
665 // if called explicitly takes precedence
666 clearTimeout(this.bytargetTimer);
669 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
671 { "command": "bytarget", "session": this.sessionID },
673 if ( data.getElementsByTagName("status")[0]
674 .childNodes[0].nodeValue == "OK" ) {
675 var targetNodes = data.getElementsByTagName("target");
676 var bytarget = new Array();
677 for ( i = 0; i < targetNodes.length; i++) {
678 bytarget[i] = new Array();
679 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
680 if ( targetNodes[i].childNodes[j].nodeType
681 == Node.ELEMENT_NODE ) {
683 targetNodes[i].childNodes[j].nodeName;
685 targetNodes[i].childNodes[j]
686 .firstChild.nodeValue;
687 bytarget[i][nodeName] = nodeText;
692 context.bytargetCounter++;
693 var delay = context.bytargetTime
694 + context.bytargetCounter * context.dumpFactor;
695 if ( context.activeClients > 0 )
696 context.bytargetTimer =
704 context.bytargetCallback(bytarget);
707 context.throwError('Bytarget failed. Malformed WS resonse.',
713 // just for testing, probably shouldn't be here
714 showNext: function(page)
716 var step = page || 1;
717 this.show( ( step * this.currentNum ) + this.currentStart );
720 showPrev: function(page)
722 if (this.currentStart == 0 )
724 var step = page || 1;
725 var newStart = this.currentStart - (step * this.currentNum );
726 this.show( newStart > 0 ? newStart : 0 );
729 showPage: function(pageNum)
731 //var page = pageNum || 1;
732 this.show(pageNum * this.currentNum);
737 ********************************************************************************
738 ** AJAX HELPER CLASS ***********************************************************
739 ********************************************************************************
741 var pzHttpRequest = function ( url, errorHandler ) {
744 this.errorHandler = errorHandler || null;
747 if ( window.XMLHttpRequest ) {
748 this.request = new XMLHttpRequest();
749 } else if ( window.ActiveXObject ) {
751 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
753 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
758 pzHttpRequest.prototype =
760 get: function ( params, callback )
762 this._send( 'GET', params, '', callback );
765 post: function ( params, data, callback )
767 this._send( 'POST', params, data, callback );
773 this.request.open( 'GET', this.url, this.async );
774 this.request.send('');
775 if ( this.request.status == 200 )
776 return this.request.responseXML;
779 _send: function ( type, params, data, callback )
781 this.callback = callback;
784 this.request.open( type, this._urlAppendParams(params), this.async );
785 this.request.onreadystatechange = function () {
786 context._handleResponse();
788 this.request.send(data);
791 _urlAppendParams: function (params)
793 var getUrl = this.url;
797 for (var key in el) {
798 if (el[key] != null) {
799 getUrl += sep + key + '=' + encodeURIComponent(el[key]);
806 _handleResponse: function ()
808 if ( this.request.readyState == 4 ) {
809 // pick up pazpr2 errors first
810 if ( this.request.responseXML
811 && this.request.responseXML.documentElement.nodeName == 'error'
812 && this.request.responseXML.getElementsByTagName("error")
815 if ( this.request.responseXML.getElementsByTagName("error")[0]
818 this.request.responseXML
819 .getElementsByTagName("error")[0]
820 .childNodes[0].nodeValue;
822 this.request.responseXML.getElementsByTagName("error")[0]
823 .getAttribute("msg");
825 this.request.responseXML.getElementsByTagName("error")[0]
826 .getAttribute("code");
828 var err = new Error(errMsg + errAddInfo);
831 if (this.errorHandler) {
832 this.errorHandler(err);
837 } else if ( this.request.status == 200 ) {
838 this.callback( this.request.responseXML );
840 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: "
841 + this.request.status + " Info: "
842 + this.request.statusText );
845 if (this.errorHandler) {
846 this.errorHandler(err);
857 ********************************************************************************
858 ** XML HELPER FUNCTIONS ********************************************************
859 ********************************************************************************
864 if ( window.ActiveXObject) {
865 var DOMDoc = document;
867 var DOMDoc = Document.prototype;
870 DOMDoc.newXmlDoc = function ( root )
874 if (document.implementation && document.implementation.createDocument) {
875 doc = document.implementation.createDocument('', root, null);
876 } else if ( window.ActiveXObject ) {
877 doc = new ActiveXObject("MSXML2.DOMDocument");
878 doc.loadXML('<' + root + '/>');
880 throw new Error ('No XML support in this browser');
887 DOMDoc.parseXmlFromString = function ( xmlString )
891 if ( window.DOMParser ) {
892 var parser = new DOMParser();
893 doc = parser.parseFromString( xmlString, "text/xml");
894 } else if ( window.ActiveXObject ) {
895 doc = new ActiveXObject("MSXML2.DOMDocument");
896 doc.loadXML( xmlString );
898 throw new Error ("No XML parsing support in this browser.");
904 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
906 if ( window.XSLTProcessor ) {
907 var proc = new XSLTProcessor();
908 proc.importStylesheet( xslDoc );
909 return proc.transformToDocument(xmlDoc);
910 } else if ( window.ActiveXObject ) {
911 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
913 alert( 'Unable to perform XSLT transformation in this browser' );
919 Element_removeFromDoc = function (DOM_Element)
921 DOM_Element.parentNode.removeChild(DOM_Element);
924 Element_emptyChildren = function (DOM_Element)
926 while( DOM_Element.firstChild ) {
927 DOM_Element.removeChild( DOM_Element.firstChild )
931 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
933 if ( window.XSLTProcessor ) {
934 var proc = new XSLTProcessor();
935 proc.importStylesheet( xslDoc );
937 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
938 DOM_Element.appendChild(docFrag);
939 } else if ( window.ActiveXObject ) {
940 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
942 alert( 'Unable to perform XSLT transformation in this browser' );
946 Element_appendTextNode = function (DOM_Element, tagName, textContent )
948 var node = DOM_Element.ownerDocument.createElement(tagName);
949 var text = DOM_Element.ownerDocument.createTextNode(textContent);
951 DOM_Element.appendChild(node);
952 node.appendChild(text);
957 Element_setTextContent = function ( DOM_Element, textContent )
959 if (typeof DOM_Element.textContent !== "undefined") {
960 DOM_Element.textContent = textContent;
961 } else if (typeof DOM_Element.innerText !== "undefined" ) {
962 DOM_Element.innerText = textContent;
964 throw new Error("Cannot set text content of the node, no such method.");
968 Element_getTextContent = function (DOM_Element)
970 if ( typeof DOM_Element.textContent != 'undefined' ) {
971 return DOM_Element.textContent;
972 } else if (typeof DOM_Element.text != 'undefined') {
973 return DOM_Element.text;
975 throw new Error("Cannot get text content of the node, no such method.");
979 /* do not remove trailing bracket */