/***************************************************************************
 *   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 "knateoncommon.h"
#include "knateonmainview.h"
#include "util/urlencode.h"

extern nmconfig stConfig;

// QPixmap *folderLocked = 0;
QPixmap *folderClosed = 0;
QPixmap *folderOpen = 0;
// QPixmap *fileNormal = 0;

class MyBuddyList : public QPtrList<Buddy>
{
public:
	MyBuddyList( const QPtrList<Buddy>& );
	virtual int compareItems(Item a, Item b)
		{
			// return (((Buddy *)a)->getName()).compare( ((Buddy *)b)->getName() );
			return (((Buddy *)b)->getName()).compare( ((Buddy *)a)->getName() );
		}
};

MyBuddyList::MyBuddyList( const QPtrList<Buddy>& ptrBuddy)
	: QPtrList<Buddy>(ptrBuddy)
{
}


KNateonMainview::KNateonMainview(QWidget* parent, const char* name, WFlags fl)
	: knateonmainviewinterface(parent,name,fl),
	  myEmoticon(0),
pWebViewer(0),
nSelectBuddy(0),
nSelectGroup(0)
{
	KStandardDirs   *dirs   = KGlobal::dirs();
	sPicsPath = dirs->findResource( "data", QString( KGlobal::instance()->aboutData()->appName() ) + "/pics/" );
	// folderLocked = new QPixmap( sPicsPath + "" /* folder_locked */ );
	folderClosed = new QPixmap( sPicsPath + "main_list_folder_close.png" /* folder_closed_xpm */ );
	folderOpen = new QPixmap( sPicsPath + "main_list_folder_open.png" /* folder_open_xpm */ );
	// fileNormal = new QPixmap( sPicsPath + "" /* pix_file */ );

	// setMinimumSize( QSize( 200, 400 ) );
	
	/// 아이콘 등록.
	initIcons();

	// PBbi->setShape( *mOnlineQI );
	PBbi->setShape( sPicsPath + "bi.bmp" );
	connect( lineEdit1, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotListSearch( const QString & ) ) );

	config = kapp->config();
	/*! 기본 설정 */
	config->setGroup( "Config_General" );
	/*! 친구 목록에 이모티콘 사용 */
	stConfig.viewemoticonlist = config->readBoolEntry( "Use_Emoticon_BuddyList", true );

	/*! 버디 리스트 설정 */
	config->setGroup( "BuddyList" );
	stConfig.typeofbuddylist = config->readNumEntry( "Type_Of_BuddyList", 3);
	stConfig.typeofbuddysort = config->readNumEntry( "Type_Of_BuddySort", 0);
	connect( listView3, SIGNAL( clicked ( QListViewItem * ) ), SLOT( slotBuddyListClicked( QListViewItem * ) ) );
	connect( listView3, SIGNAL(clickedHompy(QListViewItem*)), this,
		SLOT(slotGotoMinihompy(QListViewItem*)) );

	/*!
	 * added by luciferX2@gmail.com, 20081103 for Search
	 */
	//bSearchMode = FALSE;
}


KNateonMainview::~KNateonMainview()
{
	// if ( m_pCurrentAccount ) delete m_pCurrentAccount;
	// if ( myEmoticon ) delete myEmoticon;
	if ( pWebViewer ) delete pWebViewer;
}


/*!
  \fn KNateonMainview::initialize()
*/
bool KNateonMainview::initialize()
{
	createStatusMenu();
	createGroupRightClickMenu();
	createBuddyRightClickMenu();
	createListingMenu();

	listView3->setStaticBackground(true);
	m_pCurrentAccount = CurrentAccount::instance();

	pBuddyList = m_pCurrentAccount->getBuddyList();
	pGroupList = m_pCurrentAccount->getGroupList();

	/*!
	 * 버디리스트에서 더블클릭시
	 * 버디가 Offline이면 쪽지 보이기.
	 */
	connect( listView3, SIGNAL(doubleClicked ( QListViewItem *, const QPoint &, int )), SLOT(slotViewChat( QListViewItem *, const QPoint &, int ) ) );

  /*!
	 * 버리 리스트에서 마우스 오른쪽 클릭시
	 */
	connect( listView3, SIGNAL( contextMenuRequested(QListViewItem*,const QPoint&,int) ), SLOT( slotRightClickMenu(QListViewItem*,const QPoint&,int) ) );

	/*! 수정요망.
   /// 상태아이콘버튼을 눌렀을때 메뉴등록
   PBbi->setPopup ( pStatusClickMenu );
	*/
	connect( PBbi, SIGNAL( clicked(int) ), this,  SLOT( slotPBMenu(int) ) );
	connect( PB_SortList, SIGNAL( clicked() ), this,  SLOT( slotPBSortList() ) );
	connect( PB_Memo, SIGNAL( clicked() ), this,  SLOT( slotPBMemo() ) );


	listView3->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)2, 0, 0, listView3->sizePolicy().hasHeightForWidth() ) );
	listView3->setFullWidth( TRUE );

	// initialize buddy listview control
	listView3->clear();
	listView3->setRootIsDecorated(false);
	listView3->removeColumn(0);
	listView3->addColumn("Buddy List");
	listView3->addColumn("GName", 0);
	listView3->addColumn("Handle", 0);
	listView3->addColumn("Email", 0);
	listView3->addColumn("", 0);
	listView3->hideColumn(1);
	listView3->hideColumn(2);
	// listView3->setColumnWidthMode(3, QListView::Manual);
	listView3->hideColumn(3);
	// listView3->setColumnWidth(3,0);
	listView3->hideColumn(4);
	listView3->setSelectionMode(QListView::Extended);
	// listView3->setHScrollBarMode(QScrollView::AlwaysOff);
	listView3->setPaletteForegroundColor( QColor("#226699") );
	QFont listView3_font(  listView3->font() );
	listView3_font.setBold( TRUE );
	listView3->setFont( listView3_font );
	listView3->setStaticBackground(true);
	listView3->setPaletteBackgroundPixmap( QPixmap( sPicsPath + "buddylist_bg.bmp" ) );
  
	TL_NickName->setPaletteForegroundColor( QColor("#424242") );
	TL_NickName->setFont( listView3_font );
	TL_Status->setPaletteForegroundColor( QColor("#424242") );
	TL_Status->setFont( listView3_font );
	/*
	  setViewEmo(true);
	  setView1(0);
	  setView2(0);
	*/

	/*!
	 * added and modified by luciferX2@gmail.com 20081103, for search
	 */
	connect( m_pSearchReset, SIGNAL( clicked() ), SLOT( slotResetBuddyList() ) );
	connect( lineEdit1, SIGNAL( searchEnd() ), SLOT( slotResetBuddyList() ) );
	connect( PB_FreeSMS, SIGNAL( clicked() ), SLOT( slotFreeSMS() ) );
	
	/// 단축키 설정.
	KActionCollection *ac =  new KActionCollection ( this );
	new KAction( i18n("&GoChat"), "startchat", KShortcut( Qt::CTRL + Qt::Key_G ) , this, SLOT( slotGoChat() ), ac, "startchat" );
	new KAction( i18n("&GoMemo"), "startmemo", KShortcut( Qt::CTRL + Qt::Key_B ) , this, SLOT( slotViewMemo() ), ac, "startmemo" );
	new KAction( i18n("&GoSMS"), "startsms", KShortcut( Qt::CTRL + Qt::Key_H ) , this, SLOT( slotFreeSMS() ), ac, "startsms" );
	new KAction( i18n("&GoMail"), "startmail", KShortcut( Qt::CTRL + Qt::Key_E ) , this, SLOT( slotSendMail() ), ac, "startmail" );
	return true;
}


void KNateonMainview::slotGroupAdded(Group *pGroup)
{
#if 0
	QString sGroup( pGroup->getGName() );
	/*! %20을 공백으로 변환 */
	sGroup.replace("%20", " ");
#endif
#if 0
	ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
	pRoot->setPixmap( folderOpen );
	// emit listView3->expanded(static_cast<QListViewItem*>(pRoot));
	pRoot->setOpen(true);
#endif
  
	slotEmoticonList( stConfig.viewemoticonlist );

	Q_UNUSED( pGroup );
	return;
}


void KNateonMainview::slotBuddyAdded(Buddy *pBuddy)
{
	if ( !pBuddy ) return;

	QListViewItem* pGroup = 0;
	pGroup = listView3->findItem(pBuddy->getGID(), 1, Qt::CaseSensitive);

	if ( pGroup == 0 ) return;

	/*! Offline으로 초기화 */
	pBuddy->setStatus("F");

	/// 차단리스트 => 차단 아이콘으로 표시
	// if (pBuddy->getBuddyFlag() == "1011") return;
	/// 목록에서 삭제
	// if (pBuddy->getBuddyFlag() == "0101") return;
	/// 친구 요청 중
	// if (pBuddy->getBuddyFlag() == "0001") return;
	/*! FL(Friend List) == 0 */
	if ( /* pBuddy->getBuddyFlag()[0] == '0' */ pBuddy->isFL() == false ) { return; }
	
	slotAddBuddy(pGroup, pBuddy);

	return;
}


#include "knateonmainview.moc"

/*!
  \fn KNateonMainview::slotViewChat(QListViewItem* m_pSelectQLVI, const QPoint& m_cPointQP, int m_nID)
*/
void KNateonMainview::slotViewChat(QListViewItem* m_pSelectQLVI, const QPoint& m_cPointQP, int m_nID)
{
	// if ( pBuddy )
	if ( static_cast<ContactBase *>(m_pSelectQLVI)->getType() == ContactBase::Buddy )
	{
		Buddy *pBuddy = getContactByItem( m_pSelectQLVI );
		if ( pBuddy )
		{
			if ( pBuddy->getStatus() == "F" )
				slotViewMemo(); /// 버디가 오프라인시 쪽지 보내기.
			else
				emit startChat( pBuddy ); /// 더블 클릭으로 대화요청 시.
		}
	}
	Q_UNUSED( m_cPointQP );
	Q_UNUSED( m_nID );
}


void KNateonMainview::slotRightClickMenu(QListViewItem* item,const QPoint& point,int nID)
{
	Q_UNUSED( nID );
	
	if ( !item )
		return;

	Buddy *pBuddy;
	pBuddy = getContactByItem(item);

	/// 버디 선택해서 오른쪽 마우스 클릭이면,
	if (pBuddy != 0)
		// if ( const_cast<ContactList *>(item)->getType() == 'B' )
	{
		if ( isMultiSelected() )
		{
			pBuddyRightClickMenu->changeTitle(0, UTF8("[버디 메뉴]") );
			pBuddyRightClickMenu->popup(point);

			pBlockbuddyAction->setEnabled( FALSE );
			pViewbuddyprofileAction->setEnabled( FALSE );
			pViewminihompyAction->setEnabled( FALSE );
			pViewmessageboxAction->setEnabled( FALSE );
		}
		else
		{
			/*!
			 * 버디 이름과 이메일 주소를 오른쪽 팝업의 타이틀로 함.
			 */
			pBuddyRightClickMenu->changeTitle(0, pBuddy->getName() + " (" + pBuddy->getUID() + ")");
			pBuddyRightClickMenu->popup(point);

			pBlockbuddyAction->setEnabled( TRUE );
			pViewbuddyprofileAction->setEnabled( TRUE );
			pViewminihompyAction->setEnabled( TRUE );
			pViewmessageboxAction->setEnabled( TRUE );
      
			/*! 싸이월드를 사용하지 않으면, 미니홈피보기 disable */
			if ( ( pBuddy->getCyworld_CMN().data() )[0] == '%' )
			{
				pViewminihompyAction->setEnabled( FALSE );
			}
			else
			{
				pViewminihompyAction->setEnabled( TRUE );
			}
      
			/*! 친구 차단/친구 차단 해제 */
			/*! BL(Block List) == 1 */
			if ( /* pBuddy->getBuddyFlag()[2] == '1' */ pBuddy->isBL() == true )
			{
				pBlockbuddyAction->setText( UTF8("친구 차단 해제") );
			}
			else
			{
				pBlockbuddyAction->setText( UTF8("친구 차단") );
			}

			if ( pBuddy->getStatus() == "F" )
			{
				pChatAction->setEnabled( FALSE );
				// pSendmemoAction->setEnabled( FALSE );
				pSendfileAction->setEnabled( FALSE );
			}
			else
			{
				pChatAction->setEnabled( TRUE );
				// pSendmemoAction->setEnabled( TRUE );
				pSendfileAction->setEnabled( TRUE );
			}
		}
	}
	/// 그룹사용자 선택 후 오른쪽 클릭이면,
	else
	{
		if ( stConfig.typeofbuddysort != 2 )
		{
			pGroupRightClickMenu->changeTitle(0, item->text(0));
			pGroupRightClickMenu->popup(point);
		}
		return;
	}
	// qWarning( "KMessViewInterface::slotContextMenu(QListViewItem*,const QPoint&,int): Not implemented yet" );
}



/*!
  \fn KNateonMainview::slotItemExecuted( QListViewItem* item)
*/
void KNateonMainview::slotItemExecuted( QListViewItem* item)
{
	/*! 다중선택해서 채팅을 시작하면 */
	if ( listView3->isMultiSelection() )
	{
		QPtrList<Buddy> plBuddies;
		plBuddies.clear();

		QListViewItemIterator it( listView3 );
		for ( ; it.current(); ++it )
		{
			if (  listView3->isSelected( it.current() ) )
			{
				Buddy *pBuddy = pBuddyList->getBuddyByHandle( it.current()->text(2) );
				if (pBuddy)
				{
					pBuddy->setQuit(true);
					plBuddies.append(pBuddy);
#ifdef NETDEBUG
					kdDebug() << "[Chatting List] >>> [" << pBuddy->getName() << "]" << endl;
#endif
				}
			}
		}
		if ( plBuddies.count() )
		{
			emit startChat( plBuddies );
		}
	}
	else
	{
		Buddy *contact = getContactByItem(item);
		if (contact != 0)
			// if ( item->getType() == 'B' )
		{
			Buddy *contact = getContactByItem(item);  
			emit startChat( contact );
		}
	}
}


/*!
  \fn KNateonMainview::getContactByItem(QListViewItem* item)
*/
Buddy* KNateonMainview::getContactByItem(QListViewItem* item)
{
	ContactList* c=0;
	c = static_cast<ContactList*>( item );

	// if ( c->getType() == 'B' )
	if ( c->getType() == ContactBase::Buddy )
		return pBuddyList->getBuddyByHandle(item->text(2));
	else
		return 0;
	
		// return pBuddyList->getBuddyByHandle(item->text(2));
}

/*!
  메인창에 있는 BI 아이콘으로 상태변경 메뉴.
*/
bool KNateonMainview::createStatusMenu()
{
	/*!
	  KAction 함수 정보.
	  KAction (const QString &text, const QIconSet &pix, const KShortcut &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const char *name)
	  KAction (const QString &text, const QIconSet &pix, const KShortcut &cut, const QObject *receiver, const char *slot, QObject *parent, const char *name=0)
	*/
	pOnlineAction           = new KAction(UTF8("온라인"), *mOnlineQI, "online", this, SLOT( slotChangeStatusOnline() ), this, "online_status");
	pAwayAction             = new KAction(UTF8("자리 비움"), *mAwayQI, "away", this, SLOT( slotChangeStatusAway() ), this, "away_status");
	pBusyAction             = new KAction(UTF8("다른 용무 중"), *mBusyQI, "busy", this, SLOT( slotChangeStatusBusy() ), this, "busy_status");
	pOnphoneAction          = new KAction(UTF8("통화 중"), *mPhoneQI, "phone", this, SLOT( slotChangeStatusPhone() ), this, "onthephone_status");
	pMeetingAction          = new KAction(UTF8("회의 중"), *mMeetingQI, "meeting", this, SLOT( slotChangeStatusMeeting() ), this, "meeting_status");
	pOfflineAction          = new KAction(UTF8("오프라인 표시"), *mOfflineQI, "offline", this, SLOT( slotChangeStatusOffline() ), this, "offline_status");
	pChangenickAction       = new KAction(UTF8("내 대화명 설정"), 0, 0, this, "changenick");
	pViewprofileAction      = new KAction(UTF8("내 프로필 보기"), 0, 0, this, "removeFromGroup");
	pEditprofileAction      = new KAction(UTF8("내 프로필 설정"), 0, 0, this, "profile");

	pStatusClickMenu = new KPopupMenu(this);
	pOnlineAction           ->plug(pStatusClickMenu);
	pAwayAction             ->plug(pStatusClickMenu);
	pBusyAction             ->plug(pStatusClickMenu);
	pOnphoneAction          ->plug(pStatusClickMenu);
	pMeetingAction          ->plug(pStatusClickMenu);
	pOfflineAction          ->plug(pStatusClickMenu);
	pStatusClickMenu        ->insertSeparator();
	pChangenickAction       ->plug(pStatusClickMenu);
	pStatusClickMenu        ->insertSeparator();
	pViewprofileAction      ->plug(pStatusClickMenu);
	pEditprofileAction      ->plug(pStatusClickMenu);

	return true;
}

/*!
  버디리스트에서 그룹을 오른쪽 마우스 키 누를때 메뉴
*/
bool KNateonMainview::createGroupRightClickMenu()
{
	pGroupchatAction        = new KAction(UTF8("그룹으로 대화하기"), 0/*이미지*/, 0/*단축키*/, this, SLOT( slotGroupChat() ), this, "add");
	pGroupsendmemoAction    = new KAction(UTF8("그룹으로 쪽지 보내기"), 0, 0, this, SLOT( slotViewGroupMemo() ), this, "group_memo");
	pAddgroupAction         = new KAction(UTF8("그룹 추가"), 0, 0, this, SLOT( slotAddGroup() ), this, "add_group_rightclick");
	// pAddgroupAction         = new KAction(UTF8("Add Group"), "cancel", 0, this, "add_group_rightclick");
	pRenamegroupAction      = new KAction(UTF8("그룹 이름 변경"), 0, 0, this, SLOT( slotRenameGroup() ), this, "rename_group_rightclick");
	pBlockgroupAction       = new KAction(UTF8("그룹 차단"), 0, 0, this, SLOT( slotBlockGroup() ), this, "block_group_rightclick");

	pUnblockgroupAction       = new KAction(UTF8("그룹 차단해제"), 0, 0, this, SLOT( slotUnblockGroup() ), this, "unblock_group_rightclick");

	pDeletegroupAction      = new KAction(UTF8("그룹 삭제"), 0, 0, this, SLOT( slotDeleteGroup() ), this, "delete_group_rightclick");
	pUnfoldinggroupAction   = new KAction(UTF8("그룹 전체 열기"), 0, 0, this, SLOT( slotOpenAllGroup() ), this, "expand_group_rightclick");
	pFoldinggroupAction     = new KAction(UTF8("그룹 전체 닫기"), 0, 0, this, SLOT( slotCloseAllGroup() ), this, "collapse_group_rightclick");

	pGroupRightClickMenu    = new KPopupMenu(this);
	pGroupRightClickMenu    ->insertTitle("etc", 0);
	pGroupchatAction        ->plug(pGroupRightClickMenu);
	pGroupsendmemoAction    ->plug(pGroupRightClickMenu);
	pGroupRightClickMenu    ->insertSeparator();
	pAddgroupAction         ->plug(pGroupRightClickMenu);
	pRenamegroupAction      ->plug(pGroupRightClickMenu);
	pBlockgroupAction       ->plug(pGroupRightClickMenu);
	pUnblockgroupAction     ->plug(pGroupRightClickMenu);
	pDeletegroupAction      ->plug(pGroupRightClickMenu);
	pGroupRightClickMenu    ->insertSeparator();
	pUnfoldinggroupAction   ->plug(pGroupRightClickMenu);
	pFoldinggroupAction     ->plug(pGroupRightClickMenu);

	return true;
}

/*!
  버디리스트에서 버디를 오른쪽 마우스 키 누를때 메뉴.
*/
bool KNateonMainview::createBuddyRightClickMenu()
{
	pViewbuddyprofileAction = new KAction(UTF8("프로필 보기"), 0/*이미지*/, 0/*단축키*/, this, SLOT( slotViewProfile() ), this, "add");
	pViewmessageboxAction   = new KAction(UTF8("지난 대화 보기"), 0, 0, this, "viewChatLog");
	pChatAction             = new KAction(UTF8("대화 하기"), 0, 0, this, SLOT( slotGoChat() ), this, "memo_chatclick");
	pSendmemoAction         = new KAction(UTF8("쪽지 보내기"), 0, 0, this, SLOT( slotViewMemo() ), this, "memo_rightclick");
	pSendmailAction         = new KAction(UTF8("메일 보내기"), 0, 0, this, SLOT( slotSendMail() ), this, "sendMail");
	pSendfileAction         = new KAction(UTF8("파일 보내기"), 0, 0, this, "sendFile");
	pViewminihompyAction    = new KAction(UTF8("미니홈피 보기"), 0, 0, this, SLOT( slotViewMinihompy() ), this, "viewMiniHompy");
	pCopybuddyAction        = new KSelectAction(UTF8("친구 복사"), 0, 0, this, "copyBuddy");
	pMovebuddyAction        = new KSelectAction(UTF8("친구 이동"), 0, 0, this, "moveBuddy");
	pBlockbuddyAction       = new KAction(UTF8("친구 차단"), 0, 0, this, "blockBuddy");
	pDeletebuddyAction      = new KAction(UTF8("친구 삭제"), 0, 0, this, "deleteBuddy");

	pBuddyRightClickMenu = new KPopupMenu(this);
	pBuddyRightClickMenu    ->insertTitle("ring0320@nate.com", 0);
	pViewbuddyprofileAction ->plug(pBuddyRightClickMenu); // <<<
	pViewmessageboxAction   ->plug(pBuddyRightClickMenu);
	pBuddyRightClickMenu    ->insertSeparator();
	pChatAction             ->plug(pBuddyRightClickMenu);
	pSendmemoAction         ->plug(pBuddyRightClickMenu);
	pSendmailAction         ->plug(pBuddyRightClickMenu);
	pSendfileAction         ->plug(pBuddyRightClickMenu);
	pBuddyRightClickMenu    ->insertSeparator();
	pViewminihompyAction    ->plug(pBuddyRightClickMenu);
	pBuddyRightClickMenu    ->insertSeparator();
	pCopybuddyAction        ->plug(pBuddyRightClickMenu);
	pMovebuddyAction        ->plug(pBuddyRightClickMenu);
	pBlockbuddyAction       ->plug(pBuddyRightClickMenu);
	pDeletebuddyAction      ->plug(pBuddyRightClickMenu);

	return true;
}

void KNateonMainview::slotSetGroupList(QStringList &Group)
{
	Group.sort();
	pCopybuddyAction    ->setItems(Group);
	pMovebuddyAction    ->setItems(Group);
}

void KNateonMainview::slotGotINFY(const QStringList & slCommand)
{
	pBuddyList = m_pCurrentAccount->getBuddyList();
	pGroupList = m_pCurrentAccount->getGroupList();
  
	Buddy *pBuddy = pBuddyList->getBuddyByID(slCommand[2]);

	if (!pBuddy)
		return;

	QListViewItemIterator it( listView3 );
	ContactList* c=0;
	QString sListItem;
	ContactRoot* pRoot = 0;
	QString sTemp( pBuddy->getStatus() );
	pBuddy->setStatus( slCommand[3] );

	int nOnlineCount = 0;
	Group *pGroup;
	switch ( stConfig.typeofbuddysort )
	{
		/*! 친구 전체 보기 */ 
	case 0:
		for ( ; it.current(); ++it )
		{
			c = static_cast<ContactList*>( it.current() );
			if ( !c ) continue;
			/*!
			 * !getContactByItem(c) => 그룹인가?
			 * 그룹이고, 버디GID와 같은 버디 ListItem
			 */
			if ( !getContactByItem(c) )
			{
				pRoot = static_cast<ContactRoot*>( it.current() );
				// if ( pRoot->getType() != 'G' )
				if ( pRoot->getType() != ContactBase::Group )
					continue;
				pGroup = pGroupList->getGroupByID( pRoot->text(1) );
				if ( pGroup )
				{
					nOnlineCount = 0;
					/*!
					 * 그룹의 버디 handle 리스트에
					 * 해당 Buddy가 있으면 온라인 정보변경
					 */
          				QPtrListIterator<Buddy> iter( pGroup->getBuddyList() );
          				while( iter.current() != 0 )
					{
						Buddy *pBuddy = iter.current();
						if ( pBuddy )
						{
							if ( pBuddy->getStatus() != "F" )
								nOnlineCount++;
						}
#ifdef NETDEBUG
						else
						{
							kdDebug() << "Group Name : [" << pGroup->getGName() << "], Handle : [" << *iter << "]" << endl;
						}
#endif
            					++iter;
					}
					pRoot->setOnlineCount( nOnlineCount );
				}
			}
			else
			{
				if (c->text(2) == pBuddy->getHandle() )
				{
					c->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
				}
			}
		}
		break;
		/*! 접속한 친구만 보기 */
	case 1:
		if ( ( sTemp == "F") || ( slCommand[3] == "F" ) )
			sortGroupName( true );
		else
		{
			for ( ; it.current(); ++it )
			{
				c = static_cast<ContactList*>( it.current() );
				if (c->text(2) == pBuddy->getHandle() )
				{
					c->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
				}
				if ( c->text(1) == pBuddy->getGID() )
				{
					pRoot = static_cast<ContactRoot*>( it.current() );
				}
			}
		}
		break;
		/*! 친구 온라인/오프라인으로 보기 */ 
	case 2:
		if ( ( sTemp == "F") || ( slCommand[3] == "F" ) )
			sortOnOffline();
		else
		{
			for ( ; it.current(); ++it )
			{
				c = static_cast<ContactList*>( it.current() );
				if (c->text(2) == pBuddy->getHandle() )
				{
					// pBuddy->setStatus( slCommand[3] );
					c->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
				}
				if ( c->text(1) == pBuddy->getGID() )
				{
					pRoot = static_cast<ContactRoot*>( it.current() );
				}
			}
		}
		break;
	}
}

void KNateonMainview::initIcons()
{
	KStandardDirs   *dirs   = KGlobal::dirs();
	QString         path;
	QImage          mTemp;

#if 1
	path = dirs->findResource( "data", QString( KGlobal::instance()->aboutData()->appName() ) + "/pics/StatusBigIcons.bmp" );
	QImage *m_StatusQI = new QImage(path);
#endif
	int m_nHeight = m_StatusQI->height();

	mTemp = m_StatusQI->copy( (m_nHeight * 0), 0, m_nHeight, m_nHeight);
	mOnlineQI = new QPixmap();
	mOnlineQI->convertFromImage(mTemp);

	mTemp = m_StatusQI->copy( (m_nHeight * 1), 0, m_nHeight, m_nHeight);
	mAwayQI = new QPixmap();
	mAwayQI->convertFromImage(mTemp);

	mTemp = m_StatusQI->copy( (m_nHeight * 2), 0, m_nHeight, m_nHeight);
	mBusyQI = new QPixmap();
	mBusyQI->convertFromImage(mTemp);

	mTemp = m_StatusQI->copy( (m_nHeight * 3), 0, m_nHeight, m_nHeight);
	mPhoneQI = new QPixmap();
	mPhoneQI->convertFromImage(mTemp);

	mTemp = m_StatusQI->copy( (m_nHeight * 4), 0, m_nHeight, m_nHeight);
	mMeetingQI = new QPixmap();
	mMeetingQI->convertFromImage(mTemp);

	mTemp = m_StatusQI->copy( (m_nHeight * 5), 0, m_nHeight, m_nHeight);
	mOfflineQI = new QPixmap();
	mOfflineQI->convertFromImage(mTemp);

}

QPixmap * KNateonMainview::getStatusPixmap(QString sStatus)
{
	// QPixmap* m_BuddyQP = new QPixmap();

	if (sStatus == "O")
		return mOnlineQI;
	else if (sStatus == "B")
		return mBusyQI;
	else if (sStatus == "A")
		return mAwayQI;
	else if (sStatus == "P")
		return mPhoneQI;
	else if (sStatus == "M")
		return mMeetingQI;
	else
		return mOfflineQI;
}

void KNateonMainview::slotChangeNickName(QString sNick)
{
	Common::fixOutString( sNick );
	TL_NickName->setText( sNick );
}

void KNateonMainview::changeStatusUI(int nID)
{
	switch( nID )
	{
	case 0:
		PBbi->setShape( sPicsPath + "bi.bmp" );
		TL_Status->setText(UTF8("(온라인)"));
		break;
	case 1:
		PBbi->setShape( sPicsPath + "bi3.bmp" );
		TL_Status->setText(UTF8("(자리 비움)"));
		break;
	case 2:
		PBbi->setShape( sPicsPath + "bi2.bmp" );
		TL_Status->setText(UTF8("(다른 용무 중)"));
		break;
	case 3:
		PBbi->setShape( sPicsPath + "bi2.bmp" );
		TL_Status->setText(UTF8("(통화 중)"));
		break;
	case 4:
		PBbi->setShape( sPicsPath + "bi3.bmp" );
		TL_Status->setText(UTF8("(회의 중)"));
		break;
	case 5:
		PBbi->setShape( sPicsPath + "bi4.bmp" );
		TL_Status->setText(UTF8("(오프라인 표시)"));
		break;
	}
}

void KNateonMainview::setMemoIcon(bool isNew)
{
	if (isNew) {
		PB_Memo->setShape( sPicsPath + "main_memo_count_new_btn.bmp" );
		PB_Memo->setPressedShape( sPicsPath + "main_memo_count_new_btn_down.bmp" );
		PB_Memo->setMouseOverShape( sPicsPath + "main_memo_count_new_btn_ov.bmp" );
	} else {
		PB_Memo->setShape( sPicsPath + "main_memo_count_btn.bmp" );
		PB_Memo->setPressedShape( sPicsPath + "main_memo_count_btn_down.bmp" );
		PB_Memo->setMouseOverShape( sPicsPath + "main_memo_count_btn_ov.bmp" );
	}
}

void KNateonMainview::setHompyIcon(bool isNew)
{
	if (isNew) {
		PB_Hompy->setShape( sPicsPath + "main_hompy_new_btn.bmp" );
		PB_Hompy->setPressedShape( sPicsPath + "main_hompy_new_btn_down.bmp");
		PB_Hompy->setMouseOverShape( sPicsPath + "main_hompy_new_btn_ov.bmp");
	} else {
		PB_Hompy->setShape( sPicsPath + "main_hompy_btn.bmp" );
		PB_Hompy->setPressedShape( sPicsPath + "main_hompy_btn_down.bmp");
		PB_Hompy->setMouseOverShape( sPicsPath + "main_hompy_btn_ov.bmp");
	}
}

void KNateonMainview::slotChangeStatusOnline()
{
	emit changeStatusNumber( 0 );
}

void KNateonMainview::slotChangeStatusAway()
{
	emit changeStatusNumber( 1 );
}

void KNateonMainview::slotChangeStatusBusy()
{
	emit changeStatusNumber( 2 );
}

void KNateonMainview::slotChangeStatusPhone()
{
	emit changeStatusNumber( 3 );
}

void KNateonMainview::slotChangeStatusMeeting()
{
	emit changeStatusNumber( 4 );
}

void KNateonMainview::slotChangeStatusOffline()
{
	emit changeStatusNumber( 5 );
}

void KNateonMainview::slotViewMemo()
{
	QListViewItem* pCur;
	QString sBuddy;

	if (listView3->isMultiSelection ())
	{
		QListViewItemIterator it( listView3 );
		for ( ; it.current(); ++it )
		{
			if (  listView3->isSelected( it.current() ) )
			{
				pCur = it.current();
				Buddy *pBuddy = pBuddyList->getBuddyByHandle( pCur->text(2) );
				if (pBuddy)
				{
					if ( sBuddy.length() > 1 )
						sBuddy += ";\"" + pBuddy->getName() + "\" <" + pBuddy->getUID() + ">";
					else
						sBuddy = "\"" + pBuddy->getName() + "\" <" + pBuddy->getUID() + ">";
				}
			}
		}

	} else {
		pCur = listView3->currentItem ();
		Buddy *pBuddy = pBuddyList->getBuddyByHandle( pCur->text(2) );

		sBuddy = "\"" + pBuddy->getName() + "\" <" + pBuddy->getUID() + ">";
	}

	emit startMemoView( sBuddy );
}


void KNateonMainview::slotMemoAddBuddy(AddBuddySelector *pBuddySelector)
{
	pBuddySelector->setGroupList(pGroupList);
	pBuddySelector->setBuddyList(pBuddyList);

	pBuddySelector->show();
}

void KNateonMainview::slotViewGroupMemo()
{
	ContactRoot *pRoot = static_cast<ContactRoot*>( listView3->currentItem() );
	Group *pGroup = pGroupList->getGroupByID( pRoot->text(1) );
  QPtrListIterator<Buddy> it( pGroup->getBuddyList() );

	QString sBuddy( QString::null );
  while( it.current() != 0 )
	{
		Buddy *pBuddy = it.current();
		if (pBuddy)
		{
			if ( sBuddy.length() > 0 )
				sBuddy += ";\"" + pBuddy->getName() + "\" <" + pBuddy->getUID() + ">";
			else
				sBuddy = "\"" + pBuddy->getName() + "\" <" + pBuddy->getUID() + ">";
		}
    ++it;
	}

	if ( sBuddy.length() == QString::null )
	{
		KMessageBox::information( this, UTF8("빈 그룹 입니다."), UTF8("그룹 쪽지") );
	}
	else
	{
		emit startMemoView( sBuddy );
	}
}

QString KNateonMainview::getStatusHTML(QString sStatus)
{
	if (sStatus == "O")
		return "<img src=\"" + sPicsPath + "main_list_state_online.png\"> ";
	else if (sStatus == "B")
		return "<img src=\"" + sPicsPath + "main_list_state_otherbusiness.png\"> ";
	else if (sStatus == "A")
		return "<img src=\"" + sPicsPath + "main_list_state_vacant.png\"> ";
	else if (sStatus == "P")
		return "<img src=\"" + sPicsPath + "main_list_state_otherbusiness.png\"> ";
	else if (sStatus == "M")
		return "<img src=\"" + sPicsPath + "main_list_state_meeting.png\"> ";
	else
		return "<img src=\"" + sPicsPath + "main_list_state_offline.png\"> ";
}

void KNateonMainview::slotAddGroup()
{
	emit addGroup();
}

void KNateonMainview::slotRenameGroup()
{
	emit renameGroup(/* listView3->currentItem()->text(0) */);
}

void KNateonMainview::slotGoChat()
{
	/*! 다중선택해서 채팅을 시작하면 */
	if ( listView3->isMultiSelection() )
	{
		QPtrList<Buddy> plBuddies;
		plBuddies.clear();

		QListViewItemIterator it( listView3 );
		for ( ; it.current(); ++it )
		{
			if (  listView3->isSelected( it.current() ) )
			{
				Buddy *pBuddy = pBuddyList->getBuddyByHandle( it.current()->text(2) );
				if ( pBuddy )
				{
					if ( pBuddy->getStatus() != "F" )
					{
						pBuddy->setQuit(true);
						plBuddies.append(pBuddy);
#ifdef NETDEBUG
						kdDebug() << "[Chatting List] >>> [" << pBuddy->getName() << "]" << endl;
#endif
					}
				}
			}
		}
		if ( plBuddies.count() )
		{
			emit startChat( plBuddies );
		}
	}
	else
	{
		// Buddy *contact = getContactByItem(item);
		Buddy *contact = getContactByItem( listView3->currentItem() );
		if (contact != 0)
		{
			emit startChat( contact );
		}
	}
	/*
	  Buddy *contact = getContactByItem( listView3->currentItem() );
	  if (contact != 0)
	  {
	  emit startChat( contact );
	  }
	*/
}


void KNateonMainview::slotDeleteGroup()
{
	emit deleteGroup();
}

/*!
  QListView에 버디 추가
  - 사용 안하는것 같음. -
*/
void KNateonMainview::slotAddFriend(const QStringList & slCommand)
{
	QListViewItem* pGItem = 0;
	/*! 기타에 버디 추가 */
	pGItem = listView3->findItem("0", 1, Qt::CaseSensitive);
	pGroupList = m_pCurrentAccount->getGroupList();

	// pGroup->addBuddyHandle( "TID:" + slCommand[1] );
	
	if ( pGItem == 0 )
	{
#ifdef NETDEBUG
		kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
		return;
	}
	
	Buddy *pBuddy = m_pCurrentAccount->getBuddyList()->getBuddyByHandle( "TID:" + slCommand[1] );
	
	if ( pBuddy )
	{
		pBuddy->setHandle( slCommand[3] );
		pBuddy->setName( slCommand[4] );
		pBuddy->setNick( slCommand[4] );
		pBuddy->setStatus( "F" );
  
		Group *pGroup = pGroupList->getGroupByID("0");
		pGroup->addBuddy( pBuddy );
		
#if 0
		ContactList* pNewBuddy = new ContactList( pGItem );
		pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );

		pNewBuddy->setText( 0, slCommand[4] );
		pNewBuddy->setText( 1, "0" );
		pNewBuddy->setText( 2, slCommand[3] );
		pNewBuddy->setText( 3, pBuddy->getUID() );
#endif
		slotEmoticonList( stConfig.viewemoticonlist );
	}
	return;
}

void KNateonMainview::slotPBMenu(int notUse)
{
	/*! 현재 마우스 위치 */
	pStatusClickMenu->exec(QCursor::pos());
	
	Q_UNUSED( notUse );
}


/*!
  메인창 리스팅 메뉴 아이콘
*/
bool KNateonMainview::createListingMenu()
{
	pViewNameAction      = new KRadioAction(UTF8("친구 이름으로 보기"), 0, this, SLOT( slotListOnlyName() ), this, "view_name");
	pViewNickAction      = new KRadioAction(UTF8("친구 대화명으로 보기"), 0, this, SLOT( slotListOnlyNick() ), this, "view_nick");
	pViewNameIDAction    = new KRadioAction(UTF8("친구 이름+아이디로 보기"), 0, this, SLOT( slotListNameID() ), this, "view_name_id");
	pViewNameNickAction  = new KRadioAction(UTF8("친구 이름+대화명으로 보기"), 0, this, SLOT( slotListNameNick() ), this, "view_name_nick");

	pViewNameAction->setExclusiveGroup("view mode");
	pViewNickAction->setExclusiveGroup("view mode");
	pViewNameIDAction->setExclusiveGroup("view mode");
	pViewNameNickAction->setExclusiveGroup("view mode");

	pViewAllAction       = new KRadioAction(UTF8("친구 전체 보기"), 0, this, SLOT( slotSortNormal() ), this, "view_all");
	pViewOnlineAction    = new KRadioAction(UTF8("접속한 친구만 보기"), 0, this, SLOT( slotSortOnlyOnline() ), this, "view_online");
	pViewOnOffAction     = new KRadioAction(UTF8("친구 온라인/오프라인으로 보기"), 0, this, SLOT( slotSortOnOffline() ), this, "view_online_offline");

	pViewAllAction->setExclusiveGroup("group mode");
	pViewOnlineAction->setExclusiveGroup("group mode");
	pViewOnOffAction->setExclusiveGroup("group mode");

	pAllGroupOpenAction  = new KAction(UTF8("그룹 전체 열기"), "open", 0, this, SLOT( slotOpenAllGroup() ), this, "view_all_group_open");
	pAllGroupCloseAction = new KAction(UTF8("그룹 전체 닫기"), "close", 0, this, SLOT( slotCloseAllGroup() ), this, "view_all_group_close");
	pViewEmoticonAction  = new KToggleAction(UTF8("친구 목록에 이모티콘 표시"), 0, this, "view_emoticons");
	pViewEmoticonAction->setChecked( stConfig.viewemoticonlist );
	connect( pViewEmoticonAction, SIGNAL( toggled (bool) ), SLOT( slotEmoticonList(bool) ) );

	pListringMenu    = new KPopupMenu(this);
	// pGroupRightClickMenu    ->insertTitle("etc", 0);
	pViewNameAction     ->plug(pListringMenu);
	pViewNickAction     ->plug(pListringMenu);
	pViewNameIDAction   ->plug(pListringMenu);
	pViewNameNickAction ->plug(pListringMenu);
	pListringMenu       ->insertSeparator();
	pViewAllAction      ->plug(pListringMenu);
	pViewOnlineAction   ->plug(pListringMenu);
	pViewOnOffAction    ->plug(pListringMenu);
	pListringMenu       ->insertSeparator();
	pAllGroupOpenAction ->plug(pListringMenu);
	pAllGroupCloseAction->plug(pListringMenu);
	pListringMenu       ->insertSeparator();
	pViewEmoticonAction ->plug(pListringMenu);

	switch ( stConfig.typeofbuddylist )
	{
	case 0:
		pViewNameAction->setChecked( true );
		break;
	case 1:
		pViewNickAction->setChecked( true );
		break;
	case 2:
		pViewNameIDAction->setChecked( true );
		break;
	case 3:
		pViewNameNickAction->setChecked( true );
		break;
	}

	switch ( stConfig.typeofbuddysort )
	{
	case 0:
		pViewAllAction->setChecked( true );
		break;
	case 1:
		pViewOnlineAction->setChecked( true );
		break;
	case 2:
		pViewOnOffAction->setChecked( true );
		break;
	}

	return true;
}

void KNateonMainview::slotPBSortList()
{
	pListringMenu->exec(QCursor::pos());
}

void KNateonMainview::setView1(int nID)
{
	if (nID == 0)
		pViewNameAction->activate();
	else if (nID == 1)
		pViewNickAction->activate();
	else if (nID == 2)
		pViewNameIDAction->activate();
	else if (nID == 3)
		pViewNameNickAction->activate();
#ifdef NETDEBUG
	else
		kdDebug() << "Index Error : (0~3) : [" << QString::number(nID) << "]" << endl;
#endif
}

void KNateonMainview::setView2(int nID)
{
	if (nID == 0)
		pViewAllAction->activate();
	else if (nID == 1)
		pViewOnlineAction->activate();
	else if (nID == 2)
		pViewOnOffAction->activate();
#ifdef NETDEBUG
	else
		kdDebug() << "Index Error : (0~2) : [" << QString::number(nID) << "]" << endl;
#endif
}

void KNateonMainview::setViewEmo(bool bView)
{
	pViewEmoticonAction->setChecked(bView);
}

int KNateonMainview::getView1()
{
	if ( pViewNameAction->isChecked() )
		return 0;
	else if ( pViewNickAction->isChecked() )
		return 1;
	else if ( pViewNameIDAction->isChecked() )
		return 2;
	else if ( pViewNameNickAction->isChecked() )
		return 3;
	else
		return 0;
}

int KNateonMainview::getView2()
{
	if ( pViewAllAction->isChecked() )
		return 0;
	else if ( pViewOnlineAction->isChecked() )
		return 1;
	else if ( pViewOnOffAction->isChecked() )
		return 2;
	else
		return 0;
}

bool KNateonMainview::isViewEmo()
{
	return pViewEmoticonAction->isChecked();
}

void KNateonMainview::slotCloseAllGroup()
{
	/*! 그룹 Tree Open/Close 상태 저장. */
	config->setGroup("BuddyListTree");
  
	// Buddy *pBuddy;
	QListViewItemIterator it( listView3 );
	for ( ; it.current(); ++it )
	{
		// pBuddy = getContactByItem( it.current() );
    
		// if ( !pBuddy )
		if ( static_cast<ContactBase *>( it.current() )->getType() == ContactBase::Group )
		{
			static_cast<ContactRoot*>( it.current() )->setPixmap( folderClosed );
			it.current()->setOpen( FALSE );
			switch( stConfig.typeofbuddysort )
			{
			case 0:
			case 1:
				config->writeEntry( it.current()->text(1) , FALSE );
				break;
			case 2:
				if ( it.current()->text(1) == "0" )
					config->writeEntry( "online" , FALSE );
				else
					config->writeEntry( "offline" , FALSE );
				break;
			}
		}
	}
}

void KNateonMainview::slotOpenAllGroup()
{
	/*! 그룹 Tree Open/Close 상태 저장. */
	config->setGroup("BuddyListTree");

	// Buddy *pBuddy;
	QListViewItemIterator it( listView3 );
	for ( ; it.current(); ++it )
	{
		// pBuddy = getContactByItem( it.current() );
    
		// if ( !pBuddy )
		if ( static_cast<ContactBase *>( it.current() )->getType() == ContactBase::Group )
		{
			static_cast<ContactRoot*>( it.current() )->setPixmap( folderOpen );
			it.current()->setOpen( TRUE );
			switch( stConfig.typeofbuddysort )
			{
			case 0:
			case 1:
				config->writeEntry( it.current()->text(1) , TRUE );
				break;
			case 2:
				if ( it.current()->text(1) == "0" )
					config->writeEntry( "online" , TRUE );
				else
					config->writeEntry( "offline" , TRUE );
				break;
			}
		}
	}
}

/**
 * \brief 홈피버튼을 눌렀을때의 처리함수
 * \param item
 */
void KNateonMainview::slotGotoMinihompy(QListViewItem* item)
{
	if (item == NULL) return;

	listView3->setCurrentItem(item);
	slotViewMinihompy();
}

void KNateonMainview::slotViewMinihompy()
{
	Buddy *pBuddy = getContactByItem( listView3->currentItem() );
	if (pBuddy == NULL) return;

	/*! 주홈피가 싸이월드 미니홈피인경우 */
	if /* (1) */ ( pBuddy->getHompyType() == Buddy::Cyworld )
	{
		QString sURL("http://br.nate.com/index.php");
		sURL += "?code=D024";
		sURL += "&t=";
		sURL += m_pCurrentAccount->getMyTicket();
		sURL += "&param=";
		// sURL += pBuddy->getCyworld_CMN();
		sURL += pBuddy->getCyworld_CMN();
#ifdef NETDEBUG
		kdDebug() << "Cyworld MiniHompy : [" << sURL << "]" <<endl;
#endif
		/*
		if ( !pWebViewer )
			pWebViewer = new WebViewer();
		pWebViewer->openURL( sURL );
		pWebViewer->resize(937,584);
		pWebViewer->show();
		*/
		LNMUtils::openURL( sURL );
	}
	/*! 주홈피가 Home2 인경우 */
	else
	{
		QString sURL("http://br.nate.com/index.php");
		sURL += "?code=D012";
		sURL += "&t=";
		sURL += m_pCurrentAccount->getMyTicket();
		sURL += "&param=";
		// sURL += pBuddy->getCyworld_CMN();
		sURL += pBuddy->getHome2CMN();
		LNMUtils::openURL( sURL );
	}
}

/*!
  QListView에 버디 추가
*/
void KNateonMainview::slotAddBuddy(QListViewItem* pGroup, Buddy * pBuddy)
{
	/*! 그룹이 없으면, 기타에 등록 */
	if (!pGroup)
	{
		pGroup = listView3->findItem("0", 1, Qt::CaseSensitive);
	}

	ContactList* pNewBuddy = new ContactList(pGroup);
	pNewBuddy->setListParent(listView3);
	pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );

	pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
	pNewBuddy->setText( 0, pBuddy->getNick() );
	pNewBuddy->setText( 1, pBuddy->getGID() );
	pNewBuddy->setText( 2, pBuddy->getHandle() );
	pNewBuddy->setText( 3, pBuddy->getUID() );

	return;
}

#if 0
void KNateonMainview::slotListing()
{
	if (1) /*! 그릅과 이름으로 정렬. 그릅 : 한글 + 영문 + 기타 */
	{
		sortGroupName();
	}
}
#endif

/*!
  그릅과 이름으로 정렬. 그릅 : 한글 + 영문 + 기타
  bOnlyOnline : 온/오프라인 모두 보기 false, 온라인 버디만 보기 true
*/
void KNateonMainview::sortGroupName(bool bOnlyOnline)
{
	pBuddyList = m_pCurrentAccount->getBuddyList();
	pGroupList = m_pCurrentAccount->getGroupList();
  
	Buddy *pBuddy;
	QStringList slHan;
	QStringList slBuddyList;

	/*! 버디 정렬을 위한 임시 리스트 변수 */
	QPtrList<Buddy> myBuddy;
	myBuddy.clear();

	listView3->clear();
	listView3->setSorting(-1);
	QPtrListIterator<Group> itorGroup(*pGroupList);
	Group * pGroup;
	QStringList slGroup;
	while (itorGroup.current() != 0)
	{
		pGroup = itorGroup.current();
		slGroup.append( pGroup->getGName() );
		++itorGroup;
	}
	/*! 그룹 Tree Open/Close 상태 가지고 옴. */
	config->setGroup("BuddyListTree");

	QString etcGrpName = UTF8("기타");
	pGroup = pGroupList->getGroupByName( etcGrpName );

	if ( !pGroup ) {
		//pGroup = new Group( "0", UTF8("기타") );
		//pGroupList->addGroup( pGroup );
		etcGrpName = UTF8("ETC");
		pGroup = pGroupList->getGroupByName( etcGrpName );
		if ( !pGroup ) {
		    pGroup = pGroupList->getGroupByID("0");
		    if (!pGroup) {
		        pGroup = new Group( "0", UTF8("기타") );
		        pGroupList->addGroup( pGroup );
            }
        }
	}

#ifdef NETDEBUG
	// kdDebug() << etcGrpName << " 의 아이템 수 : [" << pGroup->getBuddyList().count() << "]" << endl;
#endif
		
	ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
	pRoot->setPixmap( folderOpen );
	pRoot->setOpen( config->readBoolEntry( pGroup->getGID() , true ) );
	if ( pRoot->isOpen() )
		pRoot->setPixmap( folderOpen );
	else
		pRoot->setPixmap( folderClosed );
  
  
	int nTotal = 0;
	int nOnlineCount = 0;
  	QPtrListIterator<Buddy> iterBL( pGroup->getBuddyList() );
  //
	while( iterBL.current() != 0 )
	{
		pBuddy = iterBL.current();
		if ( pBuddy )
		{
			/*! FL(Friend List) == 0 */
			if ( pBuddy->isFL() == FALSE ) { continue; }
			myBuddy.append( pBuddy );
			nTotal++;  
		}
#ifdef NETDEBUG
		else
		{
			kdDebug() << "111> Nothing handle value : [" << *iterBL << "]" << endl;
		}
#endif

    		++iterBL;
	}
	
	MyBuddyList  bList( myBuddy );
	bList.sort();
	QPtrListIterator<Buddy> itorBuddy( bList );
	while (itorBuddy.current() != 0)
	{
		pBuddy = itorBuddy.current();
		// pBuddy->setGID( pGroup->getGID() );

		QListViewItem* pGroupItem = 0;
		pGroupItem = listView3->findItem(pGroup->getGID(), 1, Qt::CaseSensitive);
		if ( pGroupItem == 0 )
		{
#ifdef NETDEBUG
			kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
			++itorBuddy;
			continue;
		}
		if ( pBuddy->getStatus() != "F" )
			nOnlineCount++;

		if ( bOnlyOnline )
			if ( pBuddy->getStatus() == "F" )
			{
				++itorBuddy;
				continue;
			}

		ContactList* pNewBuddy = new ContactList( pGroupItem );
		pNewBuddy->setDragEnabled ( true );
		pNewBuddy->setListParent(listView3);
		pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
		pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
		pNewBuddy->setText( 0, pBuddy->getName() );
		pNewBuddy->setText( 1, /* pBuddy->getGID() */ pGroupItem->text(1) );
		pNewBuddy->setText( 2, pBuddy->getHandle() );
		pNewBuddy->setText( 3, pBuddy->getUID() );

		++itorBuddy;
	}
#ifdef NETDEBUG
	kdDebug() << "Online Count : [" << QString::number( nOnlineCount ) << "]" << endl;
	kdDebug() << "nTotal Buddies : [" << QString::number( nTotal ) << "]" << endl;
#endif
	/*! 버디 온라인 수 */
	pRoot->setTotal( nTotal );
	pRoot->setOnlineCount( nOnlineCount );

	slGroup.sort();
	while ( !slGroup.isEmpty() )
	{
		/*! 임시 저장 변수 초기화 */
		myBuddy.clear();

		QString aa( slGroup.last() );
		/*! 영어 */
		//if ( aa != UTF8("기타") )
		if ( aa != etcGrpName )
		{
			if ( aa.lower() != aa.upper() )
			{
				pGroup = pGroupList->getGroupByName( aa );
				if ( !pGroup )
					continue;
				ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
				pRoot->setPixmap( folderOpen );
				pRoot->setOpen( config->readBoolEntry( pGroup->getGID() , true ) );
				if ( pRoot->isOpen() )
					pRoot->setPixmap( folderOpen );
				else
					pRoot->setPixmap( folderClosed );
        
				nTotal = 0;
				nOnlineCount = 0;

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

					if ( pBuddy )
					{
						// FL(Friend List) == 0
						if ( pBuddy->isFL() == FALSE ) { continue; }
						myBuddy.append( pBuddy );
						nTotal++;
					}
#ifdef NETDEBUG
					else
					{
						kdDebug() << "222> Nothing handle value : [" << *iterBL << "]" << endl;
					}
#endif
          				++iterBL;
				}
				MyBuddyList  bList( myBuddy );
				bList.sort();
				QPtrListIterator<Buddy> itorBuddy( bList );
				while (itorBuddy.current() != 0)
				{
					pBuddy = itorBuddy.current();
					// pBuddy->setGID( pGroup->getGID() );

					QListViewItem* pGroupItem = 0;
					pGroupItem = listView3->findItem(pGroup->getGID(), 1, Qt::CaseSensitive);
					if ( pGroupItem == 0 )
					{
#ifdef NETDEBUG
						kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
						++itorBuddy;
						continue;
					}
					if ( pBuddy->getStatus() != "F" )
						nOnlineCount++;
  				
					if ( bOnlyOnline )
						if ( pBuddy->getStatus() == "F" )
						{
							++itorBuddy;
							continue;
						}
					ContactList* pNewBuddy = new ContactList( pGroupItem );
					pNewBuddy->setDragEnabled ( true );    
					pNewBuddy->setListParent(listView3);
					pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
					pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
					pNewBuddy->setText( 0, pBuddy->getName() );
					//pNewBuddy->setText( 1, pBuddy->getGID() );
					pNewBuddy->setText( 1, pGroupItem->text(1) );
					pNewBuddy->setText( 2, pBuddy->getHandle() );
					pNewBuddy->setText( 3, pBuddy->getUID() );

					++itorBuddy;
				}
				// 버디 온라인 수 
				pRoot->setTotal( nTotal );
				pRoot->setOnlineCount( nOnlineCount );
			}
			else
			{
				slHan.append( aa );
			}
		}
		slGroup.pop_back();
	}


	for ( QStringList::Iterator it = slHan.begin(); it != slHan.end(); ++it )
	{
		/*! 임시 저장 변수 초기화 */
		myBuddy.clear();
		/*! 한글 */
		//if ( *it != UTF8("기타") )
		if ( *it != etcGrpName )
		{
			if ( (*it).lower() == (*it).upper() )
			{
				pGroup = pGroupList->getGroupByName( *it );
				ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
				pRoot->setPixmap( folderOpen );
				pRoot->setOpen( config->readBoolEntry( pGroup->getGID() , true ) );
				if ( pRoot->isOpen() )
					pRoot->setPixmap( folderOpen );
				else
					pRoot->setPixmap( folderClosed );
        
				nTotal = 0;
				nOnlineCount = 0;
  			
				QPtrListIterator<Buddy> iterBL( pGroup->getBuddyList() );
				while( iterBL.current() != 0 )
				{
					pBuddy = iterBL.current();

					if ( pBuddy )
					{
						/*! FL(Friend List) == 0 */
						if ( pBuddy->isFL() == FALSE ) { continue; }
						myBuddy.append( pBuddy );
						nTotal++;
					}
#ifdef NETDEBUG
					else
					{
						kdDebug() << "333> Nothing handle value : [" << *iterBL << "]" << endl;
					}
#endif
					++iterBL;
				}
				MyBuddyList  bList( myBuddy );
				bList.sort();
				QPtrListIterator<Buddy> itorBuddy( bList );
				while (itorBuddy.current() != 0)
				{
					pBuddy = itorBuddy.current();
					// pBuddy->setGID( pGroup->getGID() );

					QListViewItem* pGroupItem = 0;
					pGroupItem = listView3->findItem(pGroup->getGID(), 1, Qt::CaseSensitive);
					if ( pGroupItem == 0 )
					{
#ifdef NETDEBUG
						kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
						++itorBuddy;
						continue;
					}
					if ( pBuddy->getStatus() != "F" )
						nOnlineCount++;
  				
					if ( bOnlyOnline )
						if ( pBuddy->getStatus() == "F" )
						{
							++itorBuddy;
							continue;
						}
					ContactList* pNewBuddy = new ContactList( pGroupItem );
					pNewBuddy->setDragEnabled ( true );    
					pNewBuddy->setListParent(listView3);
					pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
					pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
					pNewBuddy->setText( 0, pBuddy->getName() );
					pNewBuddy->setText( 1, /* pBuddy->getGID() */ pGroupItem->text(1) );
					pNewBuddy->setText( 2, pBuddy->getHandle() );
					pNewBuddy->setText( 3, pBuddy->getUID() );

					++itorBuddy;
				}
				/*! 버디 온라인 수 */
				pRoot->setTotal( nTotal );
				pRoot->setOnlineCount( nOnlineCount );
			}
		}
	}
}

/*!
  온/오프라인으로 보기 정렬.
*/
void KNateonMainview::sortOnOffline()
{
	pBuddyList = m_pCurrentAccount->getBuddyList();
	pGroupList = m_pCurrentAccount->getGroupList();
  
	listView3->clear();
	listView3->setSorting(-1);

	QPtrList<Buddy> onlineBuddy;
	onlineBuddy.clear();
	QPtrList<Buddy> offlineBuddy;
	offlineBuddy.clear();

	/*
	  int nTotal = 0;
	  int nOnlineCount = 0;
	config->setGroup("BuddyListTree");
	
	pGroup = pGroupList->getGroupByName( UTF8("기타") );
	ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
	pRoot->setPixmap( folderOpen );
	pRoot->setOpen( config->readBoolEntry( pGroup->getGID() , true ) );
	if ( pRoot->isOpen() )
		pRoot->setPixmap( folderOpen );
	else
		pRoot->setPixmap( folderClosed );
	*/
	config->setGroup("BuddyListTree");
	
	ContactRoot* pRoot01 = new ContactRoot(listView3, UTF8("오프라인"), "1" );
	pRoot01->setPixmap( folderOpen );
	pRoot01->setOpen( config->readBoolEntry( "offline" , TRUE ) );
	if ( pRoot01->isOpen() )
		pRoot01->setPixmap( folderOpen );
	else
		pRoot01->setPixmap( folderClosed );
	
	ContactRoot* pRoot00 = new ContactRoot(listView3, UTF8("온라인"), "0" );
	pRoot00->setPixmap( folderOpen );
	pRoot00->setOpen( config->readBoolEntry( "online" , TRUE ) );
	if ( pRoot00->isOpen() )
		pRoot00->setPixmap( folderOpen );
	else
		pRoot00->setPixmap( folderClosed );
	
	int nOnlineCount = 0;
	int nOfflineCount = 0;
	QPtrListIterator<Buddy> itorBuddy(*pBuddyList);
	Buddy *pBuddy;
	while (itorBuddy.current() != 0)
	{
		pBuddy = itorBuddy.current();

		if ( pBuddy )
		{
			/// 차단리스트 => 차단 아이콘으로 표시
			// if (pBuddy->getBuddyFlag() == "1011") { ++itorBuddy;continue; }
			/// 목록에서 삭제
			// if (pBuddy->getBuddyFlag() == "0101") { ++itorBuddy;continue; }
			/// 친구 요청 중
			// if (pBuddy->getBuddyFlag() == "0001") { ++itorBuddy;continue; }
			/*! FL(Friend List) == 0 */
			if ( /* pBuddy->getBuddyFlag()[0] == '0' */  pBuddy->isFL() == false ) { ++itorBuddy;continue; }
			
			if ( pBuddy->getStatus() == "F" )
			{
				offlineBuddy.append( pBuddy );
				nOfflineCount++;
			}
			else
			{
				onlineBuddy.append( pBuddy );
				nOnlineCount++;
			}
		}
		++itorBuddy;
	}
	MyBuddyList  bList00( onlineBuddy );
	bList00.sort();
	QPtrListIterator<Buddy> itorBuddy00( bList00 );
	while (itorBuddy00.current() != 0)
	{
		pBuddy = itorBuddy00.current();
		ContactList* pNewBuddy = new ContactList( pRoot00 );
		pNewBuddy->setListParent(listView3);
		pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
		pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
		pNewBuddy->setText( 0, pBuddy->getName() );
		pNewBuddy->setText( 1, pBuddy->getGID() );
		pNewBuddy->setText( 2, pBuddy->getHandle() );
		pNewBuddy->setText( 3, pBuddy->getUID() );

		++itorBuddy00;
	}
	pRoot00->setTotalCount( nOnlineCount );

	MyBuddyList bList01( offlineBuddy );
	bList01.sort();
	QPtrListIterator<Buddy> itorBuddy01( bList01 );
	while (itorBuddy01.current() != 0)
	{
		pBuddy = itorBuddy01.current();
		ContactList* pNewBuddy = new ContactList( pRoot01 );
		pNewBuddy->setListParent(listView3);
		pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
		pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
		pNewBuddy->setText( 0, pBuddy->getName() );
		pNewBuddy->setText( 1, pBuddy->getGID() );
		pNewBuddy->setText( 2, pBuddy->getHandle() );
		pNewBuddy->setText( 3, pBuddy->getUID() );

		++itorBuddy01;
	}
	pRoot01->setTotalCount( nOfflineCount );
}

void KNateonMainview::slotUpdateMemoCount(int nMemoCount)
{
	if ( nMemoCount > 0 )
	{
		QString sMemoCount("(");
		sMemoCount += QString::number(nMemoCount);
		sMemoCount += ")";
		memoCountLabel->setText( sMemoCount );
		setMemoIcon(true);
	}
	else
	{
		memoCountLabel->setText("(0)");
		setMemoIcon(false);
	}
}

QListViewItem * KNateonMainview::getGroupItemByName(QString sName)
{
	QListViewItemIterator it( listView3 );
	for ( ; it.current(); ++it )
	{
		if ( it.current()->text(0).left( sName.length() ) == sName )
		{
#ifdef NETDEBUG
			kdDebug() << "sName : [" << sName << "], text(0) : [" << it.current()->text(0) << "]" << endl;
#endif
			return it.current();
		}
	}
	return 0;
}

void KNateonMainview::slotPBMemo()
{
	setMemoIcon( false );
	
	emit viewMemoBox();
}

void KNateonMainview::slotListSearch(const QString & sKeyword)
{
	Buddy *pBuddy;
	QStringList slHan;
	QStringList slBuddyList;

	if ( sKeyword.length() )
	{
		m_pSearchReset->show();
	}
	else {
		m_pSearchReset->hide();
	}

	/*! 버디 정렬을 위한 임시 리스트 변수 */
	QPtrList<Buddy> myBuddy;
	myBuddy.clear();

	listView3->clear();
	listView3->setSorting(-1);

	QPtrListIterator<Group> itorGroup(*pGroupList);
	Group * pGroup;
	QStringList slGroup;
	while (itorGroup.current() != 0)
	{
		pGroup = itorGroup.current();
		slGroup.append( pGroup->getGName() );
		++itorGroup;
	}

	pGroup = pGroupList->getGroupByName( UTF8("기타") );
	if ( !pGroup ) {
		pGroup = new Group( "0", UTF8("기타") );
		pGroupList->addGroup( pGroup );
	}

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

		if ( pBuddy )
		{
			if ( pBuddy->isFL() == false ) { 
				++iterBL;
				continue;
			}

/// 검색
			if ( ( pBuddy->getName().find( sKeyword ) == -1 ) &&
						    ( pBuddy->getNick().find( sKeyword ) == -1 ) ){
				++iterBL;
				continue;
						    }
						    myBuddy.append( pBuddy );

		}
#ifdef NETDEBUG
		else
		{
			kdDebug() << "555> Nothing handle value : " << *iterBL << endl;
		}
#endif
		++iterBL;
	}

	if ( myBuddy.count() > 0 )
	{
		ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
		pRoot->setPixmap( folderOpen );
		pRoot->setOpen(true);

		MyBuddyList bList( myBuddy );
		bList.sort();
		QPtrListIterator<Buddy> itorBuddy( bList );


		while (itorBuddy.current() != 0)
		{
			pBuddy = itorBuddy.current();
// pBuddy->setGID( pGroup->getGID() );

			QListViewItem* pGroupItem = 0;
			pGroupItem = listView3->findItem(pGroup->getGID(), 1, Qt::CaseSensitive);
			if ( pGroupItem == 0 )
			{
#ifdef NETDEBUG
				kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
				++itorBuddy;
				continue;
			}
			ContactList* pNewBuddy = new ContactList( pGroupItem );

			pNewBuddy->setListParent(listView3);
			pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
			pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
			pNewBuddy->setText( 0, pBuddy->getName() );
			pNewBuddy->setText( 1, pGroupItem->text(1) );
			pNewBuddy->setText( 2, pBuddy->getHandle() );
			pNewBuddy->setText( 3, pBuddy->getUID() );

			++itorBuddy;
		}
	}

	slGroup.sort();
	while ( !slGroup.isEmpty() )
	{
		/*! 임시 저장 변수 초기화 */
		myBuddy.clear();

		QString aa( slGroup.last() );
		/*! 한글 */
		if ( aa != UTF8("기타") )
		{
			if ( aa.lower() != aa.upper() )
			{
				pGroup = pGroupList->getGroupByName( aa );
				if ( !pGroup )
					continue;
				QPtrListIterator<Buddy> iterBL( pGroup->getBuddyList() );
				while( iterBL.current() != 0 )
				{
					pBuddy = iterBL.current();
					if ( pBuddy )
					{
						/*! FL(Friend List) == 0 */
						if ( pBuddy->isFL() == false ) { 
							++iterBL;
							continue;
						}

/// 검색
						if ( ( pBuddy->getName().find( sKeyword ) == -1 ) &&
										( pBuddy->getNick().find( sKeyword ) == -1 ) ){
							++iterBL;
							continue;
										}

										myBuddy.append( pBuddy );
					}
#ifdef NETDEBUG
					else
					{
						kdDebug() << "666> Nothing handle value : " << *iterBL << endl;
					}
#endif
					++iterBL;
				}
				if ( myBuddy.count() > 0 )
				{
					ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
					pRoot->setPixmap( folderOpen );
					pRoot->setOpen(true);

					MyBuddyList bList( myBuddy );
					bList.sort();
					QPtrListIterator<Buddy> itorBuddy( bList );
					while (itorBuddy.current() != 0)
					{
						pBuddy = itorBuddy.current();
// pBuddy->setGID( pGroup->getGID() );

						QListViewItem* pGroupItem = 0;
						pGroupItem = listView3->findItem(pGroup->getGID(), 1, Qt::CaseSensitive);
						if ( pGroupItem == 0 )
						{
#ifdef NETDEBUG
							kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
							++itorBuddy;
							continue;
						}
						ContactList* pNewBuddy = new ContactList( pGroupItem );
						pNewBuddy->setListParent(listView3);
						pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
						pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
						pNewBuddy->setText( 0, pBuddy->getName() );
						pNewBuddy->setText( 1, pGroupItem->text(1) );
						pNewBuddy->setText( 2, pBuddy->getHandle() );
						pNewBuddy->setText( 3, pBuddy->getUID() );

						++itorBuddy;
					}
				}
			}
			else
			{
				slHan.append( aa );
			}
		}
		slGroup.pop_back();
	}


	for ( QStringList::Iterator it = slHan.begin(); it != slHan.end(); ++it )
	{
		/*! 임시 저장 변수 초기화 */
		myBuddy.clear();
		/*! 한글 */
		if ( *it != UTF8("기타") )
		{
			if ( (*it).lower() == (*it).upper() )
			{
				pGroup = pGroupList->getGroupByName( *it );

				QPtrListIterator<Buddy> iterBL( pGroup->getBuddyList() );
				while( iterBL.current() != 0 )
				{
					pBuddy = iterBL.current();
					if ( pBuddy )
					{
						/*! FL(Friend List) == 0 */
						if ( pBuddy->isFL() == false ) {
							++iterBL;
							continue; 
						}

/// 검색
						if ( ( pBuddy->getName().find( sKeyword ) == -1 ) &&
										( pBuddy->getNick().find( sKeyword ) == -1 ) ){
							++iterBL;
							continue;
										}

										myBuddy.append( pBuddy );
					}
#ifdef NETDEBUG
					else
					{
						kdDebug() << "777> Nothing handle value : " << *it << endl;
					}
#endif
					++iterBL;
				}

				if ( myBuddy.count() > 0 )
				{
					ContactRoot* pRoot = new ContactRoot(listView3, pGroup->getGName(), pGroup->getGID() );
					pRoot->setPixmap( folderOpen );
					pRoot->setOpen(true);

					MyBuddyList bList( myBuddy );
					bList.sort();
					QPtrListIterator<Buddy> itorBuddy( bList );
					while (itorBuddy.current() != 0)
					{
						pBuddy = itorBuddy.current();
						pBuddy->setGID( pGroup->getGID() );

						QListViewItem* pGroupItem = 0;
						pGroupItem = listView3->findItem(pGroup->getGID(), 1, Qt::CaseSensitive);
						if ( pGroupItem == 0 )
						{
#ifdef NETDEBUG
							kdDebug() << "[KNateonMainview::slotAddFriend] Group 0 is nothing!" << endl;
#endif
							++itorBuddy;
							continue;
						}
						ContactList* pNewBuddy = new ContactList( pGroupItem );
						pNewBuddy->setListParent(listView3);
						pNewBuddy->setHasHompy( pBuddy->getCyworld_CMN() != "%00" );
						pNewBuddy->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
						pNewBuddy->setText( 0, pBuddy->getName() );
						pNewBuddy->setText( 1, pGroupItem->text(1) );
						pNewBuddy->setText( 2, pBuddy->getHandle() );
						pNewBuddy->setText( 3, pBuddy->getUID() );

						++itorBuddy;
					}
				}
			}
		}
	}
}


void KNateonMainview::slotListOnlyName()
{
	stConfig.typeofbuddylist = 0;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddyList", stConfig.typeofbuddylist );
	config->sync();
	slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateonMainview::slotListOnlyNick()
{
	stConfig.typeofbuddylist = 1;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddyList", stConfig.typeofbuddylist );
	config->sync();
	slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateonMainview::slotListNameID()
{
	stConfig.typeofbuddylist = 2;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddyList", stConfig.typeofbuddylist );
	config->sync();
	slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateonMainview::slotListNameNick()
{
	stConfig.typeofbuddylist = 3;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddyList", stConfig.typeofbuddylist );
	config->sync();
	slotEmoticonList( stConfig.viewemoticonlist );
}

/*!
 * added by luciferX2@gmail.com 20081103, for search
 */
void KNateonMainview::slotResetBuddyList()
{
	int nSort = stConfig.typeofbuddysort;

	lineEdit1->setText( UTF8("친구 검색하기") );
	lineEdit1->clearFocus();
	m_pSearchReset->hide();

	switch (nSort) {
		case 0:
			slotSortNormal();
			break;
		case 1:
			slotSortOnlyOnline();
			break;
		case 2:
			slotSortOnOffline();
			break;
	}
}

void KNateonMainview::slotSortNormal()
{
	/*!
	 * added by luciferX2@gmail.com 20081103, for search
	 */
	//if (bSearchMode) return;
	/*!
	  수정해야 함. 디폴트 정렬.
	*/
	sortGroupName( false );
	stConfig.typeofbuddysort = 0;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddySort", stConfig.typeofbuddysort );
	config->sync();
}

void KNateonMainview::slotSortOnlyOnline()
{
	/*!
	 * added by luciferX2@gmail.com 20081103, for search
	 */
	//if (bSearchMode) return;
	/*!
	  수정해야 함. 디폴트 정렬.
	*/
	sortGroupName( true );
	stConfig.typeofbuddysort = 1;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddySort", stConfig.typeofbuddysort );
	config->sync();
}

void KNateonMainview::slotSortOnOffline()
{
	/*!
	 * added by luciferX2@gmail.com 20081103, for search
	 */
	//if (bSearchMode) return;
	sortOnOffline();
	stConfig.typeofbuddysort = 2;

	config->setGroup( "BuddyList" );
	config->writeEntry( "Type_Of_BuddySort", stConfig.typeofbuddysort );
	config->sync();
}

void KNateonMainview::slotEmoticonList(bool bEmoticon)
{
	/*!
	 * added by luciferX2@gmail.com 20081103, for search
	 */
	//if (bSearchMode) return;
	
	stConfig.viewemoticonlist = bEmoticon;
	switch ( stConfig.typeofbuddysort )
	{
	case 0:
		slotSortNormal();
		break;
	case 1:
		slotSortOnlyOnline();
		break;
	case 2:
		slotSortOnOffline();
		break;
#ifdef NETDEBUG
	default:
		kdDebug() << "Not valid value!!!" << endl;
#endif
	}
}

QString KNateonMainview::getBuddyListName(Buddy * pBuddy, bool bEmoticon, unsigned short int nTypeOfBuddyList)
{
	Q_UNUSED( bEmoticon );
	QString sResult;

	/*! BL(Block List) == 1 일때 */
	if ( /* pBuddy->getBuddyFlag()[2] == '1' */ pBuddy->isBL() == true )
	{
		if ( pBuddy->getStatus() == "F" )
		{
			sResult = "<img src=\"" + sPicsPath + "main_list_state_cut_offline.png\"> ";
		}
		else
		{
			sResult = "<img src=\"" + sPicsPath + "main_list_state_cut_online.png\"> ";
		}
	}
	else
	{
		sResult = getStatusHTML( pBuddy->getStatus() );
	}
  
	QString sName( pBuddy->getName() );
	QString sNick( pBuddy->getNick() );

	/*! HTML 코드 수정 */
	// sNick.replace("&", "&amp;" );
	// sNick.replace(">", "&gt;");
	// sNick.replace("<", "&lt;");
  
	if ( stConfig.viewemoticonlist )
	{
		// if (!myEmoticon)
		//	myEmoticon = Emoticon::instance(); // myEmoticon = new Emoticon();
		Common::fixOutString( sNick );
	}
  
	switch ( nTypeOfBuddyList )
	{
	case 0: /*! 이름만 */
		sResult += "<font color=\"424242\"><B>";
		sResult += sName;
		sResult += "</B></font>";
		break;
	case 1: /*! 별명만  */
		sResult += "<font color=\"424242\"><B>";
		sResult += sNick;
		sResult += "</B></font>";
		break;
	case 2: /*! 이름 (ID) */
		sResult += "<font color=\"424242\"><B>";
		sResult += sName;
		sResult += "</B>";
		sResult += "(";
		sResult += pBuddy->getUID();
		sResult += ")</font>";
		break;
	case 3: /*! 이름 (별명) */
		sResult += "<font color=\"424242\"><B>";
		sResult += sName;
		sResult += "</B>";
		sResult += "(";
		sResult += sNick;
		sResult += ")</font>";
		break;
	}

	if ( pBuddy->getCyworld_CMN().length() > 0 )
	{
		if ( ( pBuddy->getCyworld_CMN().data() )[0] != '%' )
		{
			if ( pBuddy->isHompyNew() )
				sResult += "<img src=\"" + sPicsPath + "main_list_hompy_new.png\" width=18 height=18 />";
			else
				sResult += "<img src=\"" + sPicsPath + "main_list_hompy.png\" width=18 height=18 />";
		}
	}
	return sResult;
}

bool KNateonMainview::updateBuddy(Buddy * pBuddy)
{
	QListViewItemIterator it( listView3 );
	ContactList* c=0;
  
	for ( ; it.current(); ++it )
	{
		if ( it.current()->text(2) == pBuddy->getHandle() )
		{
			it.current()->setText( 0, pBuddy->getNick() );
			// it.current()->setText( 1, pBuddy->getGID() );
			// it.current()->setText( 2, pBuddy->getHandle() );
			// it.current()->setText( 3, pBuddy->getUID() );
			c = static_cast<ContactList*>( it.current() );
			c->setHTMLText( getBuddyListName( pBuddy, stConfig.viewemoticonlist, stConfig.typeofbuddylist ) );
		}
	}
	return true;
}

void KNateonMainview::slotFreeSMS()
{
	// KMessageBox::information( this, UTF8("서비스 준비중 입니다."), UTF8("무료문자"), 0, 0);
	QString sParam;
	sParam = "TICKET=";
	sParam += m_pCurrentAccount->getMyTicket();
	sParam += "&ID=";
	if ( m_pCurrentAccount->getMyLoginType() == 'N' )
		sParam += m_pCurrentAccount->getMyNateID();
	else
		sParam += m_pCurrentAccount->getMyCyworldID();
	sParam += "&mobile=";
	/*
	sParam += m_pCurrentAccount->getMyName();
	sParam += "|";
	sParam += m_pCurrentAccount->getMyPhone();
	*/
	
	QListViewItemIterator it( listView3 );
//	ContactList* c=0;

	QString sMobile;
	bool bTwo = FALSE;
	// QEucKrCodec *pEucKrCodec = new QEucKrCodec();
	QTextCodec *codec = QTextCodec::codecForName("eucKR"); 
	for ( ; it.current(); ++it )
	{
		if ( it.current()->isSelected () )
		{
			if ( static_cast<ContactBase *>( it.current() )->getType() == ContactBase::Buddy )
			{
				Buddy *pBuddy = pBuddyList->getBuddyByHandle( it.current()->text(2) );
				sMobile = pBuddy->getMobile();
				if ( sMobile.length() > 0 )
				{
					if ( bTwo )
						sParam += ";";
					sParam += codec->fromUnicode( pBuddy->getName() );
					sParam += "|";
					sParam += sMobile;
					bTwo = TRUE;
				}
			}
		}
	}

	URLEncode encode;
	sParam = encode.encode(sParam);
	
	QString sURL("http://br.nate.com/index.php");
	sURL += "?code=G047";
	sURL += "&param=";
	sURL += sParam;
#ifdef NETDEBUG
	kdDebug() << "문자창 [" << sURL << "]" << endl;
#endif
	LNMUtils::openURL( sURL );
}

void KNateonMainview::slotViewProfile()
{
	Buddy *pBuddy = getContactByItem( listView3->currentItem() );

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

/*!
 * 버디를 여러개 선택을 했는지 봄.
 */
bool KNateonMainview::isMultiSelected()
{
	QListViewItemIterator it( listView3 );
	int nCount = 0;
  
	for ( ; it.current(); ++it )
	{
		if ( it.current()->isSelected () )
			nCount++;
		if ( nCount > 1 )
			return TRUE;
	}
	return FALSE;
}

void KNateonMainview::slotGroupChat()
{
	ContactRoot *pRoot = static_cast<ContactRoot *>( getCurrentItem() );
	emit startGroupChat( pRoot );
}

void KNateonMainview::slotBlockGroup()
{
	ContactRoot *pRoot = static_cast<ContactRoot *>( getCurrentItem() );
	emit blockGroup( pRoot->text(1) );
}

void KNateonMainview::slotUnblockGroup()
{
	ContactRoot *pRoot = static_cast<ContactRoot *>( getCurrentItem() );
	emit unblockGroup( pRoot->text(1) );
}

void KNateonMainview::slotHompyNew()
{
	setHompyIcon(m_pCurrentAccount->isMyHompyNew());
	
	/*!
	 * 버디 리스트 Refresh
	 */
	slotEmoticonList( stConfig.viewemoticonlist );
}

void KNateonMainview::slotBuddyListClicked(QListViewItem * pSelectedItem)
{
	if ( !pSelectedItem )
		return;
	
  /*! 버디 리스트에서 그룹을 클릭 했으면 그룹 open/close */
  if ( static_cast<ContactBase *>( pSelectedItem )->getType() == ContactBase::Group )
  {
#ifdef NETDEBUG
    kdDebug() << "Group Click!" << endl;
#endif
    groupOpenClose( pSelectedItem );
  } else {
#ifdef NETDEBUG
    kdDebug() << "Buddy Click!" << endl;
#endif
    selectChanged( pSelectedItem );
  }
}

void KNateonMainview::slotSendMail()
{
	QListViewItemIterator it( listView3 );
	// QString sTo("mailto:");
	QString sTo;
	Buddy *pBuddy = 0;
	for ( ; it.current(); ++it ) {
		if ( it.current()->isSelected () ) {
			pBuddy = pBuddyList->getBuddyByHandle( it.current()->text(2) );
			if ( pBuddy ) {
				if ( sTo.length() > 8 ) {
					sTo += ";";
				}
				
				if ( pBuddy->getEmail() != "%00" ) {
					sTo += pBuddy->getEmail();
				} else {
					sTo += pBuddy->getUID();
				}
			}
			pBuddy = 0;
		}
	}
	// kdDebug() << "E-mail : ["<< sTo << "]" << endl;
	// new KRun( sTo.data() );
	LNMUtils::sendMail( sTo );
}

void KNateonMainview::selectChanged(QListViewItem * pSelectedItem)
{
	/*! XXXXXXXXXXXXXXXXX */

	QListViewItemIterator it( listView3 );
	int nBuddy = 0;
	int nGroup = 0;
	for ( ; it.current(); ++it )
	{
		if ( it.current()->isSelected () )
		{
			if ( static_cast<ContactBase *>( it.current() )->getType() == ContactBase::Buddy )
			{
				nBuddy++;
			}
			else
			{
				nGroup++;
			}
		}
	}

	if ( ( nBuddy > 0 ) && ( nGroup > 0 ) )
	{
		nGroup = 0;
		nBuddy = 0;
		listView3->clearSelection();
		if ( pSelectedItem ) {
			listView3->setSelected ( pSelectedItem, TRUE );
			if ( static_cast<ContactBase *>( pSelectedItem )->getType() == ContactBase::Group )
			{
#ifdef NETDEBUG
				kdDebug() << "Group" << endl;
#endif
				nGroup = 1;
				nBuddy = 0;
			}
			else
			{
#ifdef NETDEBUG
				kdDebug() << "Buddy" << endl;
#endif
				nGroup = 0;
				nBuddy = 1;
			}
		}
	}

	if ( nGroup > 1 )
	{
		nGroup = 0;
		nBuddy = 0;
		listView3->clearSelection();
		if ( pSelectedItem ) {
			listView3->setSelected ( pSelectedItem, TRUE );
			if ( static_cast<ContactBase *>( pSelectedItem )->getType() == ContactBase::Group )
			{
#ifdef NETDEBUG
				kdDebug() << "Group" << endl;
#endif
				nGroup = 1;
				nBuddy = 0;
			}
			else
			{
#ifdef NETDEBUG
				kdDebug() << "Buddy" << endl;
#endif
				nGroup = 0;
				nBuddy = 1;
			}
		}
	}

	nSelectBuddy = nBuddy;
	nSelectGroup = nGroup;
}

void KNateonMainview::groupOpenClose(QListViewItem * m_pSelectQLVI)
{
  /*! 그룹 Tree Open/Close 상태 저장. */
  config->setGroup("BuddyListTree");

  if ( m_pSelectQLVI->isOpen() )
  {
    m_pSelectQLVI->setOpen( FALSE );
    static_cast<ContactRoot*>(m_pSelectQLVI)->setPixmap( folderClosed );
    switch( stConfig.typeofbuddysort )
    {
      case 0:
      case 1:
        config->writeEntry( m_pSelectQLVI->text(1) , FALSE );
        break;
      case 2:
        if ( m_pSelectQLVI->text(1) == "0" )
          config->writeEntry( "online" , FALSE );
        else
          config->writeEntry( "offline" , FALSE );
        break;
    }
  }
  else
  {
    m_pSelectQLVI->setOpen( TRUE );
    static_cast<ContactRoot*>(m_pSelectQLVI)->setPixmap( folderOpen );
    switch( stConfig.typeofbuddysort )
    {
      case 0:
        config->writeEntry( m_pSelectQLVI->text(1) , TRUE );
        break;
      case 1:
        config->writeEntry( m_pSelectQLVI->text(1) , TRUE );
        break;
      case 2:
        if ( m_pSelectQLVI->text(1) == "0" )
          config->writeEntry( "online" , TRUE );
        else
          config->writeEntry( "offline" , TRUE );
        break;
    }
  }
  config->sync();
}

