/*
-** $Id: pz2.js,v 1.10 2007-04-18 04:23:53 quinn Exp $
+** $Id: pz2.js,v 1.26 2007-06-01 08:22:32 jakub Exp $
** pz2.js - pazpar2's javascript client library.
*/
Node.DOCUMENT_FRAGMENT_NODE = 11;
Node.NOTATION_NODE = 12;
}
-// check for jQuery
-if(typeof window.jQuery == "undefined"){
- throw new Error("pz2.js requires jQuery library");
-}
+
// prevent execution of more than once
if(typeof window.pz2 == "undefined") {
window.undefined = window.undefined;
//for convenience
__myself = this;
+ //supported pazpar2's protocol version
+ __myself.suppProtoVer = '1';
+ __myself.pz2String = "search.pz2";
+ __myself.stylesheet = paramArray.detailstylesheet || null;
+
+ //load stylesheet if required in async mode
+ if( __myself.stylesheet ) {
+ var request = new pzHttpRequest( __myself.stylesheet );
+ request.get(
+ {},
+ function ( doc ) {
+ __myself.xslDoc = doc;
+ }
+ );
+ }
+
// at least one callback required
if ( !paramArray )
- throw new Error("An array with parameters has to be suplied when instantiating a class");
+ throw new Error("An array with parameters has to be suplied when instantiating a class");
+
+ __myself.errorHandler = paramArray.errorhandler || null;
// function callbacks
__myself.statCallback = paramArray.onstat || null;
__myself.termlistCallback = paramArray.onterm || null;
__myself.recordCallback = paramArray.onrecord || null;
__myself.bytargetCallback = paramArray.onbytarget || null;
+ __myself.resetCallback = paramArray.onreset || null;
// termlist keys
__myself.termKeys = paramArray.termlist || "subject";
// some configurational stuff
- __myself.pz2String = "search.pz2";
__myself.keepAlive = 50000;
__myself.sessionID = null;
__myself.currQuery = null;
//timers
- __myself.statTime = paramArray.stattime || 2000;
+ __myself.statTime = paramArray.stattime || 1000;
__myself.statTimer = null;
__myself.termTime = paramArray.termtime || 1000;
__myself.termTimer = null;
__myself.bytargetTime = paramArray.bytargettime || 1000;
__myself.bytargetTimer = null;
- //useful?
+ // counters for each command and applied delay
__myself.dumpFactor = 500;
__myself.showCounter = 0;
__myself.termCounter = 0;
+ __myself.statCounter = 0;
+ __myself.bytargetCounter = 0;
// active clients, updated by stat and show
// might be an issue since bytarget will poll accordingly
__myself.activeClients = 1;
-
- // error handling
- $(document).ajaxError(
- function (request, settings, exception) {
- if ( settings.responseXML && settings.responseXML.getElementsByTagName("error") )
- {
- var err = settings.responseXML.getElementsByTagName("error")[0].childNodes[0].nodeValue;
- if (err == 'QUERY')
- alert("Your query was not understood. Please rephrase");
- else
- throw new Error( settings.responseXML.getElementsByTagName("error")[0].childNodes[0].nodeValue);
- }
- else
- throw exception;
- });
// auto init session?
if (paramArray.autoInit !== false)
- __myself.init(__myself.keepAlive);
+ __myself.init();
};
pz2.prototype = {
- init: function(keepAlive)
+ reset: function ()
{
- if ( keepAlive < __myself.keepAlive )
- __myself.keepAlive = keepAlive;
-
- $.get( __myself.pz2String,
- { "command": "init" },
- function(data) {
- if ( data.getElementsByTagName("status")[0].childNodes[0].nodeValue == "OK" ) {
- __myself.initStatusOK = true;
- __myself.sessionID = data.getElementsByTagName("session")[0].childNodes[0].nodeValue;
- setTimeout(__myself.ping, __myself.keepAlive);
+ __myself.sessionID = null;
+ __myself.initStatusOK = false;
+ __myself.pingStatusOK = false;
+ __myself.searchStatusOK = false;
+
+ clearTimeout(__myself.statTimer);
+ clearTimeout(__myself.showTimer);
+ clearTimeout(__myself.termTimer);
+ clearTimeout(__myself.bytargetTimer);
+
+ if ( __myself.resetCallback )
+ __myself.resetCallback();
+ },
+ init: function ( sessionId )
+ {
+ __myself.reset();
+ if ( sessionId != undefined ) {
+ __myself.initStatusOK = true;
+ __myself.sessionID = sessionId;
+ __myself.ping();
+
+ } else {
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
+ { "command": "init" },
+ function(data) {
+ if ( data.getElementsByTagName("status")[0].childNodes[0].nodeValue == "OK" ) {
+ if ( data.getElementsByTagName("protocol")[0].childNodes[0].nodeValue != __myself.suppProtoVer )
+ throw new Error("Server's protocol not supported by the client");
+ __myself.initStatusOK = true;
+ __myself.sessionID = data.getElementsByTagName("session")[0].childNodes[0].nodeValue;
+ setTimeout("__myself.ping()", __myself.keepAlive);
+ }
+ else
+ // if it gets here the http return code was 200 (pz2 errors are 417)
+ // but the response was invalid, it should never occur
+ setTimeout("__myself.init()", 1000);
}
- else
- // if it gets here the http return code was 200 (pz2 errors are 417)
- // but the response was invalid, it should never occur
- setTimeout("__myself.init()", 1000);
- }
- );
+ );
+ }
},
// no need to ping explicitly
- ping: function()
+ ping: function ()
{
if( !__myself.initStatusOK )
return;
// session is not initialized code here
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
{ "command": "ping", "session": __myself.sessionID },
function(data) {
if ( data.getElementsByTagName("status")[0].childNodes[0].nodeValue == "OK" ) {
}
);
},
- search: function(query, num, sort, filter)
+ search: function (query, num, sort, filter)
{
clearTimeout(__myself.statTimer);
clearTimeout(__myself.showTimer);
__myself.showCounter = 0;
__myself.termCounter = 0;
+ __myself.bytargetCounter = 0;
+ __myself.statCounter = 0;
if( !__myself.initStatusOK )
return;
var searchParams = { "command": "search", "session": __myself.sessionID, "query": __myself.currQuery, "filter": filter };
else
var searchParams = { "command": "search", "session": __myself.sessionID, "query": __myself.currQuery };
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
searchParams,
function(data) {
if ( data.getElementsByTagName("status")[0].childNodes[0].nodeValue == "OK" ) {
//piggyback search
__myself.show(0, num, sort);
if ( __myself.statCallback )
- __myself.statTimer = setTimeout("__myself.stat()", __myself.statTime / 2);
+ __myself.stat();
+ //__myself.statTimer = setTimeout("__myself.stat()", __myself.statTime / 4);
if ( __myself.termlistCallback )
- //__myself.termlist();
- __myself.termTimer = setTimeout("__myself.termlist()", __myself.termTime / 2);
+ __myself.termlist();
+ //__myself.termTimer = setTimeout("__myself.termlist()", __myself.termTime / 4);
if ( __myself.bytargetCallback )
- __myself.bytargetTimer = setTimeout("__myself.bytarget()", __myself.bytargetTime / 2);
+ __myself.bytarget();
+ //__myself.bytargetTimer = setTimeout("__myself.bytarget()", __myself.bytargetTime / 4);
}
else
// if it gets here the http return code was 200 (pz2 errors are 417)
// but the response was invalid, it should never occur
- setTimeout("__myself.search(__myself.currQuery)", 1000);
+ setTimeout("__myself.search(__myself.currQuery)", 500);
}
);
},
stat: function()
{
- if( !__myself.searchStatusOK )
+ if( !__myself.initStatusOK )
return;
// if called explicitly takes precedence
clearTimeout(__myself.statTimer);
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
{ "command": "stat", "session": __myself.sessionID },
function(data) {
if ( data.getElementsByTagName("stat") ) {
"failed": Number( data.getElementsByTagName("failed")[0].childNodes[0].nodeValue ),
"error": Number( data.getElementsByTagName("error")[0].childNodes[0].nodeValue )
};
+
+ __myself.statCounter++;
+ var delay = __myself.statTime + __myself.statCounter * __myself.dumpFactor;
+ if ( activeClients > 0 )
+ __myself.statTimer = setTimeout("__myself.stat()", delay);
+
__myself.statCallback(stat);
- if (activeClients > 0)
- __myself.statTimer = setTimeout("__myself.stat()", __myself.statTime);
}
else
// if it gets here the http return code was 200 (pz2 errors are 417)
__myself.currentStart = Number( start );
if( num !== undefined )
__myself.currentNum = Number( num );
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ var context = this;
+ request.get(
{ "command": "show", "session": __myself.sessionID, "start": __myself.currentStart,
"num": __myself.currentNum, "sort": __myself.currentSort, "block": 1 },
function(data) {
// first parse the status data send along with records
// this is strictly bound to the format
var activeClients = Number( data.getElementsByTagName("activeclients")[0].childNodes[0].nodeValue );
+ __myself.activeClients = activeClients;
var show = {
"activeclients": activeClients,
"merged": Number( data.getElementsByTagName("merged")[0].childNodes[0].nodeValue ),
}
else {
var nodeName = hits[i].childNodes[j].nodeName;
- var nodeText = hits[i].childNodes[j].firstChild.nodeValue;
+ var nodeText = hits[i].childNodes[j].firstChild.nodeValue;
show.hits[i][nodeName] = nodeText;
}
}
}
}
- __myself.showCallback(show);
__myself.showCounter++;
var delay = __myself.showTime;
if (__myself.showCounter > __myself.showFastCount)
- delay *= 2;
- if (activeClients > 0)
+ delay += __myself.showCounter * __myself.dumpFactor;
+ if ( activeClients > 0 )
__myself.showTimer = setTimeout("__myself.show()", delay);
+
+ __myself.showCallback(show);
}
else
// if it gets here the http return code was 200 (pz2 errors are 417)
if( id !== undefined )
__myself.currRecID = id;
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
{ "command": "record", "session": __myself.sessionID, "id": __myself.currRecID },
function(data) {
var recordNode;
var record = new Array();
if ( recordNode = data.getElementsByTagName("record")[0] ) {
- for ( i = 0; i < recordNode.childNodes.length; i++) {
- if ( recordNode.childNodes[i].nodeType == Node.ELEMENT_NODE ) {
- var nodeName = recordNode.childNodes[i].nodeName;
- var nodeText = recordNode.childNodes[i].firstChild.nodeValue;
- record[nodeName] = nodeText;
+ // if stylesheet was fetched do not parse the response
+ if ( __myself.xslDoc ) {
+ record['xmlDoc'] = data;
+ record['xslDoc'] = __myself.xslDoc;
+ } else {
+ for ( i = 0; i < recordNode.childNodes.length; i++) {
+ if ( recordNode.childNodes[i].nodeType == Node.ELEMENT_NODE
+ && recordNode.childNodes[i].nodeName != 'location' ) {
+ var nodeName = recordNode.childNodes[i].nodeName;
+ var nodeText = recordNode.childNodes[i].firstChild.nodeValue;
+ record[nodeName] = nodeText;
+ }
}
- }
- // the location is hard coded
- var locationNodes = recordNode.getElementsByTagName("location");
- record["location"] = new Array();
- for ( i = 0; i < locationNodes.length; i++ ) {
- record["location"][i] = {
- "id": locationNodes[i].getAttribute("id"),
- "name": locationNodes[i].getAttribute("name")
- };
- for ( j = 0; j < locationNodes[i].childNodes.length; j++) {
- if ( locationNodes[i].childNodes[j].nodeType == Node.ELEMENT_NODE ) {
- var nodeName = locationNodes[i].childNodes[j].nodeName;
- var nodeText;
- if (locationNodes[i].childNodes[j].firstChild)
- nodeText = locationNodes[i].childNodes[j].firstChild.nodeValue;
- else
- nodeText = '';
- record["location"][i][nodeName] = nodeText;
+ // the location might be empty!!
+ var locationNodes = recordNode.getElementsByTagName("location");
+ record["location"] = new Array();
+ for ( i = 0; i < locationNodes.length; i++ ) {
+ record["location"][i] = {
+ "id": locationNodes[i].getAttribute("id"),
+ "name": locationNodes[i].getAttribute("name")
+ };
+
+ for ( j = 0; j < locationNodes[i].childNodes.length; j++) {
+ if ( locationNodes[i].childNodes[j].nodeType == Node.ELEMENT_NODE ) {
+ var nodeName = locationNodes[i].childNodes[j].nodeName;
+ var nodeText = '';
+ if (locationNodes[i].childNodes[j].firstChild)
+ nodeText = locationNodes[i].childNodes[j].firstChild.nodeValue;
+ record["location"][i][nodeName] = nodeText;
+ }
}
}
}
+
__myself.recordCallback(record);
}
else
// if it gets here the http return code was 200 (pz2 errors are 417)
// but the response was invalid, it should never occur
- setTimeout("__myself.record(__myself.currRecID)", 1000);
+ setTimeout("__myself.record(__myself.currRecID)", 500);
}
);
},
return;
// if called explicitly takes precedence
clearTimeout(__myself.termTimer);
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
{ "command": "termlist", "session": __myself.sessionID, "name": __myself.termKeys },
function(data) {
if ( data.getElementsByTagName("termlist") ) {
- var termList = { "activeclients": Number( data.getElementsByTagName("activeclients")[0].childNodes[0].nodeValue ) };
+ var activeClients = Number( data.getElementsByTagName("activeclients")[0].childNodes[0].nodeValue );
+ __myself.activeClients = activeClients;
+ var termList = { "activeclients": activeClients };
var termLists = data.getElementsByTagName("list");
//for each termlist
for (i = 0; i < termLists.length; i++) {
}
}
- __myself.termlistCallback(termList);
__myself.termCounter++;
- if (termList["activeclients"] > 0)
- __myself.termTimer = setTimeout("__myself.termlist()", (__myself.termTime + __myself.termCounter*__myself.dumpFactor));
+ var delay = __myself.termTime + __myself.termCounter * __myself.dumpFactor;
+ if ( activeClients > 0 )
+ __myself.termTimer = setTimeout("__myself.termlist()", delay);
+
+ __myself.termlistCallback(termList);
}
else
// if it gets here the http return code was 200 (pz2 errors are 417)
return;
// if called explicitly takes precedence
clearTimeout(__myself.bytargetTimer);
-
- $.get( __myself.pz2String,
+ var request = new pzHttpRequest(__myself.pz2String, __myself.errorHandler);
+ request.get(
{ "command": "bytarget", "session": __myself.sessionID },
function(data) {
if ( data.getElementsByTagName("status")[0].childNodes[0].nodeValue == "OK" ) {
}
}
}
- __myself.bytargetCallback(bytarget);
+
+ __myself.bytargetCounter++;
+ var delay = __myself.bytargetTime + __myself.bytargetCounter * __myself.dumpFactor;
if ( __myself.activeClients > 0 )
- __myself.bytargetTimer = setTimeout("__myself.bytarget()", __myself.bytargetTime);
+ __myself.bytargetTimer = setTimeout("__myself.bytarget()", delay);
+
+ __myself.bytargetCallback(bytarget);
}
else
// if it gets here the http return code was 200 (pz2 errors are 417)
__myself.show(pageNum * __myself.currentNum);
}
};
+
+/*
+*********************************************************************************
+** AJAX HELPER CLASS ************************************************************
+*********************************************************************************
+*/
+var pzHttpRequest = function ( url, errorHandler ) {
+ this.request = null;
+ this.url = url;
+ this.errorHandler = errorHandler || null;
+
+ if ( window.XMLHttpRequest ) {
+ this.request = new XMLHttpRequest();
+ } else if ( window.ActiveXObject ) {
+ try {
+ this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
+ } catch (err) {
+ this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
+ }
+ }
+};
+
+pzHttpRequest.prototype =
+{
+ get: function ( params, callback )
+ {
+ this.callback = callback;
+
+ var getUrl = this.url;
+ var paramArr = new Array();
+
+ for ( var key in params ) {
+ paramArr.push(key + '=' + params[key] );
+ }
+
+ if ( paramArr.length )
+ getUrl += '?' + paramArr.join('&');
+
+ var context = this;
+ this.request.open( 'GET', getUrl, true );
+ this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
+ this.request.setRequestHeader('Accept-Charset', 'UTF-8');
+ this.request.onreadystatechange = function () {
+ context._handleResponse();
+ }
+ this.request.send(null);
+ },
+
+ _handleResponse: function ()
+ {
+ if ( this.request.readyState == 4 ) {
+ if ( this.request.status == 200 ) {
+ this.callback( this.request.responseXML );
+ }
+ // pz errors
+ else if ( this.request.status == 417 ) {
+ var errMsg = this.request.responseXML.getElementsByTagName("error")[0].childNodes[0].nodeValue;
+ var errCode = this.request.responseXML.getElementsByTagName("error")[0].getAttribute("code");
+
+ var err = new Error(errMsg);
+ err.code = errCode;
+
+ if (this.errorHandler) {
+ this.errorHandler(err);
+ }
+ else {
+ throw err;
+ }
+ }
+ else {
+ var err = new Error("XMLHttpRequest error. STATUS: "
+ + this.request.status + " STATUS TEXT: "
+ + this.request.statusText );
+ err.code = 'HTTP';
+
+ if (this.errorHandler) {
+ this.errorHandler(err);
+ }
+ else {
+ throw err;
+ }
+ }
+ }
+ }
+};
+
+/*
+*********************************************************************************
+** QUERY CLASS ******************************************************************
+*********************************************************************************
+*/
+var pzQuery = function()
+{
+ this.simpleQuery = '';
+ this.singleFilter = null;
+ this.advTerms = new Array();
+ this.filterHash = new Array();
+ this.numTerms = 0;
+ this.filterNums = 0;
+};
+pzQuery.prototype = {
+ reset: function()
+ {
+ this.simpleQuery = '';
+ this.advTerms = new Array();
+ this.simpleFilter = null;
+ this.numTerms = 0;
+ },
+ addTerm: function(field, value)
+ {
+ var term = {"field": field, "value": value};
+ this.advTerms[this.numTerms] = term;
+ this.numTerms++;
+ },
+ getTermValueByIdx: function(index)
+ {
+ return this.advTerms[index].value;
+ },
+ getTermFieldByIdx: function(index)
+ {
+ return this.advTerms[index].field;
+ },
+ /* semicolon separated list of terms for given field*/
+ getTermsByField: function(field)
+ {
+ var terms = '';
+ for(var i = 0; i < this.advTerms.length; i++)
+ {
+ if( this.advTerms[i].field == field )
+ terms = terms + this.queryHas[i].value + ';';
+ }
+ return terms;
+ },
+ addTermsFromList: function(inputString, field)
+ {
+ var inputArr = inputString.split(';');
+ for(var i=0; i < inputArr.length; i++)
+ {
+ if(inputArr[i].length < 3) continue;
+ this.advTerms[this.numTerms] = {"field": field, "value": inputArr[i] };
+ this.numTerms++;
+ }
+ },
+ removeTermByIdx: function(index)
+ {
+ this.advTerms.splice(index, 1);
+ this.numTerms--;
+ },
+ toCCL: function()
+ {
+ var ccl = '';
+ if( this.simpleQuery != '')
+ ccl = this.simpleQuery;
+ for(var i = 0; i < this.advTerms.length; i++)
+ {
+ if (ccl != '') ccl = ccl + ' and ';
+ ccl = ccl + this.advTerms[i].field+'="'+this.advTerms[i].value+'"';
+ }
+ return ccl;
+ },
+ addFilter: function(name, value)
+ {
+ var filter = {"name": name, "id": value };
+ this.filterHash[this.filterHash.length] = filter;
+ this.filterNums++
+ return this.filterHash.length - 1;
+ },
+ setFilter: function(name, value)
+ {
+ this.filterHash = new Array();
+ this.filterNums = 0;
+ this.addFilter(name, value);
+ },
+ getFilter: function(index)
+ {
+ return this.filterHash[index].id;
+ },
+ getFilterName: function(index)
+ {
+ return this.filterHash[index].name;
+ },
+ removeFilter: function(index)
+ {
+ delete this.filterHash[index];
+ this.filterNums--;
+ },
+ clearFilter: function()
+ {
+ this.filterHash = new Array();
+ this.filterNums = 0;
+ },
+ getFilterString: function()
+ {
+ //temporary
+ if( this.singleFilter != null ) {
+ return 'pz:id='+this.singleFilter.id;
+ }
+ else if( this.filterNums <= 0 ) {
+ return undefined;
+ }
+
+ var filter = 'pz:id=';
+ for(var i = 0; i < this.filterHash.length; i++)
+ {
+ if (this.filterHash[i] == undefined) continue;
+ if (filter > 'pz:id=') filter = filter + '|';
+ filter += this.filterHash[i].id;
+ }
+ return filter;
+ },
+ totalLength: function()
+ {
+ var simpleLength = this.simpleQuery != '' ? 1 : 0;
+ return this.advTerms.length + simpleLength;
+ },
+ clearSingleFilter: function()
+ {
+ this.singleFilter = null;
+ },
+ setSingleFilter: function(name, value)
+ {
+ this.singleFilter = {"name": name, "id": value };
+ },
+ getSingleFilterName: function()
+ {
+ return this.singleFilter.name;
+ }
+}
+
}