/***************************************************************************
 [ActiveAgentUI.js]
 
 Copyright (C) 2004 Next IT Corporation, Inc. Spokane, WA. All Rights Reserved. 
 This document is confidential work and intellectual property of Next IT 
 Corporation. Permission to copy, distribute or use any portion of this file 
 is prohibited without the express written consent of Next IT Corporation.

*****************************************************************************/

//*************************//
// JAVASCRIPT OBJECT CLASS //
//*************************// 

// ActiveAgentUI is a javascript object class.  Its main purpose is to have all UI
// that the bot will interface with or possibly alter be represented.  Actual page alteration
// and dealing with a bot response is handled by other classes.  This is more for setting up
// button events, enter key presses, and playing/stopping the flash via flashObject.js

// WRITTEN BY:		Roth Fouty, Chase Rogers
// ARCHITECTED BY:	Roth Fouty	

// Constructor
function ActiveAgentUI( inputID, responseID )
{
	this.inputID = inputID;
	this.responseID = responseID;
	this.input = null;
	this.response = null;
	this.playSound = true;
	this.parent = parent.opener;
	this.doImpasseTxt = "&nbsp;&nbsp;<a id=\"help_link\" class=\"bodyln\" href=\"#\" onclick=\"aaUI.DoImpasse();return false;\">Live Chat</a>";	
	this.returnToBotTxt = "<span class=\"experttitle\">---------------<br>Conversation has been returned to Spike<br>---------------<br></span>";
	this.isInImpasse = false;
	
	this.onDoImpasse = null;	//callback function to do specific ui side things
	this.onEndImpasse = null;	//callback function
	
	this.doTraining = true;
	
	this.botIDCookieName = "GuBrainID";
	chgr = new Changer();
	
	this.lastBrainResponse = null;	//will hold the last response from the bot
	this.userInput = null;			//will hold the userinput being submitted to the bot
	
	this._doingSearch = false;
	
	this._showTopicLink = "";		//we show the link instead of doing the redirect
	
	this._inputCount = 0;		//this keeps track of the number of inputs a user has put in
	this._loggedIn = false;
	this._impasse = null;
	
	this._isCleanedup = false;
	
	//impasse stuff
	this._sound = true; //for tracking sound toggle
	this._question = ""; 	
	this.liveChat = false;
	this._impasseConnected = false;
	this.bioUrl = ""; //URL to recruiters bio info (from Army?)	
	
	this.wn = null;
	this.respCount = 0;
	
	this._moreUnits = "";
	this._isRelatedLinkClick = false;
	this._relatedLinkLabel = "";
	this._webLinks = "";
	
	//email verification fields
	this._fname = "";
	this._lname = "";
	this._email = "";
	this._gradyr = "";
	this._alumni = false;
	this._zip = "";
	
	// We need to set up the load event to call our load function.
	// from a Javascript Standpoint, this is the 'start' off the code.
	// But the C# side registers startUpScripts, which also spawn object
	// creation and do a lot of variable initilization/usage.
	if( window.attachEvent )	// aka if IE
	{
		window.attachEvent( "onload", this.LoadBot );
		window.attachEvent("onunload", this.UnloadBot );
	}
	else if (window.addEventListener)	// aka if not IE
	{
		window.addEventListener("load", this.LoadBot, false);
		window.addEventListener("unload", this.UnloadBot, false);
	}	
};

ActiveAgentUI.prototype.DoFaq = function( question )
{
	this.userInput = new UserInput( question, false, user );
	this.userInput.Type = 'Typed';
	
	if ( this.isInImpasse && this._impasse != null )
		this._impasse.SendResponse();
	else
		this.GetResponse( this.userInput );
	
};

//Method to do the 'grunt-work' of changing a tabbed html form 
//Takes the desired tab to change TO as arg.
ActiveAgentUI.prototype.TabChanger = function( tab )
{
	if ( tab == "tips")
	{	
		
		var temp = document.getElementById( 'tab' ).src = 'images/bot/tab_chat_tips.gif';
		var temp2 = document.getElementById( 'help' ).style.display = 'block';
		var temp2 = document.getElementById( 'faq' ).style.display = 'none';
		currentTab = 'tips';		
	}
	else
	{	
		var temp = document.getElementById( 'tab' ).src = 'images/bot/tab_faqs.gif';
		var temp2 = document.getElementById( 'faq' ).style.display = 'block';
		var temp2 = document.getElementById( 'help' ).style.display = 'none';
		currentTab = 'faq';		
	}
};

ActiveAgentUI.prototype.Login = function()
{
	var badFlag = false;
	var error_msg = "The following items require attention:\n---------------------------------------------\n";
	
	//Email verification - NEED a valid email
	var my_emailregexp = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	var email_in = new String( document.getElementById( 'Text3' ).value );
	if ( email_in != null && email_in != "" )
	{
		if ( email_in.match( my_emailregexp ) )
		{ 
			this._email = email_in;		
		}
		else
		{
			badFlag = true;
			error_msg += "Invalid Email address\n";
		}
	}
	else
	{
		badFlag = true;
		error_msg += "Email Address Required\n";
	}
	
	//First Name verification - Must be non-blank
	var fname_in = document.getElementById( 'Text1' ).value;
	if ( fname_in != "" && fname_in != null && fname_in.length < 11 )
		this._fname = fname_in;
	else
	{
		badFlag = true;
		error_msg += "First Name Required\n";
	}
	
	//Last Name verification - Must be non-blank
	var lname_in = document.getElementById( 'Text2' ).value;
	if ( lname_in != "" && lname_in != null && lname_in.length < 25 )
		this._lname = lname_in;
	else
	{
		badFlag = true;
		error_msg += "Last Name Required\n";
	}	
	
	var cbAlumni = document.getElementById( 'Checkbox1' );
	
	if ( !cbAlumni.checked )
	{
		//Grad Year verification - 2 or 4 digits
		var my_gradyrregexp = /^(\d{4}|\d{2})$/;
		var gradyr_in = new String( document.getElementById( 'Text4' ).value );
		if ( gradyr_in.match( my_gradyrregexp ) )
		{
			this._gradyr = gradyr_in;
		}
		else
		{
			badFlag = true;
			error_msg += "Invalid Graduation Year\n";
		}
		this._alumni = true;			
	}
	else
		this._alumni = false;
		
	//Zipcode verification - 5 or 5 + 4 extension
	var my_zipregexp = /\d{5}(-\d{4})?/;
	var zip_in = new String( document.getElementById( 'Text5' ).value );
	if ( zip_in != null && zip_in != "" )
	{
		if ( zip_in.match( my_zipregexp ) )
		{ 
			this._zip = zip_in;			
		}
		else
		{
			badFlag = true;
			error_msg += "Invalid Zipcode\n";
		}
	}
	else
	{
		badFlag = true;
		error_msg += "Zipcode Required\n";
	}
	
	//Validation Test - one alert fits all
	if ( badFlag )
	{
		//alert( 'One (or more) required field is missing or invalid.' );
		alert( error_msg );
	}
	else
	{
		//Set user info cookie
		DelCookie( this.botIDCookieName );
		var usr = agent.DoLogin( this._fname, this._lname, this._email, this._gradyr, this._zip, this._alumni );
		this.ProcessLogin( usr );
				
		//Switch to Welcome div
		var tab = document.getElementById( 'main_tab' ).src = "images/bot/tab_welcome.gif";//change to "welcome" tab
		var loginStyle = document.getElementById( 'login' ).style.display = "none";//hide login ctrl
		var welcomeStyle = document.getElementById( 'welcome' ).style.display = "block";//reveal the 'welcome' div
		var userLogin = document.getElementById( 'logLink' ).innerHTML = "Logout";
		
		this._loggedIn = true;
		this._inputCount = 0;		
	}
};
;
ActiveAgentUI.prototype.ProcessLogin = function( gUser )
{
	if ( gUser != null )
	{
		var temp = document.getElementById( 'lblResponse' );
		temp.innerHTML = "";
		
		user = new User();		
		user.BrainID = gUser.BrainID;
		
		createCookie( this.botIDCookieName, user.BrainID, 365);		
		aaUI.HandleAppEvent( gUser.UserType, gUser.FirstName, gUser.BannerID );		
	}
};

function ResetFields()
{
	var fnameField = document.getElementById( 'Text1' );
	fnameField.value = "";
	
	var lnameField = document.getElementById( 'Text2' );
	lnameField.value = "";
	
	var emailField = document.getElementById( 'Text3' );
	emailField.value = "";
	
	var gradyrField = document.getElementById( 'Text4' );
	gradyrField.value = "";
	
	var zipField = document.getElementById( 'Text5' );
	zipField.value = "";
	
	var alumniField = document.getElementById( 'Checkbox1' );
	alumniField.checked = false;
};

ActiveAgentUI.prototype.CloseArmyAgent = function( closeWindow )
{
	if ( this.isInImpasse && this._impasse != null )
	{
		this._impasse.EndChat();	
	}
	
	agent.AgentCleanup( user.BrainID );	
	
	this._isCleanedup = true;
	
	DelCookie( "GuBrainID" );
	DelCookie( "GuUserStatus" );
	
	if( closeWindow )
		self.close();
};

function DelCookie( name )
{
	try
	{
		var cook = name
		var path = "/";
		var domain = "";
		document.cookie = cook + "=" +( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
	catch(e){}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

ActiveAgentUI.prototype.IssueAppCall = function(name, params)
{
	if ( gFlashObject == null )
	{
		gFlashObject = new FlashObject("flashSpan");
		if( this.playWelcome )
			gFlashObject.StartFlash("swf/welcome1.swf", "BrainAudioFile");
	}
	
	if( name == "ReturnUser" || name == "ReturnUserAutoLoggedIn" )
	{
		_returnUser = true;
	}
		
	var input = "AppEvent " + name;
	if( params.length > 0 )
	{
		for( var i = 0; i < params.length; i++ )
			input += " " + params[i];
	}
	else
	{
		input += " " + params;					
	} 	
	
	var old = GetUserInput().value;
	GetUserInput().value = input;	
	this.userInput = new UserInput( GetUserInput().value, true, user );
	
	aaUI.GetResponse(this.userInput);
	
	GetUserInput().value = old;
};

function GetUserInput()
{
	return document.getElementById('tbInput');
};

//this function will clean up and persist any information that needs to live through the next request
ActiveAgentUI.prototype.UnloadBot = function()
{
	if( !aaUI._isCleanedup )
	{
		aaUI.CloseArmyAgent( false );
	}
};

// This function sets our sound variables, plays the defaultTTS if no cookie is set, and
// attempts to play any bot response set in the cookies.
ActiveAgentUI.prototype.LoadBot = function()
{
	try
	{
		aaUI.SetInputResponse();
		aaUI.HookBotEnter();		
	}
	catch(e)
	{		
	}	
};

ActiveAgentUI.prototype.SetInputResponse = function()
{
	if( this.input == null && this.inputID.length > 0 )
		this.input = document.getElementById( this.inputID );
	if( this.response == null && this.responseID.length > 0 )
	{
		this.response = document.getElementById( this.responseID );
	}
};

// Makes sure our sound variables are set properly.
ActiveAgentUI.prototype.SetTTSFlag = function()
{
	aaUI.ToggleSound();		
};

// Get for the text of the input element.  value is cross-browser.
ActiveAgentUI.prototype.GetInput = function()
{
	this.SetInputResponse();	
	var str = this.input.value;
	str = trim(str);
	return str;	
};

function trim(s) { return (s != null)?s.replace(/^\s*|\s*$/g,""):s; }

// Sets innerHtml of the response element.
ActiveAgentUI.prototype.SetResponse = function( input )
{
	try
	{
		if( this.response.offsetHeight < 25 && this.response.offsetHeight != 0 )
		{
			this.response.parentNode.parentNode.style.height = "42px";
		}
	}
	catch(e)
	{}
	
	try
	{
		// Scroll to bottom of this.response
		this.ScrollResponse();
		
		// Get the height and scroll positions before we set the Input
		var myParentHeight = this.response.offsetParent.offsetHeight;
		var myBeforeHeight = this.response.parentNode.scrollTop;
		
		// Set the Input
		this.SetInputResponse();
		this.response.innerHTML += input;
		
		// Scroll to bottom of this.response
		this.ScrollResponse();
		
		// Get the height after we set the Input
		var myAfterHeight = this.response.parentNode.scrollTop;
		
		// Calculate if we need to go up from where we are, because the reponse could be longer than the window.
		if( (myAfterHeight - myBeforeHeight) > myParentHeight )
		{
			var offset = (myParentHeight-(myAfterHeight - myBeforeHeight) + 20);	// the 20 is for the top line, assuming text is 20 tall
			this.response.parentNode.scrollTop = ( this.response.parentNode.scrollTop + offset );
		}
	}
	catch(e)
	{}
};

// sets the text of the input element.  Mostly used to set the empty string after
// a bot response is sent, so it 'clears' out the text.
ActiveAgentUI.prototype.SetInput = function( input )
{
	this.SetInputResponse();
	this.input.value = input;
};

// Changes the url of the page.
ActiveAgentUI.prototype.ChangePage = function(url)
{
	if( url != null && url != "" )
	{
		try{
			if( this.parent.closed )		
			{		
				this.OpenParentWindow();
			}
		}
		catch(e)
		{
			this.OpenParentWindow();
		}		
		this.parent.location.href = url;		
		chgr.URLTest(url);
	}
};

// sets a few cookies and then changes the url.  Similar to the above function.
ActiveAgentUI.prototype.DoPageRedirect = function( brainRsp, userInput )
{
	if( brainRsp!= null && brainRsp.TopicUrl != null && brainRsp.TopicUrl.length > 0 )	//&& brainRsp.DoAppCallNavigation )
	{
		setCookie( "NextBrainResponse", brainRsp.Response );
		setCookie( "NextUserInput", userInput.Input );
		setCookie( "NextTTSPath", brainRsp.TextToSpeechUrl );
		setCookie( "NextITSituation", brainRsp.Situation );
		setCookie( "NextITUnitID", brainRsp.UnitID );
		
		this.ChangePage( brainRsp.TopicUrl );
		
		brainRsp.Response = brainRsp.Response + "&nbsp;<a href=\"#\" class=\"botln\" onclick=\"aaUI.ChangePage( '" + brainRsp.TopicUrl + "');return false;\" title=\"More Info\">" + ">>" + "</a>";				
	}
};

// Opens another window, and sets the parent variable to it, so we can
// mess with it.
ActiveAgentUI.prototype.OpenParentWindow = function()
{
	var w=screen.availWidth-238;
	var h=screen.availHeight;
	var popup = window.open('default.aspx', 'chatParWin', 'scrollbars=yes,' + "menubar,resizable,toolbar,status,resizeable,location=yes," + 'width=' + w + ',height=' + h);
	popup.moveTo(screen.availWidth-w,screen.availHeight-h);
	
	this.parent = popup;
	this.wn = this.parent;
	
	if ( window.focus )
		popup.focus();
};

// Setes the response scroll position.
ActiveAgentUI.prototype.ScrollResponse = function()
{
	if( this.response != null )
	{
		this.response.parentNode.parentNode.scrollTop = this.response.parentNode.parentNode.scrollHeight;						
	}	
};

// Simply allows for a training link on any given bot response, based off of the
// doTraining variable.
ActiveAgentUI.prototype.FormatResponse = function( userInput, brainRsp )
{
	var s = this.FormatNonBotResponse( userInput.Input, brainRsp.Response );
	
	if( this._showTopicLink.length > 0 )
		s += "&nbsp;" + this._showTopicLink;
	
	return s;
};

// Takes the response, and surrounds it with html to llok good on the page.
ActiveAgentUI.prototype.FormatNonBotResponse = function( userInput, brainRsp )
{
	var out = "";
	var flag = ( userInput.length > 0 && !this.IsAppEventInput( userInput ) );
	if( flag )
	{
		out += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\" valign=\"top\" nowrap>";
		out += "<span class=\"userResponse\">You Asked:&nbsp;&nbsp;</span><span class=\"userResponse\"></span></td>";
		out += "<td width=\"100%\" align=\"left\" valign=\"top\" class=\"userText\">" + userInput + "</td></tr></table>";
		out += "<br>";
	}
	if( brainRsp.length > 0 )
	{
		if( flag )
		{
			//todo
		}
		out += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\" valign=\"top\" nowrap>";
		out += "<span class=\"botResponse\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Spike:&nbsp;&nbsp;</span><span class=\"botResponse\"></span></td>";
		if( this.lastBrainResponse != null && this.lastBrainResponse.DidYouMean != null && this.lastBrainResponse.DidYouMean.length > 0 )
		{
			var dym = this.DoDidYouMean( this.lastBrainResponse );
			if( dym.length > 0 )
				out += "<br>" + dym + "<br><br>";
		}		
		out += "<td width=\"100%\" align=\"left\" valign=\"top\" class=\"userText\">" + brainRsp + "</td></tr></table><br>";
	}
	return out;
};

ActiveAgentUI.prototype.GetUserName = function()
{
	return user.UserName;
};

// Train Me popUp code
ActiveAgentUI.prototype.TrainMe = function()
{
	var popup = window.open('oops.aspx', '', 'width=400,height=215,toolbars=no,menubars=no,location=no,scrollbars=no,status=no,resizable=no');
};

// Appends a given string to the innerHtml of the response element.
ActiveAgentUI.prototype.AppendResponse = function( str )
{
	this.response.innerHTML += str;
	this.ScrollResponse();
};

ActiveAgentUI.prototype.LoadBio = function()
{
	aaUI.ChangePage( aaUI.bioUrl );
};

// Sets up an impasse
ActiveAgentUI.prototype.DoImpasse = function( agent )
{
	this.isInImpasse = true;
	this._impasse = new ChatUI( this.responseID, this.inputID, "respondid", "AgentProxy.asmx" );
	this._impasse.SetEndImpasseCallback( this.EndImpasse );
	try
	{
		this._impasse.StartChat();	
	}
	catch( ex )
	{ alert(ex.message); };
};

ActiveAgentUI.prototype.ToggleImpasseUI = function( action )
{
	var r_Text = document.getElementById( 'recruitID' );	

	if( action == "DoImpasse" )
	{
		//todo
	}
	else
	{
		r_Text.innerHTML = 'Live Chat';
		r_Text.onclick = aaUI.ResetImpasse;		
		this.input.disabled = false;
		this.response.disabled = false;
		this.input.focus();		
	}
};

ActiveAgentUI.prototype.Sound = function()
{
	aaUI.ToggleSound(this);	
};

ActiveAgentUI.prototype.ResetImpasse = function()
{
	aaUI.DoImpasse();
	return false;
}

ActiveAgentUI.prototype.LeaveChat = function()
{
	try
	{
		aaUI._impasse.EndChat();
		aaUI.isInImpasse = false;
		aaUI.ToggleImpasseUI( "EndImpasse" );
	}
	catch(e){};
	return false;
};

ActiveAgentUI.prototype.EndImpasseClick = function()
{
	if( this._impasse != null )
	{
		this._impasse.EndChat();
	}
};

// Closes the Impasse
ActiveAgentUI.prototype.EndImpasse = function( agent )
{	
	aaUI.isInImpasse = false;
	aaUI.ToggleImpasseUI( "EndImpasse" );					
};

// Lets us know if we are in an Impasse, and toggles the state with the above methods.
ActiveAgentUI.prototype.LiveChat = function( agent )
{
	if(!this.isInImpasse)
	{
		this.isInImpasse = true;
		this.DoImpasse(agent);
	}
	else
	{
		this.EndImpasse(agent);
		this.isInImpasse = false;				
	}
};

// REGION: Key interaction with the input area, and functions that they directly call.
// A activeAgentUI needs to know how to hook into itself.
ActiveAgentUI.prototype.HookBotEnter = function()
{
	//NOTE: when prototying an event through an event pointer, you cannot use the this
	// reference, because it is in the scope of the functon at that point.  Thus, you need
	// to pass it the actual object you created, despite the fact you are in that very object!
	try
	{
		if( window.attachEvent )
		{
			this.input.attachEvent( "onkeydown", function TempKeyPress(event){aaUI.OnBotKeyPress(event);} );
		}
		else if (window.addEventListener)
		{
			
			this.input.addEventListener("keydown", function TempKeyPress(event){aaUI.OnBotKeyPress(event);}, false);
		}
	}
	catch(e)
	{		
	}
};

// The event for pressing a key.  Uses cross browser detection.
// Enter key is our main concern.  It calls GetBrainResponse, then
// cancels teh event, so the key marker does not go down.
ActiveAgentUI.prototype.OnBotKeyPress = function(e) 
{
	var key = ( typeof(e.which) == 'number')?e.which:e.keyCode;
	
	if( key == 13 )	//Enter
	{
		this.GetBrainResponse( "Typed" );		
		e.cancelBubble = true;
		e.returnValue = false;
		return false;
	}	
	else if( key == 17 )//ctrl q
	{		
	}		
	return true;
};

// Sets up the userInput, and then hooks into the botResponseEngine
// calling the GetResponse
ActiveAgentUI.prototype.GetBrainResponse = function( type )
{
	if(window.event)
	{
		window.event.returnValue = false;
		window.event.cancelBubble = true;		
	}	
	
	if( user.BrainID == null )
	{
		user.BrainID = agent.CreateBrainID();
		setCookie( this.botIDCookieName, user.BrainID );
	}	
	
	if( user.ID == null || user.ID <= 0 )
		user.GetUserID();	
	
	this.userInput = new UserInput( aaUI.GetInput(), false, user );
	this.userInput.Type = type;
	
	if ( this.isInImpasse && this._impasse != null )
		this._impasse.SendResponse();
	else
		this.GetResponse( this.userInput );		
	
	try
	{
		var temp = document.getElementById( 'tbInput' ).focus();
	}
	catch( e )
	{ alert( "You must first End Chat to continue chatting with Spike" ); }
	
	if ( this._inputCount == 0 )
	{
		var tab = document.getElementById( 'main_tab' ).src = "images/bot/tab_more.gif";//turn to "here's more" tab
		var loginStyle = document.getElementById( 'login' ).style.display = "none";//login ctrl disappears
		var welcomeStyle = document.getElementById( 'welcome' ).style.display = "none";//welcome content disappears
		var moreStyle = document.getElementById( 'more' ).style.display = "block";//bring back the "here's more" div
		Collapse();
	}
	this._inputCount++;
	return false;				
};

ActiveAgentUI.prototype.UserLoginClicked = function()
{	
	var reset = false;
	if ( this._loggedIn )
	{
		var confirm_box = confirm( "A user is currently logged in.  Click Ok to login a different user or click Cancel to continue without changing user.");
		if ( confirm_box )
		{
			reset = true;
		}		
	}
	else
	{
		reset = true;
	}
	
	if ( reset )
	{
		var tab = document.getElementById( 'main_tab' ).src = "images/bot/tab_login.gif";
		var loginStyle = document.getElementById( 'login' ).style.display = "block";	
		var welcomeStyle = document.getElementById( 'welcome' ).style.display = "none";
		var moreStyle = document.getElementById( 'more' ).style.display = "none";
		var userLogin = document.getElementById( 'logLink' ).innerHTML = "User Login";
		
		
		//Empty the form input boxes
		ResetFields();
		this._inputCount = 0;
		this._loggedIn = false;
		aaUI.CloseArmyAgent( false );
	}							
};

ActiveAgentUI.prototype.PlaySound = function ( file )
{
	if( aaUI.playSound )
	{
		setTimeout( "DetectFlashHalt()", 3000 );
		setTimeout( "aaUI.timedSound('" + file + "')", 100 );
	}
};
function DetectFlashHalt()
{
	var halted = gFlashObject.SelfHalt();	
	if( halted == false )
	{
		setTimeout( "DetectFlashHalt()", 3000 );
	}
	else
	{
		//todo
	}
}
ActiveAgentUI.prototype.timedSound = function( file )
{
	gFlashObject.StartFlash( file, "BrainAudioFile" );
};


// Toggles the sound
ActiveAgentUI.prototype.ToggleSound = function()
{
	var toggle = document.getElementById( 'soundTag' );	
	
	if( aaUI.playSound )
	{
		aaUI.playSound = false;
		toggle.innerHTML = 'Sound On';
		gFlashObject.StopFlash();
		this._sound = false;	
	}
	else
	{
		aaUI.playSound = true;
		toggle.innerHTML = 'Sound Off';
		this._sound = true;
		try
		{
			if( this.lastBrainResponse != null )
			{
				this.PlaySound( this.lastBrainResponse.TextToSpeechUrl );
			}
		}
		catch(e){}
	}	
};

// When they click on toggle sound, call the ToggleSound function
ActiveAgentUI.prototype.ToggleSoundClick = function( action )
{
	if( action == 'on' && !aaUI.playSound )
		aaUI.ToggleSound();
	else if( action == 'off' && aaUI.playSound )
		aaUI.ToggleSound();
	
	//set the variable async
	try
	{
		agent.SetSoundVariable( action );
	}
	catch(e)
	{
		alert( e );
	}
};

// Clears out the input element, and toggles a bool
ActiveAgentUI.prototype.UserInputFocus = function()
{
	if( doQuestion )
	{
		aaUI.SetInput( '' );
		setCookie( "OneCallAskedQ", "true" );
		doQuestion = false;
	}	
	return false;
};

// used by the help button to start the brain response process.
ActiveAgentUI.prototype.HandleAppEvent = function( name )
{	
	//if ( this.respCount > 0 )
	//{
		var argv = this.HandleAppEvent.arguments;		
		var input = "AppEvent " + name +" ";
		
		for( var i = 1; i < argv.length; i++ )
		{
			input += "{cp " + argv[i] + " cp} ";
		}
		
		input = input.substring( 0, input.length - 1 );
		
		if( user.ID == null || user.ID <= 0 )
			user.GetUserID();
		
		this.userInput = new UserInput( input, true, user );
		
		var br = null;
		var toggled = false;
		try
		{
			toggled = true;
			br = agent.GetBrainResponse( this.userInput );		
		}
		catch(e)
		{
			if( toggled == true )
			{			
			}		
		}
	//}
	//else 
	/*{
		this.respCount++;
		var str = "";
		var welcomeText = "Welcome. I'm Spike and I'm ready to answer your questions and help you navigate the website. For a more personalized experience please login.";
		str += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\" valign=\"top\" nowrap>";
		str += "<span class=\"botResponse\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Spike:&nbsp;&nbsp;</span><span class=\"botResponse\"></span></td>";
		str += "<td width=\"100%\" align=\"left\" valign=\"top\" class=\"userText\">" + welcomeText + "</td></tr></table><br>";
		var rsp = document.getElementById( 'lblResponse' ).innerHTML = str;
		aaUI.PlaySound( "includes/welcome_new.swf" );		
	}*/	
};

// If the brain response has app events to accomplish, we do so here.
// All it really does is set cookies, and then change the url.
ActiveAgentUI.prototype.DoAppEvent = function( userInput, brainRsp, appName, value )
{
	switch(appName)
	{
		case "AppendLinkToResponse":
			var s = this.CleanUrlString( value ).split('|');
			var url = s[0];
			var label = "Click Here";
			if( s.length >1 )
				label = s[1];
			this._showTopicLink = "<a href=\"#\" onclick=\"aaUI.ChangePage('"+ url +"')\">" + label + "</a>";
			break;			
		case "JobSearch":
			var url = '';
			url = "JobSearch.aspx?MOS_LIST="+value;
			var resp = document.getElementById( 'lblResponse' );
			brainRsp.Response += "<br><a href=\"#\" onclick=\"aaUI.ChangePage( '" + url + "');return false;\"><span class=\"userInput\">" + " >>" + "</span></a>";				
			this.ChangePage(url);
			break;
		case "ImmediateImpasse":
			this.DoImpasse();
			break;
		case "OtherPossibleHits":
		case "OtherRelatedResponses":	
			var type = "";
			if( appName == "OtherPossibleHits" )
				type = "RelatedUnits";
			else
				type = "IRUnits";					
			var xml = XmlDocument();	
			try
			{
				xml.loadXML( value );
				var units = xml.selectNodes( "//units/unit" );
				FormatOtherUnits( units, type, brainRsp.UnitID );				
			}
			catch(e)
			{
				alert( e.message );
			}
			break;
		case "ShowWebLinks":
			var xml = XmlDocument();
			
			try
			{
				xml.loadXML( value );
				var units = xml.selectNodes( "//Links/Link" );
				FormatWebLinks( units );				
			}
			catch(e)
			{
				alert( e.message );
			}
			break;
		default:
			alert( 'No Appevents defined with the name ' + appName );
			break;
	}
};

function FormatWebLinks( links )
{
	var linkType, linkName, linkUrl, linkUID, linkStyle
	var out = "";
	for( var i = 0; i < links.length; i++ )
	{
		try
		{
			linkType = getInnerText(links[i].selectSingleNode( "LinkType" ));
			linkName = getInnerText(links[i].selectSingleNode( "LinkName" ));
			linkUrl = getInnerText(links[i].selectSingleNode( "page" ));
			linkUID = getInnerText(links[i].selectSingleNode( "UnitUID" ));
			linkStyle = getInnerText(links[i].selectSingleNode( "LinkStyle" ));
		}
		catch(e)
		{
			alert( 'Error getting Web Link\n' + e.message );
		}

		try
		{
			if( linkType == "Unit" )
				out += "<a class=\"weblink_" + linkStyle + "\" href=\"javascript:DoRelatedUnits( '" + EscapeLabel(linkName) + "', '" + linkUID + "', 'AnswerLink' );\">" + linkName + "</a>";
			else
				out += "<a class=\"weblink_" + linkStyle + "\" href=\"javascript:DoMessageLink( '" + linkUrl + "' );\">" + linkName + "</a>";
			out += "<br>";
		}
		catch(e)
		{
			alert( 'Error formatting Web Links\n' + e.message );
		}
	}
	
	aaUI._webLinks += out;
}

function DoMessageLink( url )
{
	//do page redirect
	aaUI.ChangePage( url );
}

ActiveAgentUI.prototype.ProcessClickedLink = function( unitID, label, type )
{
	this._isRelatedLinkClick = true;
	this._relatedLinkLabel = label;
	this.userInput = new UserInput( label, false, user );	
	
	var userInputType = "";
	if( type == "IRUnits" )
		userInputType = "IRUnitClick";
	else if( type == "RelatedUnits" )
		userInputType = "LowerUnitClick";
	else if( type == "AnswerLink" )
		userInputType = "AnswerLink";
		
	this.userInput.Type = userInputType;	
	this.userInput.UnitID = unitID;
	var br = null;
	try
	{
		br = agent.GetBrainResponse( this.userInput );
	}
	catch(e)
	{
		alert("ProcessClickedLink: " + e.message );
	}	
	this.ProcessResponse( br );
};

function DoRelatedUnits( label, unitid, type )
{
	aaUI.ProcessClickedLink( unitid, unescape(label), type );
};

function FormatOtherUnits( units, type, displayedUnitID )
{
	if( units.length > 0 )
	{
		var labelText;
		var unitIdText;
				
		var outHeader = "<span><span id=\"moreLinksContainer\">";
		var out = "<ol class=\"moreol\">";
		var outMoreThanThree = "";
		var showMore = false;			
		
		var cnt = 0;		
		for( var i = 0; i < units.length; i++ )
		{
			try
			{
				labelText = getInnerText(units[i].selectSingleNode( "label" ));
				unitIdText = getInnerText(units[i].selectSingleNode( "unitId" ));
			}
			catch(e)
			{
				//todo
			}
			
			try
			{
				if( unitIdText != displayedUnitID )
				{
					if( cnt >= 3 )
					{
						showMore = true;
						outMoreThanThree += "<li class=\"moreli\"><a class=\"more_ln\" href=\"javascript:DoRelatedUnits( '" + EscapeLabel(labelText) + "', '" + unitIdText + "', '" + type + "' );\">" + labelText + "</a></li>";
					}
					else
					{
						out += "<li class=\"moreli\"><a class=\"more_ln\" href=\"javascript:DoRelatedUnits( '" + EscapeLabel(labelText) + "', '" + unitIdText + "', '" + type + "' );\">" + labelText + "</a></li>";
						outMoreThanThree = out;
					}
					
					cnt++;
				}			
			}
			catch(e)
			{
				//todo
			}			
		}
		
		if( cnt == 0 )
			return "";
		
		out += "</ol>";
		outMoreThanThree += "</ol>";
		
		var showMoreText = "";		
		if( showMore )
		{
			showMoreText = "<div style=\"text-align:middle\"><a onclick=\"ShowMore(this);return false;\" href=\"#\" class=\"more_ln\">more ></a>&nbsp;</div>";
		}
		
		var input = "<input type=\"hidden\" id=\"hid\" value=\"" + escape(outMoreThanThree) + "\">";
		var outHeaderClose = "</span>";		
		aaUI._moreUnits = outHeader + out + outHeaderClose + showMoreText + input + outHeaderClose;
	}
	else
		aaUI._moreUnits = "";	
};

function ShowMore( el )
{
	var container = GetContainer( el );
	el.parentNode.style.display = "none";
	if( container != null )
	{
		var node;
		var ctr = null;
		var input;
		for( var i = 0; i < container.childNodes.length; i++ )
		{
			node = container.childNodes[i];
			if( node.tagName == "SPAN" && node.id == "moreLinksContainer" )
			{
				ctr = node;
			}
			else if( node.tagName == "INPUT" && node.id == "hid" )
			{
				input = node;
				if( ctr != null )
				{
					ctr.innerHTML = unescape(input.value);
				}
			}
		}
	}
	else
		alert( 'error' );
}

function GetContainer( el )
{
	var tg = el.parentNode.tagName;
	var cl = el.parentNode.className;
	while( tg != "SPAN" )
	{
			el = el.parentNode;
			tg = el.tagName;
			cl = el.className;			
	}
	
	if( tg == "SPAN" )
		return el;
	else
		return null;
}

// Use Object detection to get at the innerText of a Node object.
// Cross browser with any browser that supports NodeElement objects.
function getInnerText(node)
{
	if (typeof node.textContent != 'undefined')	
	{
		return node.textContent;
	}
	else if (typeof node.innerText != 'undefined') 
	{
		return node.innerText;
	}
	else if (typeof node.text != 'undefined') 
	{
		return node.text;
	}
	else
	{
		switch (node.nodeType) 
		{
			case 2:
			case 3:
			case 4:
				return node.nodeValue;
				break;
			case 1:
			case 11:
				var innerText = '';
			
				for (var i = 0; i < node.childNodes.length; i++) 
				{
					innerText += getInnerText(node.childNodes[i]);
				}
				
				return innerText;
				break;
			default:
				return '';
		}
	}
};


function EscapeLabel( label )
{
	return label.replace( /\'/g, "\\'" );
};

function XmlDocument()
{
	var xmlDoc = null;
	
	if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");				
	}
	else if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("", "", null);				
	}
	else
	{
		return;
	}
	return xmlDoc;
};

// What ActiveAgentUI calls to start the brain response process.
ActiveAgentUI.prototype.GetResponse = function( userInput )
{
	if( this.input.value != null && this.input.value != "" )
	{
		if( this._doingSearch )
		{
			return;
		}		
		var br = null;
		try
		{
			br = agent.GetBrainResponse( userInput );
		}
		catch(e)
		{			
		}		
		this.ProcessResponse( br );
	}
};

// This function is eventually called by the two above, and the asyncronus postBack method
// in the active agent class.  Super important function here, because it is what actually
// uses the brain response.
ActiveAgentUI.prototype.ProcessResponse = function( br )
{
	this.lastBrainResponse = br;
	this.SetInput( '' );		
	
	if( this.lastBrainResponse != null )
	{
		if( this.lastBrainResponse.Response == "" )
		{
			this.lastBrainResponse.Response = "I'm sorry a timeout has occurred.";
		}		
		this.DoPageRedirect( this.lastBrainResponse, this.userInput );
		
		var appEvent;		
		try
		{
			for( var i = 0; i < this.lastBrainResponse.Events.length; i++ )
			{
				appEvent = this.lastBrainResponse.Events[i];
				this.DoAppEvent( this.userInput, this.lastBrainResponse, appEvent.Name, appEvent.Value );
			}
		}
		catch(e)
		{}		
		
		if( true )
		{	
			var ResponseSending = '';
			ResponseSending = aaUI.FormatNonBotResponse( this.lastBrainResponse.UserInput, this.lastBrainResponse.Response );
				
			if( this.lastBrainResponse.IsInImpasse )
			{
				ResponseSending += /*this.AppendResponse*/( this.doImpasseTxt );				
			}
			
			if( this._webLinks.length > 0 )
			{
				//this.AppendResponse( "<br><br>" + this._webLinks );
				var el1 = document.getElementById( 'more' );
				el1.innerHTML = this._webLinks;
				
				this.ScrollResponse();
				
				this._webLinks = "";
			}
			
			if( this._moreUnits.length > 0 )
			{
				//apend the html
				var el = document.getElementById( 'more' );
				el.innerHTML = this._moreUnits;
				// IE FIX
				el.style.overflow ='auto';
				
				this.ScrollResponse();
				this._moreUnits = "";
			}
			
			if( this._showTopicLink.length <= 0 && !this.lastBrainResponse.DoAppCallNavigation )
			{
				//todo
			}
			
			// Actually set the resposnse
			this.SetResponse(ResponseSending);
				
			this.SetUnitID( this.lastBrainResponse.UnitID );
			
			this.PlaySound( this.lastBrainResponse.TextToSpeechUrl );
		}	
		
		this._showTopicLink = "";
		
		this._isRelatedLinkClick = false;
		this._relatedLinkLabel = "";
	}
	try
	{
		var temp = document.getElementById( 'tbInput' ).focus();		
	}
	catch(e)
	{}
};

ActiveAgentUI.prototype.DoDidYouMean = function( brainResponse )
{
	if( brainResponse.DidYouMean.length <= 0 )
		return "";
	try
	{
		var xmlDoc = XmlDocument();
		xmlDoc.loadXML( brainResponse.DidYouMean );
		
		var strOut = getInnerText( xmlDoc.selectSingleNode( "//SpellChecker/Input" ).attributes[0] );
		var formattedOut = strOut;
		
		var msWords = xmlDoc.selectSingleNode( "//SpellChecker/MisspelledWords" );
		if( msWords.childNodes.length > 0 )	//we have mis-spellings
		{
			for( var i = 0; i < msWords.childNodes.length; i++ )
			{
				try
				{
					var pos = getInnerText( msWords.childNodes[i].attributes[1] );	//.text
					var matches = msWords.childNodes[i].selectNodes("Matches/Match");
					
					if( matches != null && matches.length > 0 )
					{
						for( var j= 0; j < matches.length; j++ )
						{
							for( var k = 0; k < matches[j].attributes.length; k++ )
							{
								if( matches[j].attributes[k].nodeName == "text" )
								{
									var newWord = getInnerText( matches[0].attributes[0] );	//.text;
									var oldWord = getInnerText( msWords.childNodes[i].attributes[0] );
									strOut = strOut.replace( oldWord, newWord );
									formattedOut = formattedOut.replace( oldWord, "<b>" + newWord + "</b>" );
									j = 1000000;
									break;
								}
							}
						}
					}
				}
				catch(e)
				{
					if( msWords.childNodes.length == 1 )
					{
						return "";
					}					
				}
			}			
			return "<span class=\"didyoumean\">Did you Mean: <a class=\"didyoumean_ln\" href=\"#\" onclick=\"aaUI.OnDoYouMean('" + strOut + "')\">" + formattedOut + "</a></span>";
		}
		else
			return "";
	}
	catch(e)
	{
		return "";
	}
};

ActiveAgentUI.prototype.OnDoYouMean = function( strIn )
{
	this.SetInput( strIn );
	this.GetBrainResponse( "DidYouMeanClick" );
	
};

ActiveAgentUI.prototype.SetUnitID = function( unitID )
{
	var el = null;
	try
	{
		el = document.getElementById( 'inner_bot_response_unitid' );
	}
	catch(e)
	{}
	
	if( unitID != null && el != null && unitID.length > 0 )
	{
		el.value = unitID;		
	}
	else if( el != null )
		el.value = '0';	
};

ActiveAgentUI.prototype.IsAppEventInput = function( input )
{
	try
	{
		var reg1 = new RegExp( "AppEvent\\s\\w*\\s\\{cp\\s\\w*\\scp\\}\\w*" );
		var reg2 = new RegExp( "AppEvent\\s\\w*" );
		var flag = reg1.test( input );
		if( !flag )
			return reg2.test( input );
		return flag;
	}
	catch( e )
	{
		return false;
	}
};

ActiveAgentUI.prototype.CleanUrlString = function( url )
{
	try
	{
		var reg = "/\"/";
		url = url.replace( reg, "'" );
		return url;
	}
	catch(e)
	{
		return url;
	}
};

ActiveAgentUI.prototype.BotSetup = function( name, sound, question, liveChat )
{
	aaUI.playSound = true;
	user.UserName = name;
	this._sound = sound;
	this._question = question;
	this.liveChat = liveChat;
	
	gFlashObject.StopFlash();
	
	if (this._sound == 'True')
	{
		aaUI.playSound = true;
		aaUI.ToggleSound();
	}
	else
	{
		aaUI.playSound = false;
		aaUI.ToggleSound();
	}	
	
	if ( liveChat == 'True' )
		this.DoImpasse( agent );
		
	if(question != null && question.length>0)
	{
		window.setTimeout( "DoDelayedTimer('" + question + "')", 1000 );
	}			
};

function DoDelayedTimer(question)
{
	aaUI.SetInputResponse();
	aaUI.userInput = new UserInput( question, false, user );

	var br = null;
	try
	{
		br = agent.GetBrainResponse( aaUI.userInput );
	}
	catch(e)
	{}

	aaUI.ProcessResponse( br );
};

ActiveAgentUI.prototype.SendMail = function()
{
	//todo
};


