/***************************************************************************
 *   Copyright (C) 2008 by SK Communications.                              *
 *   http://kldp.net/projects/nateon/                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <stdlib.h>
#include "knateon.h"
#include "knateoncommon.h"
#include "network/nateondplconnection.h"
#include "network/nateondpconnection.h"
#include "network/mimemessage.h"
#include "dialog/networkwindow.h"
#include "currentaccount.h"
#include "loginview.h"
#include "logoutview.h"
#include "knateonmainview.h"
#include "chat/chatlist.h"
#include "chat/memoview.h"
#include "chat/memolist.h"
#include "systemtraywidget.h"
#include "currentaccount.h"
#include "chat/memopopupview.h"
#include "dialog/inputbox.h"
#include "dialog/addfriendview.h"
#include "util/commandqueue.h"
#include "dialog/allowaddfriend.h"
#include "dialog/preferenceview.h"
#include "dialog/preferencecyid.h"
#include "network/p2pserver.h"
#include "util/common.h"
#include "network/sendfileinfo.h"
#include "dialog/filetransfer.h"
#include "toastwindow.h"
#include "dialog/webviewer.h"
#include "idletimer.h"
#include "xautolock.h"
#include "dialog/deletebuddyview.h"
#include "sqlitedb.h"
#include "network/nomp2pbase.h"
#include "network/nomp2plist.h"

// #include "network/serversocket.h"

#include <kwallet.h>
#include <kmdcodec.h>
#include <gcrypt.h>
#include <kfiledialog.h>

nmconfig stConfig;

KNateon::KNateon(KApplication *parent, QWidget* , const char *name)
    : DCOPObject ( "knateondcop" ),
      KNateonInterface( 0, name ),
      m_pHttp(0),
      m_pWebBuffer(0),
      m_pLoginView(0),
      m_pLogoutView(0),
      m_pMainView(0),
      m_pDPLcon(0),
      m_pDPcon(0),
      m_pNetworkWindow(0),
      m_pCurrentAccount(0),
      m_pChatList(0),
      systemTrayWidget_(0),
      m_pMemoList(0),
      m_pAddGroupInputBox(0),
      m_pRenameGroupInputBox(0),
      m_pAddFriend(0),
      m_pAllowAddFriend(0),
      m_pPreferenceView(0),
      m_pP2PServer(0),
      m_pCommon(0),
      m_pFileTransfer(0),
      nREQC(0),
      pLoginAction(0),
      pToastWindow(0),
      pWebViewer(0),
      pInviteWeb(0),
      pPopup(0),
      pMemoPopup(0),
      pChatPopup(0),
      pMemoNotify(0),
      pMailPopup(0),
      nPopupX(0),
      nPopupY(0),
      bCancelFileTransfer( FALSE ),
      idleTimer_(0),
      m_pMemoPopupTimer(0),
      m_pC1C2Timer(0),
      m_pRetryConnectTimer(0),
      pMemoCountCGI(0),
      pMemoGetCGI(0),
      pProfileGetCGI(0),
      pFixBuddyCGI(0),
      pMajorHompyCGI(0),
      pHompyNewCGI(0),
      config(0),
      pSQLiteDB(0),
      sMemoDataPath(QString::null),
      sChatDataPath(QString::null),
      sDataPath(QString::null),
      sDCOPTempCommand(QString::null),
      bIsConnected( FALSE ),
      nCySync(99999),
      m_pBuddyList(0),
      m_pGroupList(0),
      bQuit( FALSE ),
      pEmoticon(0),
      sTempAddGroupName(QString::null),
      pDeleteForm(0),
      bOnline( FALSE ),
      bLogout( FALSE ),
      bConnect( FALSE ),
      bIdle( FALSE ),
      sPicsPath(QString::null),
      m_pP2PList(0)
{
	Q_UNUSED( parent );

	// assign static member of account instance
	m_pCurrentAccount = CurrentAccount::instance();

	m_pChatList = new ChatList();
	
	m_pPreferenceView = new PreferenceView( this, "Config");
	m_pPreferenceView->setCurrentAccount( m_pCurrentAccount );
	m_pPreferenceView->setOffline();
	
	pSQLiteDB = new SQLiteDB();
	config = kapp->config();
	resize( 500, 700 );
  
	DCOPClient *client = kapp->dcopClient();
	client->attach();
	client->registerAs("KNateOn");

	m_CommandQueue.clear();
	KStandardDirs   *dirs   = KGlobal::dirs();
	sPicsPath = dirs->findResource( "data", QString( KGlobal::instance()->aboutData()->appName() ) + "/pics/" );
	
	/*! 
	 * 기본 단축키( 예, Ctrl-Q(종료) )가 동작 안 하도록 함 
	 */
	KActionCollection *a = actionCollection();
	a->setAutoConnectShortcuts ( FALSE );

    m_pP2PList = new NOMP2PList();

    /*! REQC NEW에서 쓰일 DP Cookie 에서 사용 */
    nREQC = rand() / 2;
    
    /*! P2P 서버 시작 */
    m_pP2PServer = new P2PServer();
    m_pP2PServer->setPort( stConfig.p2pport );
    m_pP2PServer->startServer();
    /*! 상대에서 REQC NEW 혹은 REQC RES를 보냈을때... */
    connect( m_pP2PServer, SIGNAL( gotNewClient( QSocket * ) ), SLOT( slotP2PNewSocket( QSocket * ) ) );
}


KNateon::~KNateon()
{
	saveProperties( kapp->config() );

	if (m_pLoginView) delete m_pLoginView;
	if (m_pNetworkWindow) delete m_pNetworkWindow;
	if (m_pDPLcon) delete m_pDPLcon;
	if (m_pChatList) delete m_pChatList;
	if (m_pMemoList) delete m_pMemoList;
	if (m_pAddGroupInputBox) delete m_pAddGroupInputBox;
	if (m_pRenameGroupInputBox) delete m_pRenameGroupInputBox;
	if (m_pAddFriend) delete m_pAddFriend;
	if (m_pAllowAddFriend) delete m_pAllowAddFriend;
	if (m_pHttp) delete m_pHttp;
	if (m_pPreferenceView) delete m_pPreferenceView;
	if (m_pCommon) delete m_pCommon;
	if (m_pP2PServer) delete m_pP2PServer;
	if (m_pCurrentAccount) delete m_pCurrentAccount;
	if (pWebViewer) delete pWebViewer;
	if (idleTimer_) delete idleTimer_;
}


/*!
  \fn KNateon::initialize()
*/
bool KNateon::initialize()
{
	m_CommandQueue.setAutoDelete( FALSE );
	m_CommandQueue.clear();
    
    // m_P2PList.setAutoDelete( false );
    // m_P2PList.clear();
    
	// initialize main UI window
	if ( !KNateonInterface::initialize() )
	{
		KMessageBox::information( this, "oops, KNateoninterface initialize fail!", "caption", 0, 0);
		return false;
	}

	// initialize network packet monitoring window
	if ( !initializeNetworkWindow() )
	{
		KMessageBox::information( this, "oops, networkwindow  initialize fail!", "caption", 0, 0);
		return false;
	}

	// initialize connection to DPL(dispatch load balancer) server
	if ( !initializeNateonDPLConnection() )
	{
		KMessageBox::information( this, "oops, nateondplconnection  initialize fail!", "caption", 0, 0);
		return false;
	}

	// initialize connection to DP(dispatch server) server
	if ( !initializeNateonDPConnection() )
	{
		KMessageBox::information( this, "oops, nateondpconnection  initialize fail!", "caption", 0, 0);
		return false;
	}

	// initialize logout UI window
	if ( !initializeLogoutView() )
	{
		KMessageBox::information( this, "oops, logoutview  initialize fail!", "caption", 0, 0);
		return false;
	}
  
  
	// initialize main buddylist view
	if ( !initializeMainView() )
	{
		KMessageBox::information( this, "oops, mainview  initialize fail!", "caption", 0, 0);
		return false;
	}

  
	// initialize login UI window
	if ( !initializeLoginView() )
	{
		KMessageBox::information( this, "oops, loginview  initialize fail!", "caption", 0, 0);
		return false;
	}
  
  
	// initialize system tray view
	if ( !initializeSystemTray() )
	{
		KMessageBox::information( this, "oops, systemtray  initialize fail!", "caption", 0, 0);
		return false;
	}

	if ( !initIdleTimer() )
	{
		KMessageBox::information( this, "oops, IdleTimer  initialize fail!", "caption", 0, 0);
		return false;
	}

	/*! 설정창 보이기 */
	connect( pSetupAction, SIGNAL( activated() ), SLOT( slotSetup() ) );
	connect( pNetLogAction, SIGNAL( activated() ), SLOT( slotNetLog() ) );
	
	slotUpdateStatusText( UTF8("대기중") );
	
	/// 단축키 설정.
	KActionCollection *ac =  new KActionCollection ( this );
	new KAction( i18n("&MessageBox"), "messagebox", KShortcut( Qt::Key_F3 ) , this, SLOT( slotViewMemoBox() ), ac, "messagebox" );
	new KAction( i18n("&Setup"), "setup", KShortcut( Qt::Key_F11 ) , this, SLOT( slotSetup() ), ac, "setup" );
	new KAction( i18n("&SendFile"), "sendfile", KShortcut( Qt::CTRL + Qt::Key_T ) , this, SLOT( slotMenuSendFile() ), ac, "sendfile" );
	// new KAction( i18n("&Send3"), "memo_send3", KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_R ) , this, SLOT( slotReplyAll() ), ac, "memo_send3" );
	// new KAction( i18n("&Send4"), "memo_send4", KShortcut( Qt::Key_Escape ) , this, SLOT( close() ), ac, "memo_send4" );
	
//     connect(m_pP2PServer, SIGNAL( OutgoingMessage(const QString& ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage(const  QString& ) ) );
//     connect(m_pP2PServer, SIGNAL( IncomingMessage(const QString& ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage(const QString& ) ) );
	return true;
}


/*!
 */
bool KNateon::initializeLoginView()
{

	if (!m_pLoginView)
	{
		m_pLoginView = new LoginView(this, "loginview");
		m_pLoginView->initialize();
		setCentralWidget(m_pLoginView);
		m_pLoginView->show();
		connect( m_pLoginView->hideLoginCheckBox, SIGNAL( toggled ( bool ) ), SLOT( slotHidenLogin( bool ) ) );
		connect( m_pLoginView, SIGNAL( connectWithAccount(Account*) ), SLOT(connectWithAccount(Account*) ) );
		
		/*! 로그인취소 */
		connect( m_pLoginView, SIGNAL( disconnectFromServer() ), m_pDPLcon, SLOT( closeConnection() ) );
		connect( m_pLoginView, SIGNAL( disconnectFromServer() ), SLOT( slotDisconnected() ) );
		
	}

	/// KConfig의 설정을 가지고 옴.
	if ( !config )
		config = kapp->config(); 
  
	/*! 개인 접속 정보 */
	config->setGroup( "Login" );
	m_pLoginView->kLineEdit1->setFocus();
	QString sID( config->readEntry("ID") );
	if ( sID != QString::null )
	{
		m_pLoginView->setID( sID );
		m_pLoginView->kHistoryCombo1->setFocus();
	}

	QString sDomain( config->readEntry("Domain") );
	if ( sDomain != QString::null )
	{
		m_pLoginView->setDomain( sDomain );
		m_pLoginView->kPasswordEdit1->setFocus();
	}

	/*! 로그인 관련 */
	stConfig.autologin = config->readBoolEntry("AutoLogin", false );
	m_pLoginView->setAutoLogin( stConfig.autologin );

	QString sPassword( config->readEntry("Password") );
	if (!sPassword.isEmpty())
	{
		//printf("read config [%s]\n", sPassword.ascii());
		// Decrypt
		QCString decodePasswd = KCodecs::base64Decode(sPassword.ascii());
		char decodePasswd2[128];
		memset(decodePasswd2, 0, sizeof(decodePasswd2));
		memcpy(decodePasswd2, (const char*)decodePasswd, 128);

		char plaintext[128];
		memset(plaintext, 0, sizeof(plaintext));

		// encryption
		gcry_cipher_hd_t hd;
		gcry_error_t err;

		/*! TODO: exception */
		err = gcry_cipher_open(&hd, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
		err = gcry_cipher_setkey(hd, KNATEON_SALT_KEY, strlen(KNATEON_SALT_KEY));
		err = gcry_cipher_decrypt(hd, plaintext, sizeof(plaintext), decodePasswd2, sizeof(decodePasswd2));
		gcry_cipher_close(hd);
		sPassword = plaintext;
	}

	if ( ( sPassword != QString::null ) &&  ( stConfig.autologin ) )
	{
		m_pLoginView->setPasswd( sPassword );
	}

	stConfig.hidestart = config->readBoolEntry( "HidenLogin", false );
	m_pLoginView->hideLoginCheckBox->setChecked( stConfig.hidestart );

	if ( stConfig.autologin )
		m_pLoginView->connectToDPLserver();

	return true;
}

bool KNateon::initializeLogoutView()
{
	return true;
}


/*!
  \fn KNateon::initializeMainView()
*/
bool KNateon::initializeMainView()
{
	if ( !m_pMainView )
	{
		config->setGroup( "Config_General" );
		stConfig.viewemoticonlist = config->readNumEntry( "Use_Emoticon_BuddyList", true );

		config->setGroup( "BuddyList" );
		stConfig.typeofbuddylist = config->readNumEntry( "Type_Of_BuddyList", 3);
		stConfig.typeofbuddysort = config->readNumEntry( "Type_Of_BuddySort", 0);

		m_pMainView = new KNateonMainview(this,"m_pMainView");
		m_pMainView->initialize();
		m_pMainView->hide();
	}
	if ( !bIsConnected )
	{
		connect(m_pMainView, SIGNAL( startMemoView(const QString &) ), SLOT( slotViewMemo(const QString &) ));
	} 
	return true;
}


/*!
  \fn KNateon::connectWithAccount(Account *pAccount)
*/
void KNateon::connectWithAccount(Account *pAccount)
{
	bLogout = FALSE;
	
	slotUpdateStatusText( UTF8("접속 및 인증 확인 중") );
	// bool          bConnected;
	QString       sErrorMessage;

	if ( pAccount == 0 )
	{
		return;
	}

	// First disconnect, to unregister all contacts
	if( m_pDPLcon->isConnected() )
	{
		m_pDPLcon->closeConnection();
	}
	// copy the account to the current account
	m_pCurrentAccount->copyAccount( pAccount );
	//don't forget this :(
	if (pAccount) delete pAccount;

	// Connect to the server.
	if ( m_pDPLcon->openConnection() == FALSE ) {
		if ( m_pDPLcon->openPRSConnection() == FALSE ) {
			/*! PRS 서버 경유 */
			
			// Notify the user.
			sErrorMessage = UTF8("The connection to the server failed.") + "\r\n";
			sErrorMessage += UTF8("You may not be connected to the internet.");
			KMessageBox::error( 0, sErrorMessage );
			stConfig.autologin = false;
			m_pLoginView->setCancel( FALSE ); // m_pLoginView->setEnable( TRUE );
			
			/*! 자동로그인에서 소켓접속 에러가 나면, 자동로그인 해제 시킴 */
			if ( stConfig.autologin == true )
			{
#ifdef NETDEBUG
				kdDebug() << "XXXXXXXXXXXXX TTTTTTTTTTTTT SSSSSSSSSSSSSSSS " << endl;
#endif
				config->setGroup( "Login" );
				config->writeEntry( "AutoLogin", false );
				config->sync();
				m_pLoginView->setAutoLogin( false );
			}
			return;
		}
	}
}


/*!
  \fn KNateon::'initializeNateonDPLConnection()
*/
bool KNateon::initializeNateonDPLConnection()
{
	m_pDPLcon = new NateonDPLConnection();
	m_pDPLcon->initialize();
	if ( !bIsConnected )
	{
		connect( m_pDPLcon, SIGNAL( disconnected() ), SLOT( DPLdisconnected() ) );
		if ( m_pNetworkWindow ) {
			/* if ( m_pNetworkWindow->isShown() ) */ {
				connect( m_pDPLcon, SIGNAL( messageSent(const QString &) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage(const QString &) ) );
				connect( m_pDPLcon, SIGNAL( messageReceived(const QString &) ), m_pNetworkWindow, SLOT( addIncomingServerMessage(const QString &) ) );
			}
		}
		connect( m_pDPLcon, SIGNAL( connectDPWithAccount(Account*) ), SLOT( connectDPWithAccount(Account*) ) );
		connect( m_pDPLcon, SIGNAL( dplError421() ), SLOT( slotDPLError421() ) ); /*! PRS 경유 서버 접속 에러 */  
	}
	return true;
}


/*!
  \fn KNateon::initializeNateonDPConnection()
*/
bool KNateon::initializeNateonDPConnection()
{
	m_pDPcon = new NateonDPConnection();
	m_pDPcon->initialize();
	if ( !bIsConnected )
	{
		connect( m_pDPcon, SIGNAL( connected() ), this, SLOT( connected() ) );
		connect( m_pDPcon, SIGNAL( disconnected() ),  this, SLOT( disconnected() ) );
		if ( m_pNetworkWindow ) {
			connect( m_pDPcon, SIGNAL( messageSent(const QString &) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage(const QString &) ) );
			connect( m_pDPcon, SIGNAL( messageReceived(const QString &) ), m_pNetworkWindow, SLOT( addIncomingServerMessage(const QString &) ) );
		}
		connect( m_pDPcon, SIGNAL( ReceiveRESS(SSConnection*) ), this, SLOT( slotViewChat(SSConnection*) ));
		connect( m_pDPcon, SIGNAL( receivedINVT(const QStringList&) ), SLOT( gotINVT(const QStringList&) ) );
		connect( m_pDPcon, SIGNAL( addCommandQueue(const QStringList &) ), this, SLOT( slotAddCommandQueue(const QStringList&) ) );
		connect( m_pDPcon, SIGNAL( err300() ), this, SLOT( slotErr300() ) );
		connect( m_pDPcon, SIGNAL( err301(const QStringList&) ), SLOT( slotErr301(const QStringList&) ) );
		connect( m_pDPcon, SIGNAL( err302() ), SLOT( slotErr302() ) );
		connect( m_pDPcon, SIGNAL( err306() ), SLOT( slotErr306() ) );
		connect( m_pDPcon, SIGNAL( err309() ), SLOT( slotErr309() ) );
		connect( m_pDPcon, SIGNAL( err421() ), SLOT( slotErr421() ) );
		connect( m_pDPcon, SIGNAL( err500( const QStringList & ) ), SLOT( slotErr500( const QStringList & ) ) );
		connect( m_pDPcon, SIGNAL( err998(const QStringList&) ), SLOT( slotErr998(const QStringList&) ) );
		connect( m_pDPcon, SIGNAL( receivedLSIN() ), this, SLOT( slotLSIN() ) );
		connect( m_pDPcon, SIGNAL( showAddConfirm( const QStringList& ) ), this, SLOT( slotAddConfirm(const QStringList &) ) );
		connect( m_pDPcon, SIGNAL( err201() ), this, SLOT( slotErr201() ) );
		connect( m_pDPcon, SIGNAL( receivedNNIK( const QStringList& ) ), SLOT( slotNNIK( const QStringList& ) ) );
		/*! 버디리스트의 CPRF 변경 내용이 내려옴 */
		connect( m_pDPcon, SIGNAL( receivedNPRF( const QStringList& ) ), SLOT( slotNPRF( const QStringList& ) ) );
		connect( m_pDPcon, SIGNAL( receivedALRM( const QStringList& ) ), SLOT( slotALRM( const QStringList& ) ) );
		connect( m_pDPcon, SIGNAL( receivedCALM( const QStringList& ) ), SLOT( slotCALM( const QStringList& ) ) );
		connect( m_pDPcon, SIGNAL( updateStatusText( const QString & ) ), SLOT( slotUpdateStatusText( const QString & ) ) );
		connect( m_pDPcon, SIGNAL( pingError() ), SLOT( slotPingError() ) );
		connect( m_pDPcon, SIGNAL( addBuddyADSB_REQST( const QStringList& ) ), SLOT( slotAddBuddyADSB_REQST( const QStringList& ) ) );
		connect( m_pDPcon, SIGNAL( refreshBuddyList() ), SLOT( slotRefreshBuddyList() ) );

        /*! P2P 전송 관련 */
        connect( m_pDPcon, SIGNAL( gotREQCNEW(const QStringList&) ), SLOT( slotGotREQCNEW(const QStringList&) ) );
        connect( m_pDPcon, SIGNAL( gotREQCRES(const QStringList&) ), SLOT( slotGotREQCRES(const QStringList&) ) );
        connect( m_pDPcon, SIGNAL( receivedREFR( const QStringList& ) ), SLOT( slotGotREFR( const QStringList& ) ) );
		connect( m_pDPcon, SIGNAL( connectP2PFR(const QStringList&) ), SLOT( slotGotFR(const QStringList&) ) );

	}
	return true;
}



/*!
  \fn KNateon::disconnected()
*/
void KNateon::DPLdisconnected()
{
	
#ifdef NETDEBUG
	kdDebug() << "DPL disconnected! ( dplconnectionfail = " << stConfig.dplconnectionfail << ")" << endl;
#endif
#if 0
	if ( stConfig.dplconnectionfail == TRUE ) {
		// Notify the user.
		QString sErrorMessage("The connection to the server failed.\r\n");
		sErrorMessage += UTF8("You may not be connected to the internet.");
		KMessageBox::error( 0, sErrorMessage );
		stConfig.autologin = false;
		m_pLoginView->setEnable( TRUE );
		
		/*! 자동로그인에서 소켓접속 에러가 나면, 자동로그인 해제 시킴 */
		if ( stConfig.autologin == true )
		{
#ifdef NETDEBUG
			kdDebug() << "XXXXXXXXXXXXX TTTTTTTTTTTTT SSSSSSSSSSSSSSSS " << endl;
#endif
			config->setGroup( "Login" );
			config->writeEntry( "AutoLogin", false );
			config->sync();
			m_pLoginView->setAutoLogin( false );
		}
		return;
	}
#endif
}


/*!
  \fn KNateon::initializeNetworkWindow()
*/
bool KNateon::initializeNetworkWindow()
{

    m_pNetworkWindow = new NetworkWindow( 0, "network window" );

    if (!m_pNetworkWindow)
    {
        return false;
    }
    m_pNetworkWindow->setInitialSize(QSize(500,600), false);
#ifdef NETDEBUG
    m_pNetworkWindow->show();
#endif
    m_pNetworkWindow->move(0, 0);
    return true;
}


/*!
  \fn KNateon::connectDPWithAccount(Account* pAccount)
*/
void KNateon::connectDPWithAccount(Account* pAccount)
{
	bool          bConnected;
	QString       sErrorMessage;
  
	if ( pAccount == 0 )
	{
		return;
	}
  
	// First disconnect, to unregister all contacts
	if(m_pDPcon->isConnected())
	{
		m_pDPcon->closeConnection();
	}
  
	// Copy the account to the current account
	m_pCurrentAccount->copyAccount( pAccount );
	//don't forget this :(
	if (pAccount) delete pAccount;
  
	// Connect to the server.
	bConnected = m_pDPcon->openConnection();
	if ( !bConnected )
	{
		// Notify the user.
		sErrorMessage = UTF8("The connection to the server failed.") + "\r\n";
		sErrorMessage += UTF8("You may not be connected to the internet.");
		KMessageBox::error( 0, sErrorMessage );
		m_pLoginView->setCancel( FALSE ); // m_pLoginView->setEnable( true );
		if ( stConfig.autologin == true )
		{
#ifdef NETDEBUG
			kdDebug() << "XXXXXXXXXXXXX TTTTTTTTTTTTT SSSSSSSSSSSSSSSS " << endl;
#endif
			stConfig.autologin = false;
			config->setGroup( "Login" );
			config->writeEntry( "AutoLogin", false );
			m_pLoginView->setAutoLogin( false );
			config->sync();
		}
	}
	// m_pLoginView->setAutoLogin( stConfig.autologin );
}

/*!
  \fn KNateon::connected()
*/
void KNateon::connected()
{
	slotUpdateStatusText( UTF8("접속 됨") );
	
	/*!
	 * 로그인 접속 소리
	 */
	if ( stConfig.usesound && stConfig.usemyloginsound )
		Sound::play( stConfig.myloginsoundpath );
	
	bOnline = TRUE;
	bConnect = TRUE;
	stConfig.autologin = m_pLoginView->isAutoLogin();
	
	if ( m_pLoginView ) m_pLoginView->hide();
	if (!m_pLogoutView)
	{
		m_pLogoutView = new LogoutView(this, "logoutview");
		connect( m_pLogoutView->pushButton1, SIGNAL( clicked() ), SLOT( slotRelogin() ) );
		connect( m_pLogoutView->textLabel2, SIGNAL( clicked() ), SLOT( slotOtherLogin() ) );
		connect( m_pLoginView, SIGNAL( changeLoginID( const QString & ) ), m_pLogoutView, SLOT( slotChangeLoginID( const QString & ) ) );
		if ( stConfig.logintype == 'C' )
			m_pLogoutView->setID( m_pCurrentAccount->getMyCyworldID() );
		else
			m_pLogoutView->setID( m_pCurrentAccount->getMyNateID() );
	}
	
	if ( !m_pMainView ) return;
	setCentralWidget(m_pMainView);
	m_pMainView->show();

	/*!
	  버디 리스트를 정렬해서 보여줌.
	  옵션은 OnlyOnline은 true
	*/
	if ( !bIsConnected )
	{
		connect( m_pMainView, SIGNAL( sendToDP( const QString& ) ), m_pDPcon, SLOT( messageSent( const QString&) ) );
		connect( m_pMainView, SIGNAL( receFromDP( const QString& ) ), m_pDPcon, SLOT( messageReceived( const QString&) ) );
		/*! 단일 사용자와 체팅 시작시... */
		connect( m_pMainView, SIGNAL( startChat( Buddy* ) ), SLOT( startChat( Buddy* ) ) );
		/*! 여러 사용자와 채팅 시작시...*/
		connect( m_pMainView, SIGNAL( startChat( QPtrList<Buddy>& ) ), SLOT( startChat( QPtrList<Buddy>& ) ) );
		/*! 그룹 채팅 시작시... */ 
		connect( m_pMainView, SIGNAL( startGroupChat( const ContactRoot * ) ), SLOT( slotStartChat(  const ContactRoot * ) ) );
		/*! 그룹 차단 */
		connect( m_pMainView, SIGNAL( blockGroup( const QString & ) ), SLOT( slotLockGroup( const QString & ) ) );
		/*! 그룹 차단 해제 */
		connect( m_pMainView, SIGNAL( unblockGroup( const QString & ) ), SLOT( slotUnlockGroup( const QString & ) ) );
    
		connect( m_pDPcon, SIGNAL( receivedINFY( const QStringList& ) ), this, SLOT( slotGotINFY(const QStringList& ) ) );
		connect( pOpendownboxAction, SIGNAL( activated() ), SLOT( slotOpenTransfer() ) );
	}
  
	QStringList mGList;
	const GroupList* pGroupList;
	pGroupList = m_pCurrentAccount->getGroupList();
	QPtrListIterator<Group> iterator( *pGroupList );
	Group * pGroup;
	while(iterator.current() != 0)
	{
		pGroup = iterator.current();
		mGList.append( pGroup->getGName() );
		++iterator;
	}
	m_pMainView->slotSetGroupList( mGList );
	slotSetGroupList( mGList );
	if ( !bIsConnected )
	{
		/// 그룹정보가 변경되면, 메뉴와 오른쪽 클릭 메뉴의 그굽 리스트를 갱신한다.
		connect( this, SIGNAL( ChangeGroupList(QStringList &) ), SLOT( slotSetGroupList(QStringList &) ) );
		connect( this, SIGNAL( ChangeGroupList(QStringList &) ), m_pMainView, SLOT( slotSetGroupList(QStringList &) ));
		connect( this, SIGNAL( ChangeNickName(QString ) ), m_pMainView, SLOT( slotChangeNickName(QString) ) );
		connect( this, SIGNAL( addNewGroup(Group *) ), m_pMainView, SLOT( slotGroupAdded(Group *) ) );

		connect(m_pDPcon, SIGNAL( receivedMemoCTOC( const MimeMessage& ) ), SLOT( slotViewMemoPopup( const MimeMessage& ) ) );
		connect(m_pDPcon, SIGNAL( receivedCTOCAMSG( const MimeMessage& ) ), SLOT( slotViewAMemoPopup( const MimeMessage& ) ) );
		connect(m_pMainView, SIGNAL( addGroup() ), this, SLOT( slotAddGroup() ) );
		connect(m_pMainView, SIGNAL( renameGroup() ), this, SLOT( slotRenameGroup() ) );
		connect(m_pMainView, SIGNAL( deleteGroup() ), this, SLOT( slotDeleteGroup() ) );

		/// 그룹 추가.
		connect(pAddgroupAction, SIGNAL( activated() ), this, SLOT( slotAddGroup() ) );
		connect(m_pMainView->PB_AddGroup, SIGNAL( clicked() ), this, SLOT( slotAddGroup() ) );
		connect(pRenamegroupAction, SIGNAL( activated() ), this, SLOT( slotRenameGroup() ) );
		connect(pDeletegroupAction, SIGNAL( activated() ), this, SLOT( slotDeleteGroup() ) );

		/// 사용자 추가.
		connect(pAddfriendAction, SIGNAL( activated() ), this, SLOT( slotAddFriend() ) );
		connect(m_pMainView->PB_AddBuddy, SIGNAL( clicked() ), this, SLOT( slotAddFriend() ) );
		connect(m_pDPcon, SIGNAL( receivedREQST(const QStringList& ) ), m_pMainView, SLOT( slotAddFriend(const QStringList &) ) );
		connect(m_pDPcon, SIGNAL( receivedADDG(const QStringList&) ), this, SLOT( slotGotAddGroup(const QStringList&) ) );
		connect(pLogoutAction, SIGNAL( activated() ), this, SLOT( slotDisconnected() ) );

		/*! 통합메세지함 보이기 */
		connect(pOpenchatboxAction, SIGNAL( activated() ), SLOT( slotViewChatBox() ) );
		connect(m_pMainView, SIGNAL( viewMemoBox() ), SLOT( slotViewMemoBox() ) );
		connect(m_pMainView->pViewmessageboxAction, SIGNAL( activated() ), SLOT( slotViewChatBox() ) );

		/// 상태값 변경
		connect( m_pMainView, SIGNAL( changeStatusNumber( int ) ), SLOT( slotChangeStatusNumber( int ) ) );
		
		connect( m_pDPcon, SIGNAL( allowAccept ( QListViewItem* , Buddy* ) ), m_pMainView, SLOT( slotAddBuddy( QListViewItem*, Buddy* ) ) );

		/*! 친구 복사 */
		connect( m_pMainView->pCopybuddyAction, SIGNAL( activated (const QString &) ), SLOT(slotCopyBuddy( const QString & ) ) );
		connect( pCopyfriendSelectAction, SIGNAL( activated (const QString &) ), SLOT(slotCopyBuddy( const QString & ) ) );

		/*! 친구 이동 */
		connect( m_pMainView->pMovebuddyAction, SIGNAL( activated (const QString &) ), SLOT( slotMoveBuddy( const QString & ) ) );
		connect( pMovefriendSelectAction, SIGNAL( activated ( const QString & ) ), SLOT( slotMoveBuddy( const QString & ) ) );
		/*! 친구 이동, Drag & Drop */
		connect( m_pMainView->listView3, SIGNAL( moveBuddies( const QString & ) ), SLOT( slotMoveBuddy( const QString & ) ) );

		/*! 친구 삭제 */
		connect( m_pMainView->pDeletebuddyAction, SIGNAL( activated () ), SLOT(slotDeleteBuddy() ) );
		connect( pDeletefriendAction, SIGNAL( activated () ), SLOT(slotDeleteBuddy() ) );

		/*! 친구목록 불러오기,저장 */
		connect( pLoadBuddyListAction, SIGNAL( activated() ), SLOT(slotLoadBuddyList() ));
		connect( pSaveBuddyListAction, SIGNAL( activated() ), SLOT(slotSaveBuddyList() ));
		
	}
	emit ChangeNickName( m_pCurrentAccount->getMyNickName() );
  
	/// Queue 된 Command를 실행한다.
	/// 예> Offline일때 다른사용자가 나를 등록하고, Online이 되면서 등록 수락여부를 묻는 창.
	if ( !m_CommandQueue.isEmpty() )
	{
		CommandQueue *pCommandQueue;
		for ( pCommandQueue = m_CommandQueue.first(); pCommandQueue; pCommandQueue = m_CommandQueue.next() )
		{
			if (pCommandQueue->Code() == "ADSB")
			{
				if ( !m_pAllowAddFriend )
				{
					m_pAllowAddFriend = new AllowAddFriend();
					connect(m_pAllowAddFriend, SIGNAL(accept( QString&, QString& ) ), m_pDPcon, SLOT(slotAddAccept( QString& , QString& ) ) );
					connect(m_pAllowAddFriend, SIGNAL(reject( QString&, QString& ) ), m_pDPcon, SLOT(slotAddReject( QString& , QString& ) ) );
				}
				QStringList myList;
				/// "CMN UID"
				myList = QStringList::split(QString(" "), pCommandQueue->Body());
				m_pAllowAddFriend->setUID( myList[1] );
				m_pBuddyList = m_pCurrentAccount->getBuddyList();
				Buddy* pBuddy = m_pBuddyList->getBuddyByID( myList[1] );
				m_pAllowAddFriend->setCMN( pBuddy->getHandle() );
				m_pAllowAddFriend->setMessage( mapInvite[ pBuddy->getHandle() ] );
				m_pAllowAddFriend->exec();
			}
		}
	}

	if ( !bIsConnected )
	{
		connect( m_pMainView->pBlockbuddyAction, SIGNAL( activated() ), SLOT( slotBlockBuddy() ) );
		/*! 오른쪽 마우스 메뉴에서 파일 보내기 */
		connect(m_pMainView->pSendfileAction, SIGNAL( activated() ), SLOT( slotMenuSendFile() ) );
		connect(pSendfileAction, SIGNAL( activated() ), SLOT( slotMenuSendFile() ) );

		connect( pChatAction, SIGNAL( activated() ), m_pMainView, SLOT( slotGoChat() ) );
		connect( pSendmemoAction, SIGNAL( activated() ), m_pMainView, SLOT( slotViewMemo() ) );
		connect( pAlwaystopAction, SIGNAL( toggled (bool) ), SLOT( slotMenuAlwaysTop(bool) ) );

		/*! 버디 리스트 보기 방식 */
		connect( pBuddynamingSelectAction, SIGNAL( activated ( int ) ), SLOT( slotNamingSelect( int ) ) );
		connect( m_pMainView->pViewNameAction, SIGNAL( activated() ), SLOT( slotBuddyOnlyName() ) );
		connect( m_pMainView->pViewNickAction, SIGNAL( activated() ), SLOT( slotBuddyOnlyNick() ) );
		connect( m_pMainView->pViewNameIDAction, SIGNAL( activated() ), SLOT( slotBuddyNameID() ) );
		connect( m_pMainView->pViewNameNickAction, SIGNAL( activated() ), SLOT( slotBuddyNameNick() ) );

		/*! 버디 리스트 정렬관련 <<<<<<< */
		connect( pSortlistSelectAction, SIGNAL( activated( int ) ), SLOT( slotBuddySort( int ) ) );
		connect( m_pMainView->pViewAllAction, SIGNAL( activated() ), SLOT( slotBuddyListAll() ) );
		connect( m_pMainView->pViewOnlineAction, SIGNAL( activated() ), SLOT( slotBuddyListOnline() ) );
		connect( m_pMainView->pViewOnOffAction, SIGNAL( activated() ), SLOT( slotBuddyListOnOff() ) );
    
		/*! 다른사용자가 로그인해서 끊김. KILL을 받았을때... */
		connect( m_pDPcon, SIGNAL( kill() ), SLOT( slotKill() ) ); 
	}
	/*! 버디 리스트 네이밍 / 소팅 관련 메뉴 초기화 */
	pBuddynamingSelectAction->setCurrentItem( stConfig.typeofbuddylist );
	pSortlistSelectAction->setCurrentItem( stConfig.typeofbuddysort );

	if ( !pMemoCountCGI )
	{
		pMemoCountCGI = new WebCGI();
		connect(pMemoCountCGI, SIGNAL( gotResult( QStringList& ) ), this, SLOT( slotMemoCount( QStringList& ) ) );
	}
	/*!
	 * 싸이월드여도 Nate에서 쪽지 가지고 옴.
	 */
#if 0
	if ( stConfig.logintype == 'C' )
	{
		QString sURL("http://203.226.253.126/exipml35/memoCnt.jsp?cmn=");
		sURL += m_pCurrentAccount->getMyCyworldCMN();
		sURL += "&ticket=";
		sURL += m_pCurrentAccount->getMyTicket();
		sURL += "&id=";
		sURL += m_pCurrentAccount->getMyCyworldID();
		pMemoCountCGI->start( sURL );
	}
	else
#endif
	{
		QString sURL("http://203.226.253.126/exipml35/memoCnt.jsp?cmn=");
		sURL += m_pCurrentAccount->getMyCMN();
		sURL += "&ticket=";
		sURL += m_pCurrentAccount->getMyTicket();
		sURL += "&id=";
		sURL += m_pCurrentAccount->getMyNateID();
		pMemoCountCGI->start( sURL );
	}

	/*!
	 * 친구에게만 쪽지받기
	 * 허용된 버디에게만 대화요청 받기
	 * 등의 설정 정보를 웹서버로 부터 가지고 온다.
	 */
	if ( !pProfileGetCGI )
	{
		pProfileGetCGI = new WebCGI();
		connect( pProfileGetCGI, SIGNAL( gotResult( QStringList& ) ), this, SLOT( slotGetProfile( QStringList& ) ) );
	}
  
	/*!
	 * 싸이월드여도 Nate에서 쪽지 가지고 옴.
	 */
#if 0
	if ( stConfig.logintype == 'C' )
	{
		QString sURL("http://203.226.253.126/exipml35/get_profile.jsp?type=service&cmn=");
		sURL += m_pCurrentAccount->getMyCyworldCMN();
		sURL += "&ticket=";
		sURL += m_pCurrentAccount->getMyTicket();
		pMemoCountCGI->start( sURL );
	}
	else
#endif
	{
		QString sURL("http://203.226.253.126/exipml35/get_profile.jsp?type=service&cmn=");
		sURL += m_pCurrentAccount->getMyCMN();
		sURL += "&ticket=";
		sURL += m_pCurrentAccount->getMyTicket();
		pProfileGetCGI->start( sURL );
	}

	/*!
	 * GLST에 없는 Buddy Handle
	 * URL 호출로 Fix
	 */
	QStringList slFixHandle;
	slFixHandle = m_pDPcon->getFixHandle();
	if ( slFixHandle.count() > 0 )
	{
		QString sURL("http://203.226.253.126/exipml35/buddy_error_fix.jsp");
		sURL += "?cmn=";
		sURL += m_pCurrentAccount->getMyCMN();
		sURL += "&ticket=";
		sURL += m_pCurrentAccount->getMyTicket();
		
		for ( QStringList::Iterator it = slFixHandle.begin(); it != slFixHandle.end(); ++it )
		{
			sURL += "&buddycmn=";
			sURL += *it;
			sURL += "&gid=0";
		}
		if ( !pFixBuddyCGI)
		{
			pFixBuddyCGI= new WebCGI();
		}
#ifdef NETDEBUG
		kdDebug() << "URL : " << sURL << endl;
#endif
		pFixBuddyCGI->start( sURL );
	}
  
	/*! 환경설정파일에 저장 */
	QString sProfile("Profile_");
	if ( stConfig.logintype == 'C' )
		sProfile += m_pCurrentAccount->getMyCyworldID();
	else
		sProfile += m_pCurrentAccount->getMyNateID();
	config->setGroup( sProfile );
	/*!
	  $HOME/.kde/apps/knateon/{ID}/ 디렉토리 생성
	  <주의> 뒤에 "/"를 꼭 붙여야 디렉토리 생성이 됨.
	*/
	if ( stConfig.logintype == 'C' )
	{
		sMemoDataPath = locateLocal( "appdata", m_pCurrentAccount->getMyCyworldID() + "/memodata/", true );
		config->writeEntry("MemoPath", sMemoDataPath );
		sChatDataPath = locateLocal( "appdata", m_pCurrentAccount->getMyCyworldID() + "/chatdata/", true );
		config->writeEntry("ChatPath", sChatDataPath );
		sDataPath = locateLocal( "appdata", m_pCurrentAccount->getMyCyworldID() + "/", true );
	}
	else
	{
		sMemoDataPath = locateLocal( "appdata", m_pCurrentAccount->getMyNateID() + "/memodata/", true );
		config->writeEntry("MemoPath", sMemoDataPath );
		sChatDataPath = locateLocal( "appdata", m_pCurrentAccount->getMyNateID() + "/chatdata/", true );
		config->writeEntry("ChatPath", sChatDataPath );
		sDataPath = locateLocal( "appdata", m_pCurrentAccount->getMyNateID() + "/", true );
	}
	config->sync();
	
	if ( pSQLiteDB )
	{
		pSQLiteDB->createMemoDB( sMemoDataPath );
		pSQLiteDB->createChatDB( sChatDataPath );
		pSQLiteDB->createUserDB( sDataPath );
		pSQLiteDB->createP2PDB( sDataPath );
        stConfig.p2pdbfilepath = sDataPath + "p2p.db";
	}

	/*! 메뉴를 사용할 수 있도록 enable() 시킴 */
	OnlineEnableMenu();

	config->setGroup( "Config_General" );
	
	/*! 항상위 체크 후 항상 위 */
	stConfig.alwaystop = config->readBoolEntry( "Always_Top", false );
	slotMenuAlwaysTop( stConfig.alwaystop );
	pAlwaystopAction->setChecked ( stConfig.alwaystop );

	/*! 버디 리스트 저장 */
	saveUserDB();

	/*! 싸이월드 정보 저장 */
	stConfig.cyid = m_pCurrentAccount->getMyCyworldID();
	stConfig.cycmn = m_pCurrentAccount->getMyCyworldCMN();
	if ( ( m_pCurrentAccount->getMyCyworldCMN() == "%00" ) ||
		 ( m_pCurrentAccount->getMyCyworldCMN() == "" ) )
	{
		stConfig.usecyworld = false;
	}
	else
	{
		stConfig.usecyworld = true;
	}

	/*! 네이트 정보 저장 */
	stConfig.nateid = m_pCurrentAccount->getMyNateID();
	stConfig.natecmn = m_pCurrentAccount->getMyNateCMN();
	if ( ( m_pCurrentAccount->getMyNateID() == "%00" ) ||
		 ( m_pCurrentAccount->getMyNateID() == "" ) )
	{
		stConfig.usenatedotcom = false;
	}
	else
	{
		stConfig.usenatedotcom = true;
	}
  
	/*! 환경설정창 초기화 */
	m_pPreferenceView->initialize();

	if ( !bIsConnected )
	{
		connect( m_pDPcon, SIGNAL( receivedCPRF( const QStringList & ) ), SLOT( slotCPRF( const QStringList & ) ) );
		/*! 싸이 메인 클릭하면, */
		connect( m_pMainView->PB_Cyworld, SIGNAL( clicked() ), SLOT( slotGoCyMain() ) );
		/*! 내 미니홈피를 클릭하면, */
		connect( m_pMainView->PB_Hompy, SIGNAL( clicked() ), SLOT( slotGoMyMinihompy() ) );
		/*! 설정창 보이기 */
		connect( pSetupAction, SIGNAL( activated() ), SLOT( slotSetup() ) );

		/*! 닉 바꾸기 */
		connect( pChangenickAction, SIGNAL( activated() ), SLOT( slotShowChangeNick() ) );
		connect( m_pMainView->pChangenickAction, SIGNAL( activated() ), SLOT( slotShowChangeNick() ) );

		/*! 본인의 프로필 보기 */
		connect( m_pMainView->pViewprofileAction, SIGNAL( activated() ), SLOT( slotShowProfile() ) );

		/*! 본인의 프로필 수정 */
		connect( m_pMainView->pEditprofileAction, SIGNAL( activated() ), SLOT( slotEditProfile() ) );
	}
  
	bIsConnected = true;
	if ( stConfig.hidestart )
	{
		hide();
	}
  
	/*!
	  버디 리스트를 정렬해서 보여줌.
	  옵션은 OnlyOnline은 true
	*/
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );

	/*! system tray 메뉴 */
	pLoginAction->setEnabled( false );

    /*! 타이머 설정 */
	m_pCurrentAccount->setUseIdleTimer( stConfig.checkawaytime );
	m_pCurrentAccount->setIdleTime( stConfig.awaytime );

	/*! 오프라인으로 접속 설정 */
	if ( m_pLoginView->hideLoginCheckBox->isChecked() )
	{
		slotChangeStatusNumber( 5 );
	}
	else /*! 온라인으로 접속 설정 */
	{
		slotChangeStatusNumber( 0 );
	}

	/*! C1, C2 주계정 정보 가지고 오기. */
	if ( !m_pC1C2Timer )
	{
		m_pC1C2Timer = new QTimer( this );
		connect( m_pC1C2Timer, SIGNAL( timeout() ), SLOT( slotC1C2() ) );
	}
	m_pC1C2Timer->start( 2000, TRUE );
	
	/*!
	 * 접속되고 5초 후에
	 * 쪽지개수 갱신 후
	 * 새쪽지를 팝업으로 띄워줍니다.
	 */
	if ( !m_pMemoPopupTimer )
	{
		m_pMemoPopupTimer = new QTimer( this );
		connect( m_pMemoPopupTimer, SIGNAL( timeout() ), SLOT( slotShowMemoPopup() ) );
	}
	m_pMemoPopupTimer->start( 10000, TRUE );
}


#include "knateon.moc"


/*!
 * 1:1 대화시작
 */
void KNateon::startChat( Buddy* pBuddy)
{
	ChatView *pChat;

	pChat = m_pChatList->getChatViewByUID( pBuddy->getUID() );
	
	if ( !pChat ) {
		/// 해당 ID로 띄워진 창이 없으면,
		/// RESS를 보내고 결과로 받은 TID를 생성한 chatview에 저장한다.
		/// TID는 위젯을 찾을때 사용한다.

		int nTID = m_pDPcon->putRESS();
		pChat = createChat(nTID);
		if ( !pChat )
			return;
		pChat->addBuddy(pBuddy);
	}
	pChat->show();
	pChat->showNormal();
	pChat->raise();
	pChat->setFocus();
	pChat->setActiveWindow();
	pChat->ChatEditQTE->setFocus();
}


/*!
  \fn KNateon::viewChat(SSConnection *m_SSConnection)
  RESS 메세지를 받았을때 동작되는 slot
  m_SSConnection는 단순히 QString 값만 전달하는 역활인데... 써야하나??
*/
void KNateon::slotViewChat(SSConnection *m_SSConnection)
{
	ChatView *pChat;

	pChat = m_pChatList->getChatViewByTID(m_SSConnection->getTID());
	if ( pChat )
	{
		pChat->setServer(m_SSConnection->getServer());
		pChat->setPort(m_SSConnection->getPort());
		pChat->setAuthKey(m_SSConnection->getAuthKey());
		pChat->setID(m_pDPcon->getUserID());

		if (pChat->connectToServerSS())
		{
			kdDebug() << "Connection Success!!!" << endl;
		}
		else
		{  
			kdDebug() << "1. Connection Error!!!" << endl;
		}
	}
}

bool KNateon::initializeSystemTray()
{
	bool initialized;

	// Create the widget
	systemTrayWidget_ = new SystemTrayWidget( this, "systemtraywidget" ) ;

	if ( systemTrayWidget_ == 0 )
		return false;

	// Initialize the widget
	initialized = systemTrayWidget_->initialize();
	if ( !initialized )
		return false;

	pSetupAction->plug( systemTrayWidget_->menu() );
	systemTrayWidget_->  menu()->insertSeparator();
	pHideAction->plug( systemTrayWidget_->menu() );
	pAlwaystopAction->plug( systemTrayWidget_->menu() );
	pLoginAction       = new KAction(UTF8("로그인"), "online", 0, this, "login_menu");
	pLoginAction->plug( systemTrayWidget_->menu() );
	pLogoutAction->plug( systemTrayWidget_->menu() );

	systemTrayWidget_->  menu()->insertSeparator();
	pChangestatusSelectAction->plug( systemTrayWidget_->menu() );
	if ( !bIsConnected )
	{
		connect( pLoginAction, SIGNAL( activated() ), SLOT( slotLogin() ) );
		connect( pQuitAction, SIGNAL( activated() ), SLOT( slotCloseApp() ) );
		connect( systemTrayWidget_, SIGNAL( quitSelected() ), SLOT( slotCloseApp() ) );
	}
	systemTrayWidget_->show();

#ifdef KMESSTEST
	ASSERT( systemTrayWidget_ != 0 );
	ASSERT( systemTrayWidget_->isVisible() );
#endif

	return true;
}

void KNateon::slotViewMemo( const QString &sReceiver )
{
	MemoView *pMemo;

	if (!m_pMemoList)
		m_pMemoList = new MemoList();

	pMemo = m_pMemoList->creatMemoObj();
	pMemo->setReceiver(sReceiver);
	connect(pMemo, SIGNAL( sendMemo( MemoView* ) ), SLOT( slotSendMemo( MemoView* ) ) );
	connect(pMemo, SIGNAL( closeMemoView( MemoView* ) ), SLOT( slotCloseMemoView( MemoView* ) ) );
	
	connect(pMemo, SIGNAL( addBuddyList( AddBuddySelector* ) ), m_pMainView, SLOT( slotMemoAddBuddy(AddBuddySelector *) ) );
	connect(pMemo->textLabel1, SIGNAL( clicked() ), SLOT( slotMemoSetupReplyRole() ) );
	pMemo->show();
	pMemo->raise();
}

#include <string.h>

void KNateon::slotSendMemo(MemoView * pMemoView)
{
	QString mRef;

	/// 이메일 뽑아내는 Regexp
	QRegExp rx("<?([^@\\s<]+@[^>\\s]+)>?");

	int pos = 0;
	while ( pos >= 0 )
	{
		pos = rx.search( pMemoView->getReceiver() , pos );
		if ( pos > -1 )
		{
			if ( mRef.length() > 1 )
				mRef += ";";
			mRef += rx.cap(1);
			// mReceivers.append( rx.cap(1) );
			pos  += rx.matchedLength();
		}
	}

	if ( stConfig.logintype == 'C' )
		sendMemo(m_pCurrentAccount->getMyCyworldID(), mRef, pMemoView->getMemo() );
	else
		sendMemo(m_pCurrentAccount->getMyNateID(), mRef, pMemoView->getMemo() );

	pMemoView->close();

	if ( stConfig.logintype == 'C' )
		pSQLiteDB->saveMemoOutbox( m_pCurrentAccount->getMyCyworldID(), mRef, pMemoView->getMemo() );
	else
		pSQLiteDB->saveMemoOutbox( m_pCurrentAccount->getMyNateID(), mRef, pMemoView->getMemo() );

}


/*!
 * 쪽지 보내기 성공한 명령문.
 const QCString  m_msg02 = QCString("ring0320@nate.com A 250\r\nIMSG\r\ntitle:11\r\nfrom:ring0320@lycos.co.kr\r\nref:ring0320@nate.com\r\ndate:20070315170052\r\nsession_id:722352\r\nuuid:c21e686c-63c5-4cd3-986e-057cf1735cda\r\ncontenttype:text\r\nlength:4\r\nfont-name:Arial\r\nfont-style:%00\r\nfont-size:10\r\nfont-color:#050505\r\n\r\n11");
 emit sendToDP(m_msg02);
*/
bool KNateon::sendMemo(QString sSender, QString sRef2, QString sMemo)
{
	QString sRecvs( sRef2 );
	sRecvs.replace(";", " ");
	QString sTitle;
	QString sTitle2;
	if (sMemo.find('\n') < 0)
		sTitle2 = sMemo;
	else
		sTitle2 = sMemo.left( sMemo.find('\n') );
  
	sTitle = "title:" + sTitle2 + "\r\n";
  
	QString sFrom;
	sFrom = "from:" + sSender + "\r\n";
  
	QString sRef;
	sRef = "ref:" + sRef2 + "\r\n";
  
	QString sDate;
	sDate = "date:" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + "\r\n";
  
	QString sSession;
	sSession = "session_id:658810\r\n";
  
	QString sUuid;
	sUuid = "uuid:" + QUuid::createUuid().toString().replace(QRegExp("[{}]"),"") + "\r\n";
  
	QString sEnv;
	sEnv = "contenttype:text\r\n";
	sEnv += "length:";
  
	QString sBody;
	sBody = "\r\n";
	sBody += sMemo;
	// sBody += " ";
	sEnv += QString::number( sBody.length() );
	sEnv += "\r\n";
	sEnv += "font-name:Arial\r\n";
	sEnv += "font-style:%00\r\n";
	sEnv += "font-size:9\r\n";
	sEnv += "font-color:#0a0a0a\r\n";

	QString sIMSG;
	sIMSG = sRecvs;
	sIMSG += "\r\n";
	sIMSG +=  "IMSG\r\n";
	sIMSG += sTitle;
	sIMSG += sFrom;
	sIMSG += sRef;
	sIMSG += sDate;
	sIMSG += sSession;
	sIMSG += sUuid;
	sIMSG += sEnv;
	sIMSG += sBody;
	sIMSG += "\r\n";

	QString sCommand;
	sCommand = "N ";
	sCommand += QString::number( strlen( sIMSG.local8Bit() ) );
	sCommand += "\r\n";
	sCommand += sIMSG.local8Bit();

	m_pDPcon->sendCommand( "CMSG", UTF8( sCommand ) );
	
	return true;
}

void KNateon::slotViewAMemoPopup(const MimeMessage & sMemo)
{
	QString sBody( sMemo.getBody() );
#if 0
	if ( !m_pCommon )
		m_pCommon = new Common();
	
	m_pCommon->percent2HTML( sBody );
#endif
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	
	if ( stConfig.allowonlyfriendmemo )
	{
		Buddy *pBuddy = m_pBuddyList->getBuddyByID( sMemo.getValue("from") );
		if ( !pBuddy )
		{
#ifdef NETDEBUG
			kdDebug() << "비버디 대화자가 메시지를 보내서 차단되었습니다. ID:[" << sMemo.getValue("from") << "]" << endl;
#endif
			return;
		}
	}
	
	/*!
	 * 쪽지 받음 소리
	 */
	if ( stConfig.usesound && stConfig.usememorecievesound )
		Sound::play( stConfig.memorecievesoundpath );
	
	/*! 0 :쪽지창 바로 보여주기, 1 : 팝업창으로 알려주기 */
	if ( stConfig.receivenewmemo == 0 )
	{
		QStringList slSend = QStringList::split(";", sMemo.getValue("from") );
		QString sSender;
		for ( QStringList::Iterator it = slSend.begin(); it != slSend.end(); ++it )
		{
			Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
			if (pBuddy)
			{
				if ( sSender.length() > 1 )
					sSender += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
				else
					sSender = "\"" + pBuddy->getName() + "\" <" + *it + ">";
			}
		}
		
		QStringList slRecv = QStringList::split(";", sMemo.getValue("ref") );
		QString sReceiver;
		for ( QStringList::Iterator it = slRecv.begin(); it != slRecv.end(); ++it )
		{
			
			Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
			if ( pBuddy )
			{
				if ( sReceiver.length() > 1 )
					sReceiver += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
				else
					sReceiver = "\"" + pBuddy->getName() + "\" <" + *it + ">";
			}
			else
			{
				if ( stConfig.logintype == 'N' )
				{
					/// 받는 사람이 본인이면,
					if ( *it == m_pCurrentAccount->getMyNateID() )
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						else
							sReceiver = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
					}
					else /// 받은 사람이 목록에 없는경우.
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";" + *it;
						else
							sReceiver = *it;
					}
				}
				else
				{
					/// 받는 사람이 본인이면,
					if ( *it == m_pCurrentAccount->getMyCyworldID() )
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						else
							sReceiver = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
					}
					else /// 받은 사람이 목록에 없는경우.
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";" + *it;
						else
							sReceiver = *it;
					}
				}
			}
		}
		
		/*! 직접 쪽지 창 띄워서 보여주기 */
		MemoPopupView	*pMemo1 = new MemoPopupView();
		connect(pMemo1, SIGNAL( replyMemo( MemoPopupView::SendType, const QString& , const QString& ) ), SLOT( slotReplyMemo( MemoPopupView::SendType, const QString&, const QString& ) ) );
		connect( pMemo1, SIGNAL( deleteMemo( const QString & ) ), SLOT( slotDeleteMemo( const QString & ) ) );
		connect( pMemo1, SIGNAL( closeMemoPopup( MemoPopupView * ) ), SLOT( slotCloseMemoPopup( MemoPopupView * ) ) );
		// }
		pMemo1->setSender( sSender );
		pMemo1->setReceiver( sReceiver );
		pMemo1->setUUID( sMemo.getValue("uuid") );
		QString sTitle( sMemo.getValue("title") );
		QStringList slTitle = QStringList::split( "%0A", sTitle );
		pMemo1->setTitle( slTitle[0] );
		QString sDateTemp( sMemo.getValue("date") );
#ifdef NETDEBUG
		kdDebug() << "[] Title : [" << sMemo.getValue("title") << "]" << endl;
		kdDebug() << "[] Date : [" << sMemo.getValue("date") << "]" << endl;
		kdDebug() << "[] Title[0] : [" << slTitle[0] << "]" << endl;
#endif
		QString sDate;
		sDate = sDateTemp.left(4);
		sDate += "-";
		sDate += sDateTemp.mid(4,2);
		sDate += "-";
		sDate += sDateTemp.mid(6,2);
		sDate += " ";
		sDate += sDateTemp.mid(8,2);
		sDate += ":";
		sDate += sDateTemp.mid(10,2);
		sDate += ":";
		sDate += sDateTemp.mid(12,2);
		pMemo1->setDate( sDate );
		QString sBody2( sMemo.getBody() );
		QStringList slBody = QStringList::split( "\n", sBody2 );
		QString sAMemo;
		for ( QStringList::Iterator it = slBody.begin(); it != slBody.end(); ++it ) {
			if ( (*it).left(5) == "memo="  ) {
				sAMemo = (*it).mid( 5, (*it).length() );
			}
		}
		QRegExp rx("<FONT\\b[^>]*>(.*)</FONT>");

		rx.search( sAMemo, 0 );

#ifdef NETDEBUG
		kdDebug() << "0 : " << rx.cap(0) << endl;
		kdDebug() << "1 : " << rx.cap(1) << endl;
		kdDebug() << "2 : " << rx.cap(2) << endl;
#endif
		
		QString sFixBody( rx.cap(1) );
		sFixBody.replace("%0D", "\n");
		
		pMemo1->setBody( sFixBody );
		pMemo1->show();
		
		/*! 뒤의 "0", "1" 은 안읽음 필드 */
		pSQLiteDB->saveMemoInbox( sMemo.getValue("uuid"), sMemo.getValue("from"), sMemo.getValue("ref"), /* sMemo.getBody() */ sBody, "0" );
	}
	else
	{
		/*! 토스트 창으로 알려주기 */
		Buddy* pBuddy = m_pBuddyList->getBuddyByID( sMemo.getValue("from" ).stripWhiteSpace () );
		if ( pBuddy )
		{
			QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );
			if ( !pMemoNotify)
			{
				pMemoNotify = new PopupWindow();
				connect(pMemoNotify, SIGNAL( clickText( int, QString ) ), SLOT( slotPopupMemoFromUUID(int, QString ) ) );
				connect(pMemoNotify, SIGNAL( hidePopup() ), SLOT( slotHidePopup() ) );
			}
			
			int screen = kapp->desktop()->screenNumber();
			QRect screenSize = kapp->desktop()->availableGeometry(screen);
			
			int nX = point.x();
			int nY = screenSize.height() + screenSize.top();
			
			pMemoNotify->setID( sMemo.getValue("uuid") );
			pMemoNotify->setAnchor( QPoint(nX, nY) );
			
			pMemoNotify->setLogo( sPicsPath + "popup_notice_memo.bmp" );
			
			QString sMsg;
			sMsg = pBuddy->getName();
			
			QString sNick = pBuddy->getNick();
			
			if ( sNick.length() > 10 )
			{
				sNick = sNick.left(10);
				sNick += "...";
			}
			
			Common::fixOutString( sNick );
			sMsg += "(" + sNick + ")";
			
			sMsg += UTF8(" 님으로부터 쪽지가 도착했습니다.");
			
			pMemoNotify->setText( sMsg );
			
			/*! 0: Online, 1: incoming chat, 2: incoming memo */
			pMemoNotify->setType(2);
			pMemoNotify->show();
			nPopupY++;
			/*! 뒤의 "0", "1" 은 안읽음 필드 */
			pSQLiteDB->saveMemoInbox( sMemo.getValue("uuid"), sMemo.getValue("from"), sMemo.getValue("ref"), /* sMemo.getBody() */ sBody, "1" );
			m_pMainView->slotUpdateMemoCount( pSQLiteDB->getNewMemoCount() );
		}
	}
	/*!
	 * saveMemoInbox( from, ref, body, is unread? )
	 * 온라인 쪽지에서는 unread가 0 이다.
	 */
}


void KNateon::slotViewMemoPopup(const MimeMessage& sMemo)
{
	QString sBody( sMemo.getBody() );
	sBody.replace("<", "&lt;");
	sBody.replace(">", "&gt;");
#if 0
	if ( !m_pCommon )
		m_pCommon = new Common();
	
	m_pCommon->percent2HTML( sBody );
#endif
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
  
	if ( stConfig.allowonlyfriendmemo )
	{
		Buddy *pBuddy = m_pBuddyList->getBuddyByID( sMemo.getValue("from") );
		if ( !pBuddy )
		{
#ifdef NETDEBUG
			kdDebug() << "비버디 대화자가 메시지를 보내서 차단되었습니다. ID:[" << sMemo.getValue("from") << "]" << endl;
#endif
			return;
		}
	}

	/*!
	 * 쪽지 받음 소리
	 */
	if ( stConfig.usesound && stConfig.usememorecievesound )
		Sound::play( stConfig.memorecievesoundpath );

	/*! 0 :쪽지창 바로 보여주기, 1 : 팝업창으로 알려주기 */
	if ( stConfig.receivenewmemo == 0 )
	{
		QStringList slSend = QStringList::split(";", sMemo.getValue("from") );
		QString sSender;
		for ( QStringList::Iterator it = slSend.begin(); it != slSend.end(); ++it )
		{
			Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
			if (pBuddy)
			{
				if ( sSender.length() > 1 )
					sSender += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
				else
					sSender = "\"" + pBuddy->getName() + "\" <" + *it + ">";
			}
		}
    
		QStringList slRecv = QStringList::split(";", sMemo.getValue("ref") );
		QString sReceiver;
		for ( QStringList::Iterator it = slRecv.begin(); it != slRecv.end(); ++it )
		{
			Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
			if ( pBuddy )
			{
				if ( sReceiver.length() > 1 )
					sReceiver += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
				else
					sReceiver = "\"" + pBuddy->getName() + "\" <" + *it + ">";
			}
			else
			{
				if ( stConfig.logintype == 'N' )
				{
					/// 받는 사람이 본인이면,
					if ( *it == m_pCurrentAccount->getMyNateID() )
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						else
							sReceiver = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
					}
					else /// 받은 사람이 목록에 없는경우.
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";" + *it;
						else
							sReceiver = *it;
					}
				}
				else
				{
					/// 받는 사람이 본인이면,
					if ( *it == m_pCurrentAccount->getMyCyworldID() )
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						else
							sReceiver = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
					}
					else /// 받은 사람이 목록에 없는경우.
					{
						if ( sReceiver.length() > 1 )
							sReceiver += ";" + *it;
						else
							sReceiver = *it;
					}
				}
			}
		}
    
		/*! 직접 쪽지 창 띄워서 보여주기 */
		MemoPopupView	*pMemo1 = new MemoPopupView();
		connect(pMemo1, SIGNAL( replyMemo( MemoPopupView::SendType, const QString& , const QString& ) ), SLOT( slotReplyMemo( MemoPopupView::SendType, const QString&, const QString& ) ) );
		connect( pMemo1, SIGNAL( deleteMemo( const QString & ) ), SLOT( slotDeleteMemo( const QString & ) ) );
		connect( pMemo1, SIGNAL( closeMemoPopup( MemoPopupView * ) ), SLOT( slotCloseMemoPopup( MemoPopupView * ) ) );
		
		pMemo1->setSender( sSender );
		pMemo1->setReceiver( sReceiver );
		pMemo1->setUUID( sMemo.getValue("uuid") );
		QString sTitle( sMemo.getValue("title") );
		QStringList slTitle = QStringList::split( "%0A", sTitle );
		pMemo1->setTitle( slTitle[0] );
		QString sDateTemp( sMemo.getValue("date") );
#ifdef NETDEBUG
		kdDebug() << "[] Title : [" << sMemo.getValue("title") << "]" << endl;
		kdDebug() << "[] Date : [" << sMemo.getValue("date") << "]" << endl;
		kdDebug() << "[] Title[0] : [" << slTitle[0] << "]" << endl;
#endif
		QString sDate;
		sDate = sDateTemp.left(4);
		sDate += "-";
		sDate += sDateTemp.mid(4,2);
		sDate += "-";
		sDate += sDateTemp.mid(6,2);
		sDate += " ";
		sDate += sDateTemp.mid(8,2);
		sDate += ":";
		sDate += sDateTemp.mid(10,2);
		sDate += ":";
		sDate += sDateTemp.mid(12,2);
		pMemo1->setDate( sDate );
		pMemo1->setBody( /* sMemo.getBody() */ sBody );
		pMemo1->show();
		
		/*! 뒤의 "0", "1" 은 안읽음 필드 */
		pSQLiteDB->saveMemoInbox( sMemo.getValue("uuid"), sMemo.getValue("from"), sMemo.getValue("ref"), /* sMemo.getBody() */ sBody, "0" );
	}
	else
	{
		/*! 토스트 창으로 알려주기 */
		Buddy* pBuddy = m_pBuddyList->getBuddyByID( sMemo.getValue("from" ).stripWhiteSpace () );
		if ( pBuddy )
		{
			QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );
			if ( !pMemoNotify)
			{
				pMemoNotify = new PopupWindow();
				connect(pMemoNotify, SIGNAL( clickText( int, QString ) ), SLOT( slotPopupMemoFromUUID(int, QString ) ) );
				connect(pMemoNotify, SIGNAL( hidePopup() ), SLOT( slotHidePopup() ) );
			}

			int screen = kapp->desktop()->screenNumber();
			QRect screenSize = kapp->desktop()->availableGeometry(screen);
      
			int nX = point.x();
			int nY = screenSize.height() + screenSize.top();
				
			pMemoNotify->setID( sMemo.getValue("uuid") );
			pMemoNotify->setAnchor( QPoint(nX, nY) );
			pMemoNotify->setLogo( sPicsPath + "popup_notice_memo.bmp" );
      
			QString sMsg;
			sMsg = pBuddy->getName();

			QString sNick = pBuddy->getNick();

			if ( sNick.length() > 10 )
			{
				sNick = sNick.left(10);
				sNick += "...";
			}

			Common::fixOutString( sNick );
			sMsg += "(" + sNick + ")";
      
			sMsg += UTF8(" 님으로부터 쪽지가 도착했습니다.");

			pMemoNotify->setText( sMsg );
      
			/*! 0: Online, 1: incoming chat, 2: incoming memo */
			pMemoNotify->setType(2);
			pMemoNotify->show();
			nPopupY++;
			/*! 뒤의 "0", "1" 은 안읽음 필드 */
			pSQLiteDB->saveMemoInbox( sMemo.getValue("uuid"), sMemo.getValue("from"), sMemo.getValue("ref"), /* sMemo.getBody() */ sBody, "1" );
			m_pMainView->slotUpdateMemoCount( pSQLiteDB->getNewMemoCount() );
		}
	}
	/*!
	 * saveMemoInbox( from, ref, body, is unread? )
	 * 온라인 쪽지에서는 unread가 0 이다.
	 */
}

void KNateon::slotReplyMemo( MemoPopupView::SendType mSendType, const QString & sReceiver, const QString & sBody)
{
	MemoView *pMemo;

	if (!m_pMemoList)
		m_pMemoList = new MemoList();

	pMemo = m_pMemoList->creatMemoObj();

	/// 전체 답장에서 본인을 제외하기 위한 구문.
	QString sRecv;
	QStringList slRecv = QStringList::split(";", sReceiver );
	for ( QStringList::Iterator it = slRecv.begin(); it != slRecv.end(); ++it )
	{
		if ( stConfig.logintype == 'C' )
		{
			if ( (*it).find( m_pCurrentAccount->getMyCyworldID() ) > 0 )
				continue;
		}
		else
		{
			if ( (*it).find( m_pCurrentAccount->getMyNateID() ) > 0 )
				continue;
		}
		if ( sRecv.length() > 1 )
			sRecv += ";" + *it;
		else
			sRecv = *it;
	}

	pMemo->setReceiver(sRecv);
	QString sEditBody;

	/*!
	  HTML을 Text로 변환하는것을 개발해야 함.
	  HTML모드로 보내면 받는사람이 HTML로 받음.
	  Text모드는 Reply 할때 이모티콘이 안보임.
	*/
	// sEditBody = "<br><br>--- Original Message ---<br><br>" + sBody; /*! HTML모드 */
	bool bAttach = false;
	if ( ( mSendType == MemoPopupView::Reply ) && stConfig.replymemoattach )
		bAttach = true;
	else if ( ( mSendType == MemoPopupView::ReplyAll ) && stConfig.allreplymemoattach )
		bAttach = true;
	else if ( ( mSendType == MemoPopupView::Forward ) && stConfig.forwardmemoattach )
		bAttach = true;
  
	if ( bAttach )
	{
		QString sBody2(sBody);
		sBody2.replace("<br>", "\n");
		sEditBody = "\n\n--- Original Message ---\n\n" + sBody2; /*! Text 모드 */
		pMemo->setBody(sEditBody);
	}
	else
	{
		pMemo->setBody( QString::null );
	}
  
	pMemo->moveCursorHome();
	connect(pMemo, SIGNAL( sendMemo( MemoView* ) ), this, SLOT( slotSendMemo( MemoView* ) ) );
	connect(pMemo, SIGNAL( addBuddyList( AddBuddySelector* ) ), m_pMainView, SLOT( slotMemoAddBuddy(AddBuddySelector *) ) );
	pMemo->show();
}


/// 그룹등록
/// Send >> ADDG 17 13 새그룹
/// Recv << ADDG 17 14 12349
void KNateon::slotAddGroup()
{
	if (!m_pAddGroupInputBox)
	{
		m_pAddGroupInputBox = new InputBox(this);
		connect(m_pAddGroupInputBox, SIGNAL( returnValue(QString) ), this, SLOT( slotInputAddGroup(QString) ) );
	}
	m_pAddGroupInputBox->setLineEdit( QString::null );
	m_pAddGroupInputBox->setCaption( UTF8("그룹 추가") );
	m_pAddGroupInputBox->show();
}


void KNateon::slotInputAddGroup(QString sGroupName)
{

	const GroupList* pGroupList = m_pCurrentAccount->getGroupList();
	QPtrListIterator<Group> iterator( *pGroupList );
	while(iterator.current() != 0)
	{
		Group * pGroup = iterator.current();
		if ( pGroup->getGName() == sGroupName )
		{
			/*!
			 * 지정한 이름을 가진 그룹이 이미 있습니다.
			 * 다른 그룹 이름을 지정하십시오.
			 */
			KMessageBox::information (this, UTF8("지정한 이름을 가진 그룹이 이미 있습니다.\n다른 그룹 이름을 지정하십시오."), UTF8("그룹 추가 오류") );
			return;
		}
		++iterator;
	}
	QString sCommand;
	sCommand = QString::number( m_pDPcon->getGroupCache() ) + " " + sGroupName + "\r\n";

	/*! 그룹명을 Temp에 저장 */
	sTempAddGroupName = sGroupName;
	m_pDPcon->putADDG(sCommand);
}


void KNateon::slotGotAddGroup(const QStringList & slCommand)
{
#ifdef NETDEBUG
	kdDebug() << "[ADD GROUP] Group Name : [" << sTempAddGroupName <<"], Group ID ["<< slCommand[3] << "]" << endl;
#endif
	GroupList* pGroupList = m_pCurrentAccount->getGroupList();
	pGroupList->addGroup( slCommand[3], sTempAddGroupName );
	
	QPtrListIterator<Group> iterator( *pGroupList );
	QStringList mGList;
	while(iterator.current() != 0)
	{
		Group * pGroup = iterator.current();
		mGList.append( pGroup->getGName() );
		++iterator;
	}
	emit ChangeGroupList( mGList );
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}


/// 그룹명 변경
/// Send >> RENG 19 15 12349 변경된그룹명
/// Recv << RENG 19 16
void KNateon::slotRenameGroup()
{
	if (!m_pRenameGroupInputBox)
	{
		m_pRenameGroupInputBox = new InputBox();
		m_pRenameGroupInputBox->setCaption( UTF8("그룹명 변경") ); 
		connect(m_pRenameGroupInputBox, SIGNAL( returnValue(QString) ), this, SLOT( slotInputRenameGroup(QString) ) );
	}
	if (m_pMainView->getCurrentItem())
	{
		QListViewItem *pItem;
		pItem = m_pMainView->getCurrentItem();
		GroupList *pGroupList = m_pCurrentAccount->getGroupList(); 
		const Group *pGroup = pGroupList->getGroupByID( pItem->text(1) );
		if ( pGroup )
		{
			m_pRenameGroupInputBox->setLineEdit( pGroup->getGName() );
		}
	}
	m_pRenameGroupInputBox->show();
}


void KNateon::slotInputRenameGroup(QString sGroupName)
{
	QListViewItem *pItem;
	pItem = m_pMainView->getCurrentItem();
	QString sCommand;
	sCommand = QString::number( m_pDPcon->getGroupCache() ) + " " + pItem->text(1) + " " + sGroupName + "\r\n";
	m_pDPcon->putRENG(sCommand);

	QStringList mGList;
	const GroupList* pGroupList = m_pCurrentAccount->getGroupList();
	QPtrListIterator<Group> iterator( *pGroupList );
	Group * pGroup;
	while(iterator.current() != 0)
	{
		pGroup = iterator.current();
		if ( pItem->text(1) == pGroup->getGID() )
			pGroup->setGName( sGroupName );
		mGList.append( pGroup->getGName() );
		++iterator;
	}
	emit ChangeGroupList( mGList );
  
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateon::slotDeleteGroup()
{
	QListViewItem *pItem;
	pItem = m_pMainView->getCurrentItem();
	GroupList* pGroupList = m_pCurrentAccount->getGroupList();
  
	Group *pGroup = pGroupList->getGroupByID( pItem->text(1) );

	if ( pGroup->getBuddyList().count() > 0 )
	{
		KMessageBox::information( this, UTF8("그룹 내에 친구가 있어 그룹을 삭제할 수 없습니다. 그룹을 삭제하려면 친구를 다른 그룹으로 이동해야 합니다."), UTF8("그룹 삭제") );
		return;
	} else if ( pGroup->getGID() == "0" )
    {
		KMessageBox::information( this, UTF8("기타 그룹은 기본 그룹으로 그룹을 삭제할 수 없습니다."), UTF8("그룹 삭제") );
		return;
    }

	int result = KMessageBox::  questionYesNo(this, UTF8("그룹을 삭제 하시겠습니까?"), UTF8("그룹 삭제") );
	if ( result == KMessageBox::No ) return;
	
	QString sCommand;
	sCommand = QString::number( m_pDPcon->getGroupCache() );
	sCommand += " ";
	sCommand += pItem->text(1);
	sCommand += "\r\n";
  
	m_pDPcon->putRMVG(sCommand);
	m_pMainView->removeCurrentItem();

  

	QStringList mGList;
	QPtrListIterator<Group> iterator( *pGroupList );
	Group * pRemoveGroup = 0;
	while(iterator.current() != 0)
	{
		pGroup = iterator.current();
		if ( pItem->text(1) != pGroup->getGID() )
			mGList.append( pGroup->getGName() );
		else
			pRemoveGroup = pGroup;
		++iterator;
	}

	/*! 그룹 리스트에서 삭제 */
	pGroupList->removeGroup( pRemoveGroup );
  
	emit ChangeGroupList( mGList );
  
}

void KNateon::slotAddFriend()
{
	if (!m_pAddFriend)
	{
		m_pAddFriend = new AddFriendView(this, "add_friend");
		connect(m_pAddFriend, SIGNAL( addFriendRequire( AddFriendView* ) ), this, SLOT(slotAddFriendRequire( AddFriendView* ) ) );
		connect(m_pDPcon, SIGNAL( err304( const QString & ) ), this, SLOT( slotNotFound( const QString & ) ) );
	}
	m_pAddFriend->show();
	m_pAddFriend->setActiveWindow();
}

void KNateon::slotNotFound( const QString &sTID )
{
	m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
	if ( Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( "TID:" + sTID ) )
	{
		/// 모든 그룹에서 버디 삭제
		Group* pGroup;
		QPtrListIterator<Group> it( *m_pCurrentAccount->getGroupList() );
		while(it.current() != 0)
		{
			pGroup = it.current();
			pGroup->removeBuddy( pBuddy );
			++it;
		}

		/// 버디 목록에서 삭제
		m_pBuddyList->remove( pBuddy );
		/// 목록 refresh
		m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
	}

	KMessageBox::information (this, UTF8("아이디를 찾을 수 없습니다."), UTF8("친구 추가 에러") );
}

void KNateon::slotAddFriendRequire(AddFriendView * pAddFriendView)
{
	QString sID;
	sID = pAddFriendView->getID();
	sID += "@";
	sID += pAddFriendView->getDomain();

	reqAddFriend(sID, pAddFriendView->getMessage());
	if (m_pAddFriend)
	{
		m_pAddFriend->clear();
	}
}

void KNateon::reqAddFriend(QString sID, QString sInviteMsg, bool bShowMsgBox)
{
	/*! 추가하려는 ID가 본인의 ID이면, */
	if ( stConfig.logintype == 'C' )
	{
#ifdef NETDEBUG
		kdDebug() << "Cyworld ID : [" << sID << "], CyID : [" <<  m_pCurrentAccount->getMyCyworldID() << "]" << endl;
#endif
		if ( sID == m_pCurrentAccount->getMyCyworldID() )
		{
			if( bShowMsgBox)
				KMessageBox::information (this, UTF8("본인은 친구로 추가 할 수 없습니다."), UTF8("친구 추가 에러") );
			return;
		}
	}
	else
	{
#ifdef NETDEBUG
		kdDebug() << "Nateon ID : [" << sID << "], NateonID : [" <<  m_pCurrentAccount->getMyNateID() << "]" << endl;
#endif
		if ( sID == m_pCurrentAccount->getMyNateID() )
		{
			if(bShowMsgBox)
				KMessageBox::information (this, UTF8("본인은 친구로 추가 할 수 없습니다."), UTF8("친구 추가 에러") );
			return;
		}
	}
  
    m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
    if ( Buddy *pBuddy = m_pBuddyList->getBuddyByID( sID ) )
	{
		/*! FL(Friend List) == 1 */
		if ( pBuddy->isFL() == true )
		{
			if( bShowMsgBox)
				KMessageBox::information (this, UTF8("이미 등록된 버디 입니다."), UTF8("친구 추가 에러") );
			return;
		}
		else
		{
			pBuddy->setFL( true );
			QString sCommand;
			sCommand = "REQST %00 ";
			sCommand += sID;
			sCommand += " 0 ";
			
			QString sMessage;
			sMessage = sInviteMsg;//pAddFriendView->getMessage();
			sMessage.replace(" ", "%20");
			sMessage.replace("\n", "%0D%0A");
			sMessage.replace("\r", "%0D%0A");
			
			sCommand += sMessage + "\r\n";
			
			int nTID = m_pDPcon->putADSB(sCommand);
			
            /// TID를 저장하기 위해 임시로 사용됨.
			pBuddy->setHandle( "TID:" + QString::number(nTID) );
			
            /// 수락을 받기 전에 버디에 추가 시킴.
			m_pBuddyList->addBuddy( pBuddy );
			
            /*! 0 그룹에 등록하기. */
			m_pDPcon->setGroup0( pBuddy );
			
            /*!
             * 목록 refresh
             */
			m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
		}
	}
    else
    {
		QString sCommand;
		sCommand = "REQST %00 ";
		sCommand += sID;
		sCommand += " 0 ";
		
		QString sMessage;
		sMessage = sInviteMsg;//pAddFriendView->getMessage();
		sMessage.replace(" ", "%20");
        sMessage.replace("\n", "%0D%0A");
        sMessage.replace("\r", "%0D%0A");
	  
		sCommand += sMessage + "\r\n";

		int nTID = m_pDPcon->putADSB(sCommand);

		Buddy *pBuddy = new Buddy();
		pBuddy->setFL( true );
		pBuddy->setUID( sID );
		pBuddy->setName( sID );
		pBuddy->setNick( sID );

		/// TID를 저장하기 위해 임시로 사용됨.
        pBuddy->setHandle( "TID:" + QString::number(nTID) );

		/// 수락을 받기 전에 버디에 추가 시킴.
		m_pBuddyList->addBuddy( pBuddy );

		/*! 0 그룹에 등록하기. */
        m_pDPcon->setGroup0( pBuddy );

		/*!
         * 목록 refresh
         */
		m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
    }
}

void KNateon::gotINVT(const QStringList & slCommand)
{
	Buddy *pBuddy;

	ChatView *pChat = m_pChatList->getChatViewByUID( slCommand[1] );
	if ( pChat ) {
		pChat->disconnectFromServerSS();
		pChat->setServer( slCommand[2] );
		pChat->setPort( slCommand[3].toInt() );
		pChat->setAuthKey( slCommand[4] );
		pChat->setID(m_pDPcon->getUserID());

		if (pChat->connectToServerSS())
			kdDebug() << "Connection Success!!!" << endl; 
		else
			kdDebug() << "2. Connection Error!!!" << endl;
		/// connection이 Success되었다고 해 정말 접속이 된것이 아님.
		/// KExtendedSocket 의 connectionSuccess() signal을 받아야 정말 접속이 된것임.
	} else {
		m_pBuddyList = m_pCurrentAccount->getBuddyList(); 
		pBuddy = m_pBuddyList->getBuddyByID(slCommand[1]);
    
		/*!
		 * 비버디이고, 허용된 친구에게만 대화 받기로 되있는 경우
		 */
		if ( stConfig.allowonlypermitchat && !pBuddy )
		{
			QString sBody;
			sBody = "INCK";
			sBody += " ";
			if ( stConfig.logintype == 'C' )
				sBody += m_pCurrentAccount->getMyCyworldID();
			else
				sBody += m_pCurrentAccount->getMyNateID();
			sBody += " ";
			sBody += slCommand[4];
			// sBody += "\r\n";
      
			QString sCommand;
			sCommand = slCommand[1];
			sCommand += " ";
			sCommand += "N";
			sCommand += " ";
			sCommand += QString::number( sBody.length() );
			sCommand += "\r\n";
			sCommand += sBody;
      
			m_pDPcon->sendCommand( "CTOC", sCommand );
      
			return;
		}
    
		/// RESS를 보내고 결과로 받은 TID를 생성한 chatview에 저장한다.
		/// TID는 위젯을 찾을때 사용한다.
		pChat = createChat( m_pDPcon->getTID() );
		pChat->addBuddy( slCommand[1], TRUE ); /// <<<<====
		pChat->setServer( slCommand[2] );
		pChat->setPort( slCommand[3].toInt() );
		pChat->setAuthKey( slCommand[4] );
		pChat->setID(m_pDPcon->getUserID());

		if (pChat->connectToServerSS())
			kdDebug() << "Connection Success!!!" << endl;
		else
			kdDebug() << "3. Connection Error!!!" << endl;
	}
}

void KNateon::slotSendINVT(ChatView* pChatView)
{
#ifdef NETDEBUG
	kdDebug() << "[ENTER] slotSendINVT(ChatView* pChatView)" << endl;
#endif
	Buddy *pBuddy;
	QString m_Body;
	QString m_Header;
	QString m_INVT;

	QPtrListIterator<Buddy> iterator( pChatView->getBuddyList() );
	while(iterator.current() != 0)
	{
		pBuddy = iterator.current();

		/*! 창을 닫은 사람만... INVT를 날림. */
		if ( pBuddy->isQuit() )
		{
			m_Body = "INVT ";
			m_Body += m_pDPcon->getUserID() + " ";
			m_Body += pChatView->getServer() + " ";
			m_Body += QString::number( pChatView->getPort() ) + " ";
			m_Body += pChatView->getAuthKey();

			m_Header = pBuddy->getUID() + " N ";
			m_Header += QString::number( m_Body.length() ) + "\r\n";

			m_INVT = m_Header + m_Body;
#ifdef NETDEBUG
			kdDebug() << "INVT : ["  << m_INVT << "]" << endl;
#endif
			/// 대화초대를 함.
			m_pDPcon->putCTOC_INVT( m_INVT );
		}
		++iterator;
	}
#ifdef NETDEBUG
	kdDebug() << "[EXIT] slotSendINVT(ChatView* pChatView)" << endl;
#endif
}

void KNateon::slotAddCommandQueue(const QStringList& slCommand)
{
	if ( slCommand[0] == "LIST" )
	{
		if ( slCommand[4] == "0001" )
		{
			/// LIST 3 25 27 0001 donmana2003@nate.com 108354114 돈마나 /태극/%20[네이트온테스트] %00 %00 %00 %00 2 1 %00 %00 N
			QString sCode;
			sCode = "ADSB";
			QString sBody;
			/// "CMN UID"
			sBody = slCommand[6] + " " + slCommand[5];
			m_CommandQueue.append( new CommandQueue(sCode, sBody) );
		}
	}
}

void KNateon::slotErr300()
{
	KMessageBox::information (this, m_pCurrentAccount->getID() + UTF8(" 는 존재하지 않는 아이디입니다. 확인 후 다시 시도해 주십시오."), "NATE ON");
	if (0 != m_pMainView)
	{
		m_pMainView->hide();
	}

	if (0 != m_pLoginView)
	{
		m_pLoginView->show();
	}

}


/*!
 * #define NATE_CODE_AUTH_FAIL "301" // authentication fail 인증 실패
 */
void KNateon::slotErr301( const QStringList& slCommand )
{
	/*! 싸이연동 인증 에러 */
	if ( nCySync == slCommand[1].toInt() )
	{
		emit cySyncAuthError( true );
	}
	else
	{
		KMessageBox::information (this, UTF8("비밀번호가 틀렸습니다. 확인 후 다시 시도해 주십시오."), "NATE ON");
		if (0 != m_pMainView) m_pMainView->hide();
		if (0 != m_pLoginView)
		{
			setCentralWidget( m_pLoginView );
			m_pLoginView->show();
			m_pLoginView->kPasswordEdit1->clear();
			m_pLoginView->kPasswordEdit1->setFocus();
		}
		
	}
}

void KNateon::slotErr302()
{
	KMessageBox::information (this, UTF8("이미 로그인 되있습니다."), "NATE ON");
}

void KNateon::disconnected()
{
	/*
      if ( ( stConfig.dplconnectionfail == TRUE ) && ( stConfig.dpconnectionfail == TRUE ) ) {
		
      }
	*/
	slotUpdateStatusText( UTF8("접속 끊김") );
	bOnline = FALSE;
	saveProperties( kapp->config() );
	m_pMainView->clearList();

	if ( bLogout )
	{
		bConnect = FALSE;
		if (0 != m_pMainView)
			m_pMainView->hide();
		
		if (0 != m_pLogoutView)
		{
			setCentralWidget( m_pLogoutView );
			m_pLogoutView->show();
		}
	}
	else
	{
		if ( m_pLoginView->isShown() )
			m_pLoginView->kPasswordEdit1->setFocus();
	}
	
	GroupList *pGroupList = m_pCurrentAccount->getGroupList();
	pGroupList->clear();
  
	/* BuddyList */
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	m_pBuddyList->clear();
  
	if ( m_pLoginView->isShown() )
		m_pLoginView->setCancel( FALSE ); // m_pLoginView->setEnable( true );
	
	OfflineEnableMenu();
  
	/*! system tray 메뉴 */
	pLoginAction->setEnabled( true );
	slotChangeStatusNumber( 5 );
	
	if ( m_pChatList )
	{
		QPtrList<ChatView> m_ChatObjs = m_pChatList->getChatList();
		QPtrListIterator<ChatView> iterator(m_ChatObjs);
		while(iterator.current() != 0)
		{
			ChatView* pChatView = iterator.current();
			if ( pChatView->isShown() )
				pChatView->close();
			++iterator;
		}
		m_pChatList->clear();
	}
	
	if ( m_pMemoPopupTimer )
		m_pMemoPopupTimer->stop();
	
	if ( m_pC1C2Timer )
		m_pC1C2Timer->stop();
}

void KNateon::slotDisconnected()
{
	m_pLoginView->setCancel( FALSE );
	bLogout = TRUE;
	
	if ( m_pChatList->count() > 0 )
	{
		int result = KMessageBox::questionYesNo(this, UTF8("네이트온을 로그아웃합니다. 열려 있는 모든 창이 닫힙니다."), UTF8("네이트 온") );
		if ( result == KMessageBox::No )
		{
			return;
		}
	}
	
    if ( m_pFileTransfer )
    {
        FileTransfer *pTemp = m_pFileTransfer;
        m_pFileTransfer = 0;
        delete pTemp;
    }

	/*! 통합메시지함 닫기 */
#ifdef NETDEBUG
	kdDebug() << "DCOP COMMAND QUIT" << endl;
#endif
	DCOPClient *client=kapp->dcopClient();
	QByteArray params2;
	QDataStream stream2(params2, IO_WriteOnly);
	stream2 << UTF8("QUIT");
	if (!client->send("MessageBox-*", "messageviewer", "dcopCommand(QString)", params2))
		kdDebug() << "Error with DCOP\n" << endl;
	m_pDPcon->closeConnection();
}

void KNateon::slotLSIN()
{
	/*! 버디등록 메세지 WAS로 부터 받음. */
	if (!pInviteWeb)
	{
		pInviteWeb = new InviteWeb();
		connect(pInviteWeb, SIGNAL(gotDataFromURL(QStringList&) ), this, SLOT(slotGotInviteMsg(QStringList &) ) );
	}
	pInviteWeb->doResultFromCMN( m_pCurrentAccount->getMyCMN(), m_pCurrentAccount->getMyTicket() );
	stConfig.logintype = m_pCurrentAccount->getMyLoginType();
	stConfig.cyid = m_pCurrentAccount->getMyCyworldID();
	stConfig.cycmn = m_pCurrentAccount->getMyCyworldCMN();

  
	if ( m_pPreferenceView )
		delete m_pPreferenceView;

	/*! 네이트ID와 연동 */
	if ( stConfig.logintype == 'N' )
		m_pPreferenceView = new PreferenceView( this, "Config");
	/*! 싸이월드 ID와 연동 */
	else
		m_pPreferenceView = new PreferenceCyID( this, "Config");
	
	/*! firefox를 찾아서 기본 브라우져로 설정, 없으면 설정하지 않음. */
	setDefaultWebBrowser();
	
	/*! 완전 삭제 */
	connect( m_pPreferenceView, SIGNAL( sendRealDelete( const QString & ) ), m_pDPcon, SLOT( slotRealDelete(const QString & ) ) );
	
	/*! 웹브라우저 변경 */
	connect( m_pPreferenceView, SIGNAL( changeWebBrowser( const QString &) ), SLOT( slotChangeWebBrowser( const QString & ) ) );
	
	/*! 닉 변경 */
	connect( m_pPreferenceView, SIGNAL( changeNick( QString ) ), m_pDPcon, SLOT( slotChangeNick( QString ) ) );
	connect( m_pPreferenceView, SIGNAL( changeNick( QString ) ), m_pMainView, SLOT( slotChangeNickName( QString ) ) );
  
	/*! 항상위 : 왜 이건 안되고 밑에꺼는 될까? CheckBox의 setChecked 이거 버그가 있는것 같다. */
	connect( pAlwaystopAction, SIGNAL( toggled (bool) ), m_pPreferenceView->topCheckBox, SLOT( setChecked(bool) ) );
	connect( m_pPreferenceView->topCheckBox, SIGNAL( toggled (bool) ), pAlwaystopAction, SLOT( setChecked(bool) ) );
    /*! 리스트에 이모티콘 보이기 안보이기 */
	connect( m_pPreferenceView, SIGNAL( emoticonShow ( bool ) ), SLOT( slotListEmoticon( bool ) ) );

	connect( m_pPreferenceView->profileButton, SIGNAL( clicked() ), SLOT( slotEditProfile() ) );
	connect( m_pPreferenceView->profileViewButton, SIGNAL( clicked() ), SLOT( slotEditProfile() ) );
  
	connect( m_pPreferenceView, SIGNAL( unlockList( QStringList & ) ), m_pDPcon, SLOT( slotPutUnlockList ( QStringList & ) ) );
	connect( m_pPreferenceView, SIGNAL( lockList( QStringList & ) ), m_pDPcon, SLOT( slotPutLockList ( QStringList & ) ) );

	connect( m_pPreferenceView, SIGNAL( sendLockBuddy( const QString & ) ), m_pDPcon, SLOT( slotSendLock( const QString & ) ) );
	connect( m_pPreferenceView, SIGNAL( sendUnlockBuddy( const QString & ) ), m_pDPcon, SLOT( slotSendUnlock( const QString & ) ) );
	
    /*! 프라이버시 설정 후 버디 목록 refresh */
	connect( m_pPreferenceView, SIGNAL( refreshBuddyList() ), SLOT( slotRefreshBuddyList() ) );
  
    /*! 항상위 설정 */
	connect( m_pPreferenceView, SIGNAL( alwaysTop( bool ) ), SLOT( slotMenuAlwaysTop(bool) ) );
	connect( m_pPreferenceView, SIGNAL( alwaysTop( bool ) ), pAlwaystopAction, SLOT( setChecked (bool) ) );
	
	/*! 허용된 대화 상대에게만 대화 요청 받기 */
	connect( m_pPreferenceView, SIGNAL( onlyPermitChat( bool ) ), SLOT( slotPrivacyPermitChat( bool ) ) );

	/*! 친구에게만 쪽지 받기 */
	connect( m_pPreferenceView, SIGNAL( onlyFriendMemo( bool ) ), SLOT( slotPrivacyFriendMemo( bool ) ) );
  
	if ( stConfig.logintype == 'N' )
	{
		/*! 싸이연동 */
		connect( m_pPreferenceView, SIGNAL( cySync(const QString &, const QString &) ), SLOT( slotCySync(const QString &, const QString &) ) );
		/*! 싸이연동 정보 변경 */
		connect( m_pPreferenceView, SIGNAL( updateCyInfo( const QString & ) ), SLOT( slotCyUpdate( const QString & ) ) );
		connect( this, SIGNAL( cySyncCanceled() ), m_pPreferenceView, SLOT( slotCyCanceled() ) );
	}
	else
	{
		/*! 네이트 연동 */
		connect( m_pPreferenceView, SIGNAL( nateSync(const QString &, const QString &) ), SLOT( slotCySync(const QString &, const QString &) ) );
		connect( m_pPreferenceView, SIGNAL( nateSyncCancel() ), SLOT( slotNateSyncCancel() ) );
	}
	connect( this, SIGNAL( cySyncAuthError( bool ) ), m_pPreferenceView, SLOT( slotCySyncAuthError( bool ) ) );
  
	m_pPreferenceView->setCurrentAccount( m_pCurrentAccount );

	connect( m_pPreferenceView, SIGNAL( updateAwayTime() ), SLOT( slotUpdateAwayInfo() ) );
	connect( m_pPreferenceView, SIGNAL( addEtc( const QString & ) ), SLOT( slotAddEtc( const QString & ) ) );
}

void KNateon::readProperties(KConfig * config)
{
	KNateonInterface::readProperties(config);

	/*! 사운드 */
	KStandardDirs   *dirs   = KGlobal::dirs();
	QString sSoundPath( dirs->findResource( "data", "knateon/sound/" ) );
  
	config->setGroup("Sound");
	stConfig.usesound = config->readBoolEntry( "UseSound", false );
  
	stConfig.usebuddyconnectsound = config->readBoolEntry("IsOnFriendConnect", false );
	stConfig.buddyconnectsoundpath = config->readEntry("FriendConnect", sSoundPath + "buddy_login.wav");

	stConfig.usememorecievesound = config->readBoolEntry("IsOnReceiveMemo", false );
	stConfig.memorecievesoundpath = config->readEntry("ReceiveMemo", sSoundPath + "recv_memo.wav");

	stConfig.usefilesenddonesound = config->readBoolEntry("IsOnFileTransferDone", false );
	stConfig.filesenddonesoundpath = config->readEntry("FileTransferDone", sSoundPath + "trans_comp.wav");

	stConfig.usemyloginsound = config->readBoolEntry("IsOnLogin", false );
	stConfig.myloginsoundpath = config->readEntry("Login", sSoundPath + "login.wav");
  
	stConfig.usestartchatsound = config->readBoolEntry("IsOnChat", false );
	stConfig.startchatsoundpath = config->readEntry( "ChatRequest", sSoundPath + "recv_chat.wav" );
  
	stConfig.useminihompynewsound = config->readBoolEntry( "IsOnMiniHompyNew", false );
	stConfig.minihompynewsoundpath = config->readEntry( "MiniHompyNew", sSoundPath + "minihompy.wav" );

    /*!
     * 환경 설정을 읽어서 Away Timer를 설정.
     */
	config->setGroup( "Config_Personal" );
    /*! 자리비움 사용 유무 */
	stConfig.checkawaytime = config->readBoolEntry( "Use_Away_Time", false );
    /*! 자리비움 시간 */
	stConfig.awaytime = config->readNumEntry( "Away_Time", 10 );
  
	slotUpdateAwayInfo();

	config->setGroup( "Config_General" );
	stConfig.filedownloadpath = config->readEntry( "Down_Path", QDir::homeDirPath() );
	if ( !QDir( stConfig.filedownloadpath ).exists() )
	{
		stConfig.filedownloadpath = QDir::homeDirPath();
		config->writeEntry( "Down_Path", stConfig.filedownloadpath );
		config->sync();
	}
}

void KNateon::saveProperties(KConfig * config)
{
	/*!
      config->setGroup("Login");
      config->writeEntry( "ID", m_pLoginView->getID() );
      config->writeEntry( "Domain", m_pLoginView->getDomain() );
      config->writeEntry( "Password", m_pLoginView->getPasswd() );
      config->writeEntry( "AutoLogin", m_pLoginView->isAutoLogin() );
      config->writeEntry( "HidenLogin", m_pLoginView->hideLoginCheckBox->isChecked() );
    */
	
	KNateonInterface::saveProperties(config);
}

void KNateon::slotSetup()
{
	m_pPreferenceView->show();
	if ( bOnline )
		m_pPreferenceView->setOnline();
	else
		m_pPreferenceView->setOffline();
}

/*!
 * 파일 보내기.
 */
void KNateon::slotSendFile(SendFileInfo *pSendFileInfo)
{
    /*! 파일 정보를 P2P 서버에 등록 시킨다. */
    m_pP2PServer->addSendFileInfo( pSendFileInfo );

    QFileInfo fi( pSendFileInfo->getFileName() );
    QString sFileName = fi.fileName();
    QString sFilePath = fi.dirPath( true );
    
    QString sQuery;
    sQuery = "INSERT INTO tb_p2p ('File_Cookie', \
'Source_ID',                                                     \
'Destination_ID',                                                \
'File_Local_Path',                                               \
'P2P_Type',                                                      \
'Destination_P2P_IP',                                            \
'File_Name',                                                     \
'File_Size'                                                      \
) VALUES('";
    sQuery += pSendFileInfo->getSSCookie();
    sQuery += "', '";
    sQuery += m_pCurrentAccount->getMyID();
    sQuery += "', '";
    sQuery += pSendFileInfo->getYourID();
    sQuery += "', '";
    sQuery += sFilePath.utf8();
    sQuery += "', '";
    sQuery += "S";
    sQuery += "', '";
    sQuery += stConfig.p2pserverip;
    sQuery += "', '";
    sQuery += sFileName.utf8();
    sQuery += "', '";
    sQuery += QString::number( pSendFileInfo->getFileSize() );
    sQuery += "')";
    
    pSQLiteDB->execOne( stConfig.p2pdbfilepath, sQuery );

    /*! 파일 전송창 */
	if (! m_pFileTransfer ) {
		m_pFileTransfer = new FileTransfer();
        connect( m_pFileTransfer, SIGNAL( cancelFileTransfer( const QString & )), SLOT( slotMyTransferCancel( const QString & ) ) );

        if ( ! m_pFileTransfer->isShown() )
            m_pFileTransfer->show();
    }
    
    m_pBuddyList = m_pCurrentAccount->getBuddyList();
    Buddy* pBuddy = m_pBuddyList->getBuddyByID( pSendFileInfo->getYourID() );

    QString sReceiver;
    if ( pBuddy ) {
        sReceiver = pBuddy->getName();
        sReceiver += "(";
        sReceiver += pBuddy->getNick();
        sReceiver += ")";
    } else {
        sReceiver = pSendFileInfo->getYourID();
    }

    m_pFileTransfer->addListView(pSendFileInfo->getSSCookie(), sReceiver, sFileName,  pSendFileInfo->getFileSize(), true );
}

/*!
  파일을 받을때. Receive
  CTOC 0 xxx@nate.com N 45
  REQC NEW 59.8.174.176:5004 10003209611:7652
*/
void KNateon::slotREQCNEW( ChatView* pChat, SendFileInfo* pSendFileInfo )
{
	Q_UNUSED( pChat );
	
    /*! 파일 정보를 P2P 서버에 등록 시킨다. */
    m_pP2PServer->addSendFileInfo( pSendFileInfo );
    
    //! local IP 얻는 방법
    stConfig.p2pserverip = m_pDPcon->getLocalIP();
    
    /*!
      ex>
      CTOC 446 (Your id) N 57
      REQC NEW (My IP):5004 (My CMN):7579
    */
    QString sBody;
    sBody = "REQC";
    sBody += " ";
    sBody += "NEW";
    sBody += " ";
    sBody += stConfig.p2pserverip;
    sBody += ":";
    sBody += QString::number( stConfig.p2pport );
	sBody += " ";
    QString sP2PCookie( m_pCurrentAccount->getMyCMN() + ":" + QString::number(nREQC++) );
    sBody += sP2PCookie + "\r\n";

    /*!
      이유는 모르나,
      CTOC의 TID값을 0으로 보내야 끊기지 않습니다.
    */
    QString sCommand;
    sCommand = pSendFileInfo->getYourID();
    sCommand += " ";
    sCommand += "N";
    sCommand += " ";
    sCommand += QString::number( sBody.length() );
    sCommand += "\r\n";
    sCommand += sBody;
    /// QString sCommand = "ring0320@nate.com N 48\r\nREQC NEW 124.136.183.198:5004 10014827278:5514\r\n";

    m_pDPcon->messageSent( sCommand );

    QString sQuery;
    sQuery = "INSERT INTO tb_p2p ('File_Cookie', \
'P2P_Cookie',                                                      \
'Source_ID',                                                     \
'Destination_ID',                                                \
'File_Local_Path',                                               \
'P2P_Type',                                                      \
'Destination_P2P_IP',                                            \
'File_Name',                                                     \
'File_Size'                                                      \
) VALUES('";
    sQuery += pSendFileInfo->getSSCookie();
    sQuery += "', '";
    sQuery += sP2PCookie;
    sQuery += "', '";
    sQuery += pSendFileInfo->getYourID();
    sQuery += "', '";
    sQuery += m_pCurrentAccount->getMyID();
    sQuery += "', '";
    sQuery += stConfig.filedownloadpath;
    sQuery += "', '";
    sQuery += "R";
    sQuery += "', '";
    sQuery += stConfig.p2pserverip;
    sQuery += "', '";
    sQuery += ( pSendFileInfo->getFileName() ).utf8();
    sQuery += "', '";
    sQuery += QString::number( pSendFileInfo->getFileSize() );
    sQuery += "')";
    
    pSQLiteDB->execOne( stConfig.p2pdbfilepath, sQuery );

    /*! 파일 전송창 */
	if (! m_pFileTransfer ) {
		m_pFileTransfer = new FileTransfer();
        connect( m_pFileTransfer, SIGNAL( cancelFileTransfer( const QString & )), SLOT( slotMyTransferCancel( const QString & ) ) );
        if ( ! m_pFileTransfer->isShown() )
            m_pFileTransfer->show();
    }
    
    m_pBuddyList = m_pCurrentAccount->getBuddyList();
    Buddy* pBuddy = m_pBuddyList->getBuddyByID( pSendFileInfo->getYourID() );

    QString sReceiver;
    if ( pBuddy ) {
        sReceiver = pBuddy->getName();
        sReceiver += "(";
        sReceiver += pBuddy->getNick();
        sReceiver += ")";
    } else {
        sReceiver = pSendFileInfo->getYourID();
    }

    m_pFileTransfer->addListView(pSendFileInfo->getSSCookie(), sReceiver, pSendFileInfo->getFileName(),  pSendFileInfo->getFileSize(), false );
}


ChatView * KNateon::createChat(int nTID)
{
	ChatView *pChat;
	pChat = m_pChatList->creatChatObj(nTID);

	/*! 창을 생성하지 못했을때 */
	if ( !pChat )
	{
		KMessageBox::information( this, UTF8("창을 생성하지 못했습니다. 개발자에게 말씀 부탁드립니다."), UTF8("오류") );
		return 0;
	}
  
	pChat->setCurrentAccount( m_pCurrentAccount );

	connect(pChat, SIGNAL( putINVT(ChatView*) ), SLOT( slotSendINVT(ChatView*) ) );
	connect(pChat, SIGNAL( newConnectSS(ChatView*) ), SLOT( slotNewConnectSS(ChatView*) ) );
	connect(pChat, SIGNAL( sendFile(SendFileInfo*) ), SLOT( slotSendFile(SendFileInfo*) ) );
	connect(pChat, SIGNAL( sendRECQNEW(ChatView*, SendFileInfo*) ), SLOT( slotREQCNEW(ChatView*, SendFileInfo*) ) );

	/*! 채팅 디버그 메시지 출력 */
	if ( m_pNetworkWindow ) {
		/* if ( m_pNetworkWindow->isShown() ) */ {
			connect(pChat, SIGNAL( OutgoingMessage(const QString& ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage(const QString& ) ) );
			connect(pChat, SIGNAL( IncomingMessage(const QString& ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage(const QString& ) ) );
		}
	} 

	connect(pChat, SIGNAL( hideChat( ChatView*, bool ) ), SLOT( slotChatRemove( ChatView*, bool ) ) );
	connect(pChat, SIGNAL( saveChatLog( ChatView*, bool ) ), SLOT( slotSaveChatLog( ChatView*, bool ) ) );
	/*! 받은 파일함 열기 */
	connect( pChat, SIGNAL( showDownDir() ), SLOT( slotOpenFileBox() ) );
	/*! 대화창 메뉴에서 지난대화 보기 */
	connect( pChat, SIGNAL( showChatLog( const ChatView* ) ), SLOT( slotViewChatLog( const ChatView* ) ) );
	/*! 대화창 메뉴에서 쪽지 보내기 */
	connect( pChat, SIGNAL( sendMemo( const QString & ) ),  SLOT( slotViewMemo( const QString & ) ) );
	/*! 대화창 메뉴에서 친구 추가 */
	connect( pChat, SIGNAL( addBuddy() ), SLOT( slotAddFriend() ) );
	/*! 대화창 메뉴에서 차단/차단 해제 토글 */
	connect( pChat, SIGNAL( lockToggle( const QString & ) ), SLOT( slotBlockBuddy( const QString & ) ) );
	/*! 대화창 메뉴에서 닉 바꾸기 */
	connect( pChat, SIGNAL( changeNick() ), SLOT( slotShowChangeNick() ) );
	/*! 대화창 메뉴에서 환경설정 창 띄우기 */
	connect( pChat, SIGNAL( showSetup() ), SLOT( slotSetup() ) );
	
	/*! 대화창 메뉴에서 내 상태 바꿈 */
	connect( pChat, SIGNAL( changeStatus( int ) ), SLOT( slotChangeStatusNumber( int ) ) );

	/*! 채팅창의 상태 변경 */
	connect( this, SIGNAL( changeStatus( int ) ), pChat, SLOT( slotChangeStatus( int ) ) );
	
	connect(pChat, SIGNAL( updateInviteData( ChatView* ) ), SLOT( slotChatInviteData( ChatView* ) )  );
	connect(pChat, SIGNAL( putINVT_Invite(ChatView*, QStringList&) ), this, SLOT( slotInviteINVT( ChatView*, QStringList& ) ) );
	connect( pChat, SIGNAL( gotChatMessage( const QStringList& ) ), SLOT( slotChatMessage( const QStringList& ) ) );
	connect( pChat, SIGNAL( cancelFileTransfer( const QString& ) ), SLOT( slotTransferCancel(const QString& ) ) );
	/*!
	  파일전송을 상대에서 Cancel 했을때,
	  WHSP NACK를 받았을때...
	*/
	connect(pChat, SIGNAL( cancelReceive( const QStringList& ) ), this, SLOT( slotCancelReceive( const QStringList& ) ) );
	connect(pChat, SIGNAL( cancelReceiveAll( const QStringList& ) ), this, SLOT( slotCancelReceiveAll( const QStringList& ) ) );
	connect(this, SIGNAL( buddyChangeNick() ), pChat, SLOT( slotBuddyChangeNick() ) );
	connect( pChat, SIGNAL( showTransfer() ), SLOT( slotOpenTransfer() ) );
	
	return pChat;
}

void KNateon::slotFileAcceptOk(SendFileInfo * pSendFileInfo)
{
	if ( bCancelFileTransfer )
	{
		bCancelFileTransfer = FALSE;
	}
	else
	{
		/// 파일 전송창 보이기.
		showFileTransferDialog(pSendFileInfo);

		QString csFile = pSendFileInfo->getFileName();
		QString sFileName( csFile.right( csFile.length() - csFile.findRev("/") - 1 ) );
		
		m_pBuddyList = m_pCurrentAccount->getBuddyList();
		Buddy* pBuddy = m_pBuddyList->getBuddyByID( pSendFileInfo->getYourID() );
		
		QString sSender;
		if ( pBuddy )
		{
			sSender = pBuddy->getName();
			sSender += "(";
			sSender += pBuddy->getNick();
			sSender += ")";
		}
		else
		{
			sSender = pSendFileInfo->getYourID();
		}
		m_pFileTransfer->addListView(pSendFileInfo->getSSCookie(), sSender, sFileName,  pSendFileInfo->getFileSize(), false );
		m_pP2PServer->sendAccept(pSendFileInfo);
	}
}

void KNateon::showFileTransferDialog(SendFileInfo * pSendFileInfo)
{
	pSendFileInfo = 0;
	if ( ! m_pFileTransfer->isShown() )
		m_pFileTransfer->show();
}


/*!
 * 1:n 대화시작
 */
void KNateon::startChat(QPtrList< Buddy > & slBuddies)
{
	ChatView *pChat = 0;
	Buddy *pBuddy = 0;
	
	if ( slBuddies.count() == 1 ) {
		/*! 1:1 대화 */
		startChat( slBuddies.first() );
	} else {
		/*! 1:n 대화 */
		QStringList slUIDs;
		for ( pBuddy = slBuddies.first(); pBuddy; pBuddy = slBuddies.next() )
			slUIDs.append( pBuddy->getUID() );
		pChat = m_pChatList->getChatViewByAllUIDs( slUIDs );
		if ( !pChat ) {
			/*! 
			 * RESS를 보내고 결과로 받은 TID를 생성한 chatview에 저장한다.
			 * TID는 위젯을 찾을때 사용한다.
			 */
			int nTID = m_pDPcon->putRESS();
			
			pChat = createChat(nTID);
			if ( !pChat )
				return;
			
			for ( pBuddy = slBuddies.first(); pBuddy; pBuddy = slBuddies.next() )
				pChat->addBuddy(pBuddy);
		}
		pChat->show();
		pChat->showNormal();
		pChat->raise();
		pChat->setFocus();
		pChat->setActiveWindow();
		pChat->ChatEditQTE->setFocus();
	}
}

void KNateon::slotChatRemove(ChatView *pChatView, bool bWriteLog)
{
	QPtrListIterator<Buddy> iterator( pChatView->getBuddyList() );
	Buddy* pBuddy;
	QString sCHATUSERS;

	while(iterator.current() != 0)
	{
		pBuddy = iterator.current();
		if ( sCHATUSERS.length() > 1 )
			sCHATUSERS += ";";
		sCHATUSERS += pBuddy->getUID();
		++iterator;
	}

	/*! 저장 유무에 따라서 대화내용 저장 하기 */
	if ( bWriteLog )
	{
		QString sChatLog;
		sChatLog = pChatView->getChatLog();
		sChatLog.replace("%20", " ");
		pSQLiteDB->saveChatBox( sCHATUSERS, sChatLog );
	}
#ifdef NETDEBUG
	kdDebug() << "before chat count : " << m_pChatList->count() << endl;
#endif
	m_pChatList->removeChatObj(pChatView);
#ifdef NETDEBUG
	kdDebug() << "after chat count : " << m_pChatList->count() << endl;
#endif
}

void KNateon::slotChatInviteData(ChatView * pChatView)
{
	pChatView->updateGroupData( m_pMainView->getGroupList() );
	pChatView->updateBuddyData( m_pMainView->getBuddyList() );

	pChatView->showInviteDialog();
}

void KNateon::slotInviteINVT(ChatView * pChatView, QStringList & slInvitorList)
{
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	Buddy* pBuddy;

	for ( QStringList::Iterator it = slInvitorList.begin(); it != slInvitorList.end(); ++it )
	{
		pBuddy = m_pBuddyList->getBuddyByID(*it);
		pBuddy->setQuit(true);
		pChatView->addBuddy(pBuddy);
	}

	slotSendINVT(pChatView);
}


/*!
  NTFY 0 ring0320@nate.com O 0 %00 1
*/
void KNateon::slotGotINFY( const QStringList &slCommand )
{
	if (slCommand[0] == "NTFY")
	{
		m_pBuddyList = m_pCurrentAccount->getBuddyList();
		if ( !m_pBuddyList )
			return;

		Buddy *pBuddy = m_pBuddyList->getBuddyByID(slCommand[2]);
		if ( !pBuddy )
			return;
		
		if ( pBuddy->getStatus() == "F" )
		{
			if (systemTrayWidget_ != 0)
			{
				/*!
				 * 친구 로그인 소리
				 */
				if ( stConfig.usesound && stConfig.usebuddyconnectsound )
					Sound::play( stConfig.buddyconnectsoundpath );

				if ( stConfig.alarmbuddyconnect )
				{
					if ( !pPopup )
					{
						pPopup = new PopupWindow();
						connect(pPopup, SIGNAL( clickText( int, QString ) ), this, SLOT(slotClickChatPopup(int, QString ) ) );
						connect( pPopup, SIGNAL( hidePopup() ), SLOT( slotHidePopup() ) );
					}

					QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );

					int screen = kapp->desktop()->screenNumber();
					QRect screenSize = kapp->desktop()->availableGeometry(screen);
					
					int nX = point.x();
					int nY = screenSize.height() + screenSize.top();
					// kdDebug() << "AH : [" << screenSize.height() << "]" << endl;
					
					pPopup->setAnchor( QPoint(nX, nY) );
					pPopup->setLogo( sPicsPath + "slidewnd_login.bmp" , 16777215);

					QString sNickTemp;
					if ( pBuddy->getNick() == "%00" )
						sNickTemp = pBuddy->getName();
					else
						sNickTemp = pBuddy->getNick();
					
					int nNameLen = pBuddy->getName().length();
					int nNickLen = sNickTemp.length();
					int nAllLen = nNameLen + nNickLen;

					QString sMsg;
					sMsg = pBuddy->getName();
					sMsg += "(";
					QString sNick;
					if ( nAllLen  > 36 )
					{
						int nOver = nAllLen - 36;
						int nNickFixLen = nNickLen - ( nOver + 3 );
						sNick = sNickTemp.left( nNickFixLen );
						sNick += "...";
					}
					else
					{
						sNick = sNickTemp;
					}
#ifdef NETDEBUG
					kdDebug() << "Nick : [" << sNick << "]" << endl;
#endif
					Common::fixOutString( sNick );
#ifdef NETDEBUG
					kdDebug() << "Nick : [" << sNick << "]" << endl;
#endif
					sMsg += sNick;
					sMsg += UTF8( ") 님이 로그인 하셨습니다." );

					pPopup->setText( sMsg );

					/*! 0: Online, 1: incoming chat, 2: incoming memo */
					pPopup->setType(0);
					pPopup->setID( pBuddy->getUID() );
					pPopup->show();
					nPopupY++;
				}
			}
		}
	}

	m_pMainView->slotGotINFY( slCommand );
	
	QPtrList<ChatView> m_ChatObjs = m_pChatList->getChatList();
	QPtrListIterator<ChatView> iterator(m_ChatObjs);
	
	while(iterator.current() != 0)
	{
		ChatView* pChatView = iterator.current();
		if ( pChatView->getBuddyByID( slCommand[2] ) )
		{
			pChatView->updateUserStatus(slCommand[2], slCommand[3]);
		}
		++iterator;
	}
}

void KNateon::slotGotInviteMsg(QStringList & slCommand)
{
	for (QStringList::Iterator it = slCommand.begin(); it != slCommand.end(); ++it )
	{
		QStringList slSep = QStringList::split(' ', QString(*it));
		if (slSep.count() > 1)
			mapInvite[ slSep[0] ] = slSep[1];
	}
}

void KNateon::slotAddConfirm(const QStringList & slCommand)
{
	/*! ADDB 0 RL 106955142 xxx@nate.com 안녕하세요.홍길동입니다. */
	if ( !m_pAllowAddFriend )
	{
		m_pAllowAddFriend = new AllowAddFriend();
		connect(m_pAllowAddFriend, SIGNAL(accept( QString&, QString& ) ), m_pDPcon, SLOT(slotAddAccept( QString& , QString& ) ) );
		connect(m_pAllowAddFriend, SIGNAL(reject( QString&, QString& ) ), m_pDPcon, SLOT(slotAddReject( QString& , QString& ) ) );
	}
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	Buddy *pBuddy = m_pBuddyList->getBuddyByID( slCommand[4] );
	if ( pBuddy )
	{
		pBuddy->setHandle( slCommand[3] );
		pBuddy->setRL( TRUE );
		pBuddy->setFL( TRUE );
		pBuddy->setAL( TRUE );
		pBuddy->setStatus("F");
		Group *pGroup = m_pCurrentAccount->getGroupList()->getGroupByID( "0" );
		if ( pGroup )
            pGroup->addBuddy( pBuddy );
	}
	else
	{
		pBuddy = new Buddy();
		pBuddy->setStatus("F");
		pBuddy->setHandle( slCommand[3] );
		pBuddy->setUID( slCommand[4] );
		pBuddy->setRL( TRUE );
		pBuddy->setFL( TRUE );
		pBuddy->setAL( TRUE );
		pBuddy->setCyworld_CMN( "%00" );
		pBuddy->setHome2CMN( "%00" );
		pBuddy->setHompyType( Buddy::Cyworld );
		m_pBuddyList->addBuddy( pBuddy );
		Group *pGroup = m_pCurrentAccount->getGroupList()->getGroupByID( "0" );
		if ( pGroup )
            pGroup->addBuddy( pBuddy );
	}
	
	m_pAllowAddFriend->setCMN( slCommand[3] );
	m_pAllowAddFriend->setUID( slCommand[4] );
	m_pAllowAddFriend->setMessage( slCommand[5] );
	m_pAllowAddFriend->exec();
}

void KNateon::resizeEvent(QResizeEvent * e)
{
	KMainWindow::resizeEvent(e);
}

void KNateon::slotREFR(SendFileInfo * pSendFileInfo)
{
	pSendFileInfo = 0;
}

/*!
  파일 전송을 상대에서 Cancel했을때, WHSP NACK 받았을때
*/
void KNateon::slotCancelReceive(const QStringList & slCommand)
{
	if ( m_pFileTransfer )
	{
		if ( m_pFileTransfer->isVisible() )
		{
			QStringList slData = QStringList::split(QString("%09"), slCommand[4]);
			QStringList slDatainfo = QStringList::split(QString("|"), slData[2]);
			m_pFileTransfer->cancelTransfer( slDatainfo[2] );
		}
	}
}

void KNateon::slotP2PTimeOut(SendFileInfo * pSendFileInfo)
{
	/*!
	  FR을 사용하는 필드를 셋팅한다.
	*/
	int nTid = m_pDPcon->getTrid();

	pSendFileInfo->setUseFR();
	pSendFileInfo->setDPTid( nTid );

	QString sCommand;
	sCommand = "REFR";
	sCommand += " ";
	sCommand += QString::number( nTid );
	sCommand += " ";
	sCommand += pSendFileInfo->getYourID();
	sCommand += "\r\n";

	m_pDPcon->sendMsg( sCommand );
}


void KNateon::slotSendCTOCFR(SendFileInfo * pSendFileInfo)
{
	int nTid = m_pDPcon->getTrid();

	QString sSubCommand;
	sSubCommand = "REQC";
	sSubCommand += " ";
	sSubCommand += "FR";
	sSubCommand += " ";
	sSubCommand += pSendFileInfo->getFRIP();
	sSubCommand += ":";
	sSubCommand += QString::number( pSendFileInfo->getFRPort() );
	sSubCommand += " ";
	sSubCommand += pSendFileInfo->getDPCookie();
	sSubCommand += " ";
	sSubCommand += pSendFileInfo->getFRCookie();
	sSubCommand += "\r\n";

	QString sCommand;
	sCommand = "CTOC";
	sCommand += " ";
	sCommand += QString::number( nTid );
	sCommand += " ";
	sCommand += pSendFileInfo->getYourID();
	sCommand += " ";
	sCommand += "N";
	sCommand += " ";
	sCommand += QString::number( sSubCommand.length() );
	sCommand += "\r\n";
	sCommand += sSubCommand;

	m_pDPcon->sendMsg( sCommand );
}

void KNateon::slotShowChangeNick()
{
	m_pPreferenceView->show();
	m_pPreferenceView->showChangeNick();
}

void KNateon::slotClickChatPopup(int nType, QString sID)
{
	nType = 0;
	
	m_pBuddyList = m_pCurrentAccount->getBuddyList();

	Buddy *pBuddy = m_pBuddyList->getBuddyByID( sID );
	if ( !pBuddy )
		return;
  
	startChat( pBuddy );
}

bool KNateon::initIdleTimer()
{
#ifdef KMESSTEST
	ASSERT( idleTimer_ == 0 );
#endif
	if ( !idleTimer_ )
	{
		idleTimer_ = new IdleTimer();
		if ( idleTimer_ == 0 )
		{
#ifdef NETDEBUG
			kdDebug() << "KMess - Couldn't create the idle timer." << endl;
#endif
			return false;
		}
		// Connect the timer to signal when the user is away.
		connect( idleTimer_, SIGNAL( timeout() ), SLOT( slotUserIsIdle() ) );
		connect( idleTimer_, SIGNAL( activity() ), SLOT( slotUserIsNotIdle() ) );
	}
  
#ifdef KMESSTEST
	ASSERT( idleTimer_ != 0 );
#endif
  
	return true;
}

void KNateon::slotUserIsIdle()
{
#ifdef NETDEBUG
    kdDebug() << "[ I D L E ] [ I D L E ] [ I D L E ] [ I D L E ] [ I D L E ]" << endl;
#endif
	if ( bIdle  )
        return;
	bIdle = TRUE;
	
	emit changeStatus( 1 ); /*! 채팅에 상태값 업데이트 */
	m_pMainView->changeStatusUI( 1 ); /*! 메인창 BI 업데이트 */
	m_pDPcon->slotChangeStatusAway();
	KIconLoader *loader = KGlobal::iconLoader();
	systemTrayWidget_->setPixmap( loader->loadIcon( "main_list_state_vacant", KIcon::User ) );
}

void KNateon::slotUserIsNotIdle()
{
#ifdef NETDEBUG
    kdDebug() << "[ NOT I D L E ] [ NOT I D L E ] [ NOT I D L E ] [ NOT I D L E ] [ NOT I D L E ]" << endl;
#endif
	bIdle = FALSE;
	slotChangeStatusNumber( 0 );
}
/*!
  URL:

  http://203.226.253.126/exipml35/memoCnt.jsp?cmn={cmn}&ticket={ticket}&id={id}

  결과:

  [result]
  code=100
  message=OK

  [newmsg]
  cust=Y
  cnt=1

  [totalmbox]
  cust=Y
  cnt=0

  [totalcbox]
  cust=Y
  cnt=1

  [dml]
  cust=N
  cnt=0
  slide_wnd_text=
  slide_wnd_cmd=DMLM
*/
void KNateon::slotMemoCount(QStringList & slResult)
{
	int nCount = 0;

	bool bTitle = false;
  
	for ( QStringList::Iterator it = slResult.begin(); it != slResult.end(); ++it )
	{
		if ( (*it).find("[newmsg]") != -1 )
			bTitle = true;

		if ( bTitle )
		{
			QStringList slCnt = QStringList::split( '=', *it );
			if ( slCnt[0] == "cnt" )
			{
				nCount = slCnt[1].toInt();
				if ( nCount > 0 )
				{
					if ( !pMemoGetCGI )
					{
						pMemoGetCGI = new WebCGI();
						connect(pMemoGetCGI, SIGNAL( gotResult( QStringList& ) ), this, SLOT( slotSaveMemo( QStringList& ) ) );
					}

					/*!
					 * 싸이ID이면 싸이ID, CMN으로 쿼리해야 할것 같은데.
					 * 그게 아니다.
					 * 싸이ID로 로그인 해도 네이트 ID로 쪽지를 가지고 와야 한다.
					 */
#if 0
					if (stConfig.logintype == 'C')
					{
						QString sURL("http://203.226.253.126/exipml35/memo.jsp?cmd=query&cmn=");
						sURL += m_pCurrentAccount->getMyCyworldCMN();
						sURL += "&ticket=";
						sURL += m_pCurrentAccount->getMyTicket();
						sURL += "&id=";
						sURL += m_pCurrentAccount->getMyCyworldID();
						pMemoGetCGI->start( sURL );
					}
					else
#endif    
					{
						QString sURL("http://203.226.253.126/exipml35/memo.jsp?cmd=query&cmn=");
						sURL += m_pCurrentAccount->getMyCMN();
						sURL += "&ticket=";
						sURL += m_pCurrentAccount->getMyTicket();
						sURL += "&id=";
						sURL += m_pCurrentAccount->getMyNateID();
						pMemoGetCGI->start( sURL );
					}
				}
				break;
			}
		}
	}
	return;
}

/*!
 * map["from_full_id"] = pBuddy->getUID();
 * knateon: KEY : [seq], VALUE : [392073805]
 * knateon: KEY : [uuid], VALUE : [110E385A-2A40-4AA1-83B5-E764EBFC102E]
 * knateon: KEY : [from_id], VALUE : [ring0320]
 * knateon: KEY : [from_cmn], VALUE : [10014827278]
 * knateon: KEY : [to_ids], VALUE : [ring0320@lycos.co.kr]
 * knateon: KEY : [confirm], VALUE : [N]
 * knateon: KEY : [recv_date], VALUE : [20070619144533]
 * knateon: KEY : [subject], VALUE : [#%20버디리스트%20정렬.]
 * knateon: KEY : [content_type], VALUE : [TEXT]
 * knateon: KEY : [content], VALUE :  [안녕하세요.%20%0A반갑습니다.%0A/안녕/%20반가워~%0Aㅎㅎㅎ%20<%20>%20%0Ahttp://www.yahoo.co.kr%0Aring0320@nate.com%0A또%20뭐가%20있지?]
 */
void KNateon::slotSaveMemo(QStringList & slMemo)
{
	typedef QMap<QString, QString> fields;
	fields map;

	for ( QStringList::Iterator it = slMemo.begin(); it != slMemo.end(); ++it )
	{
		/*!
		 * nateon: OfflineMemo : [
		 * seq=686362214&
		 * uuid=C8643562-ECD2-4403-8C26-1FEF7DD0C0B6&
		 * from_id=ring0320@nate.com&
		 * from_cmn=10014827278&
		 * to_ids=ring0320@lycos.co.kr&
		 * confirm=N&recv_date=20080306164531&
		 * subject=안녕하세요.%20&
		 * content_type=TEXT&
		 * content=안녕하세요.%20%0A반갑습니다.%0A/안녕/%20반가워~%0Aㅎㅎㅎ%20<%20>%20%0Ahttp://www.yahoo.co.kr%0Aring0320@nate.com%0A또%20뭐가%20있지?
		 * ]
		 * kdDebug() << "OfflineMemo : [" << (*it) << "]" << endl;
		 */
		
		if ( (*it).left(4) == "seq=" )
		{
			map.clear();
			QStringList slData = QStringList::split( "&", *it );
			for ( QStringList::Iterator it01 = slData.begin(); it01 != slData.end(); ++it01 )
			{
				QStringList slEntry = QStringList::split( "=", *it01 );
				map[ slEntry[0] ] = slEntry[1];
#ifdef NETDEBUG
				kdDebug() << "KEY:[" << slEntry[0] << "], VALUE:[" << slEntry[1] << "]" << endl;
#endif
			}
			/*!
			  From CMN에서 ID 얻기
			*/
			m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
			Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( map["from_cmn"] );

			if ( pBuddy )
			{
				/*!
				  본문의 % 글자 없애기.
				*/
				if ( !m_pCommon )
					m_pCommon = new Common();

				m_pCommon->percent2HTML( map["subject"] );
				
				if ( map["content_type"] == "FLSH" ) {
					QRegExp rx("<FONT\\b[^>]*>(.*)</FONT>");
					rx.search( map["content"], 0 );
#ifdef NETDEBUG
					kdDebug() << "0 : " << rx.cap(0) << endl;
					kdDebug() << "1 : " << rx.cap(1) << endl;
					kdDebug() << "2 : " << rx.cap(2) << endl;
#endif
					QString sContent( rx.cap(1) );
					// m_pCommon->removePercents( sContent );
					// sContent.replace("%0D", "<br>");
					m_pCommon->percent2HTML( sContent );
					map["content"] = sContent;
				} else {
					m_pCommon->percent2HTML( map["content"] );
				}

				map["from_full_id"] = pBuddy->getUID();
				pSQLiteDB->saveMemoInbox( map );
			}
		}
	}
	
	if ( pMemoPopup )
	{
		QString sMsg;
		sMsg = UTF8( "새로운 쪽지가 " );
		sMsg += QString::number( pSQLiteDB->getNewMemoCount() );
		sMsg += UTF8( "개 도착했습니다." );
		pMemoPopup->setText( sMsg );
	}
#ifdef NETDEBUG
	else
	{
		kdDebug() << "XXXXXXXXXXXX <<<<<<<<<<<<<<< FFFFFFFFFFFF " << endl;
	}
#endif
	m_pMainView->slotUpdateMemoCount( pSQLiteDB->getNewMemoCount() );
}

void KNateon::slotViewChatBox()
{
	if ( stConfig.savechatlog != 1 ) /*! 조건 */
	{
		int result = KMessageBox::questionYesNo(this, UTF8("지난 대화를 보시려면 환경설정에서 대화 내용 자동저장을 설정하셔야합니다. 지금 설정하시겠습니까?"), UTF8("대화 저장 설정") );
		if ( result == KMessageBox::Yes )
		{
			m_pPreferenceView->show();
			m_pPreferenceView->showMessageTab();
		}
	}
	else
	{
		KRun::runCommand("nateon_messagebox");

		QListViewItem *pItem;
		pItem = m_pMainView->getCurrentItem();
		if ( pItem )
		{
			m_pBuddyList = m_pCurrentAccount->getBuddyList();
			Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( pItem->text(2) );
			if ( pBuddy )
			{
				sDCOPTempCommand = "SEARCH:CHAT:";
				sDCOPTempCommand += pBuddy->getUID();
			}
		}
	}
}


void KNateon::dcopCommand(const QString s)
{
	QStringList slCommand = QStringList::split(QString(":"), s);
	QString sUUID;

	if ( slCommand[0] == "DB" )
	{
		if ( slCommand[1] == "PATH" )
		{
			DCOPClient *client=kapp->dcopClient();
			QByteArray params2;
			QDataStream stream2(params2, IO_WriteOnly);
      
			if ( stConfig.logintype == 'C' )
				stream2 << UTF8( locateLocal( "appdata", m_pCurrentAccount->getMyCyworldID(), true ) );
			else
				stream2 << UTF8( locateLocal( "appdata", m_pCurrentAccount->getMyNateID(), true ) );
			if (!client->send("MessageBox-*", "messageviewer", "setDBPath(QString)", params2))
				kdDebug() << "Error with DCOP\n" ;
		}
		
		/*! 통합메시지함 웹브라우저 설정 */
		DCOPClient *client=kapp->dcopClient();
		QByteArray params2;
		QDataStream stream2(params2, IO_WriteOnly);
		if ( stConfig.usedefaultwebbrowser )
			stream2 << UTF8( stConfig.defaultwebbrowser );
		else
			stream2 << UTF8( "none" );
		if (!client->send("MessageBox-*", "messageviewer", "setDefaultBrowser(QString)", params2))
			kdDebug() << "Error with DCOP\n" << endl;
	}
	else if ( slCommand[0] == "MEMO" )
	{
		if ( slCommand[1] == "NEW")
		{
			// QString aa("");
			slotViewMemo( QString::null );
		}
		else if  ( slCommand[1] == "INBOX" )
		{
			rowList myList;
			QString sQuery;

			sUUID = slCommand[3];
			sQuery = "SELECT SUSER, RUSER, BODYDATA FROM tb_local_inbox WHERE UUID='";
			sQuery += sUUID;
			sQuery += "';";
			myList = pSQLiteDB->getRecords(sMemoDataPath + "local_inbox.db", sQuery);
			if ( myList.isEmpty() )
			{
#ifdef NETDEBUG
				kdDebug() << "[NOTICE] Not Found UUID : [" << s << "]" << endl;
#endif
				return;
			}

			m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
      
			QString sSender;
			Buddy* pBuddy = m_pBuddyList->getBuddyByID( myList.first()[0] );
			if ( pBuddy )
			{
				sSender = "\"";
				sSender += pBuddy->getName();
				sSender += "\" <";
				sSender += pBuddy->getUID();
				sSender += ">";
			}
			else
			{
				sSender = myList.first()[0];
			}
      
			QStringList slRecv = QStringList::split(";", myList.first()[1] );
			QString sReceivers;
			for ( QStringList::Iterator it = slRecv.begin(); it != slRecv.end(); ++it )
			{
				Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
				if ( pBuddy )
				{
					if ( sReceivers.length() > 1 )
						sReceivers += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
					else
						sReceivers = "\"" + pBuddy->getName() + "\" <" + *it + ">";
				}
				else
				{
					if ( stConfig.logintype == 'C' )
					{
						/// 받는 사람이 본인이면,
						if ( *it == m_pCurrentAccount->getMyCyworldID() )
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
							else
								sReceivers = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						}
						else /// 받은 사람이 목록에 없는경우.
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";" + *it;
							else
								sReceivers = *it;
						}
					}
					else
					{
						/// 받는 사람이 본인이면,
						if ( *it == m_pCurrentAccount->getMyNateID() )
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
							else
								sReceivers = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						}
						else /// 받은 사람이 목록에 없는경우.
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";" + *it;
							else
								sReceivers = *it;
						}
					}
				}
			}
			QString sMemoBody( myList.first()[2] );

			if ( slCommand[2] == "REPLY" )
			{
				slotReplyMemo( MemoPopupView::Reply, sSender, sMemoBody );
			}
			else if ( slCommand[2] == "REPLYALL" )
			{
				slotReplyMemo( MemoPopupView::ReplyAll, sSender+";"+sReceivers, sMemoBody );
			}
			else if ( slCommand[2] == "FORWARD" )
			{
				slotReplyMemo( MemoPopupView::Forward, "", sMemoBody );
			}
			else if ( slCommand[2] == "VIEW" )
			{
				slotPopupMemoFromUUID( 3, sUUID );
			}
		}
		else if ( slCommand[1] == "OUTBOX" )
		{
			rowList myList;
			QString sQuery;

			sUUID = slCommand[3];
			sQuery = "SELECT SUSER, RUSER, BODYDATA FROM tb_local_outbox WHERE UUID='";
			sQuery += sUUID;
			sQuery += "';";
			myList = pSQLiteDB->getRecords(sMemoDataPath + "local_outbox.db", sQuery);
			if ( myList.isEmpty() )
			{
#ifdef NETDEBUG
				kdDebug() << "[NOTICE] Not Found UUID : [" << s << "]" << endl;
#endif
				return;
			}

			m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
      
			QString sSender;
			Buddy* pBuddy = m_pBuddyList->getBuddyByID( myList.first()[0] );
			if ( pBuddy )
			{
				sSender = "\"";
				sSender += pBuddy->getName();
				sSender += "\" <";
				sSender += pBuddy->getUID();
				sSender += ">";
			}
			else
			{
				sSender = myList.first()[0];
			}
      
			QStringList slRecv = QStringList::split(";", myList.first()[1] );
			QString sReceivers;
			for ( QStringList::Iterator it = slRecv.begin(); it != slRecv.end(); ++it )
			{
				Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
				if ( pBuddy )
				{
					if ( sReceivers.length() > 1 )
						sReceivers += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
					else
						sReceivers = "\"" + pBuddy->getName() + "\" <" + *it + ">";
				}
				else
				{
					if ( stConfig.logintype == 'C' )
					{
						/// 받는 사람이 본인이면,
						if ( *it == m_pCurrentAccount->getMyCyworldID() )
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
							else
								sReceivers = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						}
						else /// 받은 사람이 목록에 없는경우.
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";" + *it;
							else
								sReceivers = *it;
						}
					}
					else
					{
						/// 받는 사람이 본인이면,
						if ( *it == m_pCurrentAccount->getMyNateID() )
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
							else
								sReceivers = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
						}
						else /// 받은 사람이 목록에 없는경우.
						{
							if ( sReceivers.length() > 1 )
								sReceivers += ";" + *it;
							else
								sReceivers = *it;
						}
					}
				}
			}
			QString sMemoBody( myList.first()[2] );

			if ( slCommand[2] == "REPLY" )
			{
				slotReplyMemo( MemoPopupView::Reply, sSender, sMemoBody );
			}
			else if ( slCommand[2] == "REPLYALL" )
			{
				slotReplyMemo( MemoPopupView::ReplyAll, sSender+";"+sReceivers, sMemoBody );
			}
			else if ( slCommand[2] == "FORWARD" )
			{
				slotReplyMemo( MemoPopupView::Forward, "", sMemoBody );
			}
		}
		else if ( slCommand[1] == "COUNT")
		{
			m_pMainView->slotUpdateMemoCount( slCommand[2].toInt() );
		}
	}
	else if ( slCommand[0] == "CHAT" )
	{
		rowList myList;
		QString sQuery;

		sUUID = slCommand[1];
		sQuery = "SELECT CHATUSERS FROM tb_local_chat WHERE UUID='";
		sQuery += sUUID;
		sQuery += "';";
		myList = pSQLiteDB->getRecords(sChatDataPath + "local_chat.db", sQuery);
		if ( myList.isEmpty() ) {
#ifdef NETDEBUG
			kdDebug() << "[NOTICE] Not Found UUID : [" << s << "]" << endl;
#endif
			return;
		}

		QString sChatUsers( myList.first()[0] );

		QStringList slChatUserList = QStringList::split( QString(";"), sChatUsers );

		if ( slChatUserList.count() == 1 ) {
			/*! 1:1 대화 */
			Buddy *pBuddy = m_pBuddyList->getBuddyByID( ( slChatUserList[0] ) );
			if ( pBuddy ) {
				startChat( pBuddy );
			}
		} else if ( slChatUserList.count() > 1 ) {
			/*! 1:n 대화 */
			QPtrList<Buddy> plBuddies;
			plBuddies.clear();
			
			m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
			for ( QStringList::Iterator it = slChatUserList.begin(); it != slChatUserList.end(); ++it )
			{
				*it;
				Buddy *pBuddy = m_pBuddyList->getBuddyByID( (*it) );
				if (pBuddy)
				{
					pBuddy->setQuit(true);
					plBuddies.append(pBuddy);
#ifdef NETDEBUG
					kdDebug() << "[Chatting List] >>> [" << pBuddy->getName() << "]" << endl;
#endif
				}
			}
			if ( plBuddies.count() )
			{
				startChat( plBuddies );
			}
		} else {
			/*! 0 or -xx ??? */
			return;
		}
	}
	else if ( slCommand[0] == "CMD" )
	{
		if ( slCommand[1] == "GET" )
		{
			if ( sDCOPTempCommand.length() > 1 )
			{
#ifdef NETDEBUG
				kdDebug() << "XXX [" << sDCOPTempCommand << "]" << endl;
#endif
				DCOPClient *client=kapp->dcopClient();
				QByteArray params2;
				QDataStream stream2(params2, IO_WriteOnly);
				stream2 << sDCOPTempCommand;
				if (!client->send("MessageBox-*", "messageviewer", "dcopCommand(QString)", params2))
					kdDebug() << "Error with DCOP\n" ;
				sDCOPTempCommand = "";
			}
		}
	}
}

void KNateon::saveUserDB()
{
	/*! 초기화 */
	pSQLiteDB->execOne( sDataPath + "local_user.db", "delete from tb_user;" );

	m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());

	QPtrListIterator<Buddy> iterator( *m_pBuddyList );
	Buddy *pBuddy;
	QString sQuery;

	sQuery = "INSERT INTO tb_user (ID, NAME, NICK, EMAIL) VALUES ('";
	if ( stConfig.logintype == 'C' )
		sQuery += m_pCurrentAccount->getMyCyworldID().utf8();
	else
		sQuery += m_pCurrentAccount->getMyNateID().utf8();
	sQuery += "', '";
	sQuery += m_pCurrentAccount->getMyName().utf8();
	sQuery += "', '";
	QString sNick( m_pCurrentAccount->getMyNickName() );
	sNick.replace("'", "''");
	sQuery += sNick.utf8();
	sQuery += "', '";
	sQuery += m_pCurrentAccount->getMyName().utf8();
	sQuery += " <";
	if ( stConfig.logintype == 'C' )
		sQuery += m_pCurrentAccount->getMyCyworldID().utf8();
	else
		sQuery += m_pCurrentAccount->getMyNateID().utf8();
	sQuery += ">');";
	pSQLiteDB->execOne( sDataPath + "local_user.db", sQuery );

	while(iterator.current() != 0)
	{
		pBuddy = iterator.current();
		sQuery = "INSERT INTO tb_user (ID, NAME, NICK, EMAIL) VALUES ('";
		sQuery += pBuddy->getUID().utf8();
		sQuery += "', '";
		sQuery += pBuddy->getName().utf8();
		sQuery += "', '";
		sNick = pBuddy->getNick();
		sNick.replace("'", "''");
		sQuery += sNick.utf8();
		sQuery += "', '";
		sQuery += pBuddy->getName().utf8();
		sQuery += " <";
		sQuery += pBuddy->getUID().utf8();
		sQuery += ">');";
		pSQLiteDB->execOne( sDataPath + "local_user.db", sQuery );

		++iterator;
	}
}


/*!
  친구 복사
*/
void KNateon::slotCopyBuddy(const QString & sGroup)
{
	/*!
	  KSelectAction의 선택을 없앰.
	*/
	m_pMainView->pCopybuddyAction->setCurrentItem(-1);
	pCopyfriendSelectAction->setCurrentItem(-1);

	QListView *pList = m_pMainView->listView3;
	m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());

	QListViewItem *groupItem = m_pMainView->getGroupItemByName( sGroup );

	if ( !groupItem )
	{
#ifdef NETDEBUG
		kdDebug() << "XXXX [" << sGroup << "]" << endl;
#endif
		return;
	}
  
	/*!
	  pGroup에서 Group의 Buddy 리스트를 얻는다.
	*/
    QPtrList<Buddy> plBuddyList = m_pCurrentAccount->getGroupList()->getGroupByName( sGroup )->getBuddyList();

	QString sBody;
	int nIDX = 0;

	if (pList->isMultiSelection ())
	{
		QListViewItemIterator it( pList );
		for ( ; it.current(); ++it )
		{
			if (  pList->isSelected( it.current() ) )
			{
				if ( plBuddyList.contains( m_pBuddyList->getBuddyByHandle( it.current()->text(2) ) ) > 0 )
				{
#ifdef NETDEBUG
					kdDebug() << "This buddy is exist : [" << it.current()->text(2) << "]" << endl;
#endif
					continue;
				}
				Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( it.current()->text(2) );
				if (pBuddy)
				{
					m_pMainView->slotAddBuddy( groupItem, pBuddy );
					sBody += QString::number( nIDX++ );
					sBody += " ";
					sBody += pBuddy->getHandle();
					sBody += " ";
					sBody += pBuddy->getUID();
					sBody += " ";
					sBody += pBuddy->getGID();
					sBody += " ";
					/*! XXXXXXXXXXXXXXX TARGET GID */
					sBody += groupItem->text(1);
					sBody += "\r\n";

					/*!
					  pGroup에 추가된 buddy handle을 추가한다.
					  같은 그룹에 계속 추가되는것을 막음.
					*/
					m_pCurrentAccount->getGroupList()->getGroupByName( sGroup )->addBuddy( pBuddy );
				}
			}
		}
	}
	/*! pList 가 멀티셀렉션으로 세팅 되있으면 isMultiSelection은 무조건 true 임.
	  else
	  {
	  Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( pList->currentItem()->text(2) );
	  m_pMainView->slotAddBuddy( groupItem, pBuddy );
	  }
	*/

	/*!
	  명령어가 있을때만 DP로 보냄.
	*/
	if ( sBody.length() )
	{
		QString sCommand;
		sCommand = QString::number( m_pDPcon->getGroupCache() );
		sCommand += " ";
		sCommand += QString::number( sBody.length() );
		sCommand += "\r\n";
		sCommand += sBody;
		m_pDPcon->sendCommand( "CPBG", sCommand );

		/*!
		 * 목록 refresh
		 */
		m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
	}
	else
	{
		KMessageBox::information (this, UTF8("이미 등록된 친구를 복사하거나, 친구 선택을 안하셨습니다.\n확인하시고 다시 실행해 주십시오."), UTF8("친구 복사 알림"));
	}
}

void KNateon::slotMoveBuddy(const QString & sGroup)
{
	/*!
	  KSelectAction의 선택을 없앰.
	*/
	m_pMainView->pMovebuddyAction->setCurrentItem(-1);
	pMovefriendSelectAction->setCurrentItem(-1);

	QListView *pList = m_pMainView->listView3;
	m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());
	QListViewItem *groupItem = m_pMainView->getGroupItemByName( sGroup );

	if ( !groupItem )
		return;
	
	/*!
	  pGroup에서 Group의 Buddy 리스트를 얻는다.
	*/
    QPtrList<Buddy> plBuddyList = m_pCurrentAccount->getGroupList()->getGroupByName( sGroup )->getBuddyList();

	QString sBody;
	int nIDX = 0;
	QListViewItemIterator it( pList );
	for ( ; it.current(); ++it )
	{
		if ( it.current()->isSelected() )
		{
			if ( plBuddyList.contains( m_pBuddyList->getBuddyByHandle( it.current()->text(2) ) ) > 0 )
			{
#ifdef NETDEBUG
				kdDebug() << "This buddy is exist : [" << it.current()->text(2) << "]" << endl;
#endif
				continue;
			}

			Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( it.current()->text(2) );
			if (pBuddy)
			{
				sBody += QString::number( nIDX++ );
				sBody += " ";
				sBody += pBuddy->getHandle();
				sBody += " ";
				sBody += pBuddy->getUID();
				sBody += " ";
				sBody += it.current()->text(1);
				sBody += " ";
				/*! XXXXXXXXXXXXXXX TARGET GID */
				sBody += groupItem->text(1);
				sBody += "\r\n";
				/*!
                  Group의 BuddyList에서 삭제된 버디 handle을 삭제한다.
                  이후 복사/이동에서 목록에 있어서 Skip 되는것을 방지한다.
				*/
				Group *pGroup = m_pCurrentAccount->getGroupList()->getGroupByID( it.current()->text(1) );
				if ( pGroup )
					pGroup->removeBuddy( pBuddy );
				/*!
                  pGroup에 추가된 buddy handle을 추가한다.
                  같은 그룹에 계속 추가되는것을 막음.
				*/
				m_pCurrentAccount->getGroupList()->getGroupByName( sGroup )->addBuddy( pBuddy );
			}
		}
	}
	/*!
	  명령어가 있을때만 DP로 보냄.
	*/
	if ( sBody.length() )
	{
		QString sCommand;
		sCommand = QString::number( m_pDPcon->getGroupCache() );
		sCommand += " ";
		sCommand += QString::number( sBody.length() );
		sCommand += "\r\n";
		sCommand += sBody;

		m_pDPcon->sendCommand( "MVBG", sCommand );
		/*!
		 * 목록 refresh
		 */
		m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
    
	}
	else
	{
		KMessageBox::information (this, UTF8("친구 선택을 안하셨습니다.\n확인하시고 다시 실행해 주십시오."), UTF8("친구 이동 알림"));
	}
}


/*!
  친구 삭제
*/
void KNateon::slotDeleteBuddy()
{
#ifdef NETDEBUG
	kdDebug() << "Selected Buddy Count : " << m_pMainView->getSelectedBuddyCount() << endl;
#endif

	QListView *pList = m_pMainView->listView3;
	m_pBuddyList = const_cast<BuddyList*>(m_pCurrentAccount->getBuddyList());

	QString sBody;
	int nIDX = 0;
	/*! pList 가 멀티셀렉션으로 세팅 되있으면 isMultiSelection은 무조건 true 임.
	  else
	  {
	  Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( pList->currentItem()->text(2) );
	  m_pMainView->slotAddBuddy( groupItem, pBuddy );
	  }
	*/
	if ( m_pMainView->getSelectedBuddyCount() > 1)
	{
		int result = KMessageBox::  questionYesNo(this, QString::number( m_pMainView->getSelectedBuddyCount() ) + UTF8("명의 친구를 삭제 하시겠습니까?"), UTF8("친구 지우기") );
		if ( result == KMessageBox::Yes )
		{
            QPtrList<Buddy> pBuddyList;
			
			QListViewItemIterator it( pList );
			while ( it.current() )
			{
				if ( it.current()->isSelected() )
				{
					Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( it.current()->text(2) );
					if (pBuddy)
					{
						sBody += QString::number( nIDX++ );
						sBody += " ";
						sBody += pBuddy->getHandle();
						sBody += " ";
						sBody += pBuddy->getUID();
						sBody += " ";
						sBody += it.current()->text(1);
						sBody += "\r\n";

						/*!
						  Group의 BuddyList에서 삭제된 버디 handle을 삭제한다.
						  이후 복사/이동에서 목록에 있어서 Skip 되는것을 방지한다.
						*/
						Group *pGroup = m_pCurrentAccount->getGroupList()->getGroupByID( it.current()->text(1) );
						if ( pGroup )
							pGroup->removeBuddy( pBuddy );
            
                        if ( pBuddyList.find( pBuddy ) == -1 )
						{
							pBuddyList.append( pBuddy );
						}
					}
				}
				++it;
			}

			/*!
			 * 명령어가 있을때만 DP로 보냄.
			 */
			if ( sBody.length() )
			{
				QString sCommand;
				sCommand = QString::number( m_pDPcon->getGroupCache() );
				sCommand += " ";
				sCommand += QString::number( sBody.length() );
				sCommand += "\r\n";
				sCommand += sBody;
				
				m_pDPcon->sendCommand( "RMBG", sCommand );
				
				m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
				m_pGroupList = const_cast<GroupList*>(m_pCurrentAccount->getGroupList());
			}
			
			QStringList slRMBGList;
            QPtrListIterator<Buddy> iterBL( pBuddyList );
            while( iterBL.current() != 0)
			{
                if( !m_pGroupList->isContain( iterBL.current() ) )
				{
					Buddy *pBuddy = iterBL.current();
					if ( pBuddy )
					{
						QString sCommand;
						sCommand += "FL";
						sCommand += " ";
						sCommand += pBuddy->getHandle();
						sCommand += " ";
						sCommand += pBuddy->getUID();
						sCommand += " ";
						sCommand += "0";
						sCommand += "\r\n";
						
						m_pDPcon->sendCommand( "RMVB", sCommand );
						pBuddy->setFL( FALSE );
					}
				}
                ++iterBL;
			}
			
		} /*! Delete? Yes */
	}
	else if ( m_pMainView->getSelectedBuddyCount() == 1 )
	{
		Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( pList->currentItem()->text(2) );
		if ( pBuddy )
		{
			if ( !pDeleteForm )
			{
				pDeleteForm = new DeleteForm( this, "Delete Buddy" );
				connect( pDeleteForm, SIGNAL( deleteInfo( DeleteForm * ) ), SLOT( slotDeleteFriend( DeleteForm * ) ) );
			}
			/*!
			 * XXXXXXXXXXXXX
			 */
			pDeleteForm->lockCheckBox->setEnabled( FALSE );
			
			pDeleteForm->setName( pBuddy->getName() );
			pDeleteForm->setUID( pBuddy->getUID() );
			pDeleteForm->setGID( pList->currentItem()->text(1) );
			pDeleteForm->setHandle( pBuddy->getHandle() );
			pDeleteForm->show();
		}
	}
	else
	{
		const GroupList *pGroupList = m_pCurrentAccount->getGroupList();
		Group *pGroup = pGroupList->getGroupByID( pList->currentItem()->text(1) );
		if ( pGroup )
			slotDeleteGroup();
		else
			KMessageBox::information (this, UTF8("삭제 할 친구 선택을 안하셨습니다.\n확인하시고 다시 실행해 주십시오."), UTF8("친구 삭제 알림"));
	}
}


/*!
  친구 목록 불러오기
*/
void KNateon::slotLoadBuddyList()
{
  QString sBdyFileNm = KFileDialog::getOpenFileName(
	QDir::homeDirPath(),
	UTF8("*.nbl|NateOn 친구 목록(*.nbl)"),
	this,
	UTF8("열기")
  );

  if( sBdyFileNm == "" )
    return;

  QDomDocument domDoc("NateOn BuddyList");

  QFile file(sBdyFileNm);


  /* Qt 4.x 에서는 다음과 같이 파일 오픈 
  if( !file.open(QIODevice::ReadOnly) ) {
    return;
  }
  */

  /* Qt 3.x 에서는 다음과 같이 파일 오픈 */
  if( !file.open(IO_ReadOnly)) {
    return;
  }

  QTextStream stream(&file);
  /* for Qt 4.x 
  stream.setCodec(QTextCodec::codecForName("Unicode"));
  */
  stream.setEncoding(QTextStream::Unicode);

  /* for Qt 4.x 
  QString sUnicodeTxt = stream.readAll();
  QString sUnicodeTxt = stream.read();
  QString sUtf8Txt(sUnicodeTxt.toUtf8());
  QString sAsciiTxt(sUnicodeTxt.toAscii());
  */

  /* for Qt 3.x  호출 */
  QString sUnicodeTxt = stream.read();
  QString sUtf8Txt = QString::fromUtf8((const char*)sUnicodeTxt.utf8());

  file.close();
  
  QString sParseErr;
  int nLine = 0, nCol = 0;
  if( !domDoc.setContent(sUnicodeTxt, &sParseErr, &nLine, &nCol) ) {
    return;
  }

  QDomElement rootElem = domDoc.documentElement();
  
  /* Qt 4.x 
  QDomNodeList childNodes = rootElem.childNodes();
  */

  /* Qt 3.x */
  QDomNodeList childNodes = rootElem.elementsByTagName("id");

  QString sInviteMsg;
  if( stConfig.logintype == 'C' )
    sInviteMsg = m_pCurrentAccount->getMyCyworldID();
  else
    sInviteMsg = m_pCurrentAccount->getMyNateID();

  sInviteMsg += UTF8("님이 당신을 네이트온 친구로 초대합니다.");

  for(int i=0; i<childNodes.length(); ++i) {
    QDomNode node = childNodes.item(i);
    
    QString sBuddyName = node.toElement().attribute("name");
    QString sNickName = node.toElement().attribute("nick");
    QString sID = node.firstChild().toCharacterData().data();

    reqAddFriend(sID, sInviteMsg, false);
  }

  
}

/*!
  친구 목록 저장하기
  이 부분에서 윈도우즈용 네이트온과 비슷한 다이얼로그 인터페이스 필요하지만 내공부족으로 
  조금 다른 방식으로 구현했습니다. (버디리스트에서 선택된 그룹or버디를 선택하고 메뉴->친구->저장 하도록)
  지금은 Kdevelop으로 .ui 에서 C++ 클래스 생성이 안되네요. 계속 Kdevelop 이 죽습니다 by 임인택 (masterhand@gmail.com)
*/
void KNateon::slotSaveBuddyList()
{
  QList<QListViewItem> selectedItems = m_pMainView->listView3->selectedItems();
  QList<QListViewItem>::iterator iter = selectedItems.begin();

  QMap<QListViewItem*, Buddy*> itemMap;

  for( ; iter!=selectedItems.end(); ++iter) {

    Buddy *pBuddy = NULL;

    ContactList *pList = NULL;
    pList = static_cast<ContactList* >((*iter));
    
    if( pList->getType() == ContactList::Buddy ) {
      // Handle = text(2), getNick(), getUID(), getName()
      pBuddy = m_pMainView->getBuddyList()->getBuddyByHandle((*iter)->text(2));
      itemMap.insert((*iter), pBuddy);
    } else {
      // 그룹에 속한 모든 Buddy 추가
      QListViewItem *pChild = (*iter)->firstChild();
      
      for(; pChild!= NULL; pChild = pChild->nextSibling()) {
	pList = static_cast<ContactList* >(pChild);

	if( pList->getType() == ContactList::Buddy ) {
	  pBuddy = m_pMainView->getBuddyList()->getBuddyByHandle(pChild->text(2));
	  itemMap.insert(pChild, pBuddy);
	}
      }
    }
  }

  QValueList<Buddy*> lstBdsToExp = itemMap.values();
  
  if( itemMap.count() == 0 ) {
    QMessageBox::information(NULL, UTF8("정보"), UTF8("친구목록에서 저장할 목록을 선택하세요"), 
			     QMessageBox::Ok);
    return;
  }

  QString sBdyFileNm = KFileDialog::getSaveFileName(
	QDir::homeDirPath(),
	UTF8("*.nbl|NateOn 친구 목록(*.nbl)"),
	this,
	UTF8("저장")
  );

  if( sBdyFileNm == "" )
    return;
  
  QFile file(sBdyFileNm);
  /* Qt 4.x   
  if( !file.open(QIODevice::WriteMode)) {
    return;
  }
  */
  
  
  /* Qt 3.x */
  if( !file.open(IO_WriteOnly) ) {
    return;
  }

  QTextStream stream(&file);

  /* for Qt 4.x 
  stream.setCodec(QTextCodec::codecForName("Unicode"));
  */
  stream.setEncoding(QTextStream::Unicode);

  stream << "<?xml version='1.0' encoding='Unicode'?>\n";
  stream << "<list>\n";

  QValueList<Buddy*>::iterator vIter = lstBdsToExp.begin();
  for( ; vIter != lstBdsToExp.end(); ++vIter) {
    stream << "<id name='" << (*vIter)->getName() << "' nick='" << (*vIter)->getNick()
	   << "'>" << UTF8((*vIter)->getUID()) << "</id>\n";
  }

  stream << "</list>";

  file.close();
}



void KNateon::slotErr201()
{
	if ( !bIsConnected )
	{
		m_pLoginView->setCancel( FALSE ); // m_pLoginView->setEnable( true );
		if ( stConfig.autologin == true )
		{
#ifdef NETDEBUG
			kdDebug() << "XXXXXXXXXXXXXXXXX TTTTTTTTTTTTTTt DDDDDDDDDDDDDd" << endl;
#endif
			config->setGroup( "Login" );
			stConfig.autologin = false;
			config->writeEntry( "AutoLogin", false );
			m_pLoginView->setAutoLogin( false );
		}
	}
}

void KNateon::slotBlockBuddy()
{
	QListViewItem *pItem = m_pMainView->getCurrentItem();
	Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( pItem->text(2) );

	QString sCommand( pBuddy->getHandle() );
	sCommand += " ";
	sCommand += pBuddy->getUID();

	/*! 친구 차단/친구 차단 해제 */
	/*! BL == 1 */
	if ( pBuddy->isBL() == true )
	{
		/*! 친구 차단 해제 */
		/*! sCommand => "CMN NateID" */
		m_pDPcon->putUnlock( sCommand );
		pBuddy->setBL( false );
	}
	else
	{
		/*! 친구 차단 */
		KMessageBox::information (this, UTF8("차단을 하시면 차단된 사람은 나의 온라인 상태 정보를 볼 수 없게 되며, 동시에 내 [미니홈피]와 [파일방]에도 접근할 수 없게 됩니다.\n(단, 미니홈피 설정이 \"전체공개\"인 경우 제외)"), UTF8("친구 차단"), UTF8("blockmsg"), KMessageBox::Notify);

		/*! sCommand => "CMN NateID" */
		m_pDPcon->putLock( sCommand );
		pBuddy->setBL( true );
	}
  
  
	QPtrList<ChatView> m_ChatObjs = m_pChatList->getChatList();
	QPtrListIterator<ChatView> iterator(m_ChatObjs);
	ChatView* pChatView;
  
	while(iterator.current() != 0)
	{
		pChatView = iterator.current();
		if ( pChatView->getBuddyByID( pBuddy->getUID() ) )
		{
			QString sFlag;
			if ( pBuddy->isFL() )
				sFlag = "1";
			else
				sFlag = "0";
			if ( pBuddy->isAL() )
				sFlag += "10";
			else
				sFlag += "01";
			if ( pBuddy->isRL() )
				sFlag += "1";
			else
				sFlag += "0";
			
			pChatView->updateUserFlag( pBuddy->getUID(), sFlag );
		}
		++iterator;
	}
	/*!
	 * 차단된것 목록 refresh
	 */
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}


void KNateon::slotMenuSendFile()
{
	QListView *pList = m_pMainView->listView3;
	QListViewItemIterator it( pList );
	m_pBuddyList = m_pCurrentAccount->getBuddyList();

	for ( ; it.current(); ++it )
	{
		if (  pList->isSelected( it.current() ) )
		{
			QListViewItem *pItem = it.current();
			Buddy *pBuddy = m_pBuddyList->getBuddyByHandle( pItem->text(2) );
			if ( pBuddy )
			{
				ChatView *pChat = m_pChatList->getChatViewByUID( pBuddy->getUID() );
				/// 해당 ID로 띄워진 창이 없으면,s
				if ( !pChat )
				{
					/// RESS를 보내고 결과로 받은 TID를 생성한 chatview에 저장한다.
					/// TID는 위젯을 찾을때 사용한다.
					int nTID = m_pDPcon->putRESS();
					pChat = createChat(nTID);
					if ( pChat )
						pChat->addBuddy(pBuddy);
				}
				/// 창이 있고, 보이지 않을때.
				if ( !pChat->isVisible() )
				{
					pChat->show();
					pChat->slotSendFile();
				}
			}
		}
	}
}

void KNateon::slotMenuAlwaysTop( bool bTop )
{
	int flags = getWFlags();
	stConfig.alwaystop = bTop;

	config->setGroup( "Config_General" );
	config->writeEntry( "Always_Top", stConfig.alwaystop );
  
	/*! 메뉴의 항상위 채크 */
	if ( bTop )
	{
		if( !testWFlags(Qt::WStyle_StaysOnTop) )
		{
			flags |= Qt::WStyle_StaysOnTop;
			QPoint p(geometry().x(),geometry().y());
			reparent(0,flags,p,true);
			/*! 왜 적용이 안될까? */
		}
	}
	else
	{
		if( testWFlags(Qt::WStyle_StaysOnTop) )
		{
			flags ^= Qt::WStyle_StaysOnTop;
			QPoint p(geometry().x(),geometry().y());
			reparent(0,flags,p,true);
			/*! 왜 적용이 안될까? */
		}
	}
}

void KNateon::slotListEmoticon(bool bEmoticon)
{
    m_pMainView->slotEmoticonList( bEmoticon );
}

void KNateon::slotNamingSelect(int nType)
{
	switch( nType )
	{
	case 0:
		m_pMainView->slotListOnlyName();
		m_pMainView->pViewNameAction->setChecked( true );
		break;
	case 1:
		m_pMainView->slotListOnlyNick();
		m_pMainView->pViewNickAction->setChecked( true );
		break;
	case 2:
		m_pMainView->slotListNameID();
		m_pMainView->pViewNameIDAction->setChecked( true );
		break;
	case 3:
		m_pMainView->slotListNameNick();
		m_pMainView->pViewNameNickAction->setChecked( true );
		break;
	}
}

void KNateon::slotBuddyOnlyName()
{
	pBuddynamingSelectAction->setCurrentItem(0);
}

void KNateon::slotBuddyOnlyNick()
{
	pBuddynamingSelectAction->setCurrentItem(1);
}

void KNateon::slotBuddyNameID()
{
	pBuddynamingSelectAction->setCurrentItem(2);
}

void KNateon::slotBuddyNameNick()
{
	pBuddynamingSelectAction->setCurrentItem(3);
}

void KNateon::slotBuddySort(int nSort)
{
	switch( nSort )
	{
	case 0:
		m_pMainView->slotSortNormal();
		m_pMainView->pViewAllAction->setChecked( true );
		break;
	case 1:
		m_pMainView->slotSortOnlyOnline();
		m_pMainView->pViewOnlineAction->setChecked( true );
		break;
	case 2:
		m_pMainView->slotSortOnOffline();
		m_pMainView->pViewOnOffAction->setChecked( true );
		break;
	}
}

void KNateon::slotBuddyListAll()
{
	pSortlistSelectAction->setCurrentItem(0);
}

void KNateon::slotBuddyListOnline()
{
	pSortlistSelectAction->setCurrentItem(1);
}

void KNateon::slotBuddyListOnOff()
{
	pSortlistSelectAction->setCurrentItem(2);
}

void KNateon::slotAllHide()
{
}

void KNateon::slotHidePopup()
{
	nPopupY--;
	if (nPopupY < 0) nPopupY = 0;
}

void KNateon::slotCySync(const QString & sID, const QString & sPW)
{
	/*!
	  QString sID = m_pCurrentAccount->getID();
	  QString sOrgPasswd = m_pCurrentAccount->getPassword();
	  /// @nate.com인 경우에는 @nate.com을 제거하고 MD5를 만듬.
	  if ( sID.right(9) == "@nate.com" )
	  sID = sID.left( sID.length() -9 );
	  KMD5 context (sOrgPasswd+sID.lower());
	  sendCommand( "LSIN", m_pCurrentAccount->getID() + " " + context.hexDigest().data() + " " + "MD5 0.01 UTF8\r\n" );
	*/
	QString sCommand;
	if ( sID != QString::null )
	{
		/*!
		 * 역시 네이트온 로긴때 MD5로 로그인 하는 형식으로 PW를 만듬.
		 * 단, 싸이월드 연동인 경우에 싸이아이디가 @nate.com 인 넘들이 있거든요..
		 * 그럼들은.. @nate.com 을 빼시면 안됩니다.
		 */
		QString sBody;
		if ( stConfig.logintype == 'N' )
			sBody = "cyworld_id=";
		else
			sBody = "nate_id=";
		sBody += sID;
		if ( stConfig.logintype == 'N' )
			sBody += "&cyworld_pw2=";
		else
			sBody += "&nate_pw2=";
		KMD5 context ( sPW + sID.lower() );
		sBody += context.hexDigest().data();
		sBody += "\r\n";

		sCommand = QString::number( sBody.length() );
		sCommand += "\r\n";
		sCommand += sBody;
	}
	else
	{
		/*!
		 * 싸이월드ID가 없으면
		 * 싸이연동 해제이다.
		 */
		QString sBody;
		if ( stConfig.logintype == 'N' )
			sBody = "cyworld_id=\r\n";
		else
			sBody = "nate_id=\r\n";
		sCommand = QString::number( sBody.length() );
		sCommand += "\r\n";
		sCommand += sBody;
	}
	/*! 싸이연동 결과를 위해 TID를 저장 */
	nCySync = m_pDPcon->sendCommand( "CPRF", sCommand );
}


/*!
 * 내 설정이 변경 되었는가?
 */
void KNateon::slotCPRF(const QStringList & slCommand)
{
	if ( slCommand[1].toInt() == nCySync )
	{
		if ( stConfig.logintype == 'N' )
		{
			if ( slCommand[2][2] == "1" )
			{
				if ( slCommand[8] != "%00" )
				{
					emit cySyncAuthError( false );
					/*! B: 친구에게만 공개, O: 모두에게 공개, C: 모두에게 비공개 */
					switch( slCommand[7].data()[0] )
					{
					case 'O' :
						stConfig.minihompypublic = 0;	
						break;
					case 'B' :
						stConfig.minihompypublic = 1;
						break;
					case 'C' :
						stConfig.minihompypublic = 2;
						break;
					}
					
					stConfig.cycmn = slCommand[8];
					m_pCurrentAccount->setMyCyworldCMN( slCommand[8] );
				}
				else
				{
					m_pCurrentAccount->setMyCyworldCMN("%00");
					m_pCurrentAccount->setMyCyworldID("%00");
					emit cySyncCanceled();
				}
			}
		}
		else
		{
			if ( ( stConfig.nateid != QString::null ) &&
				 ( stConfig.nateid != "%00" ) &&
				 ( stConfig.nateid != "" ) )
				emit cySyncAuthError( false );
		}
	}
}


/*!
 * 버디 닉 변경
 * (2007-07-04 09:23:14) <-- NNIK 0 xxx@nate.com 비가%20비가...장난이%20아냐~~
 * (2007-07-04 09:23:25) <-- PING 0
 */
void KNateon::slotNNIK(const QStringList & slCommand)
{
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	Buddy* pBuddy = m_pBuddyList->getBuddyByID( slCommand[2] );
	if ( pBuddy )
	{
		QString sNick( slCommand[3] );
		/* 닉을 알 수 없는 경우 이름을 닉으로 사용 */ 
		if ( sNick == "%00" )
			sNick = pBuddy->getName();
		else
			sNick.replace("%20", " ");
		pBuddy->setNick( sNick );
		m_pMainView->updateBuddy( pBuddy );
	}
	emit buddyChangeNick();
}


void KNateon::slotClickMessageBoxPopup(int nType, QString sID)
{
	nType = 0;
	sID = QString::null;
	
	KRun::runCommand("nateon_messagebox");
}



void KNateon::slotCyUpdate(const QString & sBody)
{
	QString sTemp( sBody );
	sTemp += "\r\n";
	
	QString sCommand( QString::number( sTemp.length() ) );
	sCommand += "\r\n";
	sCommand += sTemp;
  
	/*! 싸이연동 결과를 위해 TID를 저장 */
	m_pDPcon->sendCommand( "CPRF", sCommand );
}

void KNateon::closeEvent(QCloseEvent * e)
{
	hide();
	if ( bQuit )
	{
#ifdef NETDEBUG
		kdDebug() << "DCOP COMMAND QUIT" << endl;
#endif
		DCOPClient *client=kapp->dcopClient();
		QByteArray params2;
		QDataStream stream2(params2, IO_WriteOnly);
		stream2 << UTF8("QUIT");
		if (!client->send("MessageBox-*", "messageviewer", "dcopCommand(QString)", params2))
			kdDebug() << "Error with DCOP\n" ;
		KNateonInterface::closeEvent( e );
	}
}

void KNateon::slotCloseApp()
{
	if ( m_pChatList->count() > 0 )
	{
		int result = KMessageBox::questionYesNo(this, UTF8("네이트온을 로그아웃합니다. 열려 있는 모든 창이 닫힙니다."), UTF8("네이트온") );
		if ( result == KMessageBox::No )
		{
			return;
		}
	}
	
	bQuit = true;
	close();
}

void KNateon::slotLogin()
{
	m_pLoginView->connectToDPLserver();
}

void KNateon::slotGoMyMinihompy()
{
	int result;
	if ( m_pCurrentAccount->getMyCyworldCMN() != "%00")
	{
		m_pMainView->setHompyIcon( false );
		
		/*! Cyworld MiniHompy 이면, */
		if /* (1) */ ( m_pCurrentAccount->getHompyType() == CurrentAccount::Cyworld )
		{
			QString sURL("http://br.nate.com/index.php");
			sURL += "?code=D023";
			sURL += "&t=";
			sURL += m_pCurrentAccount->getMyTicket();
			sURL += "&param=";
			sURL += m_pCurrentAccount->getMyCyworldCMN();
#ifdef NETDEBUG
			kdDebug() << "Cyworld MiniHompy : [" << sURL << "]" <<endl;
#endif
			LNMUtils::openURL( sURL );
		}
		/*! Home2 이면, */
		else
		{
			QString sURL("http://br.nate.com/index.php");
			sURL += "?code=D011";
			sURL += "&t=";
			sURL += m_pCurrentAccount->getMyTicket();
			sURL += "&param=";
			sURL += m_pCurrentAccount->getMyHome2CMN();
			LNMUtils::openURL( sURL );
		}
	}
	else
	{
		result = KMessageBox::  questionYesNo(this, UTF8("싸이월드 미니홈피 기능을 사용하시려면 네이트온에\n미니홈피사용하기 설정이 있어야 합니다.\n\n설정하시겠습니까?"), UTF8("네이트온 미니홈피") );
		if ( result == KMessageBox::Yes )
		{
			m_pPreferenceView->show();
			m_pPreferenceView->showSyncSetup();
		}
	}
}

void KNateon::slotKill()
{
	KMessageBox::information( this, UTF8("고객님께서는 다른 PC, 모바일기기로 접속하셨거나 싸이월드 아이디를 네이트 아이디로 변경 또는 회원탈퇴로 인하여 로그아웃 되었습니다. 문의사항은 네이트온관리자(nateonmaster@nate.com) 앞으로 문의해 주시기 바랍니다."), UTF8("네이트온 - 로그아웃"), 0, 0);
	slotOtherLogin();
}

/*!
 * 채팅창이 아웃포커싱일때 채팅메세지가 오면 팝업창 보이기.
 */
void KNateon::slotChatMessage(const QStringList & slCommand)
{
	if ( stConfig.usesound && stConfig.usestartchatsound )
		Sound::play( stConfig.startchatsoundpath );

	if ( stConfig.alarmrequirechat )
	{
		QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );
		if ( !pChatPopup)
		{
			pChatPopup= new PopupWindow();
			connect(pChatPopup, SIGNAL( clickText( int, QString ) ), SLOT( slotIncomingChat(int, QString ) ) );
			connect(pChatPopup, SIGNAL( hidePopup() ), SLOT( slotHidePopup() ) );
		}
		int screen = kapp->desktop()->screenNumber();
		QRect screenSize = kapp->desktop()->availableGeometry(screen);
		
		int nX = point.x();
		int nY = screenSize.height() + screenSize.top();
		
		pChatPopup->setID( slCommand[2] );
		pChatPopup->setAnchor( QPoint(nX, nY) );
		pChatPopup->setLogo( sPicsPath + "popup_notice_chat.bmp" );
		
		m_pBuddyList = m_pCurrentAccount->getBuddyList();
		Buddy* pBuddy = m_pBuddyList->getBuddyByID( slCommand[2] );

		if ( pBuddy )
		{
			QString sMsg;
			sMsg = pBuddy->getName();
			sMsg += "...";
			sMsg += UTF8("님의 대화 :\n");
			int nSeper = slCommand[4].findRev("%09");
			QString sTemp( slCommand[4].mid( nSeper + 3 , slCommand[4].length() ) );

			if ( sTemp.find( QRegExp("<FLCON.*FLCON>") ) != -1 )
				sTemp = UTF8("플래시콘을 보내셨습니다.%0D%0A현재 리눅스 버전은 플래시콘을 지원하지 않습니다.");
			
			QString sTemp2;
			if ( sTemp.find("%0A") != -1 )
				sTemp2 = sTemp.left( sTemp.find("%0A") );
			else
				sTemp2 = sTemp;
			sMsg += sTemp2;
			
			if ( sMsg.length() > 36 )
			{
				int nOver = sMsg.length() - 36;
				
				sMsg = pBuddy->getName();
				sMsg += "...";
				sMsg += UTF8("님의 대화 :\n");
				sMsg += sTemp.left( sTemp.length() - nOver );
			}
			Common::fixOutString( sMsg );
			pChatPopup->setText( sMsg );
			
			/*! 0: Online, 1: incoming chat, 2: incoming memo */
			pChatPopup->setType(1);
			pChatPopup->show();
			nPopupY++;
		}
		else
		{
			/*!
             * 비버디 대화
             */
			QString sMsg;
			sMsg = slCommand[2];
			// sMsg += "...";
			sMsg += UTF8("님의 대화 :\n");
			int nSeper = slCommand[4].findRev("%09");
			QString sTemp( slCommand[4].mid( nSeper + 3 , slCommand[4].length() ) );
			QString sTemp2;
			if ( sTemp.find("%0A") != -1 )
				sTemp2 = sTemp.left( sTemp.find("%0A") );
			else
				sTemp2 = sTemp;
			sMsg += sTemp2;

			if ( sMsg.length() > 36 )
			{
				int nOver = sMsg.length() - 36;
				
				sMsg = pBuddy->getName();
				sMsg += "...";
				sMsg += UTF8("님의 대화 :\n");
				sMsg += sTemp.left( sTemp.length() - nOver );
			}
			Common::fixOutString( sMsg );
			pChatPopup->setText( sMsg );
			
			/*! 0: Online, 1: incoming chat, 2: incoming memo */
			pChatPopup->setType(1);
			pChatPopup->show();
			nPopupY++;
		}
	}
}

void KNateon::slotIncomingChat(int nType, QString sID)
{
	nType = 0;
	
	ChatView *pChatView = m_pChatList->getChatViewByUID( sID );
	if ( pChatView )
	{
		pChatView->show();
		pChatView->showNormal();
		pChatView->showNormal();
		pChatView->raise();
		pChatView->setFocus();
		pChatView->setActiveWindow();
		pChatView->ChatEditQTE->setFocus();
		pChatView->setWindowState ( pChatView->windowState() & ~WindowMinimized | WindowActive );
		
		int screen = kapp->desktop()->screenNumber();
		QRect screenSize = kapp->desktop()->availableGeometry(screen);
		
		int flags = Qt::WStyle_StaysOnTop;
		pChatView->reparent(0,flags, screenSize.center(), true);

		flags ^= Qt::WStyle_StaysOnTop;
		pChatView->reparent(0,flags, screenSize.center(), true);
		/*! 왜 적용이 안될까? */
	}
}

void KNateon::slotNewConnectSS(ChatView * pChatView)
{
	int nTID = m_pDPcon->putRESS();
	pChatView->setTID( nTID );
}

void KNateon::slotViewMemoBox()
{
	KRun::runCommand("nateon_messagebox");
}

void KNateon::slotGoCyMain()
{
	QString sURL("http://br.nate.com/index.php");
	sURL += "?code=D007";
	sURL += "&t=";
	sURL += m_pCurrentAccount->getMyTicket();
	LNMUtils::openURL( sURL );
}
/*!
 * NPRF [trid] [id] [type mask] [mobile] [email] [cycmn] [music_date] [tong_yn] [birth]
 * 자세한것은 "doc/싸이연동.txt" 참고.
 */
void KNateon::slotNPRF(const QStringList & slCommand)
{
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	if ( slCommand[3][2] == '1' )
	{
		Buddy* pBuddy = m_pBuddyList->getBuddyByID( slCommand[2] );
		if ( pBuddy )
		{
			pBuddy->setCyworld_CMN( slCommand[6] );
			m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
		}
	}
}

/*!
 * ALRM [trid] [SVC_GB] [from] [text] [urlgb] [url] [svc_defined]
 */
void KNateon::slotALRM(const QStringList & slCommand)
{
	/*!
	 * ex>
	 * ALRM 0 CYLD %00 %00 2 %00 ring0320@msn.com %00 Y 12737092 Y Y B
	 * [service defined 필드]
	 [연동한 싸이월드 ID], N/A, N/A, [Cyworld CMN], [싸이월드에 새글 등록시 알려주기 옵션 Y|N], [그밖의 알림 알려주기 Y|N], [모두에게 공개, 비공개, 친구에게만 공개 옵션 O|B|C]
	 O : 모두에게 공개
	 B : 친구에게 공개
	 C : 비공개
	*/
	if ( slCommand[2] == "CYLD" )
	{
		stConfig.cyid = slCommand[7];
		stConfig.cycmn = slCommand[10];
		stConfig.alarmminihompynew = ( slCommand[11] == "Y" );
		stConfig.alarmetc = ( slCommand[12] == "Y" );
		// stConfig.minihompypublic = slCommand[13].data()[0];
		/*! B: 친구에게만 공개, O: 모두에게 공개, C: 모두에게 비공개 */
		switch( slCommand[13].data()[0] )
		{
		case 'O' :
			stConfig.minihompypublic = 0;
			break;
		case 'B' :
			stConfig.minihompypublic = 1;
			break;
		case 'C' :
			stConfig.minihompypublic = 2;
			break;
		}
		
		m_pCurrentAccount->setMyCyworldID( stConfig.cyid );
		m_pCurrentAccount->setMyCyworldCMN( stConfig.cycmn );
		if ( stConfig.cycmn == "%00" )
		{
			emit cySyncCanceled();
		}
		return;
	}
	else if ( slCommand[2] == "C2ID" ) /*! 주사용계정 정보 변경 알림 */
	{
		/*!
		 * 내 주사용계정 CMN 을 변경한다.
		 * (2007-09-14 14:35:17) <-- ALRM 0 C2ID 12737092 C2 2 %00 12737092:12737092:1
		 * (2007-09-14 15:57:57) <-- ALRM 0 C2ID 12737092 C2 2 %00 12737092:a0552737:2
		 */
		return;
	}
	else if ( slCommand[2] == "MAIL" ) /*! 메일 수신 알림 */
	{
		/*!
		 * (2007-10-24 18:02:50) <-- ALRM 0 MAIL %00 %00 2 %00  홍%20길동 %00 "홍%20길동"%20<honggildong@sender.com>  "X@nate.com"%20<X@nate.com> 테스트메일 %00 %00 %00
		 */
		if ( !pMailPopup )
		{
			pMailPopup = new PopupWindow();
			connect( pMailPopup, SIGNAL( clickText( int, QString ) ), SLOT( slotShowNewMail(int, QString ) ) );
			connect( pMailPopup, SIGNAL( hidePopup() ), SLOT( slotHidePopup() ) );
		}

		QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );

		int screen = kapp->desktop()->screenNumber();
		QRect screenSize = kapp->desktop()->availableGeometry(screen);

		int nX = point.x();
		int nY = screenSize.height() + screenSize.top();

		pMailPopup->setAnchor( QPoint(nX, nY) );
		pMailPopup->setLogo( sPicsPath + "popup_notice_mail.bmp" , 16777215);

		QString sMsg( slCommand[7] );
		sMsg.replace("%20", " ");
		sMsg += UTF8(" 님으로 부터 메일이 도착했습니다.");

		pMailPopup->setText( sMsg );

		/*! 0: Online, 1: incoming chat, 2: incoming memo, 3: incoming mail */
		pMailPopup->setType(3);
		pMailPopup->show();
		nPopupY++;

		return;
	}
	else
	{
		/*!
         * (2007-08-27 16:56:59) <-- ALRM 0 C2HP a0552737 홈2%20방명록에%20새글이%20등록%20되었습니다. 1 http%253A%252F%252Fcyhome.cyworld.com%252F%253Fhome_id%253Da0552737%2526url%253D%25252Fmyhompy%25252Findex.php%25253Fhome_id%25253Da0552737%252526requireType%25253D2
		
         QString sTemp;
         sTemp =  "http%253A%252F%252Fcyhome.cyworld.com%252F%253Fhome_id%253Da0552737%2526url%253D%25252Fmyhompy%25252Findex.php%25253Fhome_id%25253Da0552737%252526requireType%25253D2";
		
         kdDebug() << "1> " << sTemp << endl;
         QUrl::decode(sTemp);
         kdDebug() << "2> " << sTemp << endl;
         QUrl::decode(sTemp);
         kdDebug() << "3> " << sTemp << endl;
         QUrl::decode(sTemp);
         kdDebug() << "4> " << sTemp << endl;
         *
         * knateon: 1> http%25253A%25252F%25252Fcyhome.cyworld.com%25252F%25253Fhome_id%25253Da0552737%252526url%25253D%2525252Fmyhompy%2525252Findex.php%2525253Fhome_id%2525253Da0552737%25252526requireType%2525253D2
         * knateon: 2> http%253A%252F%252Fcyhome.cyworld.com%252F%253Fhome_id%253Da0552737%2526url%253D%25252Fmyhompy%25252Findex.php%25253Fhome_id%25253Da0552737%252526requireType%25253D2
         * knateon: 3> http://cyhome.cyworld.com/?home_id=a0552737&url=%252Fmyhompy%252Findex.php%253Fhome_id%253Da0552737%2526requireType%253D2
         * knateon: 4> http://cyhome.cyworld.com/?home_id=a0552737&url=/myhompy/index.php?home_id=a0552737&requireType=2
		
         */

		if ( slCommand.count() < 6 )
			return;

		QString sRUrl( slCommand[6] );
		QUrl::decode( sRUrl );
		QUrl::decode( sRUrl );
		// QUrl::decode( sRUrl );
		
		bool bIsUpdate = FALSE;
		bool bIsPopup = FALSE;
		QString sBCode = QString::null;
		QString sHFlag = QString::null;
		if ( ( m_pCurrentAccount->getHompyType() == CurrentAccount::Cyworld ) && stConfig.usecyworld )
		{
			if ( slCommand[2] == "CYRP" ) /*! 미니 홈피 댓글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "B003";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CYME" ) /*! 싸이 쪽지 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "B004";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CYRG" ) /*! 이벤트 방명록 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "B012";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CYHP" ) /*! 방명록 새글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "B013";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CYFR" ) /*! 일촌 관련 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "B014";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CYPC" ) /*! 사진첩 댓글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "B015";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CLRP" ) /*! 클럽 댓글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "G032";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CLSC" ) /*! 클럽 일정 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "G032";
				sHFlag = "1";
			}
			else if ( slCommand[2] == "CLAP" ) /*! 클럽 가입 승인 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "G032";
				sHFlag = "1";
			}
			else
			{
#ifdef NETDEBUG
				kdDebug() << "Unknown Command : " << slCommand[2] << endl;
#endif
				return;
			}
		}
		else if ( ( m_pCurrentAccount->getHompyType() == CurrentAccount::Home2 ) &&
                  ( m_pCurrentAccount->getMyMajorCMN() == slCommand[3] ) )
		{
			if ( slCommand[2] == "2CRP" ) /*! Home2 클럽 댓글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D013";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "2CSC" ) /*! Home2 클럽 일정 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D013";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "2CAP" ) /*! Home2 클럽 가입 승인 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D013";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2RP" ) /*! Home2 방명록 댓글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D014";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2ME" ) /*! Home2 싸이 쪽지 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "D015";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2RG" ) /*! Home2 이벤트 방명록 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D016";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2HP" ) /*! Home2 새 방명록 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "D017";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2FR" ) /*! Home2 일촌신청 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "D018";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2PC" ) /*! Home2 사진첩 댓글 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( TRUE );
				bIsPopup = TRUE;
				sBCode = "D019";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2GF" ) /*! Home2 선물 도착 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D020";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2GR" ) /*! Home2 새 덧글 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D021";
				sHFlag = "2";
			}
			else if ( slCommand[2] == "C2ML" ) /*! 싸이월드 메일 알림 */
			{
				bIsUpdate = TRUE;
				m_pCurrentAccount->setMyHompyNew( FALSE );
				bIsPopup = TRUE;
				sBCode = "D022";
				sHFlag = "2";
			}
			else
			{
#ifdef NETDEBUG
				kdDebug() << "Unknown Command : " << slCommand[2] << endl;
#endif
				return;
			}
		}

		if ( bIsUpdate )
		{
			if ( m_pMainView )
				m_pMainView->slotHompyNew();
		}
		
		if ( bIsPopup )
		{
			QString sURL;
			sURL = "http://br.nate.com/index.php";
			sURL += "?code=";
			sURL += sBCode;
			sURL += "&r_url=";
			sURL += sRUrl;
			sURL += "&h_flag=";
			sURL += sHFlag;
			sURL += "&t=";
			sURL += m_pCurrentAccount->getMyTicket();
			
			if ( !pToastWindow )
			{
				pToastWindow = new ToastWindow();
				connect( pToastWindow, SIGNAL( textClicked( const QString & ) ), SLOT( slotHompyRUrl( const QString & ) ) );
			}
			
			QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );
			int nX = point.x() ;
			
			int screen = kapp->desktop()->screenNumber();
			QRect screenSize = kapp->desktop()->availableGeometry(screen);
#ifdef NETDEBUG
			kdDebug() << "Available Width : " << QString::number( screenSize.width() ) << ", Height : " << QString::number( screenSize.height() ) << endl;
#endif
			
			int nY = screenSize.bottom()/* - pToastWindow->height() */;
			
			pToastWindow->setAnchor( QPoint(nX, nY) );
			
			pToastWindow->setRUrl( sURL );
			QString sBody( slCommand[4] );
			sBody.replace("%20", " ");
			sBody.replace("%0D", "\r");
			sBody.replace("%0A", "\n");
			pToastWindow->setText( sBody );
			pToastWindow->show();
		}
	}
}

void KNateon::slotErr421()
{
  	// First disconnect, to unregister all contacts
	if(m_pDPcon->isConnected())
	{
		m_pDPcon->closeConnection();
	}
  
	KMessageBox::information( this, UTF8("죄송합니다. 서버 작업으로 네이트온 접속 할 수 없습니다.\n다음에 다시 접속을 시도해 주십시요."), UTF8("네이트온 - 접속에러"), 0, 0);
}

void KNateon::slotMemoSetupReplyRole()
{
	if ( !m_pPreferenceView )
		return;
	m_pPreferenceView->show();
	m_pPreferenceView->showMemoReplyRole();
}

void KNateon::slotRelogin()
{
#ifdef NETDEBUG
	kdDebug() << "Enter Relogin" << endl;
#endif
	if ( stConfig.autologin )
	{
		m_pLoginView->connectToDPLserver();
	}
	else
	{
#ifdef NETDEBUG
		kdDebug() << "Enter Relogin : autologin == false " << endl;
#endif
		if ( m_pMainView )
			m_pMainView->hide();

		if ( m_pLogoutView )
		{
#if 0
			if ( stConfig.logintype == 'C' )
				m_pLogoutView->setID( m_pCurrentAccount->getMyCyworldID() );
			else
				m_pLogoutView->setID( m_pCurrentAccount->getMyNateID() );
#endif
			m_pLogoutView->update();
			m_pLogoutView->hide();
		}
		
		if ( m_pLoginView )
		{
			setCentralWidget(m_pLoginView);
			m_pLoginView->emptyPasswordShow();
			m_pLoginView->update();
			m_pLoginView->show();
		}
	}
#ifdef NETDEBUG
	kdDebug() << "End Relogin" << endl;
#endif
}

void KNateon::slotHidenLogin(bool bHidenLogin)
{
	bHidenLogin = FALSE;
	
	config->setGroup( "Login" );
	config->writeEntry( "HidenLogin", m_pLoginView->hideLoginCheckBox->isChecked() );
}

/*!
 * #define NATE_CODE_DB_ERROR "500" // general db error
 */
void KNateon::slotErr500( const QStringList &slCommand )
{
	/*! 싸이연동 인증 에러 */
	if ( nCySync == slCommand[1].toInt() )
	{
		emit cySyncAuthError( true );
	}
}

void KNateon::slotOtherLogin()
{
#ifdef NETDEBUG
	kdDebug() << "Enter other login" << endl;
#endif
	m_pDPcon->closeConnection();
	if ( m_pMainView )
		m_pMainView->hide();
	if ( m_pLogoutView )
	{
#if 0
		if ( stConfig.logintype == 'C' )
			m_pLogoutView->setID( m_pCurrentAccount->getMyCyworldID() );
		else
			m_pLogoutView->setID( m_pCurrentAccount->getMyNateID() );
#endif
		m_pLogoutView->update();
		m_pLogoutView->hide();
	}
	if ( m_pLoginView )
	{
		setCentralWidget(m_pLoginView);
		m_pLoginView->emptyAllShow();
		m_pLoginView->show();
	}
}

void KNateon::slotErr309()
{
	if ( stConfig.logintype != 'N' )
		emit cySyncAuthError( true );
}

void KNateon::slotNateSyncCancel()
{
	/*!
	 * 네이트 ID가 없으면
	 * 네이트 연동 해제.
	 */
	QString sBody;
	sBody = "nate_id=\r\n";
  
	QString sCommand;
	sCommand = QString::number( sBody.length() );
	sCommand += "\r\n";
	sCommand += sBody;
	/*! 싸이연동 결과를 위해 TID를 저장 */
	nCySync = m_pDPcon->sendCommand( "CPRF", sCommand );
}

void KNateon::slotShowProfile()
{
	QString sURL("http://br.nate.com/index.php");
	sURL += "?code=F009";
	sURL += "&t=";
	sURL += m_pCurrentAccount->getMyTicket();
	sURL += "&param=";
	sURL += m_pCurrentAccount->getMyCMN();
#ifdef NETDEBUG
	kdDebug() << "Profile : [" << sURL << "]" <<endl;
#endif
	LNMUtils::openURL( sURL );
}

void KNateon::slotEditProfile()
{
	QString sURL("http://br.nate.com/index.php");
	sURL += "?code=F010";
	sURL += "&t=";
	sURL += m_pCurrentAccount->getMyTicket();
	sURL += "&param=";
	sURL += m_pCurrentAccount->getMyCMN();
#ifdef NETDEBUG
	kdDebug() << "Profile : [" << sURL << "]" <<endl;
#endif
	LNMUtils::openURL( sURL );
}

void KNateon::slotRefreshBuddyList()
{
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateon::slotSaveChatLog(ChatView * pChatView, bool bWriteLog)
{
	bWriteLog = FALSE;
	
	QPtrListIterator<Buddy> iterator( pChatView->getBuddyList() );
	Buddy* pBuddy;
	QString sCHATUSERS;
  
	while(iterator.current() != 0)
	{
		pBuddy = iterator.current();
		if ( sCHATUSERS.length() > 1 )
			sCHATUSERS += ";";
		sCHATUSERS += pBuddy->getUID();
		++iterator;
	}

	QString sChatLog;
	sChatLog = pChatView->getChatLog();
	sChatLog.replace("%20", " ");
	pSQLiteDB->saveChatBox( sCHATUSERS, sChatLog );
}

/*!
 * 대화창 메뉴에서 지난 대화 보기
 */
void KNateon::slotViewChatLog(const ChatView * pChatView)
{
	KRun::runCommand("nateon_messagebox");
  
	QPtrList<Buddy> m_BuddyList = pChatView->getBuddyList();
	QPtrListIterator<Buddy> iterator(m_BuddyList);
	Buddy* pBuddy = iterator.current();

	if ( pBuddy )
	{
		sDCOPTempCommand = "SEARCH:CHAT:";
		sDCOPTempCommand += pBuddy->getUID();
	}
}

void KNateon::slotBlockBuddy(const QString & sID)
{
	Buddy *pBuddy = m_pBuddyList->getBuddyByID( sID );
  
	QString sCommand( pBuddy->getHandle() );
	sCommand += " ";
	sCommand += pBuddy->getUID();
  
	/*! 친구 차단/친구 차단 해제 */
	/*! BL == 1 */
	if ( /* pBuddy->getBuddyFlag()[2] == '1'*/ pBuddy->isBL() == true )
	{
		/*! sCommand => "CMN NateID" */
		m_pDPcon->putUnlock( sCommand );
		pBuddy->setBL( false );
	}
	else
	{
		/*! sCommand => "CMN NateID" */
		m_pDPcon->putLock( sCommand );
		pBuddy->setBL( true );
	}
  
	/*!
	 * 차단된것 목록 refresh
	 */
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

/*!
 * 그룹 마우스 오른쪽
 * 채팅하기.
 */
void KNateon::slotStartChat( const ContactRoot * pRoot )
{
	const GroupList *pGroupList = m_pCurrentAccount->getGroupList();
	const Group *pGroup = pGroupList->getGroupByID( pRoot->text(1) );
	QPtrList< Buddy > Buddies;
	Buddies.clear();
    QPtrListIterator<Buddy> it( pGroup->getBuddyList() );
    while( it.current() != 0)
	{
		Buddy* pBuddy = it.current();
		if ( pBuddy && ( pBuddy->getStatus() != "F" ) )
		{
			Buddies.append( pBuddy );
		}
        ++it;
	}
	if ( Buddies.count() > 0 )
		startChat( Buddies );
	else
		KMessageBox::information( this, UTF8("빈 그룹 입니다."), UTF8("그룹 대화") );
}

void KNateon::slotLockGroup(const QString & sGID)
{
	GroupList *pGroupList = m_pCurrentAccount->getGroupList();
	Group *pGroup = pGroupList->getGroupByID( sGID );

    QPtrList<Buddy> plBuddies = pGroup->getBuddyList();
    
	/*! 친구 차단 */
	// KMessageBox::information (this, UTF8("차단을 하시면 차단된 사람은 나의 온라인 상태 정보를 볼 수 없게 되며, 동시에 내 [미니홈피]와 [파일방]에도 접근할 수 없게 됩니다.\n(단, 미니홈피 설정이 \"전체공개\"인 경우 제외)"), UTF8("친구 차단"), UTF8("blockmsg"), KMessageBox::Notify);
	int result = KMessageBox::  questionYesNo(this, UTF8("차단을 하시면 차단된 사람은 나의 온라인 상태 정보를 볼 수 없게 되며, 동시에 내 [미니홈피]와 [파일방]에도 접근할 수 없게 됩니다.\n(단, 미니홈피 설정이 \"전체공개\"인 경우 제외)"), UTF8("친구 차단") );
	if ( result == KMessageBox::No ) return;
	
    QPtrListIterator<Buddy> it(plBuddies);
    while( it.current() != 0 )
	{
		Buddy *pBuddy = it.current();
		if ( pBuddy )
		{
			QString sCommand( pBuddy->getHandle() );
			sCommand += " ";
			sCommand += pBuddy->getUID();
			
			/*! sCommand => "CMN NateID" */
			m_pDPcon->putLock( sCommand );
			pBuddy->setBL( true );
		}
#ifdef NETDEBUG
		else
		{
			kdDebug() << "Cann't Find Handle : [" << *it << "]" << endl;
		}
#endif
        ++it;
	}
  
	/*!
	 * 차단된것 목록 refresh
	 */
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateon::slotUnlockGroup(const QString & sGID)
{
	GroupList *pGroupList = m_pCurrentAccount->getGroupList();
	Group *pGroup = pGroupList->getGroupByID( sGID );
  
    QPtrListIterator<Buddy> it( pGroup->getBuddyList() );
    while( it.current() != 0 )
	{
		Buddy *pBuddy = it.current();
		QString sCommand( pBuddy->getHandle() );
		sCommand += " ";
		sCommand += pBuddy->getUID();
    
		/*! sCommand => "CMN NateID" */
		m_pDPcon->putUnlock( sCommand );
		pBuddy->setBL( false );

        ++it;
	}
  
	/*!
	 * 차단된것 목록 refresh
	 */
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

/*!
 * 파일 전송 완료 후 처리
 */
// void KNateon::finishTransfer(SendFileInfo * pSendFileInfo)
// {
// #ifdef NETDEBUG
// 	kdDebug() << "XXXXXXXXXXX File Finished !!! " << endl;
// #endif
// 	ChatView *pChatView = pSendFileInfo->getChatView();
// 	pChatView->putSuccessFileTransfer( pSendFileInfo );
// 	m_pFileTransfer->finishTransfer( pSendFileInfo->getSSCookie() );
// }

void KNateon::slotPopupMemoFromUUID(int nType, QString sUUID)
{
	nType = 0;
	
	rowList myList;
	QString sQuery;
  
	sQuery = "SELECT SUSER, RUSER, BODYDATA FROM tb_local_inbox WHERE UUID='";
	sQuery += sUUID;
	sQuery += "';";
	myList = pSQLiteDB->getRecords(sMemoDataPath + "local_inbox.db", sQuery);
	if ( myList.isEmpty() )
	{
#ifdef NETDEBUG
		kdDebug() << "[NOTICE] Not Found UUID : [" << sUUID << "]" << endl;
#endif
		return;
	}
  
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
  
	QString sSender;
	Buddy* pBuddy = m_pBuddyList->getBuddyByID( myList.first()[0] );
	if ( pBuddy )
	{
		sSender = "\"";
		sSender += pBuddy->getName();
		sSender += "\" <";
		sSender += pBuddy->getUID();
		sSender += ">";
	}
	else
	{
		sSender = myList.first()[0];
	}

	QStringList slRecv = QStringList::split(";", myList.first()[1] );
	QString sReceivers;
	for ( QStringList::Iterator it = slRecv.begin(); it != slRecv.end(); ++it )
	{
		Buddy* pBuddy = m_pBuddyList->getBuddyByID(*it);
		if ( pBuddy )
		{
			if ( sReceivers.length() > 1 )
				sReceivers += ";\"" + pBuddy->getName() + "\" <" + *it + ">";
			else
				sReceivers = "\"" + pBuddy->getName() + "\" <" + *it + ">";
		}
		else
		{
			if ( stConfig.logintype == 'C' )
			{
				/// 받는 사람이 본인이면,
				if ( *it == m_pCurrentAccount->getMyCyworldID() )
				{
					if ( sReceivers.length() > 1 )
						sReceivers += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
					else
						sReceivers = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
				}
				else /// 받은 사람이 목록에 없는경우.
				{
					if ( sReceivers.length() > 1 )
						sReceivers += ";" + *it;
					else
						sReceivers = *it;
				}
			}
			else
			{
				/// 받는 사람이 본인이면,
				if ( *it == m_pCurrentAccount->getMyNateID() )
				{
					if ( sReceivers.length() > 1 )
						sReceivers += ";\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
					else
						sReceivers = "\"" + m_pCurrentAccount->getMyName() + "\" <" + *it + ">";
				}
				else /// 받은 사람이 목록에 없는경우.
				{
					if ( sReceivers.length() > 1 )
						sReceivers += ";" + *it;
					else
						sReceivers = *it;
				}
			}  
		}
	}

	QString sMemoBody( myList.first()[2] );

	MemoPopupView	*pMemo1 = new MemoPopupView();
	connect( pMemo1, SIGNAL( replyMemo( MemoPopupView::SendType, const QString& , const QString& ) ), SLOT( slotReplyMemo( MemoPopupView::SendType, const QString&, const QString& ) ) );
	connect( pMemo1, SIGNAL( deleteMemo( const QString & ) ), SLOT( slotDeleteMemo( const QString & ) ) );
	connect( pMemo1, SIGNAL( closeMemoPopup( MemoPopupView * ) ), SLOT( slotCloseMemoPopup( MemoPopupView * ) ) );
	
	pMemo1->setSender( sSender );
	pMemo1->setReceiver( sReceivers );
	pMemo1->setBody( sMemoBody );
	pMemo1->setUUID( sUUID );
	pMemo1->show();
}

/*! 메일 알림 팝업창 클릭 */
void KNateon::slotShowNewMail( int nType, QString sUrl )
{
	/*! 네이트로 로그인 하면 상관 없지만,
	 * 싸이로 로그인 했을때에는 싸이메일 또는 네이트가 연동 되있으면,
	 * 네이트 메일로 보여지도록 처리하는 구문 빠져 있음.
	 * 네이트 ID로 로그인 후 사용하면 정상. 나머지는 비정상 적일 것임.
	 */
	nType = 0;
	sUrl = QString::null;
	
	QString sURL("http://br.nate.com/index.php");
	sURL += "?code=G051";
	sURL += "&t=";
	sURL += m_pCurrentAccount->getMyTicket();
	sURL += "&param=";
	sURL += m_pCurrentAccount->getMyCMN();
	LNMUtils::openURL( sURL );
}

/*! 허용된 대화 상대에게만 대화 요청 받기 */
void KNateon::slotPrivacyPermitChat( bool bAllow )
{
	QString sBody;
	if ( bAllow )
		sBody = "allow_nonbuddy_chat=N";
	else
		sBody = "allow_nonbuddy_chat=Y";
	sBody += "\r\n";
  
	/*! CPRF */
	QString sCommand;
	sCommand = QString::number( sBody.length() );
	sCommand += "\r\n";
	sCommand += sBody;
	m_pDPcon->sendCommand( "CPRF", sCommand );
}

/*! 친구에게만 쪽지 받기 */
void KNateon::slotPrivacyFriendMemo( bool bAllow )
{
	QString sBody;
	if ( bAllow )
		sBody = "allow_buddy_only=Y";
	else
		sBody = "allow_buddy_only=N";
	sBody += "\r\n";
  
	/*! CPRF */
	QString sCommand;
	sCommand = QString::number( sBody.length() );
	sCommand += "\r\n";
	sCommand += sBody;
	// sCommand += "\r\n";
	m_pDPcon->sendCommand( "CPRF", sCommand );
}

void KNateon::slotShowMemoPopup()
{
	if ( pSQLiteDB->getNewMemoCount() > 0)
	{
		if ( !pMemoPopup)
		{
			pMemoPopup= new PopupWindow();
			connect(pMemoPopup, SIGNAL( clickText( int, QString ) ), SLOT( slotClickMessageBoxPopup(int, QString ) ) );
			connect(pMemoPopup, SIGNAL( hidePopup() ), SLOT( slotHidePopup() ) );
		}
		/*!
		 * 쪽지 받음 소리
		 */
		if ( stConfig.usesound && stConfig.usememorecievesound )
			Sound::play( stConfig.memorecievesoundpath );
  
		QPoint point = systemTrayWidget_->mapToGlobal( systemTrayWidget_->pos() );
		int nX = point.x();

		int screen = kapp->desktop()->screenNumber();
		QRect screenSize = kapp->desktop()->availableGeometry(screen);

		int nY = screenSize.height() + screenSize.top();
		
		QString sMsg;
		sMsg = UTF8( "새로운 쪽지가 " );
		sMsg += QString::number( pSQLiteDB->getNewMemoCount() );
		sMsg += UTF8( "개 도착했습니다." );
		pMemoPopup->setText( sMsg );
  
		pMemoPopup->setAnchor( QPoint(nX, nY) );
		pMemoPopup->setLogo( sPicsPath + "popup_notice_memo.bmp" );
  
		/*! 0: Online, 1: incoming chat, 2: incoming memo */
		pMemoPopup->setType(2);
		pMemoPopup->show();
		nPopupY++;
  
		// emit updateMemoCount( pSQLiteDB->getNewMemoCount() );
		m_pMainView->slotUpdateMemoCount( pSQLiteDB->getNewMemoCount() );
	}
}

void KNateon::slotGetProfile( QStringList & slResult )
{
	for ( QStringList::Iterator it = slResult.begin(); it != slResult.end(); ++it )
	{
		if ( (*it).find("=") == -1)
			continue;
    
		QStringList slCnt = QStringList::split( '=', *it );
		QString sKey = slCnt[0].stripWhiteSpace();
		QString sValue = slCnt[1].stripWhiteSpace();

		config->setGroup( "Config_Privacy" );
    
		if ( sKey == "allow_buddy_only" )
		{
			/*!
			 * 친구에게만 쪽지 받기.
			 */
			if ( sValue == "Y" || sValue == "y" )
			{
				stConfig.allowonlyfriendmemo = TRUE;
			}
			else
			{
				stConfig.allowonlyfriendmemo = FALSE;
			}
			config->writeEntry( "Allow_Only_Friend_Memo", stConfig.allowonlyfriendmemo );
		}
		else if ( sKey == "allow_nonbuddy_chat" )
		{
			/*!
			 * 허용된 버디와 대화
			 */
			if ( sValue == "N" || sValue == "n" )
			{
				stConfig.allowother = FALSE;
				stConfig.allowonlypermitchat = TRUE;
			}
			else
			{
				stConfig.allowother = TRUE;
				stConfig.allowonlypermitchat = FALSE;
			}
			config->writeEntry( "Allow_Other", stConfig.allowother );
			config->writeEntry( "Allow_Only_Permit_Chat", stConfig.allowonlypermitchat );
		}
	}
}

void KNateon::slotUpdateAwayInfo()
{
	m_pCurrentAccount->setUseIdleTimer( stConfig.checkawaytime );
	m_pCurrentAccount->setIdleTime( stConfig.awaytime );
}

void KNateon::slotDeleteFriend(DeleteForm * pDeleteForm)
{
	/*!
     * Group의 BuddyList에서 삭제된 버디 handle을 삭제한다.
     * 이후 복사/이동에서 목록에 있어서 Skip 되는것을 방지한다.
     */
	Group *pGroup = m_pCurrentAccount->getGroupList()->getGroupByID( pDeleteForm->getGID() );
	if ( pGroup )
		pGroup->removeBuddy( m_pCurrentAccount->getBuddyList()->getBuddyByID( pDeleteForm->getUID() ) );

	QString sBody;
	sBody = "0";
	sBody += " ";
	sBody += pDeleteForm->getHandle();
	sBody += " ";
	sBody += pDeleteForm->getUID();
	sBody += " ";
	sBody += pDeleteForm->getGID();
	sBody += "\r\n";

	QString sCommand;
	sCommand = QString::number( m_pDPcon->getGroupCache() );
	sCommand += " ";
	sCommand += QString::number( sBody.length() );
	sCommand += "\r\n";
	sCommand += sBody;
	
	m_pDPcon->sendCommand( "RMBG", sCommand );

	if ( !m_pCurrentAccount->getGroupList()->isContain( m_pCurrentAccount->getBuddyList()->getBuddyByID( pDeleteForm->getUID() ) ) )
	{
		Buddy *pBuddy = m_pCurrentAccount->getBuddyList()->getBuddyByID( pDeleteForm->getUID() );
		if ( pBuddy )
		{
			QString sCommand;
			sCommand += "FL";
			sCommand += " ";
			sCommand += pDeleteForm->getHandle();
			sCommand += " ";
			sCommand += pDeleteForm->getUID();
			sCommand += " ";
			sCommand += "0";
			sCommand += "\r\n";
			m_pDPcon->sendCommand( "RMVB", sCommand );
			pBuddy->setFL( FALSE );
		}
	}
	
	if ( pDeleteForm->isLocked() )
	{
		Buddy *pBuddy = m_pCurrentAccount->getBuddyList()->getBuddyByID( pDeleteForm->getUID() );
		if ( pBuddy )
		{
			QString sCommand;
			sCommand += "BL";
			sCommand += " ";
			sCommand += pDeleteForm->getHandle();
			sCommand += " ";
			sCommand += pDeleteForm->getUID();
			sCommand += "\r\n";
			m_pDPcon->sendCommand( "ADDB", sCommand );
			pBuddy->setBL( TRUE );
		}
	}
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateon::slotDeleteMemo(const QString & sUUID)
{
	if ( sUUID == QString::null )
	{
		KMessageBox::information( this, UTF8("메모의 Key 값이 없어서 삭제를 못합니다. 개발자에게 문의 바랍니다."), UTF8("알림") );
		return;
	}
	
	pSQLiteDB->deleteMemoInbox( sUUID );
	m_pMainView->slotUpdateMemoCount( pSQLiteDB->getNewMemoCount() );
}

/*!
 * C1, C2 주계정 정보 가져 오기.
 */

void KNateon::slotMajorHompy(const QString& sResult)
{
	/*!
	 * TODO: MajorHompy
	 * nateon: C1C2 Result : [ERROR<BR>12737092:a0552737:2<BR>]
	 * nateon: [ERROR]
	 * nateon: [12737092:a0552737:2]
	 * 결과가 이상한것 같음 확인 필요.
	 */

#ifdef NETDEBUG
	kdDebug() << "C1C2 Result : [" << sResult << "]" << endl;
#endif
	QStringList slC2 = QStringList::split( "<BR>", sResult );

#ifdef NETDEBUG
	for ( QStringList::Iterator it = slC2.begin(); it != slC2.end(); ++it )
	{
		kdDebug() << "[" << *it << "]" << endl;
	}
#endif

	if ( slC2[0] != "ERROR" )
	{
#ifdef NETDEBUG
		kdDebug() << "현재 사용자의 Cyworld 연동 정보 : " << slC2[0] << endl;
#endif
		QStringList slInfo = QStringList::split( ":", slC2[0] );
		if ( slInfo[2] == "2" )
		{
			m_pCurrentAccount->setHompyType( CurrentAccount::Home2 );
			m_pCurrentAccount->setMyHome2CMN( slInfo[1] );
		}
		else
		{
			m_pCurrentAccount->setHompyType( CurrentAccount::Cyworld );
		}
		m_pCurrentAccount->setMyMajorCMN( slInfo[1] );
	}
#ifdef NETDEBUG
	else
	{
		kdDebug() << "현재 사용자는 Cyworld 연동을 하지 않고 있습니다." << endl;
	}
#endif

	int i=0;
	for ( QStringList::Iterator it = slC2.begin(); it != slC2.end(); ++it )
	{
		if ( i == 0 )
		{
			i++;
			continue;
		}

		QStringList slInfo = QStringList::split( ":", *it );
		m_pBuddyList = m_pCurrentAccount->getBuddyList();
		Buddy* pBuddy = m_pBuddyList->getBuddyByCyworldCMN( slInfo[0] );
		if ( pBuddy )
		{
			if ( slInfo[2] == "2" )
			{
				pBuddy->setHompyType( Buddy::Home2 );
				pBuddy->setHome2CMN( slInfo[1] );
			}
			else
			{
				pBuddy->setHompyType( Buddy::Cyworld );
			}
			pBuddy->setMajorCMN( slInfo[1] );
		}
	}
	
	if ( ( ( stConfig.logintype == 'N' ) && stConfig.usecyworld ) || ( stConfig.logintype == 'C' ) )
	{
		/*! 새글 정보 가져 오기 */
		if ( !pHompyNewCGI )
		{
			pHompyNewCGI = new PostCGI();
			connect(pHompyNewCGI, SIGNAL( gotResult( const QString& ) ), SLOT( slotHompyNew( const QString& ) ) );
		}
		
		QString sURL("http://www.cyworld.com/pims/nateon/nateon_new_article_c2_ticket.asp");
		QString sParam("param=");
		sParam += m_pCurrentAccount->getMyCyworldCMN();
		sParam += "%3a";
		sParam += m_pCurrentAccount->getMyMajorCMN();
		sParam += "%3a";
		if ( m_pCurrentAccount->getHompyType() == CurrentAccount::Home2 )
			sParam += "2";
		else
			sParam += "1";
		sParam += "&ticket=";
		sParam += m_pCurrentAccount->getMyTicket();
		sParam += "&buddy_list=";
		BuddyList* p_BuddyList = m_pCurrentAccount->getBuddyList();
		QPtrListIterator<Buddy> iterator( *p_BuddyList );
		QString sCMN;
		QString sCMNList;
		while(iterator.current() != 0)
		{
			Buddy *pBuddy = iterator.current();
			sCMN = pBuddy->getCyworld_CMN();
			if ( sCMN.length() > 0 )
			{
                /*!
                 * 본인의 싸이아이디가 버디리스트에 등록이 되있는 경우
                 * CyCMN이 2개 나옴.
                 */
				if ( sCMN.data()[0] != '%' )
				{
					if ( sCMNList.length() > 0 )
					{
						sCMNList += "%3b";
					}
					sCMNList += sCMN;
					sCMNList += "%3a";
					sCMNList += pBuddy->getMajorCMN();
					sCMNList += "%3a";
					if ( pBuddy->getHompyType() == Buddy::Home2 )
						sCMNList += "2";
					else
						sCMNList += "1";
				}
			}
			++iterator;
		}
		sParam += sCMNList;
#ifdef NETDEBUG
		kdDebug() << "Post Param : [" << sParam << "]" << endl;
#endif
		pHompyNewCGI->start( sURL, sParam );
	}
}

void KNateon::slotC1C2()
{
	if ( !pMajorHompyCGI )
	{
		pMajorHompyCGI = new PostCGI();
		connect(pMajorHompyCGI, SIGNAL( gotResult( const QString& ) ), SLOT( slotMajorHompy( const QString& ) ) );
	}
	QString sURL("http://www.cyworld.com/pims/nateon/nateon_get_mainid_ticket.asp");
	QString sParam;
	sParam = "param=";
	QString sMyCMN( m_pCurrentAccount->getMyCMN() );

	if ( sMyCMN.length() > 0)
	{
		if ( sMyCMN.data()[0] != '%' )
		{
			sParam += sMyCMN;
		}
		else
		{
			sParam += "";
		}
	}
	else
	{
		sParam += "";
	}

	sParam += "&ticket=";
	sParam += m_pCurrentAccount->getMyTicket();
	sParam += "&buddy_list=";
	BuddyList* pBuddyList = m_pCurrentAccount->getBuddyList();
	QPtrListIterator<Buddy> iterator( *pBuddyList );
	QString sCMN;
	QString sCMNList;
	while(iterator.current() != 0)
	{
		Buddy *pBuddy = iterator.current();
		sCMN = pBuddy->getCyworld_CMN();
		if ( sCMN.length() > 0 )
		{
            /*!
             * 본인의 싸이아이디가 버디리스트에 등록이 되있는 경우
             * CyCMN이 2개 나옴.
             */
			if ( sCMN.data()[0] != '%' )
			{
				if ( sCMNList.length() > 0 )
				{
					sCMNList += "%3b";
					sCMNList += sCMN;
				}
				else
				{
					sCMNList = sCMN;
				}
			}
		}
		++iterator;
	}
	sParam += sCMNList;
#ifdef NETDEBUG
	kdDebug() << "POST, URL :[" << sURL << "], Param : [" << sParam << "]" << endl;
#endif
	pMajorHompyCGI->start( sURL, sParam );
}

void KNateon::slotHompyNew( const QString &sResult )
{
#ifdef NETDEBUG
	kdDebug() << sResult << endl;
#endif
	QStringList slNew = QStringList::split( "<BR>", sResult );

	QStringList slMyInfo = QStringList::split( ":", slNew[0] );

	if ( slMyInfo[2] == "1" )
		m_pCurrentAccount->setMyHompyNew( TRUE );
	
	int i=0;
	for( QStringList::Iterator it = slNew.begin(); it != slNew.end(); ++it )
	{
		if ( i == 0 )
		{
			i++;
			continue;
		}

		QStringList slInfo = QStringList::split( ":", *it );
		if ( slInfo[2] == "1" )
		{
#ifdef NETDEBUG
			kdDebug() << *it << endl;
#endif
			m_pBuddyList = m_pCurrentAccount->getBuddyList();
			Buddy* pBuddy = m_pBuddyList->getBuddyByCyworldCMN( slInfo[0] );
			
			pBuddy->setHompyNew( TRUE );
		}
	}

	/*!
	 * 버디리스트 / 내홈피 새글 표시
	 */
	m_pMainView->slotHompyNew();
}

void KNateon::slotCALM(const QStringList & slCommand)
{
	m_pBuddyList = m_pCurrentAccount->getBuddyList();
	

	if ( slCommand[2] == "CYHP" ) /*! 버디의 C1 방명록에 새글이 등록되었음. */
	{
		/*!
		 * ID의 버디 홈피 New
		 */
		Buddy* pBuddy = m_pBuddyList->getBuddyByHompyMajorCMN( slCommand[3] );
		if ( pBuddy )
			pBuddy->setHompyNew( TRUE );
	}
	else if ( slCommand[2] == "C2HP" ) /*! Home2 방명록에 새글이 등록 되었음. */
	{
		/*!
		 * ID의 버디 홈피 New
		 */
		Buddy* pBuddy = m_pBuddyList->getBuddyByHompyMajorCMN( slCommand[3] );
		if ( pBuddy )
			pBuddy->setHompyNew( TRUE );
	}
	else if ( slCommand[2] == "C2ID" ) /*! 주사용계정 변경. */
	{
		/*!
		 * ID의 버디 주사용 CMN 변경.
		 */
		Buddy* pBuddy = m_pBuddyList->getBuddyByHompyMajorCMN( slCommand[3] );
		if ( pBuddy )
		{
			if ( slCommand.count() >= 8)
				pBuddy->setMajorCMN( slCommand[7] );
		}
	}
	
	/*! 버디리스트 갱신 */
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateon::slotHompyRUrl(const QString & sURL)
{
#ifdef NETDEBUG
	kdDebug() << "Click [" << sURL << "]" << endl;
#endif
	LNMUtils::openURL( sURL );
}

void KNateon::slotErr306()
{
	bLogout = FALSE;
	if ( m_pLoginView )
		m_pLoginView->kPasswordEdit1->setFocus();
		
	KMessageBox::information( this, UTF8("접속이 원활하지 못합니다. 접속을 다시 시도 바랍니다."), UTF8("접속 에러") );
}

void KNateon::slotPingError()
{
	if ( m_pMainView )
		m_pMainView->hide();
	if ( m_pLoginView )
		m_pLoginView->hide();
	if ( m_pLogoutView )
	{
		setCentralWidget( m_pLogoutView );
		m_pLogoutView->show();
	}
	
	if ( bConnect )
	{
		if ( !m_pRetryConnectTimer )
		{
			m_pRetryConnectTimer = new QTimer( this );
			connect( m_pRetryConnectTimer, SIGNAL( timeout() ), SLOT( slotRetryConnect() ) );
		}
		m_pRetryConnectTimer->start( 3000, TRUE );
	}
}

void KNateon::slotRetryConnect()
{
#ifdef NETDEBUG
	kdDebug() << "Retry Connectting..." << endl;
#endif
	if ( bOnline )
	{
		m_pRetryConnectTimer->stop();
	}
	else
	{
		m_pLoginView->connectToDPLserver();
		m_pRetryConnectTimer->start( 3000, TRUE );
	}
}

void KNateon::slotChangeStatusNumber(int nID)
{
	/*!
	 * Away Timer는
	 * 환경설정에서 Away Timer 사용이 체크되있고,
	 * 온라인 일때만 사용.
	 */
	if ( ( stConfig.checkawaytime ) && ( nID == 0 ) )
	{
		bIdle = FALSE;
#ifdef NETDEBUG
		kdDebug() << "Idle Timer On!" << endl;
#endif
	}
	else
	{
		bIdle = TRUE;
#ifdef NETDEBUG
		kdDebug() << "Idle Timer Off!" << endl;
#endif
	}
	
	emit changeStatus( nID ); /*! 채팅에 상태값 업데이트 */
	if ( pChangestatusSelectAction->currentItem () != nID )
		pChangestatusSelectAction->setCurrentItem( nID ); /*! 메인메뉴, 트레이 */
	m_pMainView->changeStatusUI( nID ); /*! 메인창 BI 업데이트 */
	switch( nID )
	{
	case 0 :
		m_pDPcon->slotChangeStatusOnline();
		m_pCurrentAccount->setStatus('O');
		break;
	case 1 :
		m_pDPcon->slotChangeStatusAway();
		m_pCurrentAccount->setStatus('A');
		break;
	case 2 :
		m_pDPcon->slotChangeStatusBusy();
		m_pCurrentAccount->setStatus('B');
		break;
	case 3 :
		m_pDPcon->slotChangeStatusPhone();
		m_pCurrentAccount->setStatus('P');
		break;
	case 4:
		m_pDPcon->slotChangeStatusMeeting();
		m_pCurrentAccount->setStatus('M');
		break;
	case 5:
		m_pDPcon->slotChangeStatusOffline();
		m_pCurrentAccount->setStatus('F');
		break;
	}
}

void KNateon::slotAddEtc(const QString & sID)
{
	QString sCommand;
	sCommand = "FL";
	sCommand += " ";
	sCommand += "%00";
	sCommand += " ";
	sCommand += sID;
	sCommand += " ";
	sCommand += "0";
	sCommand += "\r\n";
	m_pDPcon->sendCommand( "ADDB", sCommand );
	
	/*!
	 * 목록 refresh
	 */
	m_pMainView->slotEmoticonList( stConfig.viewemoticonlist );	
}

void KNateon::slotAddBuddyADSB_REQST(const QStringList & slCommand)
{
	Buddy* pBuddy = m_pCurrentAccount->getBuddyList()->getBuddyByHandle( "TID:" + slCommand[1] );
	if ( pBuddy )
	{
		// Buddy *pBuddy = new Buddy();
		
		pBuddy->setHandle( slCommand[3] );
		pBuddy->setName( slCommand[4] );
	}
}

/*!
 * 상대방이 전송중 전송 취소를 했을경우
 */
void KNateon::slotCancelReceiveAll(const QStringList & slCommand)
{
	if ( m_pFileTransfer )
	{
		QStringList slData = QStringList::split(QString("%09"), slCommand[4]);
		m_pFileTransfer->cancelTransfer( slData[2] );
	}
}

void KNateon::slotTransferCancel(const QString & sSSCookie)
{
	if ( m_pP2PServer )
	{
		SendFileInfo *pSendFileInfo = m_pP2PServer->getSendFileInfoBySSCookie( sSSCookie );
		if ( pSendFileInfo )
		{
			pSendFileInfo->setCanceled( TRUE );
 			pSendFileInfo->getChatView()->myCancel();
            pSendFileInfo->getChatView()->sendFILE_CANCEL( sSSCookie );
		}
	}
	bCancelFileTransfer = TRUE;
}

void KNateon::slotMyTransferCancel(const QString & sSSCookie)
{
if ( m_pP2PServer )
{
 		SendFileInfo *pSendFileInfo = m_pP2PServer->getSendFileInfoBySSCookie( sSSCookie );
 		if ( pSendFileInfo )
 		{
 			pSendFileInfo->setCanceled( TRUE );
 			pSendFileInfo->getChatView()->myCancel();
            pSendFileInfo->getChatView()->sendFILE_CANCEL( sSSCookie );
 		}
 	}
	bCancelFileTransfer = TRUE;
}

void KNateon::slotCloseMemoPopup(MemoPopupView * pMemoPopup)
{
	if ( pMemoPopup )
		delete pMemoPopup;
}

void KNateon::slotCloseMemoView(MemoView * pMemoView)
{
	if ( pMemoView )
		delete pMemoView;
}

void KNateon::slotOpenTransfer()
{
	if ( ! m_pFileTransfer )
	{
		m_pFileTransfer = new FileTransfer();
		connect( m_pFileTransfer, SIGNAL( cancelFileTransfer( const QString & )), SLOT( slotMyTransferCancel( const QString & ) ) );
	}
	m_pFileTransfer->show();
}

void KNateon::slotGoNateDotCom()
{
	QString sURL("http://br.nate.com/index.php");
	sURL += "?code=G035";
	LNMUtils::openURL( sURL );
}

void KNateon::slotNetLog()
{
	if ( m_pNetworkWindow )
		m_pNetworkWindow->show();
}

void KNateon::setDefaultWebBrowser()
{
	if ( !m_pPreferenceView )
		return;
	
	config->setGroup("WebBrowser");
	stConfig.defaultwebbrowser = config->readEntry("UserDefault", UTF8("설정안됨") );
	QString sTemp = ( stConfig.defaultwebbrowser ).stripWhiteSpace();
	if ( sTemp == UTF8("설정안됨") || sTemp.isEmpty() ){
        /*! firefox 우선 찾기 */
        if ( QFile::exists("/usr/bin/firefox") ) {
            stConfig.defaultwebbrowser = "/usr/bin/firefox -new-window";
        } else if ( QFile::exists("/bin/firefox") ) {
            stConfig.defaultwebbrowser = "/bin/firefox -new-window";
        } else if ( QFile::exists("/usr/local/bin/firefox") ) {
            stConfig.defaultwebbrowser = "/usr/local/bin/firefox -new-window";
        } else {
            /*! xdg-open 찾기, MIME으로 처리. */
            if ( QFile::exists( "/bin/xdg-open" ) ) {
                stConfig.defaultwebbrowser = "/bin/xdg-open";
            } else if ( QFile::exists( "/usr/bin/xdg-open" ) ) {
                stConfig.defaultwebbrowser = "/usr/bin/xdg-open";
            } else if ( QFile::exists( "/usr/local/bin/xdg-open" ) ) {
                stConfig.defaultwebbrowser = "/usr/local/bin/xdg-open";
            } else {
                /*! 사용자 기본 브라우저를 사용하지 않음 */
                stConfig.usedefaultwebbrowser = config->readBoolEntry( "UseUserDefault", FALSE );
                m_pPreferenceView->setDefaultWebBrowser( stConfig.defaultwebbrowser );
                m_pPreferenceView->setUseDefaultWebBrowser( stConfig.usedefaultwebbrowser );
                config->setGroup( "WebBrowser" );
                config->writeEntry( "UseUserDefault", stConfig.usedefaultwebbrowser );
                config->writeEntry( "UserDefault", stConfig.defaultwebbrowser );
                config->sync();
                return;
            }
            /*! 찾은 xdg-open로 웹 브라우저 호출 한다. */
            stConfig.usedefaultwebbrowser = TRUE;
            m_pPreferenceView->setDefaultWebBrowser( stConfig.defaultwebbrowser );
            m_pPreferenceView->setUseDefaultWebBrowser( stConfig.usedefaultwebbrowser );
            config->setGroup( "WebBrowser" );
            config->writeEntry( "UseUserDefault", stConfig.usedefaultwebbrowser );
            config->writeEntry( "UserDefault", stConfig.defaultwebbrowser );
            config->sync();
            return;
        }
        /*! 찾은 firefox를 기본 브라우져로 설정 */
        stConfig.usedefaultwebbrowser = TRUE;
        config->setGroup( "WebBrowser" );
        config->writeEntry( "UseUserDefault", stConfig.usedefaultwebbrowser );
        config->writeEntry( "UserDefault", stConfig.defaultwebbrowser );
        config->sync();
    } else {
        stConfig.usedefaultwebbrowser = config->readBoolEntry( "UseUserDefault", TRUE );
    }
	m_pPreferenceView->setDefaultWebBrowser( stConfig.defaultwebbrowser );
	m_pPreferenceView->setUseDefaultWebBrowser( stConfig.usedefaultwebbrowser );
	return;
}

void KNateon::slotChangeWebBrowser(const QString & sBrowser)
{
    /*! 통합메시지함 웹브라우저 설정 */
	DCOPClient *client=kapp->dcopClient();
	QByteArray params2;
	QDataStream stream2(params2, IO_WriteOnly);
	stream2 << UTF8( sBrowser );
	if (!client->send("MessageBox-*", "messageviewer", "setDefaultBrowser(QString)", params2))
		kdDebug() << "Error with DCOP\n" << endl;
}

/*! PRS 경유 서버 접속 에러 */
void KNateon::slotDPLError421()
{
	// Notify the user.
	QString sErrorMessage("The connection to the server failed.\r\n");
	sErrorMessage += UTF8("You may not be connected to the internet.");
	KMessageBox::error( 0, sErrorMessage );
	stConfig.autologin = false;
	m_pLoginView->setCancel( FALSE ); // m_pLoginView->setEnable( TRUE );
	
    /*! 자동로그인에서 소켓접속 에러가 나면, 자동로그인 해제 시킴 */
	if ( stConfig.autologin == true )
	{
#ifdef NETDEBUG
		kdDebug() << "XXXXXXXXXXXXX TTTTTTTTTTTTT SSSSSSSSSSSSSSSS " << endl;
#endif
		config->setGroup( "Login" );
		config->writeEntry( "AutoLogin", false );
		config->sync();
		m_pLoginView->setAutoLogin( false );
	}
}

/*!
  파일 보내기.
  CTOC 0 user01@nate.com 41 REQC NEW 192.168.0.1:5004 10008348086:1105
*/
void KNateon::slotGotREQCNEW(const QStringList &slCommand )
{
//     if ( isP2PActivedP2PCookie( slCommand[7] ) )
//         return;

    QStringList slServerInformation = QStringList::split( ":", slCommand[6] );
    kdDebug() << "Connecting - IP:" << slServerInformation[0] << ", Port:" << slServerInformation[1] << endl;

    NOMP2PBase *pBase = m_pP2PList->add( new NOMP2PBase( this, "p2pbase" ) );
    connect( pBase, SIGNAL( IncomingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( OutgoingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage( const QString & ) ) );
    pBase->setType( NOMP2PBase::SEND );
    pBase->setConnectType( NOMP2PBase::CLIENT ); /*! 내가 client로 상대 서버에 접속했음. */
    pBase->setP2PCookie( slCommand[7] ); /*! Server이면 ATHC로 상대가 P2PCookie를 보내나, Client일때는 직접 Setting 해야 함. */
    pBase->connectToServer( slServerInformation[0], slServerInformation[1].toInt() );
    
    QString sCommand;
    sCommand = "ATHC";
    sCommand += "|";
    sCommand += m_pCurrentAccount->getMyID();
    sCommand += " ";
    sCommand += slCommand[2];
    sCommand += " ";
    sCommand += slCommand[7];
    sCommand += " ";
    sCommand += QString::number( 6004 );
    sCommand += " ";
    sCommand += "0";
    sCommand += "\r\n";
    
    pBase->addQueue( sCommand );

    /*! 파일 전송창 */
    connect( pBase, SIGNAL( updateProgress( const QString &, const unsigned long) ) , m_pFileTransfer, SLOT( updateProgressByByte( const QString&, const unsigned long ) ) );
    connect( pBase, SIGNAL( endProgress( const QString & ) ), m_pFileTransfer, SLOT( endProgressByByte( const QString & ) ) );
}

/*!
  파일 받기.
  CTOC 0 user01@nate.com 41 REQC RES 192.168.0.1:5004 10008348086:1105
*/
void KNateon::slotGotREQCRES(const QStringList &slCommand )
{
//     if ( isP2PActivedP2PCookie( slCommand[7] ) )
//         return;

    QStringList slServerInformation = QStringList::split( ":", slCommand[6] );
    kdDebug() << "Connecting - IP:" << slServerInformation[0] << ", Port:" << slServerInformation[1] << endl;

    NOMP2PBase *pBase = m_pP2PList->add( new NOMP2PBase( this, "p2pbase" ) );
    connect( pBase, SIGNAL( IncomingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( OutgoingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( tryREFR( const QString & ) ), SLOT( slotTryREFR( const QString & ) ) );
    
	/*! 파일 전송창 */
	connect( pBase, SIGNAL( updateProgress( const QString &, const unsigned long) ) , m_pFileTransfer, SLOT( updateProgressByByte( const QString&, const unsigned long ) ) );
	connect( pBase, SIGNAL( endProgress( const QString & ) ), m_pFileTransfer, SLOT( endProgressByByte( const QString & ) ) );
	
    pBase->setType( NOMP2PBase::RECEIVE );
    pBase->setConnectType( NOMP2PBase::CLIENT ); /*! 내가 client로 상대 서버에 접속했음. */
    pBase->setP2PCookie( slCommand[7] ); /*! Server이면 ATHC로 상대가 P2PCookie를 보내나, Client일때는 직접 Setting 해야 함. */
    pBase->connectToServer( slServerInformation[0], slServerInformation[1].toInt() );
    
    QString sCommand;
    sCommand = "ATHC";
    sCommand += "|";
    sCommand += m_pCurrentAccount->getMyID();
    sCommand += " ";
    sCommand += slCommand[2];
    sCommand += " ";
    sCommand += slCommand[7];
    sCommand += " ";
    sCommand += QString::number( 6004 );
    sCommand += " ";
    sCommand += "0";
    sCommand += "\r\n";
    
    pBase->addQueue( sCommand );
}


void KNateon::slotP2PNewSocket( QSocket *pSocket )
{
    NOMP2PBase *pBase = m_pP2PList->add( new NOMP2PBase( this, "p2pbase" ) );
    pBase->setSocket( pSocket );
    connect( pBase, SIGNAL( IncomingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( OutgoingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage( const QString & ) ) );
    /*! 파일 전송창 */
    connect( pBase, SIGNAL( updateProgress( const QString &, const unsigned long) ) , m_pFileTransfer, SLOT( updateProgressByByte( const QString&, const unsigned long ) ) );
    connect( pBase, SIGNAL( endProgress( const QString & ) ), m_pFileTransfer, SLOT( endProgressByByte( const QString & ) ) );
}

void KNateon::slotTryREFR( const QString & sP2PCookie )
{
    if ( isP2PActivedP2PCookie( sP2PCookie ) )
        return;
    
    QString sQuery;
    sQuery = "SELECT Source_ID FROM tb_p2p WHERE P2P_Cookie='";
    sQuery += sP2PCookie;
    sQuery += "';";
    
    rowList myList;
    myList = pSQLiteDB->getRecords( stConfig.p2pdbfilepath, sQuery );
    if ( myList.size() > 0 ) {
        QString sCommand;
        sCommand = myList.first()[0];
        sCommand += "\r\n";
        /*! REFR 743 [Source ID]\r\n */
        int nTID = m_pDPcon->sendCommand( "REFR", sCommand );
        kdDebug() << sCommand << endl;
        
        
        // QStringList slInfomation;
        QStringList* slInfomation = new QStringList;
        slInfomation->clear();
        slInfomation->append( myList.first()[0] ); /// [0] : Source ID
        slInfomation->append( sP2PCookie ); /// [1] : P2P Cookie
        
        kdDebug() << "SourceID : " << myList.first()[0] << ", P2P Cookie : " << sP2PCookie << endl;
        
        m_SaveTID.insert( nTID, slInfomation );
    }
}

/*! REFR 743 211.234.239.175 5004 406378858\r\n */
void KNateon::slotGotREFR( const QStringList &slCommand )
{
    QStringList *slSaveTID = m_SaveTID.find( slCommand[1].toLong() );
    if ( !slSaveTID ) return;
    
    QStringList::Iterator it = slSaveTID->begin();
    QString sSourceID = *it;
    ++it;
    QString sP2PCookie = *it;

    if ( isP2PActivedP2PCookie( sP2PCookie ) )
        return;

    NOMP2PBase *pBase = m_pP2PList->add( new NOMP2PBase( this, "p2pbase" ) );
    connect( pBase, SIGNAL( IncomingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( OutgoingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( sendREQCFR( const QString & ) ), SLOT( slotSendREQCFR( const QString & ) ) );
    
    pBase->setType( NOMP2PBase::RECEIVE );
    pBase->setConnectType( NOMP2PBase::CLIENT ); /*! 내가 client로 상대 서버에 접속했음. */
    pBase->setP2PCookie( sP2PCookie ); /*! Server이면 ATHC로 상대가 P2PCookie를 보내나, Client일때는 직접 Setting 해야 함. */
    pBase->setFRCookie( slCommand[4] );
    pBase->setFRIP( slCommand[2] );
    pBase->setFRPort( slCommand[3] );
    pBase->setYourID( sSourceID );

    /* FRIN */
    pBase->connectToFRServer( slCommand[2], slCommand[3].toInt() );
    
    /*! 파일 전송창 */
    connect( pBase, SIGNAL( updateProgress( const QString &, const unsigned long) ) , m_pFileTransfer, SLOT( updateProgressByByte( const QString&, const unsigned long ) ) );
    connect( pBase, SIGNAL( endProgress( const QString & ) ), m_pFileTransfer, SLOT( endProgressByByte( const QString & ) ) );
}

/*!
  CTOC 0 ring0320@nate.com 57 REQC FR 211.234.239.175:5004 10014827278:6301 406378858
*/
void KNateon::slotGotFR( const QStringList &slCommand )
{
    if ( isP2PActivedP2PCookie( slCommand[7] ) )
        return;

    QStringList slServerInformation = QStringList::split( ":", slCommand[6] );
    kdDebug() << "Connecting - IP:" << slServerInformation[0] << ", Port:" << slServerInformation[1] << endl;

    NOMP2PBase *pBase = m_pP2PList->add( new NOMP2PBase( this, "p2pbase" ) );
    connect( pBase, SIGNAL( IncomingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addIncomingServerMessage( const QString & ) ) );
    connect( pBase, SIGNAL( OutgoingMessage( const QString & ) ), m_pNetworkWindow, SLOT( addOutgoingServerMessage( const QString & ) ) );
    
    pBase->setType( NOMP2PBase::SEND );
    pBase->setConnectType( NOMP2PBase::CLIENT ); /*! 내가 client로 상대 서버에 접속했음. */
    pBase->setP2PCookie( slCommand[7] ); /*! Server이면 ATHC로 상대가 P2PCookie를 보내나, Client일때는 직접 Setting 해야 함. */
    pBase->setFRCookie( slCommand[8] );
    pBase->setYourID( slCommand[2] );
    pBase->setMyID( m_pCurrentAccount->getMyID() );

    /*! "ATHC|[My ID] [Your ID] [P2P Cookie] 6004 0\r\n" */
    QString sCommand;
    sCommand = "ATHC";
    sCommand += "|";
    sCommand += m_pCurrentAccount->getMyID();
    sCommand += " ";
    sCommand += slCommand[2];
    sCommand += " ";
    sCommand += slCommand[7];
    sCommand += " ";
    sCommand += slCommand[8];
    sCommand += " ";
    sCommand += QString::number( 6004 );
    sCommand += " ";
    sCommand += "0";
    sCommand += "\r\n";
    
    pBase->addQueue( sCommand );

    /* FRIN */
    pBase->connectToFRServer( slServerInformation[0], slServerInformation[1].toInt() );
    
    /*! 파일 전송창 */
    connect( pBase, SIGNAL( updateProgress( const QString &, const unsigned long ) ), m_pFileTransfer, SLOT( updateProgressByByte( const QString &, const unsigned long ) ) );
    connect( pBase, SIGNAL( endProgress( const QString & ) ), m_pFileTransfer, SLOT( endProgressByByte( const QString & ) ) );
}



void KNateon::slotSendREQCFR( const QString & sCommand )
{
    m_pDPcon->sendCommand( "CTOC", sCommand );
#ifdef NETDEBUG
    kdDebug() << sCommand << endl;
#endif
}


bool KNateon::isP2PActivedFileCookie( const QString & sFileCookie )
{
    QString sQuery;
    sQuery = "SELECT P2P_Status FROM tb_p2p WHERE File_Cookie='";
    sQuery += sFileCookie;
    sQuery += "';";
    rowList myList;
    myList = pSQLiteDB->getRecords( stConfig.p2pdbfilepath, sQuery );

    if ( myList.size() > 0 ) {
        if ( myList.first()[0] == "S" )
            return false;
        else
            return true;
    }
    return false;
}

bool KNateon::isP2PActivedP2PCookie( const QString & sP2PCookie )
{
    QString sQuery;
    sQuery = "SELECT P2P_Status FROM tb_p2p WHERE P2P_Cookie='";
    sQuery += sP2PCookie;
    sQuery += "';";
    rowList myList;
    myList = pSQLiteDB->getRecords( stConfig.p2pdbfilepath, sQuery );

    if ( myList.size() > 0 ) {
        if ( myList.first()[0] == "S" )
            return false;
        else
            return true;
    }
    return false;
}

void KNateon::slotErr998(const QStringList &slCommand )
{
	LNMUtils::openBridgeURL( slCommand[2], QString::null, slCommand[3] );
}

