/***************************************************************************
 [ChatUI.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.

*****************************************************************************/

function ChatUI( lblID, txtID, btnID, wsURL )
{
	this.lbl = null;
	this.input = null;
	this.txtID = null;
	this.btnID = null;
	this.objectsLoaded = false;
	this.parentWindow = null;
	this.chatStarted = false;
	this.user = new User();
	this.user.BrainID = "";
	
	if( user != null )
		this.user = user;
		
	this.cbEndImpasse = null;	
	this.SetObjs( lblID, txtID, btnID );
	this.SetParentWindow( aaUI.parent );
	this.chatService = null;
	this.wsUrl = wsURL;
	this.doTimer = true;
	this.isInQueue = true;
	this.redirectText = " has redirected your browser to the following URL: ";
	this.didChat = false;
	this.showMsg = 0; //keeps count of the "so and so is connecting..." message when attempting an impasse chat
					  //so that the text isn't redisplayed on each timer tick during polling
	this.chatFlag = false;
	
	this.chatService = new ChatService( this.wsUrl );	
};

ChatUI.prototype.InitalizeStartingState = function()
{
	this.doTimer = true;
	this.isInQueue = true;
	this.chatStarted = false;
	this.DisableChatUI();
};

ChatUI.prototype.StartChat = function()
{
	try
	{
		this.lbl.innerHTML += "<br><span class=\"connectTxt\">Please standby while we connect you with a live operator...</span><br>";
		aaUI.ScrollResponse();
		this.InitalizeStartingState();
		if( this.user.BrainID.length <=0 )
			this.CreateBrainID();
		
		this.chatService.StartChat( this.user.BrainID,  this.GetParentURL() );
		OnChatStarted();		
		this.chatStarted = true;
	}
	catch(e)
	{	
		alert( 'Chat NOT started succesfully.' );	
	}
};

ChatUI.prototype.EndChat = function()
{
	if( this.doTimer )
	{
		this.SendResponseNoUserName("&nbsp;&nbsp;<span class=\"userResponse\">--= Chat Ended By User =--</span>");
		this.chatService.EndChat( this.user.BrainID );		
	}
	this.doTimer = false;
	
	if( this.cbEndImpasse != null )
		this.cbEndImpasse();
	
	aaUI.ScrollResponse();
	this.input.className = "chatInput";
};

function OnChatStarted()
{
	if( aaUI._impasse.doTimer )
		setTimeout("ChatServiceDoTimer();",1000);
};

function ChatServiceDoTimer()
{
	try
	{
		aaUI._impasse.CheckServer();
	}
	catch(e)
	{	
		alert( 'Error in Timer: ' + e );	
	}
};

ChatUI.prototype.CheckServer = function()
{
	if( aaUI._impasse.doTimer )
	{
		try
		{
			var rsp = this.chatService.CheckServer(this.user.BrainID);
		}
		catch(e)
		{
			alert( 'Error setting rsp from chatService.CheckServer' );
		}
		
		if( rsp != null )
		{
			try
			{
				if( typeof( rsp.State ) == "object" && rsp.State.childNodes.length > 0 )
					rsp.State = rsp.State.childNodes[0].nodeValue;
			}
			catch( e )
			{
				alert( 'Error getting rsp.State.' );
			}
			
			var staff = rsp.AssistingStaffInfo;
			if ( this.isInQueue && rsp.State == "InQueue" && staff != null && staff.ID != null && this.showMsg < 1)
			{
				// Staff is connecting, but hasn't typed anything yet
				this.lbl.innerHTML += "<br><br><span class=\"connectTxt\">Assistant " + staff.DisplayName + " is connecting...</span>";
				this.showMsg++;
				this.chatFlag = true;
				aaUI.ScrollResponse();
			}			
			if( this.isInQueue )
			{
				if ( rsp.State == "ConnectedToOperator" )
				{
					aaUI._impasseConnected = true;
					this.isInQueue = false;
					this.didChat = true;
					this.EnableChatUI();
					this.ChatLinkEnabled( false ); // undo from EnableChatUI
					this.SetInput("");
					this.FocusInput();	
					
					try
					{
						this.showMsg = 0;						
					}
					catch(e)
					{
						this.lbl.innerHTML += "<br><br>&nbsp;&nbsp;<span class=\"botResponse\">(Error Getting Recruiter Info)</span>";						
					}					
				}
				else
				{					
				}
			}
					
			this.FormatImpasseResponse( rsp );
			
			if( !rsp.Continue )
			{				
				if ( rsp.State == "NotConnected" && this.didChat == false )
				{
					if ( this.chatFlag )
					{
						this.lbl.innerHTML += "<br><br>" + "<span class=\"botResponse\">" + rsp.AssistingStaffInfo.DisplayName +
								 ":</span> <span class=\"botResponse\">" + rsp.Responses[0] + "</span>";
						this.lbl.innerHTML += "<br><br>&nbsp;&nbsp;<span class=\"botResponse\">--= Chat Ended by Operator =--</span>";						
					}
					else
					{
						var out = "";
						out += "<br><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>";
						out += "<td width=\"100%\" align=\"left\" valign=\"top\" class=\"userText\">" + "I'm sorry, a Live Assistant is not available to chat with you at this time.  Please try again shortly." + "</td></tr></table><br>";
						
						var hold = document.getElementById( 'lblResponse' );
						hold.innerHTML += out;						
					}
					this.chatFlag = false;					
					this.SetInput("");
					this.FocusInput();	
				
					//Play default no-op response.
					if (aaUI.lastBrainResponse != null) // Don't crash
					{
						aaUI.lastBrainResponse.TextToSpeechUrl = "includes/noop.swf";
						aaUI.PlaySound( aaUI.lastBrainResponse.TextToSpeechUrl );
					}
				}
				else
				{
					if( this.didChat == true && this.doTimer && rsp.State == "NotConnected" )
					{
						this.lbl.innerHTML += "<br><br>" + "<span class=\"botResponse\">" + rsp.AssistingStaffInfo.DisplayName +
								 ":</span> <span class=\"botResponse\">" + rsp.Responses[0] + "</span>";
						this.lbl.innerHTML += "<br><br>&nbsp;&nbsp;<span class=\"botResponse\">--= Chat Ended by Operator =--</span>";
					}
					else if ( this.isInQueue ) // Queue timeout reached
					{
						this.lbl.innerHTML += "<br><br>&nbsp;&nbsp;<span class=\"botResponse\">--= Unable To Connect =--</span>";
						this.SetInput("");
						this.FocusInput();	
					}
					else  // Just closing chat (possibly a server problem)
					{
						this.lbl.innerHTML += "<br><br>&nbsp;&nbsp;<span class=\"botResponse\">--= Chat Ended Unexpectedly =--</span>";
						this.SetInput("");
						this.FocusInput();	
					}
				}				
				aaUI.ScrollResponse();
				this.doTimer = false;
				this.EndChat();
				this.EnableChatUI();
				this.chatStarted = false;
			}
			
			if( rsp.URL != null && rsp.URL.length > 0 )
			{
				try
				{			
					this.lbl.innerHTML += "<br><br>" + "<span class=\"botResponse\"> Assistant \"" + rsp.AssistingStaffInfo.DisplayName +  "\" " + this.redirectText + 
									"</span> <span class=\"botResponse\">";				
					this.lbl.innerHTML += "&nbsp;<a href=\"#\" class=\"botln\" onclick=\"aaUI.ChangePage( '" + rsp.URL + "')\"title=\"More Info\">" + ">>" + "</a>";
					this.ChangePage( rsp.URL );	
					aaUI.ScrollResponse();						
				}
				catch(e)
				{}
			}	
		}
		OnChatStarted();
	}
};

ChatUI.prototype.EnableChatUI = function()
{
	if( this.objectsLoaded )
	{
		this.ChatLinkEnabled( true );		
		this.input.disabled = false;		
		this.btnEnter.disabled = false;		
	}
	var foc = document.getElementById( 'tbInput' ).focus();	
};

ChatUI.prototype.DisableChatUI = function()
{
	if( this.objectsLoaded )
	{
		this.ChatLinkEnabled( false );		
		this.input.disabled = true;		
		this.btnEnter.disabled = true;
	}
};

ChatUI.prototype.ChatLinkEnabled = function( enabled )
{
	var r_Text = document.getElementById( 'recruitID' );
	if (enabled)
	{
		r_Text.onclick = aaUI.ResetImpasse;	
		r_Text.innerHTML = 'Live Chat';							
	}
	else
	{
		this.EnableChatUI(); // Can get stuck disabled if we click the link while disabled
		r_Text.onclick = aaUI.LeaveChat;
		r_Text.innerHTML = 'End Chat';		
	}	
};

ChatUI.prototype.FormatImpasseResponse = function( response )
{	
	if( this.objectsLoaded )
	{
		for ( var i = 0; i < response.Responses.length; i++)
		{
			if ( response.Continue )
			this.lbl.innerHTML += "<br><br>" + "<span class=\"botResponse\">" + response.AssistingStaffInfo.DisplayName +
								 ":</span> <span class=\"userText\">" + response.Responses[i] + "</span>";
			aaUI.ScrollResponse();						
		}		
	}	
};

ChatUI.prototype.SendResponse = function()
{
	if( !this.chatStarted )
	{
		this.StartChat();
		ChatServiceDoTimer();
		return;
	}
	var input = this.GetInput();
	if( input.length > 0 )
	{
		var outInput = this.MakeUserInputString( this.user, input );
		this.AddToHistory( outInput );
		var ui = new UserInput( input, false, this.user )
		this.chatService.SendUserResponse( ui );
		this.input.value = "";
		aaUI.ScrollResponse();			
	}
};

ChatUI.prototype.SendResponseNoUserName = function( inputTxt )
{
	if( !this.chatStarted )
	{
		this.StartChat();
		ChatServiceDoTimer();
		return;
	}
	var input = "";
	if( inputTxt.length <= 0 )
		input = this.GetInput();
	else
		input = inputTxt;
	if( input.length > 0 )
	{
		var outInput = this.MakeUserInputString( this.user, input );		
		this.AddToHistory( inputTxt );		
		aaUI.ScrollResponse();
		input = "-= Chat Ended By User =-";
		var ui = new UserInput( input, false, this.user );
		this.chatService.SendUserResponse( ui );
		this.input.value = "";			
	}
}

ChatUI.prototype.MakeUserInputString = function( user, input )
{
	return "<span class=\"userResponse\">" + user.UserName + ":</span> <span class=\"userText\">" + input + "</span>";	
};

ChatUI.prototype.SetObjs = function( lblID, txtID, btnID )
{
	try
	{
		this.lbl = document.getElementById( lblID );
		this.input = document.getElementById( txtID );
		this.btnEnter = document.getElementById( btnID );
		this.objectsLoaded = true;		
	}
	catch(e)
	{
		this.objectsLoaded = false;
		setTimeout("this.SetObjs('" + lblID + "', '" + txtID + "', '" + btnID + "')", 500 );
	}
};

ChatUI.prototype.GetInput = function()
{
	if( this.objectsLoaded )
		return this.input.value;
	else
		return "";
};

ChatUI.prototype.SetInput = function( input )
{
	if( this.objectsLoaded )
		this.input.value = input;
};

ChatUI.prototype.SetParentWindow = function( win )
{
	if( win != null )
		this.parentWindow = win;
};

ChatUI.prototype.AddToHistory = function( item )
{
	if( this.objectsLoaded )
	{
		this.lbl.innerHTML += "<br><br>" + item;		
	}	
};

ChatUI.prototype.ChangePage = function(url)
{
	if( url != null && url.length > 0 )
	{
		if( this.parentWindow == null || this.parentWindow.closed )
		{
			this.OpenParentWindow();
		}		
		this.parentWindow.location.href = url;
		window.focus();
	}
};

ChatUI.prototype.OpenParentWindow = function()
{
	var w=screen.availWidth-238;
	var h=screen.availHeight;
	var popup = window.open('default.aspx', 'chatParWin', 'width=' + w + ',height=' + h + ', location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,titlebar=yes,toolbar=yes' );
	popup.moveTo(screen.availWidth-w,screen.availHeight-h);
	
	this.SetParentWindow( popup ); 
	aaUI.parent = popup;
	
	if ( window.focus )
		popup.focus();	
};

ChatUI.prototype.GetParentURL = function()
{
	try
	{
		if( this.parentWindow == null || this.parentWindow.closed )	
		{
			this.OpenParentWindow();
		}
	}
	catch( e )
	{
		//IE will need to use this catch, it cannot (asof ie6) seem to read any parentWindow refs once the parent is gone
		this.OpenParentWindow();
	}
	
	try
	{
		return this.parentWindow.location.href;	
	}
	catch(e)
	{
		return "";
	}
};

ChatUI.prototype.FocusInput = function()
{
	if( this.objectsLoaded )
	{
		try
		{
			window.focus(); // focus window for customers too
			this.input.focus();
		}
		catch(e)
		{}
	}
};

ChatUI.prototype.AgentCleanup = function( brainID )
{
	this.chatService.AgentCleanup( brainID );
};

ChatUI.prototype.SetEndImpasseCallback = function( cb )
{
	this.cbEndImpasse = cb;
};

ChatUI.prototype.CreateBrainID = function()
{
	this.user.BrainID = this.chatService.CreateID();
};

ChatUI.prototype.GetCyberInfo = function( id )
{
	var obj = null;
	
	obj = this.chatService.GetCyberInfo( id );
	return obj;	
};
