// ChatServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChatServer.h"
#include "ChatServerDlg.h"
#include "DataProcess.h"
#include "ListenChat.h"
#include "ClientChat.h"
#include <stdlib.h>
#include "Setting.h"
#include "SysMseeage.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

extern CString ServerSystemStatus[] = {"<STATUS>Socket Accept. Login Please.</STATUS>" , 
								"<STATUS>Login Succeed.</STATUS>",
								"<STATUS>Login Error.</STATUS>",
								"<STATUS>Server Logout.</STATUS>",
								"<STATUS>Edit Data Error</STATUS>",
								"<STATUS>密碼錯誤.</STATUS>",
								"<STATUS>帳號錯誤.</STATUS>",
								"<STATUS>註冊帳號失敗.</STATUS>"};


class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatServerDlg dialog

CChatServerDlg::CChatServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CChatServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CChatServerDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	mHollowBrush.CreateStockObject (HOLLOW_BRUSH); 
	
	Host_IP = "140.112.18.197";
	ServerPort = 10000;	
}

void CChatServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChatServerDlg)
	DDX_Control(pDX, ID_BROAD, m_BROAD);
	DDX_Control(pDX, ID_KROOM, m_KRoom);
	DDX_Control(pDX, IDOK, m_OK);
	DDX_Control(pDX, IDC_STARTSERVER, m_START);
	DDX_Control(pDX, IDC_SERVERSETTING, m_SET);
	//}}AFX_DATA_MAP
//********************************************************************
	DDX_Control(pDX, IDC_SYSMESSAGEVIEW , m_SysMsgContent );
//********************************************************************

}

BEGIN_MESSAGE_MAP(CChatServerDlg, CDialog)
	//{{AFX_MSG_MAP(CChatServerDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_CTLCOLOR()
	ON_WM_ERASEBKGND()
	ON_LBN_SELCHANGE(IDC_CHATROOMLIST, OnSelchangeChatroomlist)
	ON_LBN_SELCHANGE(IDC_USERLIST, OnSelchangeUserlist)
	ON_LBN_DBLCLK(IDC_USERLIST, OnDblclkUserlist)
	ON_LBN_DBLCLK(IDC_CHATROOMLIST, OnDblclkChatroomlist)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatServerDlg message handlers

BOOL CChatServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	Chatdb=new ChatRoom_DB;
	Chatdb->OnInitial();

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CChatServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CChatServerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
		//dc.SetBkMode(TRANSPARENT);
		//dc.SetBkColor(RGB(255,255,0));
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CChatServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CChatServerDlg::OnStartserver() 
{
	// TODO: Add your control notification handler code here
//************************************************************************
	m_plisteningSocket = new CListenChat(this) ;
	Number_of_clients  = 0 ;
//	ServerPort = 10000;
	
	if ( m_plisteningSocket->Create( ServerPort , SOCK_STREAM , FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE ) )
	{
//		m_plisteningSocket->GetSockName( Host_IP , ServerPort );
		char* tempPort = new char [6];
		_itoa( ServerPort , tempPort ,  10 );
		CString ServerMsg = _T("Chat Room Server Start At Port ")  ;
		ServerMsg += tempPort;
		ServerMsg += '\n';
		if (m_plisteningSocket->Listen( 5 ))
		{
			AddSysMsg( ServerMsg );
		}
		else
		{	
			AfxMessageBox(" Listen Socket Listen Error! ");
			m_START.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SS1)));
		}
	}
	else 
	{	
		AfxMessageBox(" Listen Socket Creation Error! ");
		m_START.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SS1)));
	}
	
//	CString commandt , paramt;
	//ParseCommend(  "<FORWORD><MAN>123</MAN><MSG>testtest</MSG></FORWORD>", commandt, paramt   );
//	ParseCommend(  "<MAN>123</MAN><MSG>testtest</MSG>", commandt, paramt   );
//****************************************************************************	
	
}

//*****************************************************************************
void CChatServerDlg::ProcessAccept()
{
	
	//加到ListBox
/*	CListBox* temp_list_box;
	temp_list_box = (CListBox*)GetDlgItem( IDC_CHATROOM );

	if( temp_list_box->FindString( -1, "Hall" ) < 0 )
	{
		temp_list_box->AddString( "All Users" );
		temp_list_box->AddString( "Hall" );
		temp_list_box->SetCurSel( 0 );
	}

	m_t_num_of_clients++;
	CString temp_num_of_clients;
	temp_num_of_clients.Format("%d",m_t_num_of_clients);
	((CEdit*)GetDlgItem( IDC_TOTAL_NUM ))->SetWindowText(temp_num_of_clients);
*/

	//處理連接
	//AfxMessageBox("Connect!");
	//CSocket* p_client = new CSocket();
	CClientChat* p_clientSocket = new CClientChat(this);

	if ( m_plisteningSocket->Accept( *p_clientSocket ))
	{
		p_clientSocket->Init();
		m_ClientList.AddTail( p_clientSocket );
		Number_of_clients++;
	}
	else
		delete p_clientSocket;
}

void CChatServerDlg::AddSysMsg( CString in )
{
/*	CString temp;
	for( int k = 1 ; k < datalength ; k++ )
		temp = temp + temp_data[k] ;
	CString temp_str;
	if(destIP == "111")
		temp_str = temp_str + SourceIP + "廣播" + "::" + temp + '\n';
	else
		temp_str = temp_str + SourceIP + "::" + temp + '\n';
*/
	m_SysMsgContent.SetSel( -1 , 0 ); // remove all selection
	m_SysMsgContent.ReplaceSel( in );
/*	m_content.SetSel( m_cur_len, m_cur_len+temp_str.GetLength()-1 );
	m_cur_len+=temp_str.GetLength();
	m_content.SetSel( m_cur_len, m_cur_len+1 );
*/
}


BOOL CChatServerDlg::ParseCommend(  CString inpmsg, CString &command, CString &param   )
{
	CString cmds[]={"<USER>" , "<PASS>" , "<FORWARD>" , "<MAN>" , "<MSG>" , "<CHAT>" ,"<BROADCAST>",
					"<REGISTER>" , "<CREAKCHATROOM>" , "<DESTROYCHATROOM>",
					"<ENTERCHATROOM>" , "<LEAVECHATROOM>" , "<LOGOUT>",
					"<EDITNICK>","<EDITPWD>","<EDITMAIL>",
					"<CHATLIST>","<USERLIST>","<CHATUSER>",
					"<USERNAME>","<PASSWORD>","<NICKNAME>","<EMAIL>",
					"<ACKUSERLIST>","<ACKCHATUSER>","<ACKINFORMATION>","END_ARRAY"};
	
	CString endcmds[]={ "</USER>" , "</PASS>" , "</FORWARD>" , "</MAN>" , "</MSG>" , "</CHAT>" ,"</BROADCAST>",
						"</REGISTER>" , "</CREAKCHATROOM>" , "</DESTROYCHATROOM>",
						"</ENTERCHATROOM>" , "</LEAVECHATROOM>" , "</LOGOUT>",
						"</EDITNICK>","</EDITPWD>","</EDITMAIL>",
						"</CHATLIST>","</USERLIST>","</CHATUSER>",
						"</USERNAME>","</PASSWORD>","</NICKNAME>","</EMAIL>",
						"</ACKUSERLIST>","</ACKCHATUSER>","</ACKINFORMATION>"};
	int  commendpos = 0 , endcompos = 0;

	if( inpmsg.Find( "<" ) != 0 )
		return false;
	commendpos = inpmsg.Find( ">" );
	command = inpmsg.Mid( 1 , commendpos - 1 );

	CString commandtemp = "<";
	commandtemp += command;
	commandtemp += ">";

	for(int i=0 ; cmds[i] != "END_ARRAY" ; i++)
	{
		
		if( commandtemp == cmds[i] )
		{
			endcompos = inpmsg.Find( endcmds[i] );
			param=inpmsg.Mid( cmds[i].GetLength()  , endcompos - cmds[i].GetLength() );
			if( inpmsg.GetLength() > endcompos + endcmds[i].GetLength() )
			{
				CString remder ;
				remder = inpmsg.Mid( endcompos + endcmds[i].GetLength()  , inpmsg.GetLength() -  endcompos - endcmds[i].GetLength()  );
				commendrender.push( remder );
			}
			return true;
		}
	}
	return false;	
}

void CChatServerDlg::ProcessRead( CClientChat* p_client )
{
	int InMsgLength = 0;
	int p_nowplace = 0;
	CString command , param;
	TCHAR InMsg[1000] ;

	ZeroMemory( InMsg , sizeof(InMsg) );

	InMsgLength = p_client->Receive( InMsg , sizeof(InMsg) , 0 );

	do
	{
		if( ParseCommend( InMsg , command , param  ) )
		{
			if( command  == "FORWARD" && p_client->IsLogin ) 
			{
				//*****************************************
					// forward message (form user to server.)
				//*****************************************
//				CString render = param;
				if( ParseCommend( param , command , param  ) )
				{
					CString nametemp = param;
					if( command == "MAN" )
					{
						CString render = commendrender.top();
						commendrender.pop();
						if( ParseCommend( render , command , param  ) )
						{
							if( command == "MSG" )
								ForwardMsg2Person( p_client , nametemp , param );
						}
					}
					else if( command == "CHAT")
					{
						CString render = commendrender.top();
						commendrender.pop();
						if( ParseCommend( render , command , param  ) )
						{
							if( command == "MSG" )
								ForwardMsg2Chatroom( p_client , nametemp , param );
						}
					}
					else
					{
						AfxMessageBox("Income Message has wrong format.");
						break;
					}
				}
				
				break;						
			}
			else if( command  == "BROADCAST" && p_client->IsLogin)
			{
				bool wrong=true;
				if( ParseCommend( param , command , param  ) )
				{
					if( command == "MAN" )
					{
						CString render = commendrender.top();
						commendrender.pop();
						if( ParseCommend( render , command , param  ) )
						{
							if( command == "MSG" )
							ForwardMsg2Every( p_client, param,1 );
							wrong=false;
						}
					}
				}
				if (wrong) 
				{
					AfxMessageBox("Income Message has wrong format.");
				}
				break;
			}
			else if( command  == "USER")
			{//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				CPerson p1=Chatdb->SearchName(param);
			  if (p1.idname!="")
			  {
				p_client->Username = param;
				//**************
				CString render = commendrender.top();
				commendrender.pop();
				if( ParseCommend( render , command , param  ) )
				{
					if( command  == "PASS" )
					{
						Login_P(p_client,param);
					}
					else
					{
						// send "error"
						p_client->Send( ServerSystemStatus[2]  , ServerSystemStatus[2].GetLength() , 0 );
						this->AddSysMsg("Income Message has wrong format.\n");
						// close the socket.
						RemoveSocket(p_client);
					}	
					break;
				}
			  }
			  else
			  {
				  //%%%%%%%%%%%%%%%%%%%%%%%%%%
					// send "error"
					p_client->Send( ServerSystemStatus[2]  , ServerSystemStatus[2].GetLength() , 0 );
					this->AddSysMsg("Income Message has unknown errors.\n");
					// close the socket.
					RemoveSocket(p_client);
					break;
					//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
			  }
			}
			else if( command  == "REGISTER" ) 
			{
				//*****************************************
					// new person.
				//*****************************************
				bool wrong=true;
				CString username;
				CString pwrd;
				CString nick;
				CString email;
				CString render;
				if( ParseCommend( param , command , param  ) )
				{
					username = param;
					p_client->Username=param;
					if( command == "USERNAME" )
					{
						render = commendrender.top();
						commendrender.pop();
						if( ParseCommend( render , command , param  ) )
						{
							pwrd = param;
							if( command == "PASSWORD" )
							{
								render = commendrender.top();
							    commendrender.pop();
								if( ParseCommend( render , command , param  ) )
								{
									nick=param;
									if(command == "NICKNAME")
									{
										render = commendrender.top();
										commendrender.pop();
										if( ParseCommend( render , command , param  ) )
										{
											email=param;
											if(command == "EMAIL")
											{
												CString tt=p_client->Username;
												RegisterNewPerson(p_client,username,pwrd,nick,email);
												wrong=false;
											}
										}
									}
								}
							}
						}
					}
				}
				if (wrong) 
				{
					this->AddSysMsg("Income Message has wrong format.\n");
					this->AddSysMsg("Register is cancelled.\n");
					RemoveSocket(p_client);
				}
				break;
			}
			else if( command  == "CREAKCHATROOM" && p_client->IsLogin) 
			{
				//*****************************************
					// CREAK CHATROOM
				//*****************************************
				CreatChatroom( p_client , param );
				AskChatMember(param);
				break;
			}
			else if( command  == "DESTROYCHATROOM" && p_client->IsLogin) 
			{
				//*****************************************
					// DESTROY CHATROOM
				//*****************************************
				DestroyChatroom( p_client , param );
				break;						
			
			}
			else if( command  == "ENTERCHATROOM" && p_client->IsLogin) 
			{
				//*****************************************
					// ENTER CHATROOM
				//*****************************************
				EnterChatroom( p_client , param );
				break;						
			
			}
			else if( command  == "LEAVECHATROOM" && p_client->IsLogin) 
			{
				//*****************************************
					// LEAVE CHATROOM
				//*****************************************
				LeaveChatroom(  p_client , param );	
				break;						
			
			}
			else if( command  == "LOGOUT" && p_client->IsLogin) 
			{
				//*****************************************
					// new person.
				//*****************************************
				Logout( p_client );
				break;						
			}
			else if( command  == "ACKUSERLIST" && p_client->IsLogin) 
			{
				//*****************************************
					// ACKUSERLIST
				//*****************************************
				OnFreshing2();
				break;
			}
			else if( command  == "ACKCHATUSER" && p_client->IsLogin) 
			{
				//*****************************************
					// ACKCHATUSER
				//*****************************************
				OnFreshing3();
				break;
			}
			else if( command  == "ACKINFORMATION" && p_client->IsLogin) 
			{
				//*****************************************
					// ACKINFORMATION
				//*****************************************
				OnFreshing4(FALSE);
				break;
			}
			//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
			else if( command  == "EDITPWD" && p_client->IsLogin)
			{
				if(!(Chatdb->EditData_PWD(p_client->Username, param)))
				{
					p_client->Send( ServerSystemStatus[4]  , ServerSystemStatus[4].GetLength() , 0 );
					this->AddSysMsg("Income Message has wrong format.\n");
					this->AddSysMsg("Data-editing is cancelled.\n");
				}
				else
				{
					CString tmp="<ACKEDITNICK></ACKEDITNICK>";
					p_client->Send( tmp , tmp.GetLength() , 0 );
					OnFreshing4(TRUE);
				}
				break;
			}
			else if( command  == "EDITNICK" && p_client->IsLogin)
			{
				if(!(Chatdb->EditData_Nick(p_client->Username, param)))
				{
					p_client->Send( ServerSystemStatus[4]  , ServerSystemStatus[4].GetLength() , 0 );
					this->AddSysMsg("Income Message has wrong format.\n");
					this->AddSysMsg("Data-editing is cancelled.\n");
				}
				else
				{
					CString tmp="<ACKEDITMAIL></ACKEDITMAIL>";
					p_client->Send( tmp , tmp.GetLength() , 0 );
					OnFreshing4(TRUE);
				}
				break;
			}
			else if( command  == "EDITMAIL" && p_client->IsLogin)
			{
				if(!(Chatdb->EditData_Email(p_client->Username, param)))
				{
					p_client->Send( ServerSystemStatus[4]  , ServerSystemStatus[4].GetLength() , 0 );
					this->AddSysMsg("Income Message has wrong format.\n");
					this->AddSysMsg("Data-editing is cancelled.\n");
				}
				else
					OnFreshing4(TRUE);
				break;
			}
			//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
			else
			{
				this->AddSysMsg("Income Message has wrong format.\n");
				this->AddSysMsg("Data-editing is cancelled.\n");
				break;
			}
		}
		else
		{	
			this->AddSysMsg("Income Message has wrong format.\n");
			break;
		}
	}while(1);

}

void CChatServerDlg::Login_P(CClientChat* p_client,CString param)
{
	int login_check=Chatdb->Login(p_client->Username,param);
	if(login_check==3)
	{
		    p_client->IsLogin =true;
		//*****************************************
		// initialize the personal data
		//*****************************************
		// add to list box
			CListBox *ListBox = (CListBox *)GetDlgItem(IDC_USERLIST);
			ListBox->AddString( p_client->Username );
		//*****************************************
							
		//*****************************************
		// add to system message list
			CString tempsysmsg = "使用者 ";
			tempsysmsg += p_client->Username;
			tempsysmsg += " 登入。" ;
			tempsysmsg += '\n';
			this->AddSysMsg( tempsysmsg );							
		//*****************************************
			p_client->Send( ServerSystemStatus[1]  , ServerSystemStatus[1].GetLength() , 0 );
			OnFreshing();
	}
	else if (login_check==0) //已在線上
	{
		p_client->Send( ServerSystemStatus[2]  , ServerSystemStatus[2].GetLength() , 0 );
		// close the socket.
		this->AddSysMsg(p_client->Username+" 已經在線上\n");
		RemoveSocket(p_client);
	}
	else if (login_check==1) //密碼錯誤
	{
		p_client->Send( ServerSystemStatus[5]  , ServerSystemStatus[5].GetLength() , 0 );
		// close the socket.
		this->AddSysMsg(p_client->Username+" password error.\n");
		RemoveSocket(p_client);
	}
	else
	{	// send "error"沒這人
		p_client->Send( ServerSystemStatus[6]  , ServerSystemStatus[6].GetLength() , 0 );
		this->AddSysMsg("No this one.\n");
		// close the socket.
		RemoveSocket(p_client);
	}
}

void CChatServerDlg::RemoveSocket( CClientChat* p_client )
{
	p_client->ShutDown( 2 );
	p_client->Close();
	POSITION pos;
	delete p_client;
	if( ( pos = m_ClientList.Find( p_client ) ) != NULL )
	{
		m_ClientList.RemoveAt( pos );
	}
	else
	{
		AfxMessageBox("The Client socket isn't on the socket-list.");
	}
}

BOOL CChatServerDlg::Send2MAN( CString MAN , CString MSG )
{
	POSITION pos;
	CClientChat* p_client;
	for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)m_ClientList.GetNext( pos ) ;
		if( p_client->Username == MAN )
		{
			p_client->Send( MSG , MSG.GetLength() , 0 );
			return true;
		}
	}
	return false;
}

void CChatServerDlg::CreatChatroom( CClientChat* p_client , CString ChatName )
{
	//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	if (!Chatdb->Open_New(p_client->Username,ChatName))
	      this->AddSysMsg( "開新聊天室失敗\n" );
	else
	{
		CString tempsysmsg = "使用者 ";
		tempsysmsg += p_client->Username;
		tempsysmsg += " 建立新聊天室 ";
		tempsysmsg += ChatName;
		tempsysmsg += "。" ;
		tempsysmsg += '\n';
		this->AddSysMsg( tempsysmsg );
		CListBox *ListBox = (CListBox *)GetDlgItem(IDC_CHATROOMLIST);
		ListBox->AddString(ChatName);
		OnFreshing();
		
	}
	return;
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
}

void CChatServerDlg::DestroyChatroom( CClientChat* p_client , CString ChatName )
{
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	if(!Chatdb->Close_Chat(p_client->Username,ChatName))
		this->AddSysMsg( "關閉聊天室失敗\n" );
	else
	{
		        CString tempsysmsg = "使用者 ";
				tempsysmsg += p_client->Username;
				tempsysmsg += " 關閉聊天室 ";
				tempsysmsg += ChatName;
				tempsysmsg += "。" ;
				tempsysmsg += '\n';
				this->AddSysMsg( tempsysmsg );
				CListBox *ListBox = (CListBox *)GetDlgItem(IDC_CHATROOMLIST);
				int nIndex;
				if ((nIndex=ListBox->FindString(-1, ChatName)) != LB_ERR)
				{
					ListBox->DeleteString( nIndex );
				}
				OnFreshing();
	}
	return;
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
}

void CChatServerDlg::EnterChatroom( CClientChat* p_client , CString ChatName )
{
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	if(!Chatdb->JOIN_Chat(p_client->Username,ChatName))
		this->AddSysMsg( "加入"+ChatName+"聊天室失敗\n" );
	else
	{			
		        CString tempsysmsg = "使用者 ";
				tempsysmsg += p_client->Username;
				tempsysmsg += " 進入聊天室 ";
				tempsysmsg += ChatName;
				tempsysmsg += "。" ;
				tempsysmsg += '\n';
				this->AddSysMsg( tempsysmsg );
				AskChatMember(ChatName);
	}
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	return;
}

void CChatServerDlg::LeaveChatroom( CClientChat* p_client , CString ChatName)
{
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	int flag=Chatdb->Left_Chat(p_client->Username,ChatName);
	if(flag==0)
		this->AddSysMsg( "離開聊天室失敗\n" );
	else if (flag==1)
	{
		DestroyChatroom( p_client ,ChatName );
	}
	else
	{
		CString tempsysmsg = "使用者 ";
		tempsysmsg += p_client->Username;
		tempsysmsg += " 離開聊天室 ";
		tempsysmsg += ChatName;
		tempsysmsg += "。" ;
		tempsysmsg += '\n';
		this->AddSysMsg( tempsysmsg );
		AskChatMember( ChatName );
	}
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	return;
}

void CChatServerDlg::Logout( CClientChat* p_client )
{
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	if(!Chatdb->Logout(p_client->Username))
		this->AddSysMsg( "登出失敗\n" );
	else
	{		
		//清除所參與的聊天室紀錄
		POSITION pos;
		for(;;) 
		{
			pos=Chatdb->WhereIs(p_client->Username);
			if(pos!=NULL) LeaveChatroom(p_client, Chatdb->Room_Memberset.GetAt(pos)._room_name);
			else break;
		}

		CString user_name=p_client->Username;
		CString tempsysmsg = "使用者 ";
		tempsysmsg += user_name;
		tempsysmsg += " 登出。" ;
		tempsysmsg += '\n';
		this->AddSysMsg( tempsysmsg );
		CListBox *ListBox = (CListBox *)GetDlgItem(IDC_USERLIST);
		int nIndex;
		if ((nIndex=ListBox->FindString(-1, user_name)) != LB_ERR)
		{
			ListBox->DeleteString( nIndex );
		}
		RemoveSocket(p_client);
		OnFreshing();
	}
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	return;
}


void CChatServerDlg::RegisterNewPerson(CClientChat* p_client, CString username,CString pwrd,
									   CString nick,CString email)
{
	//********************************************************
	if(Chatdb->SavetoDB(username,"",pwrd,nick,"","",email,"","")==2)
	{ 
		this->AddSysMsg( "註冊新帳號成功\n" );
		p_client->IsLogin =true;
		//*****************************************
		// initialize the personal data
		//*****************************************
		// add to list box
			CListBox *ListBox = (CListBox *)GetDlgItem(IDC_USERLIST);
			ListBox->AddString( p_client->Username );
		//*****************************************
							
		//*****************************************
		// add to system message list
			CString tempsysmsg = "使用者 ";
			tempsysmsg += p_client->Username;
			tempsysmsg += " 登入。" ;
			tempsysmsg += '\n';
			this->AddSysMsg( tempsysmsg );							
		//*****************************************
			p_client->Send( ServerSystemStatus[1]  , ServerSystemStatus[1].GetLength() , 0 );
			OnFreshing();
	}
	else
	{	
		this->AddSysMsg( "註冊新帳號失敗\n" );
		p_client->Send( ServerSystemStatus[7]  , ServerSystemStatus[7].GetLength() , 0 );
	}
	return;
	//*********************************************************
}

void CChatServerDlg::ForwardMsg2Person( CClientChat* p_client , CString MAN , CString MSG )
{
	CString tempmsg = "<FORWARD><MAN>";	
	tempmsg += p_client->Username + "</MAN><MSG>" + MSG + "</MSG></FORWARD>";
	if( !Send2MAN( MAN , tempmsg ) )
		AddSysMsg( "Send to user[" + MAN + "] error.\n" );
//	else
//		AddSysMsg( tempmsg );

	return;
}

void CChatServerDlg::ForwardMsg2Chatroom( CClientChat* p_client , CString CHAT , CString MSG )
{
	CStringList vec;
	Chatdb->Get_Chat_List(CHAT,vec);
	POSITION pos;
	if ((pos=vec.Find(p_client->Username))!=NULL)
	{
		CString MAN;
		CString tempmsg = "<FORWARD><CHAT>";	
		tempmsg += CHAT+ "</CHAT><MSG>" + MSG + "</MSG><MAN>"+ p_client->Username+"</MAN></FORWARD>";
	    for (pos=vec.GetHeadPosition(); pos!=NULL;)
		{
		   MAN=vec.GetNext(pos);
		   if(p_client->Username!=MAN)
		   {
			   if( !Send2MAN( MAN , tempmsg ) )
				   AddSysMsg( "Send to user[" + MAN + "] error.\n" );
//			   else
//				   AddSysMsg( tempmsg );
		   }
		}
	}
	else
	{
		this->AddSysMsg("不在聊天室內\n");
	}
	return;
}

void CChatServerDlg::ForwardMsg2Every( CClientChat* p_client, CString MSG , int flag)
{
	CString tempmsg = "<BROADCAST><MAN>";	
	
	if (flag)
		tempmsg += p_client->Username + "</MAN><MSG>" + MSG + "</MSG></BROADCAST>";
	else
		tempmsg +="Server</MAN><MSG>" + MSG + "</MSG></BROADCAST>";

	for( POSITION pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		CClientChat* p_temp=(CClientChat*)m_ClientList.GetNext(pos);
			if( !Send2MAN( p_temp->Username , tempmsg ) )
				AddSysMsg( "Send to user[" + p_temp->Username + "] error.\n" );
//			else
//				AddSysMsg( tempmsg );
	}
	return;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void CChatServerDlg::AskChatMember( CString CHAT )
{
	CStringList vec;
	if (Chatdb->Get_Chat_List(CHAT,vec))
	{
	CString MEN="";
	CString tmp;
	POSITION pos,pos2;
	POSITION pos_end=vec.GetTailPosition();
	CPtrList Temp_List;
	CClientChat* p_client=new CClientChat;
	for (pos=vec.GetHeadPosition(); pos!=NULL;)
	{
			for( pos2 = m_ClientList.GetHeadPosition() ; pos2 != NULL ; )
			{
				p_client = (CClientChat*)m_ClientList.GetNext( pos2 );
				if(p_client->Username==vec.GetAt(pos))
					Temp_List.AddTail(p_client);
			}
		if (pos!=pos_end)
			tmp=vec.GetNext(pos)+";";
		else
			tmp=vec.GetNext(pos);
		MEN+=tmp;	
	}
	CString tempmsg = "<CHATUSER><CHAT>";	
	tempmsg += CHAT+ "</CHAT><MAN>" + MEN + "</MAN></CHATUSER>";
	 
	for( pos = Temp_List.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)Temp_List.GetNext( pos );
		p_client->Send( tempmsg , tempmsg.GetLength() , 0 );
	}
	}
	return;
}

CString CChatServerDlg::AskChatMember2(CString CHAT)
{
	CString tempmsg="";
	CStringList vec;
	if (Chatdb->Get_Chat_List(CHAT,vec))
	{
	CString MEN="";
	CString tmp;
	POSITION pos;
	POSITION pos_end=vec.GetTailPosition();
	for (pos=vec.GetHeadPosition(); pos!=NULL;)
	{
		if (pos!=pos_end)
			tmp=vec.GetNext(pos)+";";
		else
			tmp=vec.GetNext(pos);
		MEN+=tmp;	
	}
	tempmsg = "<CHAT>";	
	tempmsg += CHAT+ "</CHAT><MAN>" + MEN + "</MAN>";
	}
	return tempmsg;
}

void CChatServerDlg::OnFreshing()
{
	CStringList vec;
	Chatdb->GetAllChatroom(vec);
	CString CHATS="";
	CString tmp;
	ATForce="";
	POSITION pos_end=vec.GetTailPosition();
	POSITION pos;
	for ( pos=vec.GetHeadPosition(); pos!=NULL;)
	{
		ATForce+=AskChatMember2(vec.GetAt(pos));
		if (pos!=pos_end)
			tmp=vec.GetNext(pos)+";";
		else
			tmp=vec.GetNext(pos);
		CHATS+=tmp;
	}
	CString tempmsg = "<CHATLIST>"+CHATS+"</CHATLIST>";

	CClientChat* p_client;
	for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)m_ClientList.GetNext( pos );
		p_client->Send( tempmsg , tempmsg.GetLength() , 0 );
		
	}
	return;
}

void CChatServerDlg::OnFreshing2()
{
	CString client_names="";
	CClientChat* p_client;
	POSITION pos;
	for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)m_ClientList.GetNext( pos );
		client_names+=p_client->Username;
		if (pos!=NULL)  client_names+=";";
	}

	CString tempmsg ="<USERLIST>"+client_names+ "</USERLIST>";

	for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)m_ClientList.GetNext( pos );
		p_client->Send( tempmsg , tempmsg.GetLength() , 0 );
	}
	return;
}

void CChatServerDlg::OnFreshing3()
{
	CClientChat* p_client;
	POSITION pos;
	SEKAI="";
	CString tempmsg ="<CHATUSER>"+ATForce+ "</CHATUSER>";
	for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)m_ClientList.GetNext( pos );
		p_client->Send( tempmsg , tempmsg.GetLength() , 0 );
		CPerson P1=Chatdb->SearchName(p_client->Username);
		SEKAI+="<USERNAME>"+P1.idname+"</USERNAME>";
		SEKAI+="<NICKNAME>"+P1.nickname+"</NICKNAME>";
		SEKAI+="<EMAIL>"+P1.email+"</EMAIL>";
	}
	return;
}

void CChatServerDlg::OnFreshing4(BOOL flag)
{
	CClientChat* p_client;
	POSITION pos;
	CString tempmsg="";
	if (!flag)
		tempmsg ="<INFORMATION>"+SEKAI+ "</INFORMATION>";
	else
	{
		SEKAI="";
		for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
		{	
		p_client = (CClientChat*)m_ClientList.GetNext( pos );
		CPerson P1=Chatdb->SearchName(p_client->Username);
		SEKAI+="<USERNAME>"+P1.idname+"</USERNAME>";
		SEKAI+="<NICKNAME>"+P1.nickname+"</NICKNAME>";
		SEKAI+="<EMAIL>"+P1.email+"</EMAIL>";
		}
		tempmsg ="<INFORMATION>"+SEKAI+ "</INFORMATION>";
	}

	for( pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		p_client = (CClientChat*)m_ClientList.GetNext( pos );
		p_client->Send( tempmsg , tempmsg.GetLength() , 0 );
	}
	return;
}
//*********************************************************************

void CChatServerDlg::OnServersetting() 
{
	// TODO: Add your control notification handler code here
//***********************************************************************
	CSetting dlg;
//	dlg.setparant(this);

	dlg.SetBitmap(IDB_BIT,BITMAP_CENTER);
	if( m_plisteningSocket != NULL )
		dlg.IP = Host_IP;

	dlg.port =	ServerPort ;			

	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
//		dlg.UpdateData();
		//if( m_plisteningSocket == NULL )
		{
			ServerPort = dlg.port;		
		}
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel		
		return;
	}

//***********************************************************************
}



void CChatServerDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CRect rect_dlg,rectim1,rectim2,rectim3,rectim4,rectim5;
	this->GetWindowRect(rect_dlg);
	m_START.GetWindowRect(rectim1);
	m_SET.GetWindowRect(rectim2);
	m_OK.GetWindowRect(rectim3);
	m_BROAD.GetWindowRect(rectim4);
	m_KRoom.GetWindowRect(rectim5);

	const int top1=14;
	int left1=rectim1.left-rect_dlg.left;
	int right1=rectim1.right-rect_dlg.left;
	const int bottom1=83;

	int left2=rectim2.left-rect_dlg.left;
	int right2=rectim2.right-rect_dlg.left;

	int left3=rectim3.left-rect_dlg.left;
	int right3=rectim3.right-rect_dlg.left;

	int left4=rectim4.left-rect_dlg.left;
	int right4=rectim4.right-rect_dlg.left;

	int left5=rectim5.left-rect_dlg.left;
	int right5=rectim5.right-rect_dlg.left;

	if((point.x<=right1) && (point.x>=left1) && (point.y>=top1) && (point.y<=bottom1))
	{
		m_START.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SS2)) );
		OnStartserver();
	}
	else if((point.x<=right2) && (point.x>=left2) && (point.y>=top1) && (point.y<=bottom1))
	{	
		m_SET.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SE2)) );
		OnServersetting();
	}
	else if((point.x<=right3) && (point.x>=left3) && (point.y>=top1) && (point.y<=bottom1))
		m_OK.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_CS2)) );
	else if((point.x<=right4) && (point.x>=left4) && (point.y>=top1) && (point.y<=bottom1))
	{	
		m_BROAD.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SBro2)) );
		ServerBroadcast();
	}
	else if((point.x<=right5) && (point.x>=left5) && (point.y>=top1) && (point.y<=bottom1))
	{	
		m_KRoom.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_KRoom2)) );
		KillAny();
	}

	CDialog::OnLButtonDown(nFlags, point);
}

void CChatServerDlg::OnLButtonUp(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	m_START.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SS1)));	
	m_SET.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SE1)));
	m_OK.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_CS1)));
	m_BROAD.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SBro)) );
	m_KRoom.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_KRoom)) );
	CDialog::OnLButtonUp(nFlags, point);
}



HBRUSH CChatServerDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{	
	// TODO: Change any attributes of the DC here
	if (mBitmap.GetSafeHandle()!=NULL) 
	{ 
		switch (nCtlColor) 
		{ 
		case CTLCOLOR_STATIC:
			pDC->SetBkMode (TRANSPARENT); 
			return (HBRUSH) mHollowBrush.m_hObject; 
			break; 
		default: 
			HBRUSH hbr = CDialog::OnCtlColor (pDC, pWnd, nCtlColor); 
			return hbr ; 
			break; 
		} 
	}
	else 
	{ 
		HBRUSH hbr = CDialog::OnCtlColor (pDC, pWnd, nCtlColor); 
		return hbr; 
	} 
	// TODO: Return a different brush if the default is not desired
}



void CChatServerDlg::SetBitmap (UINT ResID, int Type) 

{ 
	mBitmap.DeleteObject();
	mBitmap.LoadBitmap(ResID);
	mType=Type;

}

BOOL CChatServerDlg::OnEraseBkgnd(CDC* pDC) 
{
	// TODO: Add your message handler code here and/or call default
		if (mBitmap.m_hObject!=NULL) 
	{ 
		CDC MemDC; 
		BITMAP bm; 
		CRect Rect;
		int x=0, y=0; 
		GetClientRect (&Rect); 
		mBitmap.GetObject (sizeof(BITMAP),&bm); 
		MemDC.CreateCompatibleDC(pDC); 
		CBitmap* pOldBitmap=MemDC.SelectObject(&mBitmap); 
		if (mType==BITMAP_CENTER) 
		{ 
			CDialog::OnEraseBkgnd(pDC); 
			x= (Rect.Width()-bm.bmWidth) /2; 
			y= (Rect.Height()-bm.bmHeight) /2; 
			pDC->BitBlt (x,y,bm.bmWidth,bm.bmHeight, &MemDC, 0, 0, SRCCOPY);
		} 
		else 
		{ 
			while (y<Rect.Height ()) 
			{ 
				while (x<Rect.Width ()) 
				{ 
					pDC->BitBlt (x,y,bm.bmWidth,bm.bmHeight, &MemDC,0,0,SRCCOPY ); 
					x=x+bm.bmWidth; 
				} 
				x=0; 
				y=y+bm.bmHeight; 
			} 
		} 
		MemDC.SelectObject (pOldBitmap);  
		return TRUE; 
	} 
	else 
		return CDialog::OnEraseBkgnd (pDC); 
	
}



void CChatServerDlg::OnSelchangeChatroomlist() 
{
	// TODO: Add your control notification handler code here
	CListBox* temp_list_box;
	temp_list_box = (CListBox*)GetDlgItem( IDC_CHATROOMLIST );

	CListBox* temp_list_box_u;
	temp_list_box_u = (CListBox*)GetDlgItem( IDC_USERLIST );

	if( temp_list_box_u->GetCurSel( ) != LB_ERR  )
		temp_list_box_u->SetCurSel( -1);

}

void CChatServerDlg::OnSelchangeUserlist() 
{
	// TODO: Add your control notification handler code here
	CListBox* temp_list_box;
	temp_list_box = (CListBox*)GetDlgItem( IDC_CHATROOMLIST );

	CListBox* temp_list_box_u;
	temp_list_box_u = (CListBox*)GetDlgItem( IDC_USERLIST );

	if( temp_list_box->GetCurSel( ) != LB_ERR  )
		temp_list_box->SetCurSel( -1);
	
}

void CChatServerDlg::KillAny()
{
	CListBox* temp_list_box;
	temp_list_box = (CListBox*)GetDlgItem( IDC_CHATROOMLIST );

	CListBox* temp_list_box_u;
	temp_list_box_u = (CListBox*)GetDlgItem( IDC_USERLIST );

	CString com = "<KILL>";
	CString com_end = "</KILL>";

	CString com_c = "<KILLCHAT>";
	CString com_cend = "</KILLCHAT>";


	if( temp_list_box->GetCurSel( ) != LB_ERR  )
	{
		POSITION a;
		a = Chatdb->Chatroomvec.GetHeadPosition( );
		CString name_c;
		int pi_c = temp_list_box->GetCurSel( );
		temp_list_box->GetText( pi_c , name_c );

		ChatRoom temppp;
		do{
			temppp = Chatdb->Chatroomvec.GetNext( a );
			if( temppp.GetName() == name_c )
				Send2MAN( temppp.GetOwner() , com_c + temppp.GetName() + com_cend );
			if( a == NULL )
				break;
		}while(1);

			
		
	}
	else if( temp_list_box_u->GetCurSel( ) != LB_ERR  )
	{
		CString name;
		int pi = temp_list_box_u->GetCurSel( );
		temp_list_box_u->GetText( pi , name );
		Send2MAN( name , com + com_end );
	}
}


void CChatServerDlg::OnDblclkUserlist() 
{
	// TODO: Add your control notification handler code here
//***********************************************************************
	CSysMseeage dlg;
//	dlg.setparant(this);

	dlg.SetBitmap(IDB_BIT);
	CListBox* temp_list_box_u;
	temp_list_box_u = (CListBox*)GetDlgItem( IDC_USERLIST );


	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK

		CString com = "<BROADCAST>";
		CString com_end = "</BROADCAST>";

		CString com_c = "<MAN>" ;
		CString com_cend = "</MAN>";

		CString com_m = "<MSG>";
		CString com_mend = "</MSG>";


		CString name;
		int pi = temp_list_box_u->GetCurSel( );
		temp_list_box_u->GetText( pi , name );
		Send2MAN( name , com + com_c + "Server" + com_cend + com_m + dlg.content + com_mend + com_end );

	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel		
		return;
	}

//***********************************************************************


}

void CChatServerDlg::OnDblclkChatroomlist() 
{
	// TODO: Add your control notification handler code here
//***********************************************************************
	CSysMseeage dlg;
//	dlg.setparant(this);

	dlg.SetBitmap(IDB_BIT);

	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK

		CString com = "<FORWARD>";
		CString com_end = "</FORWARD>";

		CString com_c = "<CHAT>" ;
		CString com_cend = "</CHAT>";

		CString com_m = "<MSG>";
		CString com_mend = "</MSG>";


		CListBox* temp_list_box;
		temp_list_box = (CListBox*)GetDlgItem( IDC_CHATROOMLIST );


		POSITION a;
		a = Chatdb->Chatroomvec.GetHeadPosition( );
		CString name_c;
		int pi_c = temp_list_box->GetCurSel( );
		temp_list_box->GetText( pi_c , name_c );

		CString TotalAddMSG_head = "{\\rtf1\\ansi\\ansicpg950\\deff0\\deflang1033\\deflangfe1028{\\fonttbl{\\f0\\froman\\fprq2\\fcharset136 \\'b7\\'73\\'b2\\'d3\\'a9\\'fa\\'c5\\'e9;}}\n\\viewkind4\\uc1\\pard\\lang1028\\f0\\fs18 ";
		CString TotalAddMSG_end = "\n\\par }\n";

//		if( temp_list_box->GetCurSel( ) != LB_ERR  )
		{
			ChatRoom temppp;
			do{
				temppp = Chatdb->Chatroomvec.GetNext( a );
				if( temppp.GetName() == name_c )
					Send2MAN( temppp.GetOwner() , com + com_c + name_c  + com_cend + com_m + TotalAddMSG_head + dlg.content + TotalAddMSG_end + com_mend + "<MAN>" +"Server" + "</MAN>" + com_end );
				if( a == NULL )
					break;
			}while(1);
		}
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel		
		return;
	}

//***********************************************************************
	
}

void CChatServerDlg::ServerBroadcast()
{
	CSysMseeage dlg;
//	dlg.setparant(this);

	
	CListBox* temp_list_box_u;
	temp_list_box_u = (CListBox*)GetDlgItem( IDC_USERLIST );
	
	dlg.SetBitmap(IDB_BIT);
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
		ForwardMsg2Every( NULL, dlg.content, 0);
		m_BROAD.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_SBro)) );
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel		
		return;
	}
}

void CChatServerDlg::OnOK() 
{
	// TODO: Add extra validation here
	for( POSITION pos = m_ClientList.GetHeadPosition() ; pos != NULL ; )
	{
		CClientChat* p_temp=(CClientChat*)m_ClientList.GetNext(pos);
		Send2MAN( p_temp->Username , ServerSystemStatus[3] ) ;
	}
	AddSysMsg( "Server Logout\n" );
	CDialog::OnOK();
}
