// ///////////////////////////////////////////////////////////////////////////////////////////
//      SCRIPT NAME:	askamedlib.js
//    SCRIPT AUTHOR:	Mark Vega
//      SCRIPT DATE:	April 2007
//  SCRIPT LOCATION:	pitcairn://target1s3/Web2/htdocs/www/libraries/grunigen/scripts/
//  SCRIPT FUNCTION:	Functions for handling Ask a Medical Librarian xmlhttprequest responses
//                  	and errors.
//     SCRIPT NOTES:	
// OTHER FILES USED:
//    LAST MODIFIED:	Changed all paths for new home on pitcairn.  06/13/2007 MFV	
//
// ///////////////////////////////////////////////////////////////////////////////////////////
//
// DEBUG WRITE STATEMENT
// alert("loading askamedlib.js");
// 
// http request response handler variables
var homeStatusResponse = '';
var startStatusResponse = '';
var monitorStatusResponse = '';
var libStatusResponse = '';
var patronStatusResponse = '';
var resumeTimeout;
var scriptUrl = '';
var statusPic = '';
var statusResponse = '';
// addobject variables
var elemtype = '';
var elemattnames = '';
var elemattvalues = '';
// replaceurls variables
var thisstring = '';
// wave player attribute names array
var playerattvalues = new Array();
playerattvalues[0] = "alertplayer";
playerattvalues[1] = "../audio/singlemoo.wav";
playerattvalues[2] = true;
playerattvalues[3] = false;
playerattvalues[4] = true;
// wave player attribute values array
var playerattnames = new Array();
playerattnames[0] = "id";
playerattnames[1] = "src";
playerattnames[2] = "autostart";
playerattnames[2] = "autoplay";
playerattnames[3] = "loop";
playerattnames[4] = "hidden";
// askamedlib status responses array
var responses = new Array();
responses[0] = "online";
responses[1] = "idle";
responses[2] = "mobile";
responses[3] = "away";
responses[4] = "offline";
responses[5] = "server";
responses[6] = "system";
// askamedlib status buttons array
var buttons = new Array();
buttons[0] = "askamedlib/images/imonline.gif";
buttons[1] = "askamedlib/images/imonline.gif";
buttons[2] = "askamedlib/images/imonline.gif";
buttons[3] = "askamedlib/images/imoffline.gif";
buttons[4] = "askamedlib/images/imoffline.gif";
buttons[5] = "askamedlib/images/imoffline.gif";
buttons[6] = "askamedlib/images/imoffline.gif";
// replacetext match patterns array
var matchthis = new Array();
matchthis[0] = /\b(ftp|http|https):\/\/([^\s\?]+)+[\?]?([^\s?]+)+\b/gi;
matchthis[1] = /\:\)/g;
matchthis[2] = /\:\(/g;
matchthis[3] = /\*-\)/g;
matchthis[4] = /\:s/g;
// replacetext replacement strings array
var replacewith = new Array();
replacewith[0] = '';
replacewith[1] = '<img src="images/imsmiling.gif" height="18" width="18" align="top" border="0" alt="smiling smiley" />';
replacewith[2] = '<img src="images/imfrowning.gif" height="18" width="18" align="top" border="0" alt="frowning smiley" />';
replacewith[3] = '<img src="images/imthinking.gif" height="18" width="18" align="top" border="0" alt="thinking smiley" />';
replacewith[4] = '<img src="images/imconfused.gif" height="18" width="18" align="top" border="0" alt="confused smiley" />';

//
// FUNCTION TO HANDLE HTTP REQUEST ERRORS
//
function rqstErrHandler() {
// get image element by id
statusPic = document.getElementById('statusImg');
// set value of statuspic source to offline gif
statusPic.src = "askamedlib/images/imoffline.gif";
}
//
// FUNCTION TO HANDLE INDEX HTTP REQUEST RESPONSE
//
// reads status response from http request initiated by index page and 
// assigns appropriate value to IM panel button img source.
//
function homeCheckStatus() {
// initialize local variables
var basePath= "http://grunigen.lib.uci.edu/";
var buttonSrc = '';
var longButtonSrc = '';
var savedButtonSrc = '';
var buttonPic = '';

// check value of readystate
if (httpRequest.readyState == 4) {
// check value of http status
if (httpRequest.status == 200) {
// set value of statusresponse
homeStatusResponse = httpRequest.responseText;
// loop through responses array
for (i = 0; i < responses.length; i++) {
// check value of statusresponse
if (homeStatusResponse == responses[i]) {
// check for existence of buttonimg
if (buttonPic = document.getElementById('buttonImg')) {
// save value of current buttonpic source for comparison
savedButtonSrc = buttonPic.src;
// set value of source to be compared to saved
compButtonSrc = buttons[i];
// concatenate base path and comparison values
longButtonSrc = basePath + compButtonSrc;
// if long source not equal to saved source
if (savedButtonSrc != longButtonSrc) {
// set as new value of button pic source
buttonPic.src = compButtonSrc;
}
}
// reset temporary variables
compButtonSrc = '';
longButtonSrc = '';
}
}
// if http status not 200
} else {
// check for existence of buttonimg
if (buttonPic = document.getElementById('buttonImg')) {
// save value of current buttonpic source for comparison
savedButtonSrc = buttonPic.src;
// set value of source to be compared to saved
compButtonSrc = "askamedlib/images/imoffline.gif";
// concatenate base path and comparison values
longButtonSrc = basePath + compButtonSrc;
// if long source not equal to saved source
if (savedButtonSrc != longButtonSrc) {
// set as new value of button pic source
buttonPic.src = compButtonSrc;
}
}
// reset temporary variables
compButtonSrc = '';
longButtonSrc = '';
}
}
return;
}
//
// FUNCTION TO HANDLE LIBMONITOR HTTP REQUEST RESPONSE
//
// reads status response from http request initiated by libmonitor page and 
// pops up new message window with alert sound if response is not false.
//
function monitorCheckStatus() {
// check value of readystate
if (httpRequest.readyState == 4) {
// check value of http status
if (httpRequest.status == 200) {
// set value of statusresponse
monitorStatusResponse = httpRequest.responseText;
// if response not false
if (monitorStatusResponse != 'false') {
// if imwin not already open
if (!imWin) {
// autoplay im alert sound
playSound();
// send to libsession page
// newWin('askamedlib/libsession.html','im');
newWin('libsession.html','im');
// cancel http requests
window.clearTimeout(requestTimeout);
}
// if response is false
} else {
//
}
// if not 200
} else {
// handle not 200 error
}
}
return;
}
//
// FUNCTION TO HANDLE PATRON START HTTP REQUEST RESPONSE
//
// reads status response from http request initiated by patronstart page and begins
// new session if response is 'available' or displays system message if response is not
// 'available'.
//
function startCheckStatus() {
var sysmessage = '';
var sysurl = '';
// check value of readystate
if (httpRequest.readyState == 4) {
// check value of http status
if (httpRequest.status == 200) {
// set value of statusresponse
startStatusResponse = httpRequest.responseText;
// if response is available
if (startStatusResponse == 'available') {
// redirect to patronstart page
window.location.href = "patronstart.html";
// if response is unavailable
} else if (startStatusResponse == 'notavailable') {
// redirect to system message page
sysmessage = "The librarian is currently busy assisting another patron. Please try sending your message again later or call our Reference Desk at 714-456-5583.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "patronsysmessages.html?sysmessage=" + sysmessage;
window.location.href = sysurl;
// if response is error
} else if (startStatusResponse == 'error') {
// redirect to system message page
sysmessage = "IM session could not be created or has been disconnected. Please try sending your message again or call our Reference Desk at 714-456-5583.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "patronsysmessages.html?sysmessage=" + sysmessage;
window.location.href = sysurl;

}
// if not 200
} else {
// redirect to system message page
/* sysmessage =  "Unable to establish connection with IM server. Please call our Reference Desk at 714-456-5583 to report this problem.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "patronsysmessages.html?sysmessage=" + sysmessage;
window.location.href = sysurl; */
}
}
// cancel http requests
window.clearTimeout(requestTimeout);
return;
}
//
// FUNCTION TO HANDLE LIB SESSION HTTP REQUEST RESPONSE
//
// reads status response from http request initiated by libsession page and displays
// chat messages if response is not false or system messages if response is false.
//
function libCheckStatus() {
var i = 0;
var innerhtml = '';
var sysmessage = '';
var sysurl = '';
// check value of readystate
if (httpRequest.readyState == 4) {
// check value of http status
if (httpRequest.status == 200) {
// set value of statusresponse
libStatusResponse = httpRequest.responseText;
// if response not false
if (libStatusResponse != 'false') {
// clean data string for html display
libStatusResponse = libStatusResponse.replace(/\\'/g,'\'');
// trim leading and trailing blank spaces around delimiter
libResponses = libStatusResponse.replace(/^\s+|\s+$/g,''); 
// split string at delimiter
libResponses = libStatusResponse.split('|');
// reset messages value
// loop through split array
for (i = 0; i < (libResponses.length - 1); i++) {
// find and replace urls and smileys with hyperlinks and images
libResponses[i] = replaceText(libResponses[i]);
// assign text color for username
if ((i == 0) || (i % 2 == 0) && (libResponses[i].substr(0,1) != '*')) {
if (libResponses[i].substr(0,9) == 'ucimedlib') {
innerhtml += '<span style="color:blue;font-weight: bold;">' + libResponses[i] + ':</span> ';
} else {
innerhtml += '<span style="color:red;font-weight: bold;">' + libResponses[i] + ':</span> ';
}
} else if (libResponses[i].substr(0,1) == '*') {
innerhtml += '<span style="color:red;font-weight: bold;">' + libResponses[i] + '</span><br />';
} else {
innerhtml += libResponses[i] + '<br />';
}
}
// display messages
document.getElementById("d_immessages").innerHTML = innerhtml;
// scroll window to bottom of page
document.getElementById("d_immessages").scrollTop = document.getElementById("d_immessages").scrollHeight;
// if response is false
} else {
// redirect to system message page
sysmessage = "This IM session has been ended, inadvertently disconnected, or could not be created. Please click on the <strong>Close</strong> button below to return to the GML home page.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "libsysmessages.html?sysmessage=" + sysmessage;
parent.location.href = sysurl;
// cancel http requests
window.clearTimeout(requestTimeout);
}
// if not 200
} else {
// redirect to system message page
/* sysmessage = "Unable to establish connection with IM server. Please call our Reference Desk at 714-456-5583 to report this problem.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "libsysmessages.html?sysmessage=" + sysmessage;
parent.location.href = sysurl;
*/
// cancel http requests
window.clearTimeout(requestTimeout);
}
}
return;
}
//
// FUNCTION TO HANDLE PATRON SESSION HTTP REQUEST RESPONSE
//
// reads status response from http request initiated by patronsession page and displays
// chat messages if response is not false or system messages if response is false.
//
function patronCheckStatus() {
var i = 0;
var innerhtml = '';
var sysmessage = '';
var sysurl = '';
// check value of readystate
if (httpRequest.readyState == 4) {
// check value of http status
if (httpRequest.status == 200) {
// set value of statusresponse
patronStatusResponse = httpRequest.responseText;
// if response not false
if (patronStatusResponse != 'false') {
// clean data string for html display
patronStatusResponse = patronStatusResponse.replace(/\\'/g,'\'');
// trim leading and trailing blank spaces around delimiter
patronResponses = patronStatusResponse.replace(/^\s+|\s+$/g,''); 
// split string at delimiter
patronResponses = patronStatusResponse.split('|');
// loop through split array
for (i = 0; i < (patronResponses.length - 1); i++) {
// find and replace urls and smileys with hyperlinks and images
patronResponses[i] = replaceText(patronResponses[i]);
// assign text color for username
if ((i == 0) || (i % 2 == 0) && (patronResponses[i].substr(0,1) != '*')) {
// ucimedlib librarian is blue
if (patronResponses[i].substr(0,9) == 'ucimedlib') {
innerhtml += '<span style="color:blue;font-weight: bold;">' + patronResponses[i] + ':</span> ';
// patron name is red
} else {
innerhtml += '<span style="color:red;font-weight: bold;">' + patronResponses[i] + ':</span> ';
}
} else if (patronResponses[i].substr(0,1) == '*') {
innerhtml += '<span style="color:red;font-weight: bold;">' + patronResponses[i] + '</span><br />';
} else {
innerhtml += patronResponses[i] + '<br />';
}
}
// display messages
document.getElementById("d_immessages").innerHTML = innerhtml;
// scroll window to bottom of page
document.getElementById("d_immessages").scrollTop = document.getElementById("d_immessages").scrollHeight;
// if response is false
} else {
// redirect to system message page
sysmessage = "This IM session has been ended. If you feel you were disconnected in error, or if you are in need of further assistance, please call our Reference Desk at 714-456-5583.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "patronsysmessages.html?sysmessage=" + sysmessage;
parent.location.href = sysurl;
// cancel http requests
window.clearTimeout(requestTimeout);
}
// if not 200
} else {
// redirect to system message page
/* sysmessage = "Unable to establish connection with IM server. Please call our Reference Desk at 714-456-5583 to report this problem.";
sysmessage = encodeURIComponent(sysmessage);
sysurl = "patronsysmessages.html?sysmessage=" + sysmessage;
parent.location.href = sysurl;
*/
// cancel http requests
window.clearTimeout(requestTimeout);
}
}
return;
}
//
// FUNCTION TO SEND PATRON START IM
//
// reads status response from http request saved since last sendRequest when 
// called by onclick event.  cancels send im request if ucimedlib is offline and displays page 
// with formatted message.
//
function sendIM() {
// initialize variables
var sendMessage = '';

// check value of status response
if (homeStatusResponse == 'offline') {
// if offline, set value of sendmessage to false
sendMessage = false;
} else {
// set value of sendmessage to true
sendMessage = true;
}
// check sendmessage flag
if (sendMessage == false) {
// if false, display offline page
window.location.href = "imnotonline.html";
// set return value to false
// return false;
// if flag is true
} else {
window.location.href = "askamedlib/getsessionstatus.html";
// set return value to true
// return true;
}
// cancel http requests
window.clearTimeout(requestTimeout);
}
//
// FUNCTION TO PAUSE IM AUTOSCROLL WHEN USER SCROLLS
//
function pauseIMAutoScroll() {
if (window.requestTimeout) {
window.clearTimeout(requestTimeout);
}
resumeTimeout = window.setTimeout('resumeIMAutoScroll()',15000);
}
//
// FUNCTION TO RESUME IM AUTOSCROLL AFTER SET PAUSE
//
function resumeIMAutoScroll() {
if (window.resumeTimeout) {
clearTimeout(resumeTimeout);
}
sendRequest(_rqstmethod,_rqsturl,_rqsthandler,_rqstasynch,_rqstsendxml,_rqstinterval,_rqstdata);
}
//
// FUNCTION TO REPLACE URLS AND TEXT MARKERS WITH HYPERLINKS AND SMILEYS
//
// performs pattern matching on im messages string and replaces urls with hyperlinks
// and text markers with smiley images.
//
function replaceText(thisstring) {
// initialize local variables
var j = 0;
var k = 0;
var matched = '';

// loop through matchthis array
for (j = 0; j < matchthis.length; j++) {
// if matches found
if (matched = thisstring.match(matchthis[j])) {
// loop through matches array
for (k = 0; k < matched.length; k++) {
if (j == 0) {
replacewith[0] = "<a href=\"javascript:newWin('" + matched[k] + "','link');\">" + matched[k] + "<\/a>";
// perform replacement
thisstring = thisstring.replace(matched[k],replacewith[0]);
} else {
// perform replacement
thisstring = thisstring.replace(matched[k],replacewith[j]);
}
}
}
}
// return string with replacements
return thisstring;
}
//
// FUNCTION TO CREATE WAVE PLAYER OBJECT FOR IM ALERT SOUND
//
function addObj(elemtype,elemattnames,elemattvalues) {
// get the reference for the body
objBody = document.getElementsByTagName("body")[0];
// create object as object element
objElement = document.createElement(elemtype);
// append object to body
objBody.appendChild(objElement);
// set object attributes
for (i = 0; i < elemattnames.length; i++) {
objElement.setAttribute(elemattnames[i], elemattvalues[i]);
}
// set timer to remove player element
addObjTimeout = window.setTimeout('removeObj(objElement)',3000);
}
//
// FUNCTION TO REMOVE WAVE PLAYER FOR IM ALERT SOUND
//
function removeObj(thisobj) {
// remove player element
objBody.removeChild(thisobj);
// cancel remove timer
window.clearTimeout(addObjTimeout);
return;
}
//
// FUNCTION TO AUTOPLAY IM ALERT SOUND
//
function playSound() {
// autoplay im alert sound
addObj('embed',playerattnames,playerattvalues);
}
//
// END