/**********************************************************************************/
/** © 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.                                                                       **/
/**********************************************************************************/
/**********************************************************************************/
/** FUNCTIONS USED ON THE LOGIN/INDEX PAGE                                       **/
/**********************************************************************************/
//called after page loads to setup defaults for the page...
function load(){
	//set the page focus to the username field
	if(document.getElementById("username")){
		document.getElementById("username").focus();
	}

	//used to validate the username and password to only allow certain characters in their fields
	var strForm = 'login_form'; //This is the form that the elements that need to be validated belong to.
	var aValidateElements = new Array("username", "password"); //These are the elements that need to be validated in the form
	aCheckKey["username"] = new Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@._-", false, "error"); //This defines the validation for the "username" field
	aCheckKey["password"] = new Array("!@#$%^&*()_ ", true, "error"); //This defines the validation for the "password" field
	for(var i=0; i<aValidateElements.length; i++){
		var el = document.forms[strForm].elements[aValidateElements[i]];
		//This statement adds the keyup event to the elements
		if(el.addEventListener){
			el.addEventListener('keyup', checkKey, false);
		}else if (el.attachEvent){
			el.attachEvent('onkeyup', checkKey);
		}
	}
}

//used to login
function login(){
	
	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Logging In...","<img src='images/loading.gif' border='0' />","None",[null]);	

	
	var OSName="Unknown OS";
	if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
	if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
	if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
	if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

	var request = new SimpleRequest();
	var strParams = "", strForm = "login_form";
	strParams = "action=login";
	strParams += "&forcelogout=" + document.forms[strForm].elements['force_logout'].value;
	strParams += "&username=" + document.forms[strForm].elements['username'].value;
	strParams += "&password=" + document.forms[strForm].elements['password'].value;
	strParams += "&remember=" + ((document.forms[strForm].elements['remember'].checked)?document.forms[strForm].elements['remember'].value:"0");
	strParams += "&application=" + navigator.appName;
	strParams += "&hardware=PC";
	strParams += "&operatingsystem="+OSName;
	request.connect(PROXY, "POST", strParams, function(request){processLogin(request);},"xml");
}

//used to process the return from the login request.
function processLogin(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 login request
		var strForm = "login_form";
		setFormValue(strForm,'force_logout',0); //changes the force_logout value to 0 because there was a problem logging into the system
		
		switch(response.errorid){
			case "112": //if the error is user already logged in, need to ask if the user wants to login anyways.
				strMessage = "<p class='required' style='font-weight:bold;'>Your account seems to be logged in from your last session.</p>Do you wish to end the session and end any calls that may be in progress?";
				aHandler = ["forceLogin()",null];
				var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
				messagebox.showMessage("Already Logged In",strMessage,"YesNo",aHandler);
				break;
				
			default: //all other errors, just display the OKOnly message to let the user know that there was an issue.
				strMessage = "Error " + response.errorid + ": " + response.errormessage;
				//aHandler = ['eError="error";if(eError!=undefined && eError!=null && eError!=""){document.getElementById(eError).innerHTML = "";document.getElementById(eError).style.display = "none";}'];
				var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
				messagebox.showMessage("Login Error",strMessage,"OKOnly",aHandler);
				break;

		}
		
	} else { //the request was processed successfully
		// set global variables
		gUserID = response.userid; //sets the global userid
		gSessionID = response.sessionid; //sets the global sessionid
		gUser = response.user; //sets the global user
		gInternational = response.international;
		if(response.message.toLowerCase() == "is911=true"){ //connect to an active emergency call
			//go to place call with the active callID...
			gANI = response.ani;
			gDialed = response.dialed;
			gCallID = response.callid; //set the global callid to the active callid
			
			//Go to Place Call page - this is done when their is a successfull return from the wait for call request.
			var strForm = "place_call_form";
			setFormValue(strForm, "ani", gANI); //set the value for ani
			setFormValue(strForm, "dialed", gDialed); //set the value for dialed
			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
			
			submitForm("place_call_form"); //submit place_call_form
		}else{ //start a new session
			setLocalSession();
		}
	}
}

function setLocalSession() {

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.showMessage("Setting Session...","<img src='images/loading.gif' border='0' />","None",[null]);	
	
	var request = new SimpleRequest();
	var url = "../services/session_set.asp";
	var strParams = "";
	strParams = "uid=" + gUserID;
	strParams += "&sid=" + gSessionID;
	request.connect(url, "POST", strParams, processLocalSession,"xml");
	return;
}

function processLocalSession(xmlResponse) {

	var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
	messagebox.closeMessage();	
	
	var response = new UTIResponse(xmlResponse);
	if (response.status == "success") {
		startSessionInterval(); //ensure that the session stays alive while the user is trying to enter their phone number...
		getPhoneNumber(true);
	} else {
		strTitle = "<font color='red'>Session Error (#" + response.errorid + ")</font>";
		strMessage = " " + response.errormessage;
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage(strTitle,strMessage,"OkOnly",null);		
		bKeepsessionAlive = false;
	}

}

//used to force the user to login, if the user has not ended their session properly
function forceLogin(){
	var strForm = "login_form";
	setFormValue(strForm,'force_logout',1); //changes the force_logout value to 1 to close all active sessions for the user
	login();
}

//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")){
		
		var messagebox = new SimpleMessageBox("loadingbox","loadingboxscreen");
		messagebox.showMessage("Setting your telephone number...","<img src='images/loading.gif' border='0' />","None",[null]);	
	
		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, processCallback, "xml"); //this is the call to make the request
		
	}else{
		getPhoneNumber();
		var elMessageError = document.getElementById('messageerror');
		if(elMessageError!=null){ //if the element exists
			elMessageError.style.display = "block"; //show the element
			elMessageError.innerHTML = "Please enter in a valid phone number." + (gInternational)?"":" (xxx-xxx-xxxx)"; //display the error message.
		}
	}
}

//used to process the return from the setCallbackNumber request
function processCallback(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, go to wait for call page.
		strMessage = "Error " + response.errorid + ": " + response.errormessage;
		aHandler = ["processCallbackError()"];
		var messagebox = new SimpleMessageBox("messagebox","messageboxscreen");
		messagebox.showMessage("Set Callback Number Error",strMessage,"OkOnly",aHandler);	
	}else{ //the request was processed successfully, go to place call page.
		gCallback = response.ani; //set the global callback number to the number returned
		navigatePlaceCall();
	}
}

//used to process an error from processing the set callback error
function processCallbackError(){
	gCallback = "";
	navigatePlaceCall();
}
