/**********************************************************************************/
/** © 1998 - 2009 Ultratec, Inc.                                                 **/
/**                                                                              **/
/** Disclaimer:                                                                  **/
/**   Ultratec, Inc. is providing this code as an example of how to access their **/
/**   Externally Hosted CapTel Application Programming Interface. All example    **/
/**   source code obtained from Ultratec, Inc is delivered "AS IS." Ultratec,    **/
/**   Inc specifically disclaims any and all warranties, expressed or implied,   **/
/**   including but not limited to any implied warranties of merchantability or  **/
/**   fitness for a particular purpose. Ultratec, Inc. does not represent or     **/
/**   warrant that any program is error free or that its use will be             **/
/**   uninterrupted. Ultratec, Inc. shall not be liable for any loss of profit,  **/
/**   loss of business or goodwill, loss of data, interruption in business, nor  **/
/**   for indirect, special, incidental, or consequential damages of any kind    **/
/**   under or arising out of the use or implementation of the example source    **/
/**   code, however caused, whether for breach or warranty, breach or            **/
/**   repudiation of contract, tort, negligence, or otherwise, even if Ultratec, **/
/**   Inc has been advised of the possibility of such a loss. Also Ultratec,     **/
/**   Inc. shall not have any obligation to provide techincal support or         **/
/**   development assistance for the example source code obtained from Ultratec, **/
/**   Inc.                                                                       **/
/**********************************************************************************/
/**********************************************************************************/
/** Global Functions that are used throughout the webcaptel site                 **/
/**********************************************************************************/
//This function is used to navigate the user to different pages depending on what is passed into the function
//  NOTE: the only reason why I use forms to navigate to pages is because I don't
//		want to pass information between pages in the Query String. There are many
//		other ways to do this (session, cookies, etc...). This is just one example.
function goTo(strPage){
	switch(strPage.toLowerCase()){
		case "placecall":
			navigatePlaceCall();
			break;

		case "waitforcall":
			navigateWaitForCall();
			break;
			
		case "profile":
			navigateProfile();
			break;

		case "contacts":
			navigateContacts();
			break;

		case "faqs":
			navigateFAQs();
			break;
			
		case "manageusers":
			navigateManageUsers();
			break;

		case "logout": //This calls the logout function to log the user out of the application
			logout();
			break;
	}
}

//This function is used to send the logout request
function logout(){

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Logging out...","<img src='images/loading.gif' border='0' />","None",[null]);	
	
	var request = new SimpleRequest();
	var strParams = "";
	strParams = "action=logout";
	strParams += "&userid=" + gUserID;
	strParams += "&sessionid=" + gSessionID;
	
	request.connect(PROXY, "POST", strParams, function(request){processLogout(request);}, "xml"); 
}

//This function is used to process the logout request
function processLogout(xmlResponse){
	var response = new UTIResponse(xmlResponse);
	var aHandler = new Array(), strMessage = "";
	if(response.status == "error"){ //if there was an error with the logout request
		handleLogoutError();
	}else{ //the request was processed successfully
		handleLogoutError(); 
	}
}

//this handles the OK click from the logout error
function handleLogoutError(){
	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.closeMessage();	
	changeURL("/Default.asp"); //changes URL to index.asp...
}

//this function takes the user to the profile page
function navigatePlaceCall(){
	var strForm = ""; //sets default form to submit
	if(gCallback=="" || gCallback==undefined || gCallback==null){//Go to Wait For Call page - this is done to force the person to set a callback number before doing anything else.
		strForm = "nav_wait_for_call_form"; //sets the form value to the wait for call form
		setFormValue(strForm, "userid", gUserID); //set the value for userid
		setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
		setFormValue(strForm, "callback", gCallback); //set the value for the callback number
		setFormValue(strForm, "user", gUser); //set the value for user
		setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	}else{//Go to Place Call page - this is done when their is a successfull return from the wait for call request.
		strForm = "nav_place_call_form"; //sets form value to the place call form
		setFormValue(strForm, "callback", (gCallback=="")?gANI:gCallback); //set the value for the calback number
		setFormValue(strForm, "ani", gANI); //set the value for ani
		setFormValue(strForm, "userid", gUserID); //set the value for userid
		setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
		setFormValue(strForm, "callid", gCallID); //set the value for callid
		setFormValue(strForm, "user", gUser); //set the value for user
		setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	}
	submitForm(strForm); //submits the appropriate form to navigate the user to the appropriate page.
}

function navigateWaitForCall() {
	strForm = "nav_wait_for_call_form"; //sets the form value to the wait for call form
	setFormValue(strForm, "userid", gUserID); //set the value for userid
	setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
	setFormValue(strForm, "callback", gCallback); //set the value for the callback number
	setFormValue(strForm, "user", gUser); //set the value for user
	setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	submitForm(strForm); //submits the appropriate form to navigate the user to the appropriate page.
}
//this function takes the user to the profile page
function navigateProfile(){
	var strForm = "nav_profile_form";
	setFormValue(strForm, "userid", gUserID); //set the value for userid
	setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
	setFormValue(strForm, "user", gUser); //set the value for user
	setFormValue(strForm, "callback", gCallback); //set the value for the callback number
	setFormValue(strForm, "ani", gANI); //set the value for ani
	setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	submitForm(strForm); //submits the appropriate form to navigate the user to the appropriate page.
}

//this function takes the user to the profile page
function navigateContacts(){
	var strForm = "nav_contacts_form";
	setFormValue(strForm, "userid", gUserID); //set the value for userid
	setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
	setFormValue(strForm, "user", gUser); //set the value for user
	setFormValue(strForm, "callback", gCallback); //set the value for the callback number
	setFormValue(strForm, "ani", gANI); //set the value for ani
	setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	submitForm(strForm); //submits the appropriate form to navigate the user to the appropriate page.
}

//this function takes the user to the profile page
function navigateFAQs(){
	var strForm = "nav_faqs_form";
	setFormValue(strForm, "userid", gUserID); //set the value for userid
	setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
	setFormValue(strForm, "user", gUser); //set the value for user
	setFormValue(strForm, "callback", gCallback); //set the value for the callback number
	setFormValue(strForm, "ani", gANI); //set the value for ani
	setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	submitForm(strForm); //submits the appropriate form to navigate the user to the appropriate page.
}

//this function takes the user to the profile page
function navigateManageUsers(){
	var strForm = "nav_manageusers_form";
	setFormValue(strForm, "userid", gUserID); //set the value for userid
	setFormValue(strForm, "sessionid", gSessionID); //set the value for sessionid
	setFormValue(strForm, "user", gUser); //set the value for user
	setFormValue(strForm, "callback", gCallback); //set the value for the callback number
	setFormValue(strForm, "ani", gANI); //set the value for ani
	setFormValue(strForm, "international", (gInternational)?1:0); //set the value for international flag
	submitForm(strForm); //submits the appropriate form to navigate the user to the appropriate page.
}

//this function loads the states into the passed in drop down list in the passed in form
function loadStates(){

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Loading States...","<img src='images/loading.gif' border='0' />","None",[null]);	
	
	var request = new SimpleRequest();
	var strParams = "";
	strParams = "action=get_supported_states";
	request.connect(PROXY, "POST", strParams, processStates, "xml");
	return;
}

//This function is used to process the loadStates request
function processStates(xmlResponse){
	var response = new UTIResponse(xmlResponse);
	var aHandler = new Array(), strMessage = "";
	if(response.status == "error"){ //if there was an error with the keep session alive request
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		strMessage = "Error " + response.errorid + ": " + response.errormessage;
		messagebox.showMessage("<font color='red'>Error.</font>",strMessage,"OKOnly",["handleKeepSessionAlive()"]);	
	}else{ //the request was processed successfully
		if(window.location.href.substr(window.location.href.lastIndexOf('/')+1) == "Profile.asp"){
			var strForm = "profile_form", strSelect = "selStates";
		}else if(window.location.href.substr(window.location.href.lastIndexOf('/')+1) == "ManageUsers.asp"){
			var strForm = "manageusers_form", strSelect = "state";
		}
		if(response.states!=null && response.states!=undefined && response.states!=""){
			for(var i=0; i<response.states.length; i++){
				var strValue = response.states[i]["abbreviation"];
				var strText = response.states[i]["name"];
				addOption(strForm, strSelect, strValue, strText);
			}
		}else{
			var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
			messagebox.showMessage("Loading Error","The states could not be loaded. Please refresh the page to try and load the states again.","OkOnly",null);		//SHOULD LOG THE ERROR SOMEWHERE FOR DEBUGGING PURPOSES?
		}
	}
	
	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.closeMessage();	
	
	//if the page is profile.asp, then call loadProfile()
	if(window.location.href.substr(window.location.href.lastIndexOf('/')+1) == "Profile.asp"){
		loadProfile(); //this function is located in the profile.js
	}
	
	if (gFillFormName == "edituser") {
		requestEditUser(gFillFormUserID);
	}
	return;
}

/**********************************************************************************/
/** KEEP SESSION ALIVE                                                           **/
/**********************************************************************************/
//This function is used to start the timer that keeps the session alive
function startSessionInterval(){
	bKeepSessionAlive = true; //only necessary if using setTimeout...
	if(gUserID!="" && gSessionID!=""){//if there is a session and a user, then keep the session alive...
		keepSessionAlive();
	}
}

//This function keeps the user's session alive...
function keepSessionAlive(){
	if(bKeepSessionAlive){ //only necessary in the setTimeout version
		var request = new SimpleRequest();
		var strParams = "";
		strParams = "action=keep_session_alive";
		strParams += "&userid=" + gUserID;
		strParams += "&sessionid=" + gSessionID;

		request.connect(PROXY, "POST", strParams, processKeepSessionAlive, "xml");
	}
}

//This function is used to process the logout request
function processKeepSessionAlive(xmlResponse){
	if(bKeepSessionAlive){ //only necessary in the setTimeout version
		var response = new UTIResponse(xmlResponse);
		var aHandler = new Array(), strMessage = "";
		if(response.status == "error"){ //if there was an error with the keep session alive request
			//log the user out if there is an issue with checking for a call because the session will expire if the webservice doesn't work, or the session has already expired which is the reason why the webservice errored out
			strTitle = "<font color='red'>Session Error (#" + response.errorid + ")</font>";
			strMessage = "Due to a issue with your session you will be logged out of the system.  Please log back in and try again.";
			var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
			messagebox.showMessage(strTitle,strMessage,"OkOnly",['logout();']);	
		}else{ //the request was processed successfully

		}
		setTimeout('keepSessionAlive()',iSessionTimeout); //only necessary in the setTimeout version
	}
}

/**********************************************************************************/
/** CHECK FOR INCOMING CALL                                                      **/
/**********************************************************************************/
//This function is used to start the timer that checks for incoming calls
function startCheckForCall(){
	bCheckForCall = true;
	if(gUserID!="" && gSessionID!=""){//if there is a session and a user, then check for an incoming call...
		checkForCall(); 
	}
}

//This function checks for an incoming call
function checkForCall(){
	if(bCheckForCall){
		var request = new SimpleRequest();
		var strParams = "";
		strParams = "action=check_for_incoming_call";
		strParams += "&userid=" + gUserID;
		strParams += "&sessionid=" + gSessionID;

		request.connect(PROXY, "POST", strParams, processIncomingCall, "xml");
	}
}

//This function is used to process the check for an incoming call
function processIncomingCall(xmlResponse){
	window.status = Date();
	if(bCheckForCall){
		var response = new UTIResponse(xmlResponse);
		var aHandler = new Array(), strMessage = "";
		if(response.status == "error"){ //if there was an error with the check for incoming call... do nothing...
			startSessionInterval();
			if (response.errorid == 160) {
				gCallback = "";
				document.getElementById("divWaitingForCall").style.display = "none";
				document.getElementById("divReceiveACall").style.display = "none";	
				document.getElementById("divFirstLink").innerHTML = "<li><a href=\"javascript:goTo('waitforcall');\">Waiting For Call</a></li>";		
				if (gPage=="placecall") {
					navigateWaitForCall();
				}
			}
		}else{ //the request was processed successfully
			if (response.message == "checkincomingcall=true") { // If there was an incoming call then it should prompt if the user wants to accept the incoming call...
				bEndCall = false;
				bKeepSessionAlive = false;
				bCheckForCall = false;
				
				gSessionID = response.sessionid;
				gCallID = response.callid;
				gMessageID = (response.messagefragmentid=="" || response.messagefragmentid==null || response.messagefragmentid==undefined)?0:response.messagefragmentid; //sets it to 0 or the messagefragmentid
				gANI = response.ani;
				gDialed = response.dialed;
				
				showConsole(); //this will allow the application grab the messages from the CA
				
			} else { // Otherwise if there isn't an incoming call, then do nothing...
				gCallback = response.ani;
				document.getElementById("displayCallback").innerHTML = (gInternational)?formatIntlPhone(gCallback,""):formatPhone(gCallback,""); // display the new callback number...
				if(window.location.href.substr(window.location.href.lastIndexOf('/')+1)=="PlaceCall.asp" && document.placecall_form.ani.value==""){
					document.placecall_form.ani.value = (gInternational)?formatIntlPhone(gCallback,""):formatPhone(gCallback,"");
				}
						
				document.getElementById("divWaitingForCall").style.display = "block";
				document.getElementById("divReceiveACall").style.display = "block";	
				document.getElementById("divFirstLink").innerHTML = "<li><a href=\"javascript:goTo('placecall');\">Place Call</a></li>";
			}
		}
		if(bCheckForCall){
			setTimeout('checkForCall()', iCheckCallTimeout); // only necessary for setTimeout version
		}
	}
}

/**********************************************************************************/
/** CONSOLE FUNCTIONS                                                            **/
/**********************************************************************************/
//this function is used to change the font in the captions
function setCaptionFont(){
	var strFontFamily = "tahoma", strFontSize = "medium", strFontColor = "black", strBackgroundColor = "white";
	strFontFamily = document.getElementById("selFontFamily").value; //get font family from the form value
	strFontSize = document.getElementById("selFontSize").value; //get the font size from the form value
	strFontColor = document.getElementById("selFontColor").value; //get the foreground color from the form value
	strBackgroundColor = document.getElementById("selBackground").value; //get the background color from the form value
	
	var elCaption = document.getElementById("consolecaptions");
	elCaption.style.fontWeight = "normal";
	elCaption.style.fontSize = strFontSize;
	elCaption.style.fontFamily = strFontFamily; //set the font
	elCaption.style.color = strFontColor; //set the foreground color
	elCaption.style.background = strBackgroundColor; //set the background color	
	
	document.getElementById('consolecaptions').scrollTop = document.getElementById('consolecaptions').scrollHeight; //scroll to the bottom of the screen

}

function saveUserSettings(){
	var strFontFamily = "tahoma", strFontSize = "medium", strFontColor = "black", strBackgroundColor = "white";
	strFontFamily = document.getElementById("selFontFamily").value; //get font family from the form value
	strFontSize = document.getElementById("selFontSize").value; //get the font size from the form value
	strFontColor = document.getElementById("selFontColor").value; //get the foreground color from the form value
	strBackgroundColor = document.getElementById("selBackground").value; //get the background color from the form value

	var url = "../services/usersettings_update.asp";
	var request = new SimpleRequest();
	var strParams = "";
	strParams += "uid=" + gUserID;
	strParams += "&sid=" + gSessionID;
	strParams += "&userid=" + gUserID;
	strParams += "&fontface=" + strFontFamily;
	strParams += "&fontsize=" + strFontSize;
	strParams += "&fontcolor=" + strFontColor;
	strParams += "&background=" + strBackgroundColor;

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Applying user settings...","<img src='images/loading.gif' border='0' />","None",[null]);	
	
	request.connect(url, "POST", strParams, processUpdateUserSettings, "xml");
}

function processUpdateUserSettings(xmlResponse) {

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.closeMessage();
	
	var response = new UTIResponse(xmlResponse);
	if (response.status != "success") {
		strTitle = "<font color='red'>Update User Settings Error (#" + response.errorid + ")</font>";
		strMessage = response.errormessage;
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage(strTitle,strMessage,"OkOnly",null);		
	}
}

function setConsoleUserSettings() {
	var url = "../services/users_list.asp";
	var request = new SimpleRequest();
	var strParams = "";
	strParams += "uid=" + gUserID;
	strParams += "&sid=" + gSessionID;
	strParams += "&userid=" + gUserID;
	
	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Updating User Settings...","<img src='images/loading.gif' border='0' />","None",[null]);	
	
	request.connect(url, "POST", strParams, processConsoleUserSettings, "xml");
}
	
function processConsoleUserSettings(xmlResponse) {

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.closeMessage();	
	
	var response = new UTIResponse(xmlResponse);

	if (response.status == "success") {
		var strFontFamily = "tahoma", strFontSize = "medium", strFontColor = "black", strBackgroundColor = "white";
		strFontFamily = response.users[0].fontface; //get font family from the form value
		strFontSize = response.users[0].fontsize; //get the font size from the form value
		strFontColor = response.users[0].fontcolor; //get the foreground color from the form value
		strBackgroundColor = response.users[0].backgroundcolor; //get the background color from the form value
		
		var elCaption = document.getElementById("consolecaptions");
		elCaption.style.font = "normal " + strFontSize + " " + strFontFamily; //set the font
		elCaption.style.color = strFontColor; //set the foreground color
		elCaption.style.background = strBackgroundColor; //set the background color	
		
		document.getElementById("selFontFamily").value = strFontFamily;
		document.getElementById("selFontSize").value = strFontSize;
		document.getElementById("selFontColor").value = strFontColor;
		document.getElementById("selBackground").value = strBackgroundColor;
		
	} else {
		strTitle = "<font color='red'>User Error (#" + response.errorid + ")</font>";
		strMessage = response.errormessage;
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage(strTitle,strMessage,"OkOnly",[null]);	
	}

	//get the messages from the CA
	startGettingMessages();

}
	

//This functions ends an existing call
function endCall(){
	bGetMessage = false;
	
	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Ending Call...","<img src='/images/loading.gif' border='0' />","none",null);
			
	if(document.getElementById("displayANI")){
		gCallback = numbersOnly(document.getElementById("displayCallback").innerHTML);
	}
	
	var request = new SimpleRequest();
	var strParams = "";
	strParams = "action=end_call";
	strParams += "&callback=" + gCallback;
	strParams += "&userid=" + gUserID;
	strParams += "&sessionid=" + gSessionID;
	
	request.connect(PROXY, "POST", strParams, function(request){processEndCall(request)}, "xml"); //this is the call to make the request
}

//used to process the return from the endCall request - this reuses the set_callback webservice because that ends the call and creates a new waiting for call session which is what we want to do...
function processEndCall(xmlResponse){

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.closeMessage();

	var response = new UTIResponse(xmlResponse);
	var aHandler = new Array(), strMessage = "";
	if(response.status == "error"){ //if there was an error with the request
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage("Ending Error","Error " + response.errorid + ": " + response.errormessage,"OKOnly",null);
	}else{ //the request was processed successfully
		gCallID = response.callid; //set the global callid to the active callid
		changeDisplayEndCall();
	}
}

function changeDisplayEndCall(){
	var messagebox = new SimpleMessageBox("messagebox","messageboxscreen"); //what is this for?
	messagebox.closeMessage(); //what is this for?
	//add end call message to the console window...
	var strMessage = "<br/><br/>--- CONVERSATION ENDED LC ---<br/>Call terminated LC. Please hang up the phone.";
	addConsoleMessage(strMessage);
	
	startCheckForCall(); //start checking for incoming calls
	
	//enable scrolling on the caption window.
	var elCaptions = document.getElementById("consolecaptions");
	elCaptions.style.overflowY = "scroll"; //this enables the vertical scroll bar to allow the person to review the conversation...
	elCaptions.scrollTop = elCaptions.scrollHeight; //scroll to the bottom of the screen
	
	//this ensures that the "end call" button is hidden and the "close captions" button is displayed
	document.getElementById("btnEndCall").style.display = "none";
	document.getElementById("btnCloseCaptions").style.display = "inline";
	
	window.scrollTo(0,0);
	window.onscroll = function(){window.scrollTo(0,0);};
	window.onresize = function(){setContent("messagebox");setContent("console");setContent("loading");}; //This tells the browser to center the messagebox to the middle of the screen when the browser gets resized
	setContent("console");
}

//used to set the callback number for the user if the call is ended from the gateway...
function setEndCallCallbackNumber(){
	bGetMessage = false;
	
	var request = new SimpleRequest();
	var strParams = "";
	strParams = "action=wait_for_call";
	strParams += "&callback=" + gCallback;
	strParams += "&userid=" + gUserID;
	strParams += "&sessionid=" + gSessionID;
	
	request.connect(PROXY, "POST", strParams, function(request){processEndCallCallback(request)}, "xml"); //this is the call to make the request
}

//used to process the return from the setCallbackNumber request
function processEndCallCallback(xmlResponse){
	var response = new UTIResponse(xmlResponse);
	var aHandler = new Array(), strMessage = "";
	if(response.status == "error"){ //if there was an error with the request, go to wait for call page.
		processCallbackError();
	}else{ //the request was processed successfully, go to place call page.
		gCallback = response.ani; //set the global callback number to the number returned
		changeDisplayEndCall();
	}
}

//used to process an error from processing the set callback error
function processCallbackError(){
	gCallback = "";
	changeDisplayEndCall();
}

/**********************************************************************************/
/** GET MESSAGES FOR A CALL                                                      **/
/**********************************************************************************/
//This function is used to start the timer that keeps the session alive
function startGettingMessages(){
	bGetMessage = true;
	if(gUserID!="" && gSessionID!=""){//if there is a session and a user, then keep the session alive...
		getMessages();
	}
}

//This function is used to check for new messages from the CA
function getMessages(){
	if(bGetMessage){
		var request = new SimpleRequest();
		var strParams = "";
		strParams = "action=get_message";
		strParams += "&userid=" + gUserID;
		strParams += "&sessionid=" + gSessionID;
		strParams += "&callid=" + gCallID;
		strParams += "&messageid=" + gMessageID;

		request.connect(PROXY, "POST", strParams, processGetMessages, "xml");
	}
}

//This function is used to process the logout request
function processGetMessages(xmlResponse){
	if(bGetMessage){
		var response = new UTIResponse(xmlResponse);
		var aHandler = new Array(), strMessage = "";
		if(response.status == "error"){ //if there was an error with getting the message... ignore for now
			//log the user out if there is an issue with checking for a call because the session will expire if the webservice doesn't work, or the session has already expired which is the reason why the webservice errored out
			showMessage("Get Messages Error", "Error " + response.errorid + ": " + response.errormessage, "OKOnly", ["handleLogoutError()"]);
		}else{ //the request was processed successfully
			if(response.message == "getmessages=callended"){ //the call has ended
				bEndCall = true;
			}else{
				//set up values for next get message request...
				gCallID = response.callid;
				gMessageID = response.messagefragmentid;
				gANI = response.ani;
				gDialed = response.dialed;
			}
			
			//add message to the console...
			strMessage = stripMessage(response.messagefragment);
			if(strMessage!="" && strMessage!=null && strMessage!=undefined){
				addConsoleMessage(strMessage);
			}
		}
		if(bEndCall){
			setEndCallCallbackNumber();
		}
		if(bGetMessage){ //only run if bGetMessage is still true
			setTimeout('getMessages()', iGetMessageTimeout);
		}
	}
}

//This function is used to strip the message of ~ for breaks in the console...
function stripMessage(strMessage){
	strMessage = new String(strMessage);
	var strReplace = new String("<br/>");
	
	strMessage = strMessage.replace(/~ ~/gi, strReplace); //replaces "~ ~" with "<br/>"
	strMessage = strMessage.replace(/~~/gi, strReplace); //replaces "~~" with "<br/>"
	strMessage = strMessage.replace(/~/gi, strReplace); //replaces "~" with "<br/>"
	
	return (strMessage==null || strMessage==undefined)?"":strMessage;
}

//used to prompt the user for a phone number
function getPhoneNumber(bLogin){
	if (gInternational) {
		strMessage = 'What number do you want to use to place and receive calls? (xxx-xxx-xxxx)';
		aHandler = ["setCallbackNumber()"];
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage("My Telephone Number",strMessage,(bLogin)?"intlphone":"intlphonecancel",aHandler);	
	} else {
		strMessage = 'What number do you want to use to place and receive calls? (xxx-xxx-xxxx)';
		aHandler = ["setCallbackNumber()"];
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage("My Telephone Number",strMessage,(bLogin)?"phone":"phonecancel",aHandler);
	}
}

//used to set the callback number for the user
function setCallbackNumber(){
	var elMessageError = document.getElementById("messageerror");
	gCallback = document.getElementById('txtmessagebox1').value; //sets the global ANI to the entered phone number
	if((gInternational)?validateIntlPhone(gCallback,"messageerror"):validateUSPhone(gCallback,"messageerror")){
		bCheckForCall = false;
		
		var request = new SimpleRequest();
		if(request == null){
			var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
			messagebox.showMessage("Waiting for Call","Unable to create request.","OKOnly",null);		
			return;
		}
		var params = "";
		params = "action=wait_for_call";
		params += "&callback=" + gCallback;
		params += "&userid=" + gUserID;
		params += "&sessionid=" + gSessionID;
			
		request.connect(PROXY, "POST", params, processCallback,"xml"); //this is the call to make the request
		
	}else{
		getPhoneNumber();
		var elMessageError = document.getElementById('messageerror');
		if(elMessageError!=null){ //if the element exists
			strMessage = "Please enter in a valid phone number." + (gInternational)?"":" (xxx-xxx-xxxx)"; //display the error message.
			var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
			messagebox.showMessage(" ",strMessage,"OkOnly",aHandler);	
		}
	}
}

//used to process the return from the setCallbackNumber request
function processCallback(xmlResponse){
	var response = new UTIResponse(xmlResponse);
	var aHandler = new Array(), strMessage = "";
	if(response.status == "error"){ //if there was an error with the request, go to wait for call page.
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage("Set Callback Number Error","Error " + response.errorid + ": " + response.errormessage,"OKOnly",null);
	}else{ //the request was processed successfully, go to place call page.
		gCallback = response.ani; //set the global callback number to the number returned
		
		if(window.location.href.substr(window.location.href.lastIndexOf('/')+1) == "WaitForCall.asp"){
			navigatePlaceCall();
			return;
		}
		
		document.getElementById("displayCallback").innerHTML = (gInternational)?formatIntlPhone(gCallback,""):formatPhone(gCallback,""); // display the new callback number...
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.closeMessage();	
		
		if(window.location.href.substr(window.location.href.lastIndexOf('/')+1) == "PlaceCall.asp"){
		document.placecall_form.ani.value = (gInternational)?formatIntlPhone(gCallback,""):formatPhone(gCallback,"");
		}
	}
	
	bKeepSessionAlive = false;
	startCheckForCall();
}

function disableForm(sForm) {

	var count = document.forms[sForm].elements.length;
	for (i=0; i<count; i++) {
		document.forms[sForm].elements[i].disabled=true; 
	}
	return;
}

function enableForm(sForm) {

	var count = document.forms[sForm].elements.length;
	for (i=0; i<count; i++) {
		document.forms[sForm].elements[i].disabled=false; 
	}
	return;
}



function showContacts(sType) {
	sContactType = sType;
	
	strTitle = "Contacts";
	strMessage = "<div id='addressbook-navigation'></div><br><div id='divAddressBook' style='height: 250px; overflow-y: auto; overflow-x: none;'>Loading...<br/><img src='images/loading.gif' border='0' /></div>";
	var messagebox = new SimpleMessageBox("addressbook","addressbookscreen");
	messagebox.showMessage(strTitle,strMessage,"OkOnly",null);

	var request = new SimpleRequest();
	if(request == null){
		strMessage = "Unable to create request to check on the session";
		strTitle = "<font color='red'>Request Error</font>";
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage(strTitle,strMessage,"OkOnly",[null]);		
		return;
	}
	
	var url = "../services/contacts_list.asp";
	var params = "";
	params += "uid=" + gUserID;
	params += "&sid=" + gSessionID;
	params += "&userid=" + gUserID;
	request.connect(url, "POST", params, processAddressBook, "xml");	
}

function processAddressBook(xmlResponse) {
	var response = new UTIResponse(xmlResponse);
	var sContacts = "";
	var sBookmarkLetter = "?";
	var strLastnameLetters = "";
	
	if (response.contacts != null) {
		for (i=0;i<response.contacts.length;i++) {
				strLastnameLetters += response.contacts[i].lastname.substr(0,1).toUpperCase();
				
				if (response.contacts[i].lastname.substr(0,1).toUpperCase() != sBookmarkLetter) {
					sBookmarkLetter = response.contacts[i].lastname.substr(0,1).toUpperCase();
					sContacts += "<h3 class=\"legend-contacts\" style=\"font-size: 1em;\"><a name=\"" + sBookmarkLetter + "\">" + sBookmarkLetter + "</a></h3>";
					sContacts += "<div class=\"clear\"></div><!-- THIS IS A CSS HACK TO FORCE THE \"content\" ELEMENT ABOVE TO CONTAIN IT'S CHILD ELEMENTS THAT ARE FLOATING -->";
				}
		
				sContacts += "<fieldset class=\"fieldset-contacts\">";
				sContacts += "	<div class=\"form-row-contacts\">";
				if (response.contacts[i].firstname == "") {
					sContacts += "		<p class=\"contact-name\" style=\"font-size: 1em; float:left;\">" + response.contacts[i].lastname + "</p>";
				} else{
					sContacts += "		<p class=\"contact-name\" style=\"font-size: 1em; float:left;\">" + response.contacts[i].lastname + ", " + response.contacts[i].firstname + "</p>";
				}
				
				sContacts += "		<div class=\"clear\"></div><!-- THIS IS A CSS HACK TO FORCE THE \"content\" ELEMENT ABOVE TO CONTAIN IT'S CHILD ELEMENTS THAT ARE FLOATING -->";
				
				for (ii=0;ii<response.contacts[i].numbers.length;ii++) {
					sContacts += "		<p class=\"contact-number\" style=\"font-size: 1em;\"><a href=\"javascript: setPhone('" + sContactType + "','" + response.contacts[i].numbers[ii].phonenumber + "')\">" + response.contacts[i].numbers[ii].categoryname + ": " + formatIntlPhone(response.contacts[i].numbers[ii].phonenumber) + "</a></p>";
				}
				
				sContacts += "	</div>";
				sContacts += "</fieldset>";

		}
	} else {
		sContacts += "<center style='font-size:14px;'><br/>You have no contacts!<br/></center>";
	}
		
	document.getElementById("divAddressBook").innerHTML = sContacts + "<br/><br/><br/><br/><br/>";
	
	var strContactNavigation = "";
	
	for (i=1;i<27;i++) {
		if (strLastnameLetters.indexOf(String.fromCharCode(i+64))>-1) {
			strContactNavigation += "<a href=\"#" + String.fromCharCode(i+64) + "\">" + String.fromCharCode(i+64) + "</a> ";
		} else {
			strContactNavigation += String.fromCharCode(i+64) + " ";
		}
	}
	document.getElementById("addressbook-navigation").innerHTML = strContactNavigation;
}

function setPhone(sSet,sPhone) {
	if (sSet=="to") {
		document.getElementById("dialed").value = formatIntlPhone(sPhone);
	}

	if (sSet=="from") {
		document.getElementById("ani").value = formatIntlPhone(sPhone);
	}
	
	if (sSet == "txtmessagebox1") {
		document.getElementById("txtmessagebox1").value = formatIntlPhone(sPhone);
	}
	
	var messagebox = new SimpleMessageBox("addressbook","addressbookscreen");
	messagebox.closeMessage();
}
