using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Text;
using AgentObjects;

namespace ChatClient
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class ChatClientForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.TextBox ChatOut;
		private System.Windows.Forms.StatusBar statusBar1;
		private System.ComponentModel.Container components = null;
		private System.Windows.Forms.Button btnConnect;
		private System.Windows.Forms.Button btnSend;
		private int serverport;
		private NetworkStream ns;
		private StreamReader sr;
		private TcpClient clientsocket;
		private Thread receive = null;
		private string serveraddress;
		private System.Windows.Forms.ListBox lbChatters;
		private System.Windows.Forms.RichTextBox rtbChatIn;
		private System.Windows.Forms.Button btnDisconnect;
		private string clientname;
		//private string destclient;
		private bool connected = false;
		private bool logging = false;
		private bool privatemode = false;
				
						
		private System.Windows.Forms.Button btnLog;
		private System.Windows.Forms.CheckBox cbPrivate;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem menuItem3;
		private AxAgentObjects.AxAgent AgentCtl;
		private StreamWriter logwriter;
		private IAgentCtlCharacterEx Peedy;
		private System.Windows.Forms.MenuItem mnuAgentLoad;
		private System.Windows.Forms.MenuItem mnuAgentHideShow;
		private System.Windows.Forms.MenuItem mnuAgentIntro;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem mnuAgentInstructions;
		private IAgentCtlRequest LoadRequest;


		public ChatClientForm()
		{
			InitializeComponent();
			serverport = 5555;
			btnDisconnect.Enabled = false;
			btnSend.Enabled = false;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ChatClientForm));
			this.cbPrivate = new System.Windows.Forms.CheckBox();
			this.btnLog = new System.Windows.Forms.Button();
			this.btnSend = new System.Windows.Forms.Button();
			this.lbChatters = new System.Windows.Forms.ListBox();
			this.ChatOut = new System.Windows.Forms.TextBox();
			this.btnConnect = new System.Windows.Forms.Button();
			this.rtbChatIn = new System.Windows.Forms.RichTextBox();
			this.statusBar1 = new System.Windows.Forms.StatusBar();
			this.btnDisconnect = new System.Windows.Forms.Button();
			this.mainMenu1 = new System.Windows.Forms.MainMenu();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.mnuAgentLoad = new System.Windows.Forms.MenuItem();
			this.mnuAgentIntro = new System.Windows.Forms.MenuItem();
			this.mnuAgentHideShow = new System.Windows.Forms.MenuItem();
			this.menuItem4 = new System.Windows.Forms.MenuItem();
			this.AgentCtl = new AxAgentObjects.AxAgent();
			this.mnuAgentInstructions = new System.Windows.Forms.MenuItem();
			((System.ComponentModel.ISupportInitialize)(this.AgentCtl)).BeginInit();
			this.SuspendLayout();
			// 
			// cbPrivate
			// 
			this.cbPrivate.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.cbPrivate.Location = new System.Drawing.Point(492, 130);
			this.cbPrivate.Name = "cbPrivate";
			this.cbPrivate.Size = new System.Drawing.Size(81, 27);
			this.cbPrivate.TabIndex = 10;
			this.cbPrivate.Text = "Private";
			this.cbPrivate.CheckStateChanged += new System.EventHandler(this.cbPrivate_CheckedChanged);
			// 
			// btnLog
			// 
			this.btnLog.Location = new System.Drawing.Point(481, 93);
			this.btnLog.Name = "btnLog";
			this.btnLog.Size = new System.Drawing.Size(103, 27);
			this.btnLog.TabIndex = 9;
			this.btnLog.Text = "Start Logging";
			this.btnLog.Click += new System.EventHandler(this.btnLog_Click);
			// 
			// btnSend
			// 
			this.btnSend.Location = new System.Drawing.Point(338, 268);
			this.btnSend.Name = "btnSend";
			this.btnSend.Size = new System.Drawing.Size(82, 28);
			this.btnSend.TabIndex = 5;
			this.btnSend.Text = "Send";
			this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
			// 
			// lbChatters
			// 
			this.lbChatters.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lbChatters.ItemHeight = 14;
			this.lbChatters.Location = new System.Drawing.Point(348, 19);
			this.lbChatters.Name = "lbChatters";
			this.lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.None;
			this.lbChatters.Size = new System.Drawing.Size(113, 228);
			this.lbChatters.TabIndex = 7;
			// 
			// ChatOut
			// 
			this.ChatOut.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.ChatOut.Location = new System.Drawing.Point(10, 268);
			this.ChatOut.Name = "ChatOut";
			this.ChatOut.Size = new System.Drawing.Size(307, 23);
			this.ChatOut.TabIndex = 2;
			this.ChatOut.Text = "";
			this.ChatOut.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ChatOut_KeyPress);
			// 
			// btnConnect
			// 
			this.btnConnect.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.btnConnect.Location = new System.Drawing.Point(481, 19);
			this.btnConnect.Name = "btnConnect";
			this.btnConnect.Size = new System.Drawing.Size(103, 27);
			this.btnConnect.TabIndex = 4;
			this.btnConnect.Text = "Connect";
			this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
			// 
			// rtbChatIn
			// 
			this.rtbChatIn.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.rtbChatIn.Location = new System.Drawing.Point(10, 19);
			this.rtbChatIn.Name = "rtbChatIn";
			this.rtbChatIn.ReadOnly = true;
			this.rtbChatIn.Size = new System.Drawing.Size(307, 245);
			this.rtbChatIn.TabIndex = 6;
			this.rtbChatIn.Text = "";
			// 
			// statusBar1
			// 
			this.statusBar1.Location = new System.Drawing.Point(0, 317);
			this.statusBar1.Name = "statusBar1";
			this.statusBar1.Size = new System.Drawing.Size(611, 19);
			this.statusBar1.SizingGrip = false;
			this.statusBar1.TabIndex = 3;
			this.statusBar1.Text = "Disconnected";
			// 
			// btnDisconnect
			// 
			this.btnDisconnect.Location = new System.Drawing.Point(481, 56);
			this.btnDisconnect.Name = "btnDisconnect";
			this.btnDisconnect.Size = new System.Drawing.Size(103, 27);
			this.btnDisconnect.TabIndex = 8;
			this.btnDisconnect.Text = "Disconnect";
			this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
			// 
			// mainMenu1
			// 
			this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItem3});
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 0;
			this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.mnuAgentLoad,
																					  this.mnuAgentIntro,
																					  this.mnuAgentInstructions,
																					  this.mnuAgentHideShow,
																					  this.menuItem4});
			this.menuItem3.Text = "&Agent";
			// 
			// mnuAgentLoad
			// 
			this.mnuAgentLoad.Index = 0;
			this.mnuAgentLoad.Text = "&Load";
			this.mnuAgentLoad.Click += new System.EventHandler(this.menuItem4_Click);
			// 
			// mnuAgentIntro
			// 
			this.mnuAgentIntro.Enabled = false;
			this.mnuAgentIntro.Index = 1;
			this.mnuAgentIntro.Text = "&Introduce Peedy";
			this.mnuAgentIntro.Click += new System.EventHandler(this.mnuAgentIntro_Click);
			// 
			// mnuAgentHideShow
			// 
			this.mnuAgentHideShow.Enabled = false;
			this.mnuAgentHideShow.Index = 3;
			this.mnuAgentHideShow.Text = "&Hide";
			this.mnuAgentHideShow.Click += new System.EventHandler(this.mnuAgentHideShow_Click);
			// 
			// menuItem4
			// 
			this.menuItem4.Index = 4;
			this.menuItem4.Text = "&Option";
			this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click_1);
			// 
			// AgentCtl
			// 
			this.AgentCtl.Enabled = true;
			this.AgentCtl.Location = new System.Drawing.Point(552, 256);
			this.AgentCtl.Name = "AgentCtl";
			this.AgentCtl.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("AgentCtl.OcxState")));
			this.AgentCtl.Size = new System.Drawing.Size(32, 32);
			this.AgentCtl.TabIndex = 11;
			this.AgentCtl.ClickEvent += new AxAgentObjects._AgentEvents_ClickEventHandler(this.AgentCtl_ClickEvent);
			this.AgentCtl.Command += new AxAgentObjects._AgentEvents_CommandEventHandler(this.AgentCtl_Command);
			// 
			// mnuAgentInstructions
			// 
			this.mnuAgentInstructions.Enabled = false;
			this.mnuAgentInstructions.Index = 2;
			this.mnuAgentInstructions.Text = "I&nstructions";
			this.mnuAgentInstructions.Click += new System.EventHandler(this.mnuAgentInstructions_Click);
			// 
			// ChatClientForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
			this.ClientSize = new System.Drawing.Size(611, 336);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.AgentCtl,
																		  this.cbPrivate,
																		  this.btnLog,
																		  this.btnDisconnect,
																		  this.lbChatters,
																		  this.rtbChatIn,
																		  this.btnSend,
																		  this.btnConnect,
																		  this.statusBar1,
																		  this.ChatOut});
			this.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.Menu = this.mainMenu1;
			this.Name = "ChatClientForm";
			this.Text = "Peedy\'s Chat Room";
			((System.ComponentModel.ISupportInitialize)(this.AgentCtl)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion
		protected override void OnClosed(EventArgs e)
		{
			QuitChat();
			if(receive != null && receive.IsAlive)
				receive.Abort();
			
			base.OnClosed(e);
		}

		private void EstablishConnection()
		{
			statusBar1.Text = "Connecting to Server";
			try 
			{
				clientsocket = new TcpClient(serveraddress,serverport);
				ns = clientsocket.GetStream();
				sr = new StreamReader(ns);
				connected = true;
			}
			catch (Exception e)
			{
				if (Peedy.Visible)
				{
					Peedy.Play("Decline");
					Peedy.Speak("Could not connect to Server",null);
				}
				else
				{
					MessageBox.Show("Could not connect to Server","Error",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
				statusBar1.Text = "Disconnected";
			}
		}
		private void RegisterWithServer()
		{
			try 
			{
				string command = "CONN|" + ChatOut.Text;
				Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
				ns.Write(outbytes,0,outbytes.Length);
				
				string serverresponse = sr.ReadLine();
				serverresponse.Trim();
				string[] tokens = serverresponse.Split(new Char[]{'|'});
				if(tokens[0] == "LIST")
				{
					statusBar1.Text = "Connected";
					btnDisconnect.Enabled = true;
				}
				for(int n=1; n<tokens.Length-1; n++)
					lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'}));
				this.Text ="Hi, "+ clientname + " this is Peedy's Chat Room";
				
			}
			catch (Exception e)
			{
				if (Peedy.Visible)
				{
					Peedy.Play("Decline");
					Peedy.Speak("Could not connect to Server",null);
				}
				else
				{
					MessageBox.Show("Error Registering","Error",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
			}
		}
		
		private void ReceiveChat()
		{
			bool keepalive = true;
			while (keepalive) 
			{
				try
				{
					Byte[] buffer = new Byte[2048];
					ns.Read(buffer,0,buffer.Length);
					string chatter = System.Text.Encoding.ASCII.GetString(buffer);

					string[] tokens = chatter.Split(new Char[]{'|'});
					// CHAT|clientname|ChatOut
					if (tokens[0] == "CHAT")
					{
						if (tokens[2].Substring(0,1)=="/")
						{
							// Chat|Mary|/Acknowledge Yes,you are right.
							string tmp=tokens[2].Substring(1);
							rtbChatIn.AppendText(tokens[1]+":"+tokens[2].Substring(tokens[2].IndexOf(" ")+1));
							if (Peedy.Visible)
								ag_Parse(tokens[2].Substring(1));
						}
						else
							rtbChatIn.AppendText(tokens[1]+":"+tokens[2]);
						if(logging)
							logwriter.WriteLine(tokens[1]);
					}
					if (tokens[0] == "PRIV") 
					{
						rtbChatIn.AppendText("Private from ");
						rtbChatIn.AppendText(tokens[1].Trim() );
						rtbChatIn.AppendText(": ");
						rtbChatIn.AppendText(tokens[2] + "\r\n");
						if (Peedy.Visible)
                            ag_Parse(tokens[2].Substring(1));
						if(logging)
						{
							logwriter.Write("Private from ");
							logwriter.Write(tokens[1].Trim() );
							logwriter.WriteLine(tokens[2] + "\r\n");
						}
					}
					if (tokens[0] == "JOIN")
					{
						rtbChatIn.AppendText(tokens[1].Trim() );
						rtbChatIn.AppendText(" has joined the Chat\r\n");
						if(logging)
						{
							logwriter.WriteLine(tokens[1]+" has joined the Chat");
						}
						string newguy = tokens[1].Trim(new char[]{'\r','\n'});
						lbChatters.Items.Add(newguy);
					}
					if (tokens[0] == "GONE")
					{
						rtbChatIn.AppendText(tokens[1].Trim() );
						rtbChatIn.AppendText(" has left the Chat\r\n");
						if(logging)
						{
							logwriter.WriteLine(tokens[1]+" has left the Chat");
						}
						lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'}));
					}
					if (tokens[0] == "QUIT")
					{
						ns.Close();
						clientsocket.Close();
						keepalive = false;
						statusBar1.Text = "Server has stopped";
						connected= false;
						btnSend.Enabled = false;
						btnDisconnect.Enabled = false;
					}
				}
				catch(Exception e){}
			}
		}
		private void QuitChat() 
		{
			if(connected) 
			{
				try
				{
					string command = "GONE|" + clientname;
					Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
					ns.Write(outbytes,0,outbytes.Length);
					clientsocket.Close();
				}
				catch(Exception ex)
				{
				}
			}
			if(logging)
				logwriter.Close();

			if(receive != null && receive.IsAlive)
				receive.Abort();
			this.Text = "ChatClient";
			
		}

		private void StartStopLogging() 
		{
			if(!logging)
			{
				if(!Directory.Exists("logs"))
					Directory.CreateDirectory("logs");
				string fname = "logs\\" + DateTime.Now.ToString("ddMMyyHHmm") + ".txt";
				logwriter = new StreamWriter(new FileStream(fname, FileMode.OpenOrCreate,
					FileAccess.Write));
				logging = true;
				btnLog.Text = "Stop Logging";
				statusBar1.Text = "Connected - Log on";
			}
			else
			{
				logwriter.Close();
				logging = false;
				btnLog.Text = "Start Logging";
				statusBar1.Text = "Connected - Log off";
			}

		}
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(String[] args) 
		{
			ChatClientForm cf = new ChatClientForm();
			if(args.Length == 0)
				cf.serveraddress = "localhost";
			else
				cf.serveraddress = args[0];

			Application.Run(cf);
		}

		private void btnConnect_Click(object sender, System.EventArgs e)
		{
			if(ChatOut.Text == "")
			{
				MessageBox.Show("Enter a name in the box before connecting","Error",
					MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			else
				clientname = ChatOut.Text;
			
			EstablishConnection();
			
			if(connected)
			{
				RegisterWithServer();
				receive = new Thread(new ThreadStart(ReceiveChat));
				receive.Start();
				btnSend.Enabled = true;
				btnConnect.Enabled = false;
				ChatOut.Text = "";
			}
		}

		private void btnSend_Click(object sender, System.EventArgs e)
		{
			try
			{
				if(!privatemode)
				{
					string pubcommand = "CHAT|" + clientname + "|" + ChatOut.Text + "\r\n";
					Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(pubcommand.ToCharArray());
					ns.Write(outbytes,0,outbytes.Length);
					ChatOut.Text = "";
				}
				else
				{
					if(lbChatters.SelectedIndex == -1)
					{
						MessageBox.Show("Select a chatter name from the list","Error",
							MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
						return;
					}

					string destclient = lbChatters.SelectedItem.ToString();
					string command = "PRIV|" + clientname + "|" + ChatOut.Text + "|" + destclient;
					Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
					ns.Write(outbytes,0,outbytes.Length);
					ChatOut.Text = "";
				}

			}
			catch(Exception ex)
			{
				MessageBox.Show("Connection with Server lost","Error",
					MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				ns.Close();
				clientsocket.Close();
				if(receive != null && receive.IsAlive)
					receive.Abort();
				connected = false;
				statusBar1.Text = "Disconnected";
			}
		}

		private void btnDisconnect_Click(object sender, System.EventArgs e)
		{
			QuitChat();
			btnDisconnect.Enabled = false;
			btnConnect.Enabled = true;
			btnSend.Enabled = false;
			ns.Close();
			clientsocket.Close();
			receive.Abort();
			connected = false;
			lbChatters.Items.Clear();
			statusBar1.Text = "Disconnected";
		}

		private void ChatOut_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) 
		{
			if(e.KeyChar == '\r')
				if(connected)
					btnSend_Click(sender, e);
				else
					btnConnect_Click(sender, e);
		}

		private void btnLog_Click(object sender, System.EventArgs e) 
		{
			StartStopLogging();
		}

		private void cbPrivate_CheckedChanged(object sender, System.EventArgs e) 
		{
			if(cbPrivate.Checked)
			{
				privatemode = true;
				lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.One;
			}
			else
			{
				privatemode = false;
				lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.None;
			}
		}

		private void InitializeMSAgent()
		{
			
			//-- Load the character from the \msagent\chars subdirectory
			LoadRequest = AgentCtl.Characters.Load ("char1", "f:\\winnt\\msagent\\chars\\Peedy.acs");

			//-- If the character wasn't found, put up a message
			if (LoadRequest.Status == 1) 
				MessageBox.Show( "You don't have Peedy stored in the \\chars directory.\nYou can download him from the Microsoft Agent Downloads page.");
			

			//-- Set an object variable to the character 
			//-- loaded into the collection
			Peedy = AgentCtl.Characters["char1"];

			//-- Set the character's language to English
			Peedy.LanguageID = 0x0409;

			//-- Now check for it
			if (Peedy.SRModeID == "")
				MessageBox.Show("Either you have disabled speech input,\n- you don't have a compatible sound card,\n- or you haven't installed a compatible speech recognition engine .\n(You can download it from the Microsoft Agent Downloads page.)");
			

			//-- Check for the TTS engine engine
			if (Peedy.TTSModeID == "") 
				MessageBox.Show("Either you have disabled speech output,\n- you don't have a compatible sound card,\n- or you haven't installed a compatible text-to-speech engine.\n(You can download it from the Microsoft Agent Downloads page.)");


			//-- Add page's entry on to the character's pop-up menu
			//-- to enable switching back to this client's (page's) script
			//-- (this will only be seen if another client becomes input active)
			Peedy.Commands.Caption = "Peedy's Pizza Palace";
			Peedy.Commands.Voice = "Peedy's Pizza Palace";

			//-- Move the character and make it visible
			Peedy.MoveTo( 20,90,null);
			Peedy.Show(false);

			//-- Initialize the voice grammar for the demo
			InitializeCommands();

		}

		private void InitializeCommands()
		{
			//-------------------------------------------------
			//-- This subroutine creates the commands the
			//-- application will use.
			//-------------------------------------------------

			//-- Add Introduce button voice grammar
			Peedy.Commands.Add( "Introduce", "&Introduce", "(introduce[yourself])",true,true);
			Peedy.Commands["Introduce"].ConfidenceText = "Didn't understand your request.";
			Peedy.Commands["Introduce"].Confidence = -60;

			//-- Add Instruction button voice grammar
			Peedy.Commands.Add( "Instructions", "I&nstructions", "(how do I use [the chat room]|[give me] [(some|the) instructions])",true,true);
			Peedy.Commands["Instructions"].ConfidenceText = "Didn't understand your request.";
			Peedy.Commands["Instructions"].Confidence = -60;

			//-- Add Send button voice grammar
			Peedy.Commands.Add ("Send","&Send","send",true,true);
			Peedy.Commands["Send"].ConfidenceText = "Didn't understand your request.";
			Peedy.Commands["Send"].Confidence = -60;

			//-- Add Connect button voice grammar
			Peedy.Commands.Add ("Connect","&Connect","connect",true,true);
			Peedy.Commands["Connect"].ConfidenceText = "Didn't understand your request.";
			Peedy.Commands["Connect"].Confidence = -60;

			//-- Add Disconnect button voice grammar
			Peedy.Commands.Add ("Disconnect","&Disconnect","disconnect",true,true);
			Peedy.Commands["Disconnect"].ConfidenceText = "Didn't understand your request.";
			Peedy.Commands["Disconnect"].Confidence = -60;

			//-- Add Exit button voice grammar
			Peedy.Commands.Add ("Exit","&Exit","exit",true,true);
			Peedy.Commands["Exit"].ConfidenceText = "Didn't understand your request.";
			Peedy.Commands["Exit"].Confidence = -60;
   		}

		private void DoIntro()
		{
			//------------------------------------------
			//-- Introduce Peedy
			//------------------------------------------
			//-- And play an intro animations
			Peedy.Play( "GestureLeft");
			Peedy.Speak( "Welcome to Peedy's Chat Room.",null);
			Peedy.Play( "Greet");
			Peedy.Speak( "I am Peedy.",null);
			Peedy.Play( "Restpose");
			Peedy.Speak ("Your online chating assistant.",null);
		}

		private void  DoInstructions()
		{
			//--------------------------------------------------
			//-- Have Peedy provide chat room using instructions
			//--------------------------------------------------
 
			//-- Move the character to the starting position
			Peedy.MoveTo( 20, 90,null);

			//-- Point to the TextOut	
			Peedy.Play( "GestureDown");
			Peedy.Speak ("First, Please enter your nickname and press the 'Connect' butten to connect to the server.",null);

			//-- Move over and point to the pizza toppings	
			Peedy.MoveTo (420,280,null);
			Peedy.Play ("GestureLeft");
			Peedy.Speak( "Then the the chatter's list will appear here.",null);
	
			Peedy.Play ("RestPose");
			Peedy.Speak ("When you're ready to send , just say 'Send  my word',",null);
	
			Peedy.Speak ("And I'll help you with that.",null);

			Peedy.Play ("Think");
			Peedy.Speak ("By the way,",null);
	
			Peedy.Speak ("You can request instructions again by clicking the 'Instructions' button.",null);
			Peedy.Play ("LookUpRight");
			Peedy.Play ("LookUpRightBlink");
			Peedy.Play ("LookUpRightReturn");

			if (AgentCtl.SpeechInput.Enabled == true)
			{
				Peedy.Play ("Alert");
				Peedy.Speak ("You can also interrupt me at any time by pressing the " + AgentCtl.SpeechInput.HotKey + " key.",null);
			}
			Peedy.Play ("Blink");
			Peedy.Speak( "Let's get started.",null);
			Peedy.MoveTo (200,280,null);
		}

		private void menuItem4_Click(object sender, System.EventArgs e)
		{
			InitializeMSAgent();
			mnuAgentLoad.Enabled=false;
			mnuAgentIntro.Enabled =true;
			mnuAgentInstructions.Enabled =true;
			mnuAgentHideShow.Enabled=true;

		}

		private void ag_Parse(string message)
		{
			string [] tokens=message.Split();
			if (tokens[0].ToLower()!="say")
			{
				Peedy.Play(tokens[0]);
				if (tokens[1]!="")				
					Peedy.Speak(message.Substring(message.IndexOf(" ")+1),null);
				Peedy.Play("RestPose");
			}
			else
			{
				if (tokens[1]!="")
                       Peedy.Speak(message.Substring(message.IndexOf(" ")+1),null);
			}
		}

		private void mnuAgentHideShow_Click(object sender, System.EventArgs e)
		{
			if (mnuAgentHideShow.Text=="Hide")
			{
				mnuAgentHideShow.Text="&Show";
				Peedy.Hide(false);
			}
			else
			{
				mnuAgentHideShow.Text="&Hide";
				Peedy.Show(false);
			}
		}

		private void mnuAgentIntro_Click(object sender, System.EventArgs e)
		{
			//-- Start Peedy's Intro
			DoIntro();		
		}

		private void menuItem4_Click_1(object sender, System.EventArgs e)
		{
			AgentCtl.ShowDefaultCharacterProperties(20,90);
		}

		private void AgentCtl_Command(object sender, AxAgentObjects._AgentEvents_CommandEvent e)
		{
			
			IAgentCtlUserInput ui;
			ui = (IAgentCtlUserInput)e.userInput;
			
			switch(ui.Name)       
			{   
				case "Introduce":
					DoIntro();
					break;
				case "Instructions":
					DoInstructions();
					break;
				case "Send":
					Peedy.Speak("Send message to the server",null);
					btnSend_Click(null,null);        
					break;
				case "Connect":   
					Peedy.Speak("Connect to the server",null);
					btnConnect_Click(null,null);
					break;                  
				case "Disconnect":
					Peedy.Speak("Disconnect from the server",null);
					btnDisconnect_Click(null,null);
					break;	
				case "Exit":
					Peedy.Speak("Good Bye",null);
					Peedy.Hide(false);
					Application.Exit();
					break;	
				          
			} 
		}

		private void AgentCtl_ClickEvent(object sender, AxAgentObjects._AgentEvents_ClickEvent e)
		{
			//-- If the user clicks the character with button one,
			//-- make him say something 
			if (e.button== 1)
			{
				Peedy.Play("Surprised");
				Peedy.Speak( "Hey, what can I do for you!|At your service!",null);
				Peedy.Play("Alert");
			}
		}

		private void  OrderPrompt()
		{}

		private void menuItem2_Click(object sender, System.EventArgs e)
		{
			Application.Exit();
		}

		private void mnuAgentInstructions_Click(object sender, System.EventArgs e)
		{
			DoInstructions();
		}
	}
}
