/***************************************************************************
                          dcoptions.cpp  -  description
                             -------------------
    begin                : Sun Feb 24 2002
    copyright            : (C) 2002 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "dcoptions.h"

#include <QDir>
#include <QDialog>
#include <QLineEdit>
#include <QTextEdit>
#include <QComboBox>
#include <QListWidget>
#include <QTabWidget>
#include <QCheckBox>
#include <QRadioButton>
#include <QPushButton>
#include <QFileDialog>
#include <QLabel>
#include <QMessageBox>
#include <QSpinBox>
#include <QStyleFactory>
#include <QApplication>
#include <QInputDialog>
#include <QFontDialog>
#include <QLayout>
#include <QColorDialog>
#include <QToolButton>
#include <QImage>
#include <QCursor>
#include <QTextCodec>
#include <QPixmap>
#include <QProcess>
#include <QHeaderView>
#include <QHttp>
#include <QHostAddress>
#include <QStyle>
#include <QFile>
#include <QFileInfo>
#include <QInputDialog>

#include <dclib/core/cstring.h>
#include <dclib/core/cnetaddr.h>
#include <dclib/core/cdir.h>
#include <dclib/cfilemanager.h>

#include "dcmenuhandler.h"
#include "dciconloader.h"
#include "dctransferview.h"
#include "dcdownloadalias.h"

#include "DCDialogEditSharePath.h"

#include "dcusercommandeditor.h"
#include "dcguiutils.h"

#include <dclib/dcos.h>
#include <math.h>

/* need PACKAGE_VERSION for HTTP User-Agent */
#ifdef HAVE_CONFIG_H
#include <config.h>
#else
#define PACKAGE_VERSION "Unknown"
#endif

#define TAB_IDENTIFY		0
#define TAB_TRANSFER		1
#define TAB_CONNECTION		2
#define TAB_GUI			3
#define TAB_SOUND		4
#define TAB_LOG			5
#define TAB_HUBLISTS		6
#define TAB_SECURITY		7
#define TAB_AUTO_RESPONSES	8
#define TAB_OTHER		9

#define TAB_TRANSFER_SHARES	0
#define TAB_TRANSFER_DOWNLOADS	1
#define TAB_TRANSFER_UPLOADS	2
#define TAB_TRANSFER_SETTINGS	3

#define TAB_CONNECTION_MODE	0
#define TAB_CONNECTION_SETTINGS	1

#define TAB_GUI_GENERAL		0
#define TAB_GUI_TRANSFER	1
#define TAB_GUI_CHAT		2
#define TAB_GUI_COLORS		3
#define TAB_GUI_COMMANDS	4
#define TAB_GUI_MENUS		5
#define TAB_GUI_CLIENT		6
#define TAB_GUI_ICONS		7
#define TAB_GUI_FILELIST	8

/** */
DCOptions::DCOptions(QWidget * parent) : QDialog(parent) {
    m_pHttp = 0;

    setupUi(this);

    /* icons moved out of .ui files so that they can be themed */
    QIcon browsefolder(DCIconLoader::Instance()->GetPixmap(eiFOLDER_BLUE_OPEN));
    QIcon editadd(DCIconLoader::Instance()->GetPixmap(eiEDITADD));
    QIcon editdelete(DCIconLoader::Instance()->GetPixmap(eiEDITDELETE));
    QIcon editedit(DCIconLoader::Instance()->GetPixmap(eiEDIT));
    QIcon play(DCIconLoader::Instance()->GetPixmap(eiPLAYER_PLAY));
    ToolButton_BROWSEDOWNLOADFINISHEDFOLDER->setIcon(browsefolder);
    ToolButton_BROWSEDOWNLOADFOLDER->setIcon(browsefolder);
    ToolButton_CREATESHARELIST->setIcon(QIcon(DCIconLoader::Instance()->GetPixmap(eiRELOAD)));
    ToolButton_BROWSEFILELIST->setIcon(QIcon(DCIconLoader::Instance()->GetPixmap(eiVIEW_SIDETREE)));
    ToolButton_SHARELISTINFO->setIcon(QIcon(DCIconLoader::Instance()->GetPixmap(eiINFO)));
    ToolButton_ADDSHAREDFOLDER->setIcon(editadd);
    ToolButton_REMOVESHAREDFOLDER->setIcon(editdelete);
    ToolButton_EDITSHAREDFOLDER->setIcon(editedit);
    ToolButton_BROWSELANGUAGEFILE->setIcon(browsefolder);
    ToolButton_SELECTLANGUAGE->setIcon(QIcon(DCIconLoader::Instance()->GetPixmap(eiCHOOSE_LANGUAGE)));
    ToolButton_BROWSEAPPFONT->setIcon(browsefolder);
    ToolButton_BROWSEDATAFOLDER->setIcon(browsefolder);
    ToolButton_BROWSEBROWSER->setIcon(browsefolder);
    ToolButton_ADD_USER_MENU_COMMAND->setIcon(editadd);
    ToolButton_EDIT_USER_MENU_COMMAND->setIcon(editedit);
    ToolButton_REMOVE_USER_MENU_COMMAND->setIcon(editdelete);
    ToolButton_BROWSESOUNDPLAYER->setIcon(browsefolder);
    ToolButton_BROWSESOUNDFILEDISCONNECT->setIcon(browsefolder);
    ToolButton_BROWSESOUNDFILESEND->setIcon(browsefolder);
    ToolButton_BROWSESOUNDFILERECEIVE->setIcon(browsefolder);
    ToolButton_BROWSESOUNDFILEFIRSTRECEIVE->setIcon(browsefolder);
    ToolButton_BROWSESOUNDFILECONNECT->setIcon(browsefolder);
    ToolButton_BROWSESOUNDFILENICKMENTIONED->setIcon(browsefolder);
    ToolButton_PREVIEWSOUNDFILECONNECT->setIcon(play);
    ToolButton_PREVIEWSOUNDFILEDISCONNECT->setIcon(play);
    ToolButton_PREVIEWSOUNDFILESEND->setIcon(play);
    ToolButton_PREVIEWSOUNDFILERECEIVE->setIcon(play);
    ToolButton_PREVIEWSOUNDFILEFIRSTRECEIVE->setIcon(play);
    ToolButton_PREVIEWSOUNDFILENICKMENTIONED->setIcon(play);
    ToolButton_BROWSELOGFILE->setIcon(browsefolder);
    ToolButton_LOGCHAT_NICKNAMEFILTER_ADD->setIcon(editadd);
    ToolButton_LOGCHAT_NICKNAMEFILTER_DEL->setIcon(editdelete);
    ToolButton_ADDHUBLISTURL->setIcon(editadd);
    ToolButton_EDITHUBLISTURL->setIcon(editedit);
    ToolButton_REMOVEHUBLISTURL->setIcon(editdelete);
    ToolButton_BROWSETRANSFERCERT->setIcon(browsefolder);
    ToolButton_BROWSETRANSFERKEY->setIcon(browsefolder);
    ToolButton_BROWSE_DCLIB_PLUGIN_PATH->setIcon(browsefolder);
    toolButton_ADDALIAS->setIcon(editadd);
    toolButton_REMALIAS->setIcon(editdelete);

    // set default icon
    setWindowIcon(DCIconLoader::Instance()->GetPixmap(eiCONFIGURE));

    InitDocument();
}

/** */
DCOptions::~DCOptions() {
    /* If they were saved, the map is empty */
    for (QMap<int, DC_UserMenuCommand*>::const_iterator it = usercommands.constBegin(); it != usercommands.constEnd(); ++it) {
        delete it.value();
    }
    usercommands.clear();

    if (m_pHttp) {
        disconnect(m_pHttp, SIGNAL(done(bool)), this, SLOT(slotGotInternetIP(bool)));
        m_pHttp->abort(); // emits done signal
        delete m_pHttp;
    }

    QTreeWidgetItemIterator it(treeWidget_DOWNLOADALIASES, QTreeWidgetItemIterator::NotHidden);

    while (*it) {
	if (*it)
	    delete *it;
	++it;
    }
}

/** */
void DCOptions::InitDocument() {
    // insert speed
    ComboBox_SPEED->addItem("28.8Kbps");
    ComboBox_SPEED->addItem("33.6Kbps");
    ComboBox_SPEED->addItem("56Kbps");
    ComboBox_SPEED->addItem("Modem");
    ComboBox_SPEED->addItem("Satellite");
    ComboBox_SPEED->addItem("ISDN");
    ComboBox_SPEED->addItem("DSL");
    ComboBox_SPEED->addItem("Cable");
    ComboBox_SPEED->addItem("LAN(T1)");
    ComboBox_SPEED->addItem("LAN(T3)");
    ComboBox_SPEED->addItem("Microwave");
    ComboBox_SPEED->addItem("Wireless");
    ComboBox_SPEED->addItem("0.005");
    ComboBox_SPEED->addItem("0.01");
    ComboBox_SPEED->addItem("0.02");
    ComboBox_SPEED->addItem("0.05");
    ComboBox_SPEED->addItem("0.1");
    ComboBox_SPEED->addItem("0.2");
    ComboBox_SPEED->addItem("0.5");
    ComboBox_SPEED->addItem("1");
    ComboBox_SPEED->addItem("2");
    ComboBox_SPEED->addItem("5");
    ComboBox_SPEED->addItem("10");
    ComboBox_SPEED->addItem("20");
    ComboBox_SPEED->addItem("50");
    ComboBox_SPEED->addItem("100");
    ComboBox_SPEED->addItem("1000");

    DCGuiUtils::AddEncodings(ComboBox_REMOTE_ENCODING);

    // set width mode
    // QT3 ListView_OPTIONTREE->setColumnWidthMode( 0, Q3ListView::Maximum );
    // hide the column header
    TreeWidget_OPTIONTREE->header()->hide();

    // set up icons theme lists
    setupIconThemeComboBoxes();

    // setup the option tree
    plviIdentify = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviIdentify->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiUSERS)));
    plviIdentify->setText(0, tr("Identify"));

    plviTransfer = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviTransfer->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiTRANSFER)));
    plviTransfer->setText(0, tr("Transfer"));
    plviTransfer->setExpanded(true);
    plviTransfer->setFlags(Qt::ItemIsEnabled);
    plviTransferShares = new QTreeWidgetItem(plviTransfer);
    plviTransferShares->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiFOLDER_BLUE)));
    plviTransferShares->setText(0, tr("Shares"));
    plviTransferDownloads = new QTreeWidgetItem(plviTransfer);
    plviTransferDownloads->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiDOWN)));
    plviTransferDownloads->setText(0, tr("Downloads"));
    plviTransferUploads = new QTreeWidgetItem(plviTransfer);
    plviTransferUploads->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiUP)));
    plviTransferUploads->setText(0, tr("Uploads"));
    plviTransferSettings = new QTreeWidgetItem(plviTransfer);
    plviTransferSettings->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiCONFIGURE)));
    plviTransferSettings->setText(0, tr("Settings"));

    plviConnection = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviConnection->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiCONNECT)));
    plviConnection->setText(0, tr("Connection"));
    plviConnection->setExpanded(true);
    plviConnection->setFlags(Qt::ItemIsEnabled);
    plviConnectionMode = new QTreeWidgetItem(plviConnection);
    plviConnectionMode->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiSUPPORT)));
    plviConnectionMode->setText(0, tr("Mode"));
    plviConnectionSettings = new QTreeWidgetItem(plviConnection);
    plviConnectionSettings->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiQUICKOPTIONS)));
    plviConnectionSettings->setText(0, tr("Settings"));

    plviGUI = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviGUI->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiGUI)));
    plviGUI->setText(0, tr("GUI"));
    plviGUI->setExpanded(true);
    plviGUI->setFlags(Qt::ItemIsEnabled);
    plviGUIGeneral = new QTreeWidgetItem(plviGUI);
    plviGUIGeneral->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiCHOOSE_LANGUAGE)));
    plviGUIGeneral->setText(0, tr("General"));
    plviGUITransfer = new QTreeWidgetItem(plviGUI);
    plviGUITransfer->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiTRANSFER)));
    plviGUITransfer->setText(0, tr("Transfer"));
    plviGUIChat = new QTreeWidgetItem(plviGUI);
    plviGUIChat->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiCHAT)));
    plviGUIChat->setText(0, tr("Chat"));
    plviGUIColors = new QTreeWidgetItem(plviGUI);
    plviGUIColors->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiCOLORS)));
    plviGUIColors->setText(0, tr("Colors"));
    plviGUICommands = new QTreeWidgetItem(plviGUI);
    plviGUICommands->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiRELOAD_PLUGINS)));
    plviGUICommands->setText(0, tr("Commands"));
    plviGUIMenus = new QTreeWidgetItem(plviGUI);
    plviGUIMenus->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiMENU)));
    plviGUIMenus->setText(0, tr("Menus"));
    plviGUIClient = new QTreeWidgetItem(plviGUI);
    plviGUIClient->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiCLIENT)));
    plviGUIClient->setText(0, tr("Client"));
    plviGUIIcons = new QTreeWidgetItem(plviGUI);
    plviGUIIcons->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiICONS)));
    plviGUIIcons->setText(0, tr("Icons"));
    plviGUIFilelistBrowser = new QTreeWidgetItem(plviGUI);
    plviGUIFilelistBrowser->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiTEXT_SELECT_ALL)));
    plviGUIFilelistBrowser->setText(0, tr("Filelist browser"));

    plviSound = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviSound->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiINFO)));
    plviSound->setText(0, tr("Notifications"));

    plviLog = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviLog->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiLOG)));
    plviLog->setText(0, tr("Log"));

    plviHubLists = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviHubLists->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiTEXT_SELECT_ALL)));
    plviHubLists->setText(0, tr("Hub Lists"));

    plviSecurity = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviSecurity->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiSSL_YES)));
    plviSecurity->setText(0, tr("Security"));

    plviAutoResponse = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviAutoResponse->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiVRU)));
    plviAutoResponse->setText(0, tr("Auto Responses"));

    plviOther = new QTreeWidgetItem(TreeWidget_OPTIONTREE);
    plviOther->setIcon(0, QIcon(DCIconLoader::Instance()->GetPixmap(eiOTHER)));
    plviOther->setText(0, tr("Other"));

    connect(ToolButton_PHOTO, SIGNAL(clicked()), this, SLOT(slotChangePhoto()));

    connectOptionsTreeWidget();

    TrayMessageType t_type = DCConfig::Instance()->GetTrayMessageType();

    if (IS_TRAY_MSG_NONE(t_type)) {
        checkBox_ENABLENOTIFY->setChecked(false);

        checkBox_PRIVATE->setEnabled(false);
        checkBox_NICKINCHAT->setEnabled(false);
        checkBox_CONNECTIONLOST->setEnabled(false);
        checkBox_WNDACTV->setEnabled(false);
    } else
        checkBox_ENABLENOTIFY->setChecked(true);

    checkBox_CONNECTIONLOST->setChecked(IS_TRAY_MSG_DISC(t_type));
    checkBox_PRIVATE->setChecked(IS_TRAY_MSG_PRIV(t_type));
    checkBox_NICKINCHAT->setChecked(IS_TRAY_MSG_NICK(t_type));
    checkBox_WNDACTV->setChecked(IS_TRAY_WND_ACTV(t_type));
    checkBox_WNDVSBL->setChecked(IS_TRAY_WND_VSBL(t_type));

    connect(checkBox_ENABLENOTIFY, SIGNAL(clicked()), this, SLOT(slotTrayMessageType()));
    connect(checkBox_PRIVATE, SIGNAL(clicked()), this, SLOT(slotTrayMessageType()));
    connect(checkBox_NICKINCHAT, SIGNAL(clicked()), this, SLOT(slotTrayMessageType()));
    connect(checkBox_CONNECTIONLOST, SIGNAL(clicked()), this, SLOT(slotTrayMessageType()));
    connect(checkBox_WNDACTV, SIGNAL(clicked()), this, SLOT(slotTrayMessageType()));
    connect(checkBox_WNDVSBL, SIGNAL(clicked()), this, SLOT(slotTrayMessageType()));

    connect(stackedWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabWidgetDCGUICurrentChanged(int)));
    connect(TabWidget_TRANSFER, SIGNAL(currentChanged(int)), this, SLOT(slotTabWidgetTransferCurrentChanged(int)));
    connect(TabWidget_CONNECTION, SIGNAL(currentChanged(int)), this, SLOT(slotTabWidgetConnectionCurrentChanged(int)));
    connect(TabWidget_GUI, SIGNAL(currentChanged(int)), this, SLOT(slotTabWidgetGUICurrentChanged(int)));

    connect(ToolButton_ADD_USER_MENU_COMMAND, SIGNAL(clicked()), this, SLOT(slotAddUserMenuCommand()));
    connect(ToolButton_EDIT_USER_MENU_COMMAND, SIGNAL(clicked()), this, SLOT(slotEditUserMenuCommand()));
    connect(ToolButton_REMOVE_USER_MENU_COMMAND, SIGNAL(clicked()), this, SLOT(slotRemoveUserMenuCommand()));
    connect(ToolButton_UP_USER_MENU_COMMAND, SIGNAL(clicked()), this, SLOT(slotUpUserMenuCommand()));
    connect(ToolButton_DOWN_USER_MENU_COMMAND, SIGNAL(clicked()), this, SLOT(slotDownUserMenuCommand()));
    connect(TreeWidget_MENU_COMMANDS, SIGNAL(itemSelectionChanged()), this, SLOT(slotUserMenuCommandsSelectionChanged()));
    connect(TreeWidget_MENU_COMMANDS, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(slotUserMenuCommandsDoubleClicked(QTreeWidgetItem *, int)));

    connect(TreeWidget_CHAT_COMMANDS, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(slotContextMenuUserChatCommands(const QPoint &)));

    connect(TreeWidget_AUTO_RESPONSES, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(slotContextMenuAutoResponses(const QPoint &)));

    connect(ToolButton_BROWSESOUNDFILECONNECT, SIGNAL(clicked()), this, SLOT(slotBrowseSoundFileConnect()));
    connect(ToolButton_BROWSESOUNDFILEDISCONNECT, SIGNAL(clicked()), this, SLOT(slotBrowseSoundFileDisconnect()));
    connect(ToolButton_BROWSESOUNDFILESEND, SIGNAL(clicked()), this, SLOT(slotBrowseSoundFileSend()));
    connect(ToolButton_BROWSESOUNDFILERECEIVE, SIGNAL(clicked()), this, SLOT(slotBrowseSoundFileReceive()));
    connect(ToolButton_BROWSESOUNDFILEFIRSTRECEIVE, SIGNAL(clicked()), this, SLOT(slotBrowseSoundFileFirstReceive()));
    connect(ToolButton_BROWSESOUNDFILENICKMENTIONED, SIGNAL(clicked()), this, SLOT(slotBrowseSoundFileNickMentioned()));

    connect(ToolButton_PREVIEWSOUNDFILECONNECT, SIGNAL(clicked()), this, SLOT(slotPreviewSoundFileConnect()));
    connect(ToolButton_PREVIEWSOUNDFILEDISCONNECT, SIGNAL(clicked()), this, SLOT(slotPreviewSoundFileDisconnect()));
    connect(ToolButton_PREVIEWSOUNDFILESEND, SIGNAL(clicked()), this, SLOT(slotPreviewSoundFileSend()));
    connect(ToolButton_PREVIEWSOUNDFILERECEIVE, SIGNAL(clicked()), this, SLOT(slotPreviewSoundFileReceive()));
    connect(ToolButton_PREVIEWSOUNDFILEFIRSTRECEIVE, SIGNAL(clicked()), this, SLOT(slotPreviewSoundFileFirstReceive()));
    connect(ToolButton_PREVIEWSOUNDFILENICKMENTIONED, SIGNAL(clicked()), this, SLOT(slotPreviewSoundFileNickMentioned()));

	connect(RadioButton_ACTIVEMODE,SIGNAL(toggled(bool)),ButtonGroup_ACTIVEMODESETTINGS,SLOT(setEnabled(bool)));
	connect(RadioButton_PASSIVEMODE,SIGNAL(toggled(bool)),ButtonGroup_PASSIVEMODESETTINGS,SLOT(setEnabled(bool)));
	connect(RadioButton_IPHOSTNAME,SIGNAL(toggled(bool)),PushButton_GETINTERNETIP,SLOT(setEnabled(bool)));
	connect(RadioButton_INTERFACE,SIGNAL(toggled(bool)),PushButton_GETINTERFACE,SLOT(setEnabled(bool)));
	connect(CheckBox_AUTOAWAYMODE,SIGNAL(toggled(bool)),Frame_AUTOAWAYTIME,SLOT(setEnabled(bool)));
	connect(CheckBox_CHATSHOWJOINSANDPARTS,SIGNAL(toggled(bool)),CheckBox_CHATSHOWJOINSANDPARTSONLYFAV,SLOT(setEnabled(bool)));
	connect(CheckBox_SENDUNKNOWNCOMMANDS,SIGNAL(toggled(bool)),LineEdit_ALLOWED_UNKNOWN_COMMANDS,SLOT(setDisabled(bool)));
	connect(CheckBox_ENABLE_ZPIPE,SIGNAL(toggled(bool)),CheckBox_ENABLE_ZPIPE,SLOT(setEnabled(bool)));
	connect(checkBox_PRIVATE,SIGNAL(toggled(bool)),spinBox_NOTIFYLENGTHPRIV,SLOT(setEnabled(bool)));
	connect(checkBox_NICKINCHAT,SIGNAL(toggled(bool)),spinBox_NOTIFYLENGTHNICK,SLOT(setEnabled(bool)));
	connect(checkBox_CONNECTIONLOST,SIGNAL(toggled(bool)),spinBox_NOTIFYLENGTHDISC,SLOT(setEnabled(bool)));

    connect(toolButton_ADDALIAS, SIGNAL(clicked()), this, SLOT(slotAddDownloadAlias()));
    connect(toolButton_REMALIAS, SIGNAL(clicked()), this, SLOT(slotRemDownloadAlias()));

    connect(ToolButton_BROWSESOUNDPLAYER, SIGNAL(clicked()), this, SLOT(slotBrowseSoundPlayer()));

    // Transfer->Folder
    connect(ToolButton_BROWSEDOWNLOADFOLDER, SIGNAL(clicked()), this, SLOT(slotBrowseDownloadFolder()));
    connect(ToolButton_BROWSEDOWNLOADFINISHEDFOLDER, SIGNAL(clicked()), this, SLOT(slotBrowseDownloadFinishedFolder()));

    connect(ToolButton_CREATESHARELIST, SIGNAL(clicked()), this, SLOT(slotCreateShareList()));
    connect(ToolButton_BROWSEFILELIST, SIGNAL(clicked()), this, SLOT(slotBrowseShareList()));
    connect(ToolButton_SHARELISTINFO, SIGNAL(clicked()), this, SLOT(slotShareListInfo()));
    connect(ToolButton_ADDSHAREDFOLDER, SIGNAL(clicked()), this, SLOT(slotAddSharedFolder()));
    connect(ToolButton_REMOVESHAREDFOLDER, SIGNAL(clicked()), this, SLOT(slotRemoveSharedFolder()));
    connect(ToolButton_EDITSHAREDFOLDER, SIGNAL(clicked()), this, SLOT(slotEditSharedFolder()));

    connect(TreeWidget_SHAREDFOLDERS, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(slotDoubleClickedSharedFolder(QTreeWidgetItem *, int)));
    connect(TreeWidget_SHAREDFOLDERS, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(slotContextMenuSharedFolder(const QPoint &)));
    connect(TreeWidget_SHAREDFOLDERS, SIGNAL(itemSelectionChanged()), this, SLOT(slotSharedFoldersSelectionChanged()));

    connect(PushButton_TESTHOST, SIGNAL(clicked()), this, SLOT(slotTestHost()));
    connect(PushButton_GETINTERFACE, SIGNAL(clicked()), this, SLOT(slotGetInterface()));
    connect(PushButton_GETINTERNETIP, SIGNAL(clicked()), this, SLOT(slotGetInternetIP()));

    // GUI->General
    connect(ToolButton_BROWSELANGUAGEFILE, SIGNAL(clicked()), this, SLOT(slotBrowseLanguageFile()));
    connect(ToolButton_SELECTLANGUAGE, SIGNAL(clicked()), this, SLOT(slotSelectLanguage()));
    connect(PushButton_SETTHEME, SIGNAL(clicked()), this, SLOT(slotSetTheme()));
    connect(ToolButton_BROWSEAPPFONT, SIGNAL(clicked()), this, SLOT(slotBrowseAppFont()));
    connect(ToolButton_BROWSEDATAFOLDER, SIGNAL(clicked()), this, SLOT(slotBrowseDataFolder()));

    // GUI->Chat
    connect(ToolButton_BROWSEBROWSER, SIGNAL(clicked()), this, SLOT(slotBrowseBrowser()));
    connect(ListBox_CHATCOLOR, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotDoubleClickedChatColor(QListWidgetItem *)));
    connect(ToolButton_CHAT_BG_COLOR, SIGNAL(clicked()), this, SLOT(slotBackgroundColorDialog()));
    connect(ToolButton_REVERSE_COLORS, SIGNAL(clicked()), this, SLOT(slotReverseChatColors()));

    // LOG->Chat
    connect(ToolButton_LOGCHAT_NICKNAMEFILTER_ADD, SIGNAL(clicked()), this, SLOT(slotLogChatAddNickNameFilter()));
    connect(ToolButton_LOGCHAT_NICKNAMEFILTER_DEL, SIGNAL(clicked()), this, SLOT(slotLogChatDelNickNameFilter()));

    //
    connect(ToolButton_BROWSETRANSFERCERT, SIGNAL(clicked()), this, SLOT(slotBrowseTransferCert()));
    connect(ToolButton_BROWSETRANSFERKEY, SIGNAL(clicked()), this, SLOT(slotBrowseTransferKey()));
    connect(ToolButton_BROWSE_DCLIB_PLUGIN_PATH, SIGNAL(clicked()), this, SLOT(slotBrowseDclibPluginFolder()));

    // Hub List
    connect(ToolButton_ADDHUBLISTURL, SIGNAL(clicked()), this, SLOT(slotAddHubListUrl()));
    connect(ToolButton_EDITHUBLISTURL, SIGNAL(clicked()), this, SLOT(slotEditHubListUrl()));
    connect(ToolButton_REMOVEHUBLISTURL, SIGNAL(clicked()), this, SLOT(slotRemoveHubListUrl()));

    connect(ListWidget_HUBLISTURL, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotDoubleClickedHubListUrl(QListWidgetItem *)));
    connect(ListWidget_HUBLISTURL, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(slotContextMenuHubListUrl(const QPoint &)));
    connect(ListWidget_HUBLISTURL, SIGNAL(itemSelectionChanged()), this, SLOT(slotHubListUrlsSelectionChanged()));

    connect(CheckBox_SOUNDDISABLED, SIGNAL(clicked()), this, SLOT(slotDisableSound()));

    connect(ToolButton_BROWSELOGFILE, SIGNAL(clicked()), this, SLOT(slotBrowseLogFile()));

    connect(PushButton_GENERATE_CERT, SIGNAL(clicked()), this, SLOT(slotGenerateKeyCert()));

    // style options
    ComboBox_THEME->clear();

    if (DCConfig::Instance()->GetThemeSupport()) {
        QStringList list = QStyleFactory::keys();

        if (list.count() > 0) {
            list.sort();
            ComboBox_THEME->addItems(list);
            list.clear();
        }
    } else {
        // disable the theme support
        ComboBox_THEME->setEnabled(false);
        PushButton_SETTHEME->setEnabled(false);
    }

    loadDownloadAliases();
}

/** */
void DCOptions::connectOptionsTreeWidget() {
    connect(TreeWidget_OPTIONTREE, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(slotTreeWidgetOptionTreeCurrentChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
}

/** */
void DCOptions::disconnectOptionsTreeWidget() {
    disconnect(TreeWidget_OPTIONTREE, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(slotTreeWidgetOptionTreeCurrentChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
}

/** */
void DCOptions::accept() {
    if (LineEdit_DOWNLOADFOLDER->text().isEmpty()) {
        QMessageBox::critical(this, "EiskaltDC",
                tr("You must set a Download Folder!"));
        return;
    }

    if (LineEdit_DOWNLOADFINISHEDFOLDER->text() == LineEdit_DOWNLOADFOLDER->text()) {
        QMessageBox::critical(this, "EiskaltDC",
                tr("Download Finished Folder and Download Folder must be different!"));
        return;
    }

    // check active mode settings
    if (RadioButton_ACTIVEMODE->isChecked()) {
        // check fake host
        if (RadioButton_IPHOSTNAME->isChecked() &&
                (LineEdit_IP->text().isEmpty()))
 {
            QMessageBox::critical(this, "EiskaltDC",
                    tr("You must enter a valid 'Fake Host'!"));
            return;
        }

        // check interface
        if (RadioButton_INTERFACE->isChecked() &&
                (LineEdit_IP->text().isEmpty()))
 {
            QMessageBox::critical(this, "EiskaltDC",
                    tr("You must enter a valid interface!"));
            return;
        }

#ifndef WIN32
        if ((SpinBox_TCPLISTENPORT->value() < 1024) || (SpinBox_CRYPTO_PORT->value() < 1024) || (SpinBox_UDPLISTENPORT->value() < 1024)) {
            QMessageBox::critical(this, "EiskaltDC",
                    tr("You have set EiskaltDC to listen on a port < 1024! You can run EiskaltDC only as root in active mode!"));
        }
#endif
    }

    // no nick is given
    if (LineEdit_NICK->text().isEmpty()) {
        QMessageBox::critical(this, "EiskalDC",
                tr("You must enter a valid nick!"));
        return;
    }

    // no search nick is given
    if ((LineEdit_SEARCHNICK->text().isEmpty()) || (LineEdit_SEARCHNICK->text() == "nick_search")) {
        QMessageBox::critical(this, "EiskaltDC",
                tr("You must enter a valid search nick!"));
        return;
    }

    if (SpinBox_TCPLISTENPORT->value() == SpinBox_CRYPTO_PORT->value()) {
        QMessageBox::critical(
                this,
                "EiskaltDC",
                tr("Standard and encrypted port must be different.")
                );
        return;
    }

    /* Warn about using certain options */
    QString recommended, notrecommended;

    if (!CheckBox_DESCRIPTION_TAG->isChecked() && DCConfig::Instance()->GetDescriptionTag()) {
        recommended += CheckBox_DESCRIPTION_TAG->text();
        recommended += '\n';
    }

    if (!CheckBox_EXT_HUB_COUNT->isChecked() && DCConfig::Instance()->GetUseExtendedHubCount()) {
        recommended += CheckBox_EXT_HUB_COUNT->text();
        recommended += '\n';
    }

    if (CheckBox_DISABLEHASHLIST->isChecked() && !DCConfig::Instance()->GetDisableHashList()) {
        notrecommended += CheckBox_DISABLEHASHLIST->text();
        notrecommended += '\n';
    }

    if (CheckBox_ENABLE_ZPIPE->isChecked() && !DCConfig::Instance()->GetZPipeEnabled()) {
        notrecommended += CheckBox_ENABLE_ZPIPE->text();
        notrecommended += '\n';
    }

    /* possibly also check compressed and encrypted transfers, they are not very useful */
    /* the auto responder really should not have been added but it is GUI only so unlikely to break anything */

    if (!recommended.isEmpty() || !notrecommended.isEmpty()) {
        QString msg;
        if (!recommended.isEmpty()) {
            msg += tr("These options are recommended:\n");
            msg += recommended;
        }

        if (!notrecommended.isEmpty()) {
            msg += "\n";
            msg += tr("These options are not recommended:\n");
            msg += notrecommended;
        }

        if (QMessageBox::warning(
                this,
                tr("Settings Problems"),
                msg,
                QMessageBox::Ignore | QMessageBox::Cancel,
                QMessageBox::Ignore
                ) == QMessageBox::Cancel) {
            return;
        }
    }

    if (GroupBox_APPFONT->isChecked()) {
        if ((!(LineEdit_APPFONT->text().isEmpty())) && (LineEdit_APPFONT->text() != DCConfig::Instance()->GetAppFont())) {
            QFont font;
            if (font.fromString(LineEdit_APPFONT->text())) {
                QApplication::setFont(font);
            }
        }
    }

    QDialog::accept();
}

/** */
void DCOptions::SetUserPhoto(QString filename) {
    QImage im;

    if (!filename.isEmpty()) {
        if (im.load(filename)) {
            if ((im.width() > 32) ||
                    (im.height() > 32)) {
                im = im.scaled(32, 32, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            }

            if (im.depth() > 8)
                im = im.convertToFormat(QImage::Format_Indexed8);

            if (im.numColors() > 256)
                im.setNumColors(256);

            if (im.save((DCConfig::Instance()->GetConfigPath() + "photo.png").Data(), "PNG", 0) == false) {
                QMessageBox::critical(this, "EiskaltDC", tr("Can't save Image!"));
            } else {
                ToolButton_PHOTO->setIcon(QIcon(QPixmap::fromImage(im)));
                // ToolButton_PHOTO->setTextLabel(filename);
                ToolButton_PHOTO->setText((DCConfig::Instance()->GetConfigPath() + "photo.png").Data());
            }
        } else {
            QMessageBox::critical(this, "EiskaltDC", tr("Can't load Image!"));
        }
    }
}

/** */
void DCOptions::slotChangePhoto() {
    QString file = QFileDialog::getOpenFileName(this, tr("Select a 64x64 Photo"), ToolButton_PHOTO->text());

    if (file.isEmpty()) {
        ToolButton_PHOTO->setIcon(QIcon());
        ToolButton_PHOTO->setText(QString());
    } else {
        SetUserPhoto(file);
    }
}

/** */
void DCOptions::slotDoubleClickedChatColor(QListWidgetItem * item) {
    QPixmap p(10, 10);
    QColor color(item->icon().pixmap(10, 10).toImage().pixel(0, 0));
    color = QColorDialog::getColor(color);
    if (color.isValid()) {
        p.fill(color);
        item->setIcon(p);
    }
}

/** */
void DCOptions::slotBackgroundColorDialog() {
    QPixmap pixmap = ToolButton_CHAT_BG_COLOR->icon().pixmap(10, 10);

    QColor color = pixmap.toImage().pixel(0, 0);
    color = QColorDialog::getColor(color);

    if (color.isValid()) {
        pixmap.fill(color);
        ToolButton_CHAT_BG_COLOR->setIcon(QIcon(pixmap));
    }
}

/** */
void DCOptions::slotReverseChatColors() {
    QColor color;
    QPixmap p(10, 10);

    for (int i = 0; i < ListBox_CHATCOLOR->count(); ++i) {
        color = QColor(ListBox_CHATCOLOR->item(i)->icon().pixmap(10, 10).toImage().pixel(0, 0));
        color.setRed(255 - color.red());
        color.setGreen(255 - color.green());
        color.setBlue(255 - color.blue());
        p.fill(color);
        ListBox_CHATCOLOR->item(i)->setIcon(QIcon(p));
    }
}

/** */
void DCOptions::slotLogChatAddNickNameFilter() {
    bool ok = false;

    QString text = QInputDialog::getText(
            this,
            tr("Add new nick name filter"),
            tr("Please enter a nick"),
            QLineEdit::Normal,
            QString(),
            &ok
            );

    if (ok && !text.isEmpty()) {
        if ((ListBox_LOGCHAT_NICKNAMEFILTER_LIST->findItems(text, Qt::MatchExactly)).size() == 0) {
            new QListWidgetItem(text, ListBox_LOGCHAT_NICKNAMEFILTER_LIST);
        }
    }
}

/** */
void DCOptions::slotLogChatDelNickNameFilter() {
    int i = ListBox_LOGCHAT_NICKNAMEFILTER_LIST->currentRow();

    if (i >= 0) {
        QListWidgetItem * item = ListBox_LOGCHAT_NICKNAMEFILTER_LIST->takeItem(i);

        if (item != 0) {
            delete item;
        }
    }
}

/** */
void DCOptions::slotTestHost() {
    QString sip;
    CString errmsg;
    QString s;
    QString failmsg;

    if (RadioButton_IPHOSTNAME->isChecked()) {
        s = LineEdit_IP->text();
        s.remove(' ');
        LineEdit_IP->setText(s);

        if (!s.isEmpty()) {
            sip = CNetAddr::GetHostI4(s.toAscii().constData(), &errmsg).Data();
        }

        if (sip.isEmpty()) {
            failmsg = tr("Can't get Host IP!");
            if (errmsg.NotEmpty()) {
                failmsg += "\n\n";
                failmsg += errmsg.Data();
            }
            QMessageBox::critical(this, "EiskaltDC", failmsg);
        } else {
            QMessageBox::information(this, "EiskaltDC", tr("Host IP: ") + sip);
        }
    } else {
        sip = CNetAddr::GetInterfaceI4(LineEdit_IP->text().toAscii().constData(), &errmsg).Data();

        if (sip.isEmpty()) {
            failmsg = tr("Can't get interface IP!");
            if (errmsg.NotEmpty()) {
                failmsg += "\n\n";
                failmsg += errmsg.Data();
            }
            QMessageBox::critical(this, "EiskaltDC", failmsg);
        } else {
            QMessageBox::information(this, "EiskaltDC", tr("Interface IP: ") + sip);
        }
    }
}

/** */
void DCOptions::slotGetInterface() {
    CList<CString> interfacelist;
    CString errmsg;
    CString * s;
    QStringList lst;
    long res = CNetAddr::GetInterfaceList(&interfacelist, &errmsg);

    if (res > 0) {
        s = 0;

        while ((s = interfacelist.Next(s)) != 0) {
            lst << s->Data();
        }

        bool ok = false;

        QString res = QInputDialog::getItem(
                this,
                tr("Interface List"),
                tr("Please select an interface"),
                lst,
                1,
                true,
                &ok
                );

        if (ok) {
            LineEdit_IP->setText(res);
        }
    } else {
        QString failmsg = tr("No interfaces found!");
        if ((res < 0) && errmsg.NotEmpty()) {
            failmsg += "\n\n";
            failmsg += errmsg.Data();
        }
        QMessageBox::information(this, "EiskaltDC", failmsg);
    }
}

/** */
void DCOptions::slotGetInternetIP() {
    PushButton_GETINTERNETIP->setEnabled(false);

    QHttpRequestHeader header("GET", "/ip.php");
    header.setValue("Host", "wxdcgui.sourceforge.net");
    QString useragent = QString("EiskaltDC/") + PACKAGE_VERSION;
    //printf("User-Agent=%s\n", useragent.toAscii().constData());
    header.setValue("User-Agent", useragent);

    m_pHttp = new QHttp();
    connect(m_pHttp, SIGNAL(done(bool)), this, SLOT(slotGotInternetIP(bool)));
    m_pHttp->setHost("wxdcgui.sourceforge.net");
    m_pHttp->request(header);
}

/** */
void DCOptions::slotGotInternetIP(bool error) {
    if (error) {
        QMessageBox::warning(
                this,
                tr("Error getting IP"),
                m_pHttp->errorString()
                );
    } else {
        QString html = QString(m_pHttp->readAll());
        int start = html.indexOf("&lt;ip&gt;");
        int end = html.indexOf("&lt;/ip&gt;", start);

        if ((start == -1) || (end < start)) {
            QMessageBox::warning(
                    this,
                    tr("Get Internet IP"),
                    tr("Unexpected response from ") + "http://wxdcgui.sourceforge.net"
                    );
        } else {
            start += 10;
            QString ip = html.mid(start, end - start);

            if (QHostAddress().setAddress(ip)) {
                LineEdit_IP->setText(ip);
            } else {
                QMessageBox::warning(
                        this,
                        tr("Get Internet IP"),
                        ip + tr(" does not look valid")
                        );
            }
        }

    }

    delete m_pHttp;
    m_pHttp = 0;

    PushButton_GETINTERNETIP->setEnabled(true);
}

/** */
void DCOptions::slotDisableSound() {
    const bool b = !CheckBox_SOUNDDISABLED->isChecked();
    CheckBox_SOUNDDISABLEDAWAY->setEnabled(b);
    GroupBox_EXTERNALPLAYER->setEnabled(b);
    GroupBox_SOUND_FILES->setEnabled(b);

    CheckBox_SOUNDDISABLEDWACTIVE->setEnabled(b);
    CheckBox_SOUNDDISABLEDWSHOW->setEnabled(b);
}

/** */
void DCOptions::slotBrowseSoundPlayer() {
    QString file = QFileDialog::getOpenFileName(this, tr("Select sound player"), LineEdit_EXTERNALPLAYER->text());

    if (!file.isEmpty()) {
        LineEdit_EXTERNALPLAYER->setText(file);
    }
}

/** */
void DCOptions::slotBrowseTransferCert() {
    QString file = QFileDialog::getSaveFileName(this, tr("Select transfer cert"), LineEdit_TRANSFERCERT->text(), QString(), 0, QFileDialog::DontConfirmOverwrite);

    if (!file.isEmpty()) {
        LineEdit_TRANSFERCERT->setText(file);
    }
}

/** */
void DCOptions::slotBrowseTransferKey() {
    QString file = QFileDialog::getSaveFileName(this, tr("Select transfer key"), LineEdit_TRANSFERKEY->text(), QString(), 0, QFileDialog::DontConfirmOverwrite);

    if (!file.isEmpty()) {
        LineEdit_TRANSFERKEY->setText(file);
    }
}

/** */
void DCOptions::slotBrowseDclibPluginFolder() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select plugin folder"), LineEdit_DCLIB_PLUGIN_PATH->text());

    if (!dir.isEmpty()) {
        LineEdit_DCLIB_PLUGIN_PATH->setText(dir);
    }
}

/** */
void DCOptions::slotBrowseBrowser() {
    QString file = QFileDialog::getOpenFileName(this, tr("Select a browser"), LineEdit_BROWSER->text());

    if (!file.isEmpty()) {
        LineEdit_BROWSER->setText(file);
    }
}

/** */
void DCOptions::BrowseSoundFile(eUserSound usersound) {
    QString current;
    QString filter = tr("au") + " (*.au);;" +
            tr("wav") + " (*.wav);;" +
            tr("All Files") + " (*)";

    switch (usersound) {
        case eusCONNECT:
            current = LineEdit_SOUNDFILECONNECT->text();
            break;
        case eusDISCONNECT:
            current = LineEdit_SOUNDFILEDISCONNECT->text();
            break;
        case eusSEND:
            current = LineEdit_SOUNDFILESEND->text();
            break;
        case eusRECEIVE:
            current = LineEdit_SOUNDFILERECEIVE->text();
            break;
        case eusFIRSTRECEIVE:
            current = LineEdit_SOUNDFILEFIRSTRECEIVE->text();
            break;
        case eusNICKMENTIONED:
            current = LineEdit_SOUNDFILENICKMENTIONED->text();
            break;
        default:
            break;
    }

    QString file = QFileDialog::getOpenFileName(this, tr("Select sound file"), current, filter);

    if (!file.isEmpty()) {
        switch (usersound) {
            case eusCONNECT:
                LineEdit_SOUNDFILECONNECT->setText(file);
                break;
            case eusDISCONNECT:
                LineEdit_SOUNDFILEDISCONNECT->setText(file);
                break;
            case eusSEND:
                LineEdit_SOUNDFILESEND->setText(file);
                break;
            case eusRECEIVE:
                LineEdit_SOUNDFILERECEIVE->setText(file);
                break;
            case eusFIRSTRECEIVE:
                LineEdit_SOUNDFILEFIRSTRECEIVE->setText(file);
                break;
            case eusNICKMENTIONED:
                LineEdit_SOUNDFILENICKMENTIONED->setText(file);
                break;
            default:
                break;
        }
    }
}

/** */
void DCOptions::PreviewSoundFile(eUserSound usersound) {
    QString file;

    switch (usersound) {
        case eusCONNECT:
            file = LineEdit_SOUNDFILECONNECT->text();
            break;
        case eusDISCONNECT:
            file = LineEdit_SOUNDFILEDISCONNECT->text();
            break;
        case eusSEND:
            file = LineEdit_SOUNDFILESEND->text();
            break;
        case eusRECEIVE:
            file = LineEdit_SOUNDFILERECEIVE->text();
            break;
        case eusFIRSTRECEIVE:
            file = LineEdit_SOUNDFILEFIRSTRECEIVE->text();
            break;
        case eusNICKMENTIONED:
            file = LineEdit_SOUNDFILENICKMENTIONED->text();
            break;
        default:
            break;
    }

    DCConfig::Instance()->PlaySound(file);
}

/** */
void DCOptions::slotBrowseDownloadFolder() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select download folder"), LineEdit_DOWNLOADFOLDER->text());

    if (!dir.isEmpty()) {
        LineEdit_DOWNLOADFOLDER->setText(dir);
    }
}

/** */
void DCOptions::slotBrowseDownloadFinishedFolder() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select download finished folder"), LineEdit_DOWNLOADFINISHEDFOLDER->text());

    if (!dir.isEmpty()) {
        LineEdit_DOWNLOADFINISHEDFOLDER->setText(dir);
    }
}

/** */
void DCOptions::slotBrowseDataFolder() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select data folder"), LineEdit_DATAFOLDER->text());

    if (!dir.isEmpty()) {
        LineEdit_DATAFOLDER->setText(dir);
    }
}

/** */
void DCOptions::slotBrowseShareList() {
    DCTransferView::Instance()->NewLocalFileBrowser(true);
}

/** */
void DCOptions::slotBrowseLogFile() {
    QString logfile = QFileDialog::getSaveFileName(this, tr("Select log file"), LineEdit_LOGFILENAME->text());

    if (!logfile.isEmpty()) {
        LineEdit_LOGFILENAME->setText(logfile);
    }
}

/** */
void DCOptions::slotAddSharedFolder() {
    CDir di;
    CString s;
    int i;

    QString dir = QFileDialog::getExistingDirectory(this, tr("Select share folder"));

    if (!dir.isEmpty()) {
        if (TreeWidget_SHAREDFOLDERS->findItems(dir, Qt::MatchExactly, 0).size() == 0) {
            di.SetPath(dir.toAscii().constData());
            s = di.Path();
            i = 1;

            while (TreeWidget_SHAREDFOLDERS->findItems(di.DirName().Data(), Qt::MatchExactly, 1).size() != 0) {
                di.SetPath(s + CString::number(i));
                i++;
            }

            QTreeWidgetItem * item = new QTreeWidgetItem(TreeWidget_SHAREDFOLDERS);
            item->setText(0, dir);
            item->setText(1, di.DirName().Data());
        }
    }
}

/** */
void DCOptions::slotRemoveSharedFolder() {
    QTreeWidgetItem * item = TreeWidget_SHAREDFOLDERS->currentItem();

    if (item) {
        TreeWidget_SHAREDFOLDERS->takeTopLevelItem(TreeWidget_SHAREDFOLDERS->indexOfTopLevelItem(item));
        delete item;
    }
}

/** */
void DCOptions::slotEditSharedFolder() {
    editSharedFolder(TreeWidget_SHAREDFOLDERS->currentItem());
}

/** */
void DCOptions::editSharedFolder(QTreeWidgetItem * item) {
    if (item) {
        QDialog * dlg = new QDialog(this);

        Ui::DCDialogEditSharePath ui;
        ui.setupUi(dlg);

        ui.LineEdit_PATH->setText(item->text(0));
        ui.LineEdit_ALIAS->setText(item->text(1));

        if (dlg->exec() == QDialog::Accepted) {
            item->setText(0, ui.LineEdit_PATH->text());

            QString s = ui.LineEdit_ALIAS->text();
            s.remove('\\');
            s.remove('/');
            item->setText(1, s);
        }

        delete dlg;
    }
}

/** */
void DCOptions::slotDoubleClickedSharedFolder(QTreeWidgetItem * item, int /* column */) {
    if (item) // always true since signal is only emitted on valid items
    {
        editSharedFolder(item);
    } else {
        slotAddSharedFolder();
    }
}

/** */
void DCOptions::slotContextMenuSharedFolder(const QPoint & pos) {
    QMenu * m = new QMenu(this);
    QTreeWidgetItem * item = TreeWidget_SHAREDFOLDERS->itemAt(pos);
    bool enabled = (item != 0);

    QAction * add = DCMenuHandler::addAction(m, emiADD);
    QAction * edit = DCMenuHandler::addAction(m, emiEDIT, enabled);
    QAction * remove = DCMenuHandler::addAction(m, emiREMOVE, enabled);

    QAction * chosen = m->exec(QCursor::pos());

    delete m;

    if (chosen == 0) {
        return;
    } else if (chosen == add) {
        slotAddSharedFolder();
    } else if (chosen == edit) {
        editSharedFolder(item);
    } else if (chosen == remove) {
        delete item;
    }
}

/** */
void DCOptions::slotSharedFoldersSelectionChanged() {
    if (TreeWidget_SHAREDFOLDERS->selectedItems().size() == 1) {
        ToolButton_REMOVESHAREDFOLDER->setEnabled(true);
        ToolButton_EDITSHAREDFOLDER->setEnabled(true);
    } else {
        ToolButton_REMOVESHAREDFOLDER->setEnabled(false);
        ToolButton_EDITSHAREDFOLDER->setEnabled(false);
    }
}

/** */
void DCOptions::SetValues() {
    int i;
    CList<DCConfigShareFolder> list;
    DCConfigShareFolder * csf;
    QTreeWidgetItem * qtwitem;

    // identify
    LineEdit_NICK->setText(DCConfig::Instance()->GetNick().Data());
    LineEdit_SEARCHNICK->setText(DCConfig::Instance()->GetSearchNick().Data());
    LineEdit_EMAIL->setText(DCConfig::Instance()->GetEMail(true).Data());
    CheckBox_ANTISPAM->setChecked(DCConfig::Instance()->GetAntiSpam());
    LineEdit_DESCRIPTION->setText(DCConfig::Instance()->GetDescription(true).Data());
    CheckBox_DESCRIPTION_TAG->setChecked(DCConfig::Instance()->GetDescriptionTag());
    CheckBox_EXT_HUB_COUNT->setChecked(DCConfig::Instance()->GetUseExtendedHubCount());
    LineEdit_AWAYPREFIX->setText(DCConfig::Instance()->GetAwayPrefix().Data());
    spinBox_NOTIFYLENGTHPRIV->setValue(DCConfig::Instance()->GetNotifyLength(eTrayMessageTypePRIV));
    spinBox_NOTIFYLENGTHNICK->setValue(DCConfig::Instance()->GetNotifyLength(eTrayMessageTypeNICK));
    spinBox_NOTIFYLENGTHDISC->setValue(DCConfig::Instance()->GetNotifyLength(eTrayMessageTypeDISC));
    SetUserPhoto(DCConfig::Instance()->GetUserPhotoFileName());

    i = ComboBox_SPEED->findText(QString::fromAscii(DCConfig::Instance()->GetSpeed().Data()));
    if (i != -1) {
        ComboBox_SPEED->setCurrentIndex(i);
    }

    i = ComboBox_APPLICATION_ICONS->findText(DCConfig::Instance()->GetApplicationIconTheme());
    if (i != -1) {
        ComboBox_APPLICATION_ICONS->setCurrentIndex(i);
    }

    i = ComboBox_EMOTICONS->findText(DCConfig::Instance()->GetEmoticonTheme());
    if (i != -1) {
        ComboBox_EMOTICONS->setCurrentIndex(i);
    }

    i = ComboBox_USERLIST_ICONS->findText(DCConfig::Instance()->GetUserListIconTheme());
    if (i != -1) {
        ComboBox_USERLIST_ICONS->setCurrentIndex(i);
    }

    TextEdit_AWAYMESSAGE->setText(QString(DCConfig::Instance()->GetAwayMessage().Data()).remove("\r"));

    // transfer->folder
    LineEdit_DOWNLOADFOLDER->setText(DCConfig::Instance()->GetDownloadFolder().Data());
    LineEdit_DOWNLOADFINISHEDFOLDER->setText(DCConfig::Instance()->GetDownloadFinishedFolder().Data());
    SpinBox_MIN_SEG_SIZE->setValue((int) DCConfig::Instance()->GetMinSegSize() / 1048576);

    // save shared folders
    TreeWidget_SHAREDFOLDERS->clear();

    DCConfig::Instance()->GetSharedFolders(&list);

    csf = 0;
    while ((csf = list.Next(csf)) != 0) {
        QTreeWidgetItem * item = new QTreeWidgetItem(TreeWidget_SHAREDFOLDERS);
        item->setText(0, csf->m_sPath.Data());
        item->setText(1, csf->m_sAlias.Data());
    }
    slotSharedFoldersSelectionChanged();

    DCConfig::Instance()->GetUserMenuCommands(&usercommands);
    for (QMap<int, DC_UserMenuCommand*>::const_iterator it = usercommands.constBegin(); it != usercommands.constEnd(); ++it) {
        qtwitem = new QTreeWidgetItem(TreeWidget_MENU_COMMANDS);
        qtwitem->setText(0, it.value()->m_sName);
        qtwitem->setText(1, it.value()->m_sCommand);
    }

    slotUserMenuCommandsSelectionChanged();

    QList<DC_UserChatCommand*> ucclist;
    DCConfig::Instance()->GetUserChatCommands(&ucclist);
    for (QList<DC_UserChatCommand*>::const_iterator it = ucclist.constBegin(); it != ucclist.constEnd(); ++it) {
        qtwitem = new QTreeWidgetItem(TreeWidget_CHAT_COMMANDS);
        qtwitem->setText(0, (*it)->m_sName);
        qtwitem->setText(1, (*it)->m_sCommand);
        qtwitem->setFlags(qtwitem->flags() | Qt::ItemIsEditable);
        delete *it;
    }
    ucclist.clear();

    CheckBox_AUTORECREATESHARELIST->setChecked(DCConfig::Instance()->GetAutoRecreateShareList());
    CheckBox_DONTSHAREDOTFILES->setChecked(DCConfig::Instance()->GetDontShareDotFiles());

    // transfer->settings
    SpinBox_SAVEDOWNLOADQUEUETIME->setValue(DCConfig::Instance()->GetDownloadQueueTime());
    SpinBox_USERUPLOADSLOTS->setValue(DCConfig::Instance()->GetUserUploadSlots());
    CheckBox_DYNAMICUPLOADRATE->setChecked(DCConfig::Instance()->GetDynamicUploadRate());
    SpinBox_MAXUPLOADRATE->setValue((DCConfig::Instance()->GetMaxUploadRate()) / 1024.0);
    SpinBox_MAXDOWNLOADRATE->setValue((DCConfig::Instance()->GetMaxDownloadRate()) / 1024.0);
    SpinBox_MAXSIMULTANEOUSUPLOADS->setValue(DCConfig::Instance()->GetMaxUpload());
    SpinBox_TRANSFERRESENDTIMEOUT->setValue(DCConfig::Instance()->GetTransferResendTimeout());
    SpinBox_TRANSFERRESPONSETIMEOUT->setValue(DCConfig::Instance()->GetTransferResponseTimeout());
    SpinBox_AUTOSEARCHINTERVAL->setValue(DCConfig::Instance()->GetAutoSearchInterval());
    SpinBox_SMALLFILESIZE->setValue(DCConfig::Instance()->GetSmallFileSize());
    checkBox_IGNOREHANDSHAKES->setChecked(DCConfig::Instance()->GetIgnoreHandshake());

    SpinBox_EXTRA_SLOTS_RATE->setValue((int) DCConfig::Instance()->GetExtraSlotsRate() / 1024);
    SpinBox_MAX_EXTRA_SLOTS->setValue(DCConfig::Instance()->GetMaxExtraSlots());

    switch (DCConfig::Instance()->GetHubOfflineTransferClose()) {
        case ectNONE:
            RadioButton_NONE->setChecked(true);
            break;
        case ectUPLD:
            RadioButton_UPLOAD->setChecked(true);
            break;
        case ectDLD:
            RadioButton_DOWNLOAD->setChecked(true);
            break;
        case ectBOTH:
            RadioButton_BOTH->setChecked(true);
            break;
    }

    CheckBox_TRANSFERAUTOSEARCH->setChecked(DCConfig::Instance()->GetTransferAutoSearch());
    CheckBox_DISABLEHASHLIST->setChecked(DCConfig::Instance()->GetDisableHashList());
    CheckBox_COMPRESSEDTRANSFERS->setChecked(DCConfig::Instance()->GetCompressedTransfers());
    SpinBox_RECREATESHARELISTTIME->setValue(DCConfig::Instance()->GetRecreateShareListTime());

    // connection->mode
    if (DCConfig::Instance()->GetMode(true) == ecmPASSIVE) {
        RadioButton_PASSIVEMODE->setChecked(true);
    } else {
        RadioButton_ACTIVEMODE->setChecked(true);
    }

    if (DCConfig::Instance()->GetExternalIP()) {
        RadioButton_IPHOSTNAME->setChecked(true);
    } else {
        RadioButton_INTERFACE->setChecked(true);
    }

    LineEdit_IP->setText(DCConfig::Instance()->GetHost().Data());
    LineEdit_LISTENIP->setText(DCConfig::Instance()->GetListenHost().Data());
    SpinBox_TCPLISTENPORT->setValue(DCConfig::Instance()->GetTCPListenPort());
    SpinBox_CRYPTO_PORT->setValue(DCConfig::Instance()->GetCryptoListenPort());
    SpinBox_UDPLISTENPORT->setValue(DCConfig::Instance()->GetUDPListenPort());
    CheckBox_SENDMESSAGEONACTIVEMODEREQUEST->setChecked(DCConfig::Instance()->GetSendMessageOnActiveModeRequest());

    // connection->settings
    SpinBox_RECONNECTCOUNT->setValue(DCConfig::Instance()->GetReconnectCount());
    SpinBox_RECONNECTTIMEOUT->setValue(DCConfig::Instance()->GetReconnectTimeout());
    CheckBox_FORCEMOVEENABLED->setChecked(DCConfig::Instance()->GetForceMoveEnabled());

    if (DCConfig::Instance()->GetCheckPrivateAddressSpace()) {
        ComboBox_PRIVATEADDRESSSPACE->setCurrentIndex(1);
    } else if (DCConfig::Instance()->GetPrivateAddressSpaceOnly()) {
        ComboBox_PRIVATEADDRESSSPACE->setCurrentIndex(2);
    } else {
        ComboBox_PRIVATEADDRESSSPACE->setCurrentIndex(0);
    }

    // gui->general
    LineEdit_LANGUAGEFILE->setText(DCConfig::Instance()->GetLanguageFile());

    i = ComboBox_THEME->findText(DCConfig::Instance()->GetTheme());
    if (i != -1) {
        ComboBox_THEME->setCurrentIndex(i);
    } else {
        // if theme not in list, pick the current theme
#if defined(Q_OS_MACX)
        i = ComboBox_THEME->findText("mac", Qt::MatchStartsWith);
#else
        i = ComboBox_THEME->findText(DCGuiUtils::DetectAppStyleKey());
#endif

        if (i != -1) {
            ComboBox_THEME->setCurrentIndex(i);
        }
    }

    m_sTestedTheme = ComboBox_THEME->currentText();

    switch (DCConfig::Instance()->GetUnit()) {
        case euBYTE:
            RadioButton_UNITBYTE->setChecked(true);
            break;
        case euKBYTE:
            RadioButton_UNITKBYTE->setChecked(true);
            break;
        case euMBYTE:
            RadioButton_UNITMBYTE->setChecked(true);
            break;
        case euGBYTE:
            RadioButton_UNITGBYTE->setChecked(true);
            break;
        default:
            RadioButton_UNITAUTO->setChecked(true);
            break;
    }

    LineEdit_APPFONT->setText(DCConfig::Instance()->GetAppFont());
    GroupBox_APPFONT->setChecked(DCConfig::Instance()->GetUseCustomFont());
    LineEdit_DATAFOLDER->setText(DCConfig::Instance()->GetValknutDataPath());
    CheckBox_SHOWSTATUSMESSAGE->setChecked(DCConfig::Instance()->GetShowStatusMessage());
    CheckBox_QUERYONEXIT->setChecked(DCConfig::Instance()->GetQueryOnExit());
    CheckBox_QUERYONFILEDELETE->setChecked(DCConfig::Instance()->GetQueryOnFileDelete());

    // gui->transfer
    CheckBox_TV_PERCENTCHUNK->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoCHUNKPERCENT));
    CheckBox_TV_PERCENTFILE->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoFILEPERCENT));
    CheckBox_TV_CHUNKSIZE->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoCHUNKSIZE));
    CheckBox_TV_FILESIZE->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoFILESIZE));
    CheckBox_TV_DOWNLOADRATESINGLE->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoDOWNLOADRATESINGLE));
    CheckBox_TV_ELAPSEDTIMESINGLE->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoELAPSEDTIMESINGLE));
    CheckBox_TV_DOWNLOADRATEMULTI->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoDOWNLOADRATEMULTI));
    CheckBox_TV_ELAPSEDTIMEMULTI->setChecked(DCConfig::Instance()->GetTransferViewOptions(etvoELAPSEDTIMEMULTI));

    // gui->chat
    CheckBox_OPENPRIVATECHATWINDOW->setChecked(DCConfig::Instance()->GetOpenPrivateChatWindow());
    CheckBox_SHOWCHATINTAB->setChecked(DCConfig::Instance()->GetShowChatInTab());
    CheckBox_SENDHIDEPRIVATECHATTOPUBLICCHAT->setChecked(DCConfig::Instance()->GetSendHidePrivateChatToPublicChat());
    CheckBox_EMOTICONS->setChecked(DCConfig::Instance()->GetEnableEmoticons());
    CheckBox_SHOWCHATSENDBUTTON->setChecked(DCConfig::Instance()->GetShowChatSendButton());
    CheckBox_CHATSHOWJOINSANDPARTS->setChecked(DCConfig::Instance()->GetChatShowJoinsAndParts());
    CheckBox_CHATSHOWJOINSANDPARTSONLYFAV->setChecked(DCConfig::Instance()->GetChatShowJoinsAndPartsOnlyFav());
    CheckBox_CHATRECVFROMOFFLINE->setChecked(DCConfig::Instance()->GetChatRecvFromOffline());
    CheckBox_CHATSENDTOOFFLINE->setChecked(DCConfig::Instance()->GetChatSendToOffline());
    SpinBox_CHATMAXPARAGRAPH->setValue(DCConfig::Instance()->GetChatMaxParagraph());
    SpinBox_CHATMESSAGEMAXLINES->setValue(DCConfig::Instance()->GetChatMessageMaxLines());
    LineEdit_SUPPRESS_NICKS->setText(DCConfig::Instance()->GetSuppressedNicks());
    CheckBox_SENDUNKNOWNCOMMANDS->setChecked(DCConfig::Instance()->GetSendUnknownCommandsAsChat());
    LineEdit_ALLOWED_UNKNOWN_COMMANDS->setText(DCConfig::Instance()->GetAllowedUnknownCommands());

    ComboBox_SENDCHAT->setCurrentIndex(DCConfig::Instance()->GetSendChat());

    GroupBox_CUSTOM_BROWSER->setChecked(DCConfig::Instance()->GetCustomBrowser());
    LineEdit_BROWSER->setText(DCConfig::Instance()->GetBrowser());

    QColor c;
    QPixmap p(10, 10);

    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATTIMESTAMP));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Timestamp"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATLOCALNICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Local Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATLOCALTEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Local Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATREMOTENICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Remote Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATREMOTETEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Remote Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATSTATUSNICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Status Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATSTATUSTEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Status Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATTIMESTAMP));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Timestamp"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATLOCALNICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Local Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATLOCALTEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Local Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATREMOTENICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Remote Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATREMOTETEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Remote Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATSTATUSNICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Status Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATSTATUSTEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat Status Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICPRIVATECHATNICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Private Chat Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICPRIVATECHATTEXT));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Private Chat Text"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccCHATSAY));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Chat Say"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccPUBLICCHATMENICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Public Chat ME Nick"), ListBox_CHATCOLOR);
    c.setNamedColor(DCConfig::Instance()->GetChatColor(eccOPNICK));
    p.fill(c);
    new QListWidgetItem(QIcon(p), tr("Operator Nick"), ListBox_CHATCOLOR);

    GroupBox_CHAT_BACKGROUND->setChecked(DCConfig::Instance()->GetChatBackgroundColorEnabled());
    c.setNamedColor(DCConfig::Instance()->GetChatBackgroundColor());
    p.fill(c);
    ToolButton_CHAT_BG_COLOR->setIcon(QIcon(p));

    CheckBox_ALT_ROW_COLORS->setChecked(DCConfig::Instance()->GetAlternatingRowColors());

    // gui->client
    ComboBox_OPEN_CLIENT_WINDOWS_HOW->setCurrentIndex(DCConfig::Instance()->GetOpenClientWindows());
    CheckBox_USERLISTRIGHTALIGNMENT->setChecked(DCConfig::Instance()->GetUserListRightAlignment());
    CheckBox_AUTOAWAYMODE->setChecked(DCConfig::Instance()->GetAutoAwayMode());
    SpinBox_AUTOAWAYTIME->setValue(DCConfig::Instance()->GetAutoAwayTime());
    ComboBox_DOUBLECLICK->setCurrentIndex(DCConfig::Instance()->GetDoubleClickAction());

    // sound
    CheckBox_SOUNDDISABLED->setChecked(DCConfig::Instance()->GetSoundDisabled());

    SoundDisableMode s_mode = DCConfig::Instance()->GetSoundDisableMode();

    CheckBox_SOUNDDISABLEDWACTIVE->setChecked(IS_SOUNDDISABLEWACTIVE(s_mode));
    CheckBox_SOUNDDISABLEDWSHOW->setChecked(IS_SOUNDDISABLEWSHOW(s_mode));

    CheckBox_SOUNDDISABLEDAWAY->setChecked(DCConfig::Instance()->GetSoundDisabledAway());
    GroupBox_EXTERNALPLAYER->setChecked(DCConfig::Instance()->GetExternalSoundPlayer());
    LineEdit_EXTERNALPLAYER->setText(DCConfig::Instance()->GetExternalPlayer());
    LineEdit_SOUNDFILECONNECT->setText(DCConfig::Instance()->GetSoundFile(eusCONNECT));
    LineEdit_SOUNDFILEDISCONNECT->setText(DCConfig::Instance()->GetSoundFile(eusDISCONNECT));
    LineEdit_SOUNDFILESEND->setText(DCConfig::Instance()->GetSoundFile(eusSEND));
    LineEdit_SOUNDFILERECEIVE->setText(DCConfig::Instance()->GetSoundFile(eusRECEIVE));
    LineEdit_SOUNDFILEFIRSTRECEIVE->setText(DCConfig::Instance()->GetSoundFile(eusFIRSTRECEIVE));
    LineEdit_SOUNDFILENICKMENTIONED->setText(DCConfig::Instance()->GetSoundFile(eusNICKMENTIONED));
    GroupBox_SOUNDPLAYCONNECT->setChecked(DCConfig::Instance()->GetSoundEnabled(eusCONNECT));
    GroupBox_SOUNDPLAYDISCONNECT->setChecked(DCConfig::Instance()->GetSoundEnabled(eusDISCONNECT));
    GroupBox_SOUNDPLAYSEND->setChecked(DCConfig::Instance()->GetSoundEnabled(eusSEND));
    GroupBox_SOUNDPLAYRECEIVE->setChecked(DCConfig::Instance()->GetSoundEnabled(eusRECEIVE));
    GroupBox_SOUNDPLAYFIRSTRECEIVE->setChecked(DCConfig::Instance()->GetSoundEnabled(eusFIRSTRECEIVE));
    GroupBox_SOUNDPLAYNICKMENTIONED->setChecked(DCConfig::Instance()->GetSoundEnabled(eusNICKMENTIONED));

    // log
    CheckBox_LOGFILE->setChecked(DCConfig::Instance()->GetLogFile());
    CheckBox_LOGDOWNLOADS->setChecked(DCConfig::Instance()->GetLogFinishedDownloads());
    CheckBox_LOGUPLOADS->setChecked(DCConfig::Instance()->GetLogFinishedUploads());
    CheckBox_LOGDETAILS->setChecked(DCConfig::Instance()->GetLogDetails());
    LineEdit_LOGFILENAME->setText(DCConfig::Instance()->GetLogFileName().Data());
    CheckBox_TIMESTAMPPRIVATECHAT->setChecked(DCConfig::Instance()->GetTimeStamp(etsPRIVATECHAT));
    CheckBox_TIMESTAMPHUBCHAT->setChecked(DCConfig::Instance()->GetTimeStamp(etsHUBCHAT));

    GroupBox_CHAT_LOGGING->setChecked(DCConfig::Instance()->GetLogChatOption(elcoENABLELOGGING));
    CheckBox_LOGCHAT_APPENDDATE->setChecked(DCConfig::Instance()->GetLogChatOption(elcoAPPENDDATE));
    CheckBox_LOGCHAT_APPENDHUBNAME->setChecked(DCConfig::Instance()->GetLogChatOption(elcoAPPENDHUBNAME));
    CheckBox_LOGCHAT_APPENDHUBHOST->setChecked(DCConfig::Instance()->GetLogChatOption(elcoAPPENDHUBHOST));
    CheckBox_LOGCHAT_DISABLEPUBLICCHAT->setChecked(DCConfig::Instance()->GetLogChatOption(elcoDISABLEPUBLICCHAT));
    GroupBox_LOGNICKNAMEFILTER->setChecked(DCConfig::Instance()->GetLogChatOption(elcoENABLENICKNAMEFILTER));
    CheckBox_LOGCHAT_NICKNAMEFILTER_ENABLELOGGING->setChecked(DCConfig::Instance()->GetLogChatOption(elcoNICKNAMEFILTER_ENABLELOGGING));


    ListBox_LOGCHAT_NICKNAMEFILTER_LIST->clear();
    ListBox_LOGCHAT_NICKNAMEFILTER_LIST->addItems(DCConfig::Instance()->GetLogChatNickNameFilter());

    // other
    CheckBox_HUBLISTSTORELOCAL->setChecked(DCConfig::Instance()->GetHubListStoreLocal());
    SpinBox_RELOADHUBLISTTIME->setValue(DCConfig::Instance()->GetReloadHubListTime());

    DCConfigHubListUrl * hublisturl = 0;

    CList<DCConfigHubListUrl> hublisturllist;
    DCConfig::Instance()->GetHubListUrlList(&hublisturllist);

    while ((hublisturl = hublisturllist.Next(hublisturl)) != 0) {
        QListWidgetItem * lwi = new QListWidgetItem(hublisturl->sUrl.Data(), ListWidget_HUBLISTURL);
        if (hublisturl->bEnabled) {
            lwi->setCheckState(Qt::Checked);
        } else {
            lwi->setCheckState(Qt::Unchecked);
        }
    }
    slotHubListUrlsSelectionChanged();

    // security
    SpinBox_FLOODCOUNT->setValue(DCConfig::Instance()->GetFloodCount());
    CheckBox_FLOODOPKICK->setChecked(DCConfig::Instance()->GetFloodOpKick());
    LineEdit_FLOODOPKICKMESSAGE->setText(QString(DCConfig::Instance()->GetFloodOpKickMessage().Data()).remove("\r"));
    LineEdit_TRANSFERCERT->setText(DCConfig::Instance()->GetTransferCert().Data());
    LineEdit_TRANSFERKEY->setText(DCConfig::Instance()->GetTransferKey().Data());
    CheckBox_OLD_DCLIB_SSL_SUPPORT->setChecked(DCConfig::Instance()->GetOldSSLSupport());
    LineEdit_DCLIB_PLUGIN_PATH->setText(DCConfig::Instance()->GetDCLibPluginPath().Data());

    // init the sound tab
    slotDisableSound();

    // auto response settings
    CheckBox_ENABLE_AUTO_RESPONDER->setChecked(DCConfig::Instance()->GetAutoResponderEnabled());
    CheckBox_ENABLE_AUTO_RESPONDER_FOR_PM->setChecked(DCConfig::Instance()->GetAutoResponderEnabledForPM());
    SpinBox_AUTORESPONSEDELAY->setValue(DCConfig::Instance()->GetAutoResponseDelay());
    LineEdit_AUTO_RESPONSE_IGNORE->setText(DCConfig::Instance()->GetAutoResponseIgnores());

    // fill auto response list box
    QList<DC_AutoResponseObject*> arlist;
    DCConfig::Instance()->GetAutoResponses(&arlist);
    for (QList<DC_AutoResponseObject*>::const_iterator it = arlist.constBegin(); it != arlist.constEnd(); ++it) {
        QString cs;
        DC_AutoResponseObject * aro = *it;
        if (aro->m_bCaseSensitive) {
            cs = tr("Yes");
        } else {
            cs = tr("No");
        }
        qtwitem = new QTreeWidgetItem(TreeWidget_AUTO_RESPONSES);
        qtwitem->setText(0, aro->m_sTrigger);
        qtwitem->setText(1, cs);
        qtwitem->setText(2, aro->m_sResponse);
        qtwitem->setFlags(qtwitem->flags() | Qt::ItemIsEditable);

        delete aro;
    }
    arlist.clear();

    ComboBox_REMOTE_ENCODING->setEditText(DCConfig::Instance()->GetRemoteEncoding().Data());
    Label_ENCODING_DISABLE_HOWTO->setText(tr("Setting remote encoding to %1 will disable most conversions.").arg(DCConfig::Instance()->GetLocalEncoding().Data()));

    CheckBox_FOLDERS_RIGHT_PANE->setChecked(DCConfig::Instance()->GetFoldersInRightPane());
    CheckBox_FOLDERS_RIGHT_PANE_ON_TOP->setChecked(DCConfig::Instance()->GetFoldersInRightPaneOnTop());
    CheckBox_SIZES_LEFT_PANE->setChecked(DCConfig::Instance()->GetFolderSizesInLeftPane());

    CheckBox_ENABLE_USERIP2->setChecked(DCConfig::Instance()->GetUserIP2Enabled());
    CheckBox_ENABLE_ZPIPE->setChecked(DCConfig::Instance()->GetZPipeEnabled());

    CheckBox_ADJUST_SR->setChecked(DCConfig::Instance()->GetAdjustSearchResultHubNames());
    CheckBox_ENABLE_REMOVE_PUBLIC_HUB->setChecked(DCConfig::Instance()->GetRemovePublicHubEnabled());
    ComboBox_TAB_COMPLETE_MATCH_MODE->setCurrentIndex(DCConfig::Instance()->GetTabCompleteMatchMode());
    CheckBox_TAB_COMPLETE_STRIP_TAGS->setChecked(DCConfig::Instance()->GetTabCompleteStripTags());

    SpinBox_READFILEBUFFERSIZE->setValue(DCConfig::Instance()->GetReadFileBufferSize());

    CheckBox_NO_ADCGET_WITHOUT_TTH->setChecked(DCConfig::Instance()->GetDisableADCGetWithoutTTH());
    CheckBox_NO_XMLLIST_WITHOUT_TTH->setChecked(DCConfig::Instance()->GetDisableXMLListWithoutTTH());
    CheckBox_ENABLE_OBSOLETE_EXT->setChecked(DCConfig::Instance()->GetEnableObsoleteExt());
    CheckBox_THREADS_FOR_SHELL_COMMANDS->setChecked(DCConfig::Instance()->GetThreadsForShellCommands());
    SpinBox_SHELL_COMMAND_TIMEOUT->setValue(DCConfig::Instance()->GetShellCommandTimeout());
    CheckBox_OPEN_FOLDERS_RIGHT_PANE->setChecked(DCConfig::Instance()->GetOpenFoldersInRightPane());
    CheckBox_ENABLE_USERCOMMAND_SUPPORT->setChecked(DCConfig::Instance()->GetEnableUserCommand());
    CheckBox_USER_COMMAND_SUBMENU->setChecked(DCConfig::Instance()->GetUserCommandSubmenu());

    switch (DCConfig::Instance()->GetMagnetAction(eChatMagnet)) {
        case eMagnetPrompt:
            ComboBox_CHAT_MAGNETS->setCurrentIndex(0);
            break;
        case eMagnetSearch:
            ComboBox_CHAT_MAGNETS->setCurrentIndex(1);
            break;
        case eMagnetDownload:
            /* not supported */
            break;
        case eMagnetNothing:
            ComboBox_CHAT_MAGNETS->setCurrentIndex(2);
            break;
        default:
            break;
    }
}

/** */
void DCOptions::GetValues() {
    DCConfig::Instance()->SetNick(LineEdit_NICK->text().toAscii().constData());
    DCConfig::Instance()->SetSearchNick(LineEdit_SEARCHNICK->text().toAscii().constData());
    DCConfig::Instance()->SetAwayMessage(TextEdit_AWAYMESSAGE->toPlainText().replace("\n", "\xd\xa").toAscii().constData());
    DCConfig::Instance()->SetDescription(LineEdit_DESCRIPTION->text().toAscii().constData());
    DCConfig::Instance()->SetAwayPrefix(LineEdit_AWAYPREFIX->text().toAscii().constData());
    DCConfig::Instance()->SetDescriptionTag(CheckBox_DESCRIPTION_TAG->isChecked());
    DCConfig::Instance()->SetUseExtendedHubCount(CheckBox_EXT_HUB_COUNT->isChecked());
    DCConfig::Instance()->SetEMail(LineEdit_EMAIL->text().toAscii().constData());
    DCConfig::Instance()->SetAntiSpam(CheckBox_ANTISPAM->isChecked());
    DCConfig::Instance()->SetNotifyLength(eTrayMessageTypePRIV,spinBox_NOTIFYLENGTHPRIV->value());
    DCConfig::Instance()->SetNotifyLength(eTrayMessageTypeDISC,spinBox_NOTIFYLENGTHDISC->value());
    DCConfig::Instance()->SetNotifyLength(eTrayMessageTypeNICK,spinBox_NOTIFYLENGTHNICK->value());

    if (ComboBox_PRIVATEADDRESSSPACE->currentIndex() == 0) {
        DCConfig::Instance()->SetCheckPrivateAddressSpace(false);
        DCConfig::Instance()->SetPrivateAddressSpaceOnly(false);
    } else if (ComboBox_PRIVATEADDRESSSPACE->currentIndex() == 1) {
        DCConfig::Instance()->SetCheckPrivateAddressSpace(true);
        DCConfig::Instance()->SetPrivateAddressSpaceOnly(false);
    } else if (ComboBox_PRIVATEADDRESSSPACE->currentIndex() == 2) {
        DCConfig::Instance()->SetCheckPrivateAddressSpace(false);
        DCConfig::Instance()->SetPrivateAddressSpaceOnly(true);
    }

    DCConfig::Instance()->SetShowChatSendButton(CheckBox_SHOWCHATSENDBUTTON->isChecked());
    DCConfig::Instance()->SetCustomBrowser(GroupBox_CUSTOM_BROWSER->isChecked());
    DCConfig::Instance()->SetBrowser(LineEdit_BROWSER->text());
    DCConfig::Instance()->SetDynamicUploadRate(CheckBox_DYNAMICUPLOADRATE->isChecked());
    DCConfig::Instance()->SetShowChatInTab(CheckBox_SHOWCHATINTAB->isChecked());
    DCConfig::Instance()->SetChatMaxParagraph(SpinBox_CHATMAXPARAGRAPH->value());
    DCConfig::Instance()->SetTransferAutoSearch(CheckBox_TRANSFERAUTOSEARCH->isChecked());
    DCConfig::Instance()->SetDisableHashList(CheckBox_DISABLEHASHLIST->isChecked());
    DCConfig::Instance()->SetCompressedTransfers(CheckBox_COMPRESSEDTRANSFERS->isChecked());

    DCConfig::Instance()->SetUserPhotoFileName(ToolButton_PHOTO->text());

    DCConfig::Instance()->SetSpeed(ComboBox_SPEED->currentText().toAscii().constData());
    DCConfig::Instance()->SetDownloadFolder(LineEdit_DOWNLOADFOLDER->text().toAscii().constData());
    DCConfig::Instance()->SetDownloadFinishedFolder(LineEdit_DOWNLOADFINISHEDFOLDER->text().toAscii().constData());
    DCConfig::Instance()->SetMinSegSize(((ulonglong) SpinBox_MIN_SEG_SIZE->value()) * 1048576);
    DCConfig::Instance()->SetValknutDataPath(LineEdit_DATAFOLDER->text());

    DCConfig::Instance()->SetAutoRecreateShareList(CheckBox_AUTORECREATESHARELIST->isChecked());
    DCConfig::Instance()->SetDontShareDotFiles(CheckBox_DONTSHAREDOTFILES->isChecked());
    DCConfig::Instance()->SetRecreateShareListTime(SpinBox_RECREATESHARELISTTIME->value());

    DCConfig::Instance()->SetFloodOpKickMessage(LineEdit_FLOODOPKICKMESSAGE->text().replace("\n", "\xd\xa").toAscii().constData());
    DCConfig::Instance()->SetFloodCount(SpinBox_FLOODCOUNT->value());
    DCConfig::Instance()->SetFloodOpKick(CheckBox_FLOODOPKICK->isChecked());

    DCConfig::Instance()->SetTransferCert(LineEdit_TRANSFERCERT->text().toAscii().constData());
    DCConfig::Instance()->SetTransferKey(LineEdit_TRANSFERKEY->text().toAscii().constData());
    DCConfig::Instance()->SetOldSSLSupport(CheckBox_OLD_DCLIB_SSL_SUPPORT->isChecked());
    DCConfig::Instance()->SetDCLibPluginPath(LineEdit_DCLIB_PLUGIN_PATH->text().toAscii().constData());

    SaveSharedFolders();

    /* ownership transferred to DCConfig::Instance() which clears the map */
    DCConfig::Instance()->SetUserMenuCommands(&usercommands);

    SaveUserChatCommands();

    DCConfig::Instance()->SetAutoResponderEnabled(CheckBox_ENABLE_AUTO_RESPONDER->isChecked());
    DCConfig::Instance()->SetAutoResponderEnabledForPM(CheckBox_ENABLE_AUTO_RESPONDER_FOR_PM->isChecked());
    DCConfig::Instance()->SetAutoResponseDelay(SpinBox_AUTORESPONSEDELAY->value());
    DCConfig::Instance()->SetAutoResponseIgnores(LineEdit_AUTO_RESPONSE_IGNORE->text());
    SaveAutoResponses();

    DCConfig::Instance()->SetMaxUpload(SpinBox_MAXSIMULTANEOUSUPLOADS->value());
    DCConfig::Instance()->SetMaxUploadRate((ulonglong) (SpinBox_MAXUPLOADRATE->value()*1024));
    DCConfig::Instance()->SetMaxDownloadRate((ulonglong) (SpinBox_MAXDOWNLOADRATE->value()*1024));
    DCConfig::Instance()->SetDownloadQueueTime(SpinBox_SAVEDOWNLOADQUEUETIME->value());
    DCConfig::Instance()->SetAutoSearchInterval(SpinBox_AUTOSEARCHINTERVAL->value());
    DCConfig::Instance()->SetSmallFileSize(SpinBox_SMALLFILESIZE->value());
    DCConfig::Instance()->SetIgnoreHandshake(checkBox_IGNOREHANDSHAKES->isChecked());

    DCConfig::Instance()->SetExtraSlotsRate(1024 * ((ulonglong) SpinBox_EXTRA_SLOTS_RATE->value()));
    DCConfig::Instance()->SetMaxExtraSlots(SpinBox_MAX_EXTRA_SLOTS->value());

    DCConfig::Instance()->SetTCPListenPort(SpinBox_TCPLISTENPORT->value());
    DCConfig::Instance()->SetCryptoListenPort(SpinBox_CRYPTO_PORT->value());
    DCConfig::Instance()->SetUDPListenPort(SpinBox_UDPLISTENPORT->value());
    DCConfig::Instance()->SetExternalIP(RadioButton_IPHOSTNAME->isChecked());

    if (RadioButton_ACTIVEMODE->isChecked())
        DCConfig::Instance()->SetMode(ecmACTIVE);
    else
        DCConfig::Instance()->SetMode(ecmPASSIVE);

    DCConfig::Instance()->SetHost(LineEdit_IP->text().toAscii().constData());
    DCConfig::Instance()->SetListenHost(LineEdit_LISTENIP->text().toAscii().constData());
    DCConfig::Instance()->SetSendMessageOnActiveModeRequest(CheckBox_SENDMESSAGEONACTIVEMODEREQUEST->isChecked());

    // gui settings
    DCConfig::Instance()->SetOpenPrivateChatWindow(CheckBox_OPENPRIVATECHATWINDOW->isChecked());
    DCConfig::Instance()->SetEnableEmoticons(CheckBox_EMOTICONS->isChecked());

    if (RadioButton_UNITBYTE->isChecked())
        DCConfig::Instance()->SetUnit(euBYTE);
    else if (RadioButton_UNITKBYTE->isChecked())
        DCConfig::Instance()->SetUnit(euKBYTE);
    else if (RadioButton_UNITMBYTE->isChecked())
        DCConfig::Instance()->SetUnit(euMBYTE);
    else if (RadioButton_UNITGBYTE->isChecked())
        DCConfig::Instance()->SetUnit(euGBYTE);
    else
        DCConfig::Instance()->SetUnit(euAUTO);

    DCConfig::Instance()->SetTheme(ComboBox_THEME->currentText());
    DCConfig::Instance()->SetSendChat(eSendChatKey(ComboBox_SENDCHAT->currentIndex()));
    DCConfig::Instance()->SetLanguageFile(LineEdit_LANGUAGEFILE->text());
    DCConfig::Instance()->SetShowStatusMessage(CheckBox_SHOWSTATUSMESSAGE->isChecked());
    DCConfig::Instance()->SetQueryOnExit(CheckBox_QUERYONEXIT->isChecked());
    DCConfig::Instance()->SetQueryOnFileDelete(CheckBox_QUERYONFILEDELETE->isChecked());
    DCConfig::Instance()->SetSendHidePrivateChatToPublicChat(CheckBox_SENDHIDEPRIVATECHATTOPUBLICCHAT->isChecked());
    DCConfig::Instance()->SetChatSendToOffline(CheckBox_CHATSENDTOOFFLINE->isChecked());
    DCConfig::Instance()->SetChatRecvFromOffline(CheckBox_CHATRECVFROMOFFLINE->isChecked());
    DCConfig::Instance()->SetChatMessageMaxLines(SpinBox_CHATMESSAGEMAXLINES->value());
    DCConfig::Instance()->SetSuppressedNicks(LineEdit_SUPPRESS_NICKS->text());
    DCConfig::Instance()->SetSendUnknownCommandsAsChat(CheckBox_SENDUNKNOWNCOMMANDS->isChecked());
    DCConfig::Instance()->SetAllowedUnknownCommands(LineEdit_ALLOWED_UNKNOWN_COMMANDS->text());

    // sound settings
    DCConfig::Instance()->SetSoundDisabled(CheckBox_SOUNDDISABLED->isChecked());
    DCConfig::Instance()->SetSoundDisabledAway(CheckBox_SOUNDDISABLEDAWAY->isChecked());

    SoundDisableMode s_mode = 0;
    if (CheckBox_SOUNDDISABLEDWACTIVE->isChecked()) {
        SET_SOUNDDISABLEWACTIVE(s_mode);
    } else
        USET_SOUNDDISABLEWACTIVE(s_mode);
    if (CheckBox_SOUNDDISABLEDWSHOW->isChecked()) {
        SET_SOUNDDISABLEWSHOW(s_mode);
    } else
        USET_SOUNDDISABLEWSHOW(s_mode);

    DCConfig::Instance()->SetSoundDisableMode(s_mode);

    DCConfig::Instance()->SetSoundEnabled(eusCONNECT, GroupBox_SOUNDPLAYCONNECT->isChecked());
    DCConfig::Instance()->SetSoundEnabled(eusDISCONNECT, GroupBox_SOUNDPLAYDISCONNECT->isChecked());
    DCConfig::Instance()->SetSoundEnabled(eusSEND, GroupBox_SOUNDPLAYSEND->isChecked());
    DCConfig::Instance()->SetSoundEnabled(eusRECEIVE, GroupBox_SOUNDPLAYRECEIVE->isChecked());
    DCConfig::Instance()->SetSoundEnabled(eusFIRSTRECEIVE, GroupBox_SOUNDPLAYFIRSTRECEIVE->isChecked());
    DCConfig::Instance()->SetSoundEnabled(eusNICKMENTIONED, GroupBox_SOUNDPLAYNICKMENTIONED->isChecked());

    DCConfig::Instance()->SetExternalSoundPlayer(GroupBox_EXTERNALPLAYER->isChecked());
    DCConfig::Instance()->SetExternalPlayer(LineEdit_EXTERNALPLAYER->text());
    DCConfig::Instance()->SetSoundFile(eusCONNECT, LineEdit_SOUNDFILECONNECT->text());
    DCConfig::Instance()->SetSoundFile(eusDISCONNECT, LineEdit_SOUNDFILEDISCONNECT->text());
    DCConfig::Instance()->SetSoundFile(eusSEND, LineEdit_SOUNDFILESEND->text());
    DCConfig::Instance()->SetSoundFile(eusRECEIVE, LineEdit_SOUNDFILERECEIVE->text());
    DCConfig::Instance()->SetSoundFile(eusFIRSTRECEIVE, LineEdit_SOUNDFILEFIRSTRECEIVE->text());
    DCConfig::Instance()->SetSoundFile(eusNICKMENTIONED, LineEdit_SOUNDFILENICKMENTIONED->text());

    DCConfig::Instance()->SetAppFont(LineEdit_APPFONT->text());
    DCConfig::Instance()->SetUseCustomFont(GroupBox_APPFONT->isChecked());

    // gui->chat
    DCConfig::Instance()->SetChatShowJoinsAndParts(CheckBox_CHATSHOWJOINSANDPARTS->isChecked());
    DCConfig::Instance()->SetChatShowJoinsAndPartsOnlyFav(CheckBox_CHATSHOWJOINSANDPARTSONLYFAV->isChecked());

    // gui->client
    DCConfig::Instance()->SetOpenClientWindows(eOpenClientWindow(ComboBox_OPEN_CLIENT_WINDOWS_HOW->currentIndex()));
    DCConfig::Instance()->SetUserListRightAlignment(CheckBox_USERLISTRIGHTALIGNMENT->isChecked());
    DCConfig::Instance()->SetAutoAwayMode(CheckBox_AUTOAWAYMODE->isChecked());
    DCConfig::Instance()->SetAutoAwayTime(SpinBox_AUTOAWAYTIME->value());
    DCConfig::Instance()->SetDoubleClickAction(eDoubleClickUser(ComboBox_DOUBLECLICK->currentIndex()));

    QString oldappicons = DCConfig::Instance()->GetApplicationIconTheme();
    QString oldemoticons = DCConfig::Instance()->GetEmoticonTheme();

    // gui->icons
    if (ComboBox_APPLICATION_ICONS->count() > 0) {
        DCConfig::Instance()->SetApplicationIconTheme(ComboBox_APPLICATION_ICONS->currentText());
    }
    if (ComboBox_EMOTICONS->count() > 0) {
        DCConfig::Instance()->SetEmoticonTheme(ComboBox_EMOTICONS->currentText());
    }
    if (ComboBox_USERLIST_ICONS->count() > 0) {
        DCConfig::Instance()->SetUserListIconTheme(ComboBox_USERLIST_ICONS->currentText());
    }

    if (oldappicons != DCConfig::Instance()->GetApplicationIconTheme()) {
        // reload icons with new theme
        DCIconLoader::Instance()->Load();
    }

    // reload emoticons
    if (DCConfig::Instance()->GetEmoticonTheme() != oldemoticons) {
        DCConfig::Instance()->LoadEmoticons();
    }

    // log settings
    DCConfig::Instance()->SetLogFile(CheckBox_LOGFILE->isChecked());
    DCConfig::Instance()->SetLogFinishedDownloads(CheckBox_LOGDOWNLOADS->isChecked());
    DCConfig::Instance()->SetLogFinishedUploads(CheckBox_LOGUPLOADS->isChecked());
    DCConfig::Instance()->SetLogDetails(CheckBox_LOGDETAILS->isChecked());
    DCConfig::Instance()->SetLogFileName(LineEdit_LOGFILENAME->text().toAscii().constData());
    DCConfig::Instance()->SetTimeStamp(etsPRIVATECHAT, CheckBox_TIMESTAMPPRIVATECHAT->isChecked());
    DCConfig::Instance()->SetTimeStamp(etsHUBCHAT, CheckBox_TIMESTAMPHUBCHAT->isChecked());

    DCConfig::Instance()->SetLogChatOption(elcoENABLELOGGING, GroupBox_CHAT_LOGGING->isChecked());
    DCConfig::Instance()->SetLogChatOption(elcoAPPENDDATE, CheckBox_LOGCHAT_APPENDDATE->isChecked());
    DCConfig::Instance()->SetLogChatOption(elcoAPPENDHUBNAME, CheckBox_LOGCHAT_APPENDHUBNAME->isChecked());
    DCConfig::Instance()->SetLogChatOption(elcoAPPENDHUBHOST, CheckBox_LOGCHAT_APPENDHUBHOST->isChecked());
    DCConfig::Instance()->SetLogChatOption(elcoDISABLEPUBLICCHAT, CheckBox_LOGCHAT_DISABLEPUBLICCHAT->isChecked());
    DCConfig::Instance()->SetLogChatOption(elcoENABLENICKNAMEFILTER, GroupBox_LOGNICKNAMEFILTER->isChecked());
    DCConfig::Instance()->SetLogChatOption(elcoNICKNAMEFILTER_ENABLELOGGING, CheckBox_LOGCHAT_NICKNAMEFILTER_ENABLELOGGING->isChecked());

    int i = 0;
    QStringList nnflist;

    for (i = 0; i < ListBox_LOGCHAT_NICKNAMEFILTER_LIST->count(); i++) {
        nnflist << ListBox_LOGCHAT_NICKNAMEFILTER_LIST->item(i)->text();
    }

    DCConfig::Instance()->SetLogChatNickNameFilter(nnflist);

    // other settings
    DCConfig::Instance()->SetHubListStoreLocal(CheckBox_HUBLISTSTORELOCAL->isChecked());
    DCConfig::Instance()->SetReconnectCount(SpinBox_RECONNECTCOUNT->value());
    DCConfig::Instance()->SetReconnectTimeout(SpinBox_RECONNECTTIMEOUT->value());
    DCConfig::Instance()->SetTransferResendTimeout(SpinBox_TRANSFERRESENDTIMEOUT->value());
    DCConfig::Instance()->SetTransferResponseTimeout(SpinBox_TRANSFERRESPONSETIMEOUT->value());
    DCConfig::Instance()->SetForceMoveEnabled(CheckBox_FORCEMOVEENABLED->isChecked());
    DCConfig::Instance()->SetReloadHubListTime(SpinBox_RELOADHUBLISTTIME->value());

    // transfer view settings
    DCConfig::Instance()->SetTransferViewOptions(etvoCHUNKPERCENT, CheckBox_TV_PERCENTCHUNK->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoFILEPERCENT, CheckBox_TV_PERCENTFILE->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoCHUNKSIZE, CheckBox_TV_CHUNKSIZE->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoFILESIZE, CheckBox_TV_FILESIZE->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoDOWNLOADRATESINGLE, CheckBox_TV_DOWNLOADRATESINGLE->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoELAPSEDTIMESINGLE, CheckBox_TV_ELAPSEDTIMESINGLE->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoDOWNLOADRATEMULTI, CheckBox_TV_DOWNLOADRATEMULTI->isChecked());
    DCConfig::Instance()->SetTransferViewOptions(etvoELAPSEDTIMEMULTI, CheckBox_TV_ELAPSEDTIMEMULTI->isChecked());
    DCConfig::Instance()->SetUserUploadSlots(SpinBox_USERUPLOADSLOTS->value());

    if (RadioButton_NONE->isChecked())
        DCConfig::Instance()->SetHubOfflineTransferClose(ectNONE);
    else if (RadioButton_UPLOAD->isChecked())
        DCConfig::Instance()->SetHubOfflineTransferClose(ectUPLD);
    else if (RadioButton_DOWNLOAD->isChecked())
        DCConfig::Instance()->SetHubOfflineTransferClose(ectDLD);
    else if (RadioButton_BOTH->isChecked())
        DCConfig::Instance()->SetHubOfflineTransferClose(ectBOTH);

    CList<DCConfigHubListUrl> hublisturllist;

    for (i = 0; i < ListWidget_HUBLISTURL->count(); i++) {
        DCConfigHubListUrl * hublisturl = new DCConfigHubListUrl();

        QListWidgetItem * item = ListWidget_HUBLISTURL->item(i);
        hublisturl->sUrl = item->text().toAscii().constData();
        hublisturl->bEnabled = (item->checkState() == Qt::Checked);

        hublisturllist.Add(hublisturl);
    }

    DCConfig::Instance()->SetHubListUrlList(&hublisturllist);

    /* set i to start of ListBox_CHATCOLOR */
    i = 0;
    DCConfig::Instance()->SetChatColor(eccCHATTIMESTAMP, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATLOCALNICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATLOCALTEXT, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATREMOTENICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATREMOTETEXT, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATSTATUSNICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATSTATUSTEXT, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATTIMESTAMP, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATLOCALNICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    QString string_PUBLICCHATLOCALTEXT = QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name();
    DCConfig::Instance()->SetChatForegroundColor(string_PUBLICCHATLOCALTEXT);
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATLOCALTEXT, string_PUBLICCHATLOCALTEXT);
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATREMOTENICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATREMOTETEXT, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATSTATUSNICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATSTATUSTEXT, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICPRIVATECHATNICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICPRIVATECHATTEXT, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccCHATSAY, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccPUBLICCHATMENICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());
    DCConfig::Instance()->SetChatColor(eccOPNICK, QColor(ListBox_CHATCOLOR->item(i++)->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());

    DCConfig::Instance()->SetChatBackgroundColor(GroupBox_CHAT_BACKGROUND->isChecked(), QColor(ToolButton_CHAT_BG_COLOR->icon().pixmap(10, 10).toImage().pixel(0, 0)).name());

    DCConfig::Instance()->SetAlternatingRowColors(CheckBox_ALT_ROW_COLORS->isChecked());

    DCConfig::Instance()->SetRemoteEncoding(ComboBox_REMOTE_ENCODING->currentText().toAscii().constData());

    DCConfig::Instance()->SetFoldersInRightPane(CheckBox_FOLDERS_RIGHT_PANE->isChecked());
    DCConfig::Instance()->SetFoldersInRightPaneOnTop(CheckBox_FOLDERS_RIGHT_PANE_ON_TOP->isChecked());
    DCConfig::Instance()->SetFolderSizesInLeftPane(CheckBox_SIZES_LEFT_PANE->isChecked());

    DCConfig::Instance()->SetUserIP2Enabled(CheckBox_ENABLE_USERIP2->isChecked());
    DCConfig::Instance()->SetZPipeEnabled(CheckBox_ENABLE_ZPIPE->isChecked());
    DCConfig::Instance()->SetAdjustSearchResultHubNames(CheckBox_ADJUST_SR->isChecked());

    /* If this has been turned off, we need to save the public hub list now */
    if ((CheckBox_ENABLE_REMOVE_PUBLIC_HUB->isChecked() == false) && DCConfig::Instance()->GetRemovePublicHubEnabled()) {
        DCConfig::Instance()->SaveDCPublicHub();
    }
    DCConfig::Instance()->SetRemovePublicHubEnabled(CheckBox_ENABLE_REMOVE_PUBLIC_HUB->isChecked());

    DCConfig::Instance()->SetTabCompleteMatchMode(eTabCompleteMode(ComboBox_TAB_COMPLETE_MATCH_MODE->currentIndex()));
    DCConfig::Instance()->SetTabCompleteStripTags(CheckBox_TAB_COMPLETE_STRIP_TAGS->isChecked());

    DCConfig::Instance()->SetReadFileBufferSize(SpinBox_READFILEBUFFERSIZE->value());

    DCConfig::Instance()->SetDisableADCGetWithoutTTH(CheckBox_NO_ADCGET_WITHOUT_TTH->isChecked());
    DCConfig::Instance()->SetDisableXMLListWithoutTTH(CheckBox_NO_XMLLIST_WITHOUT_TTH->isChecked());
    DCConfig::Instance()->SetEnableObsoleteExt(CheckBox_ENABLE_OBSOLETE_EXT->isChecked());
    DCConfig::Instance()->SetThreadsForShellCommands(CheckBox_THREADS_FOR_SHELL_COMMANDS->isChecked());
    DCConfig::Instance()->SetShellCommandTimeout(SpinBox_SHELL_COMMAND_TIMEOUT->value());
    DCConfig::Instance()->SetOpenFoldersInRightPane(CheckBox_OPEN_FOLDERS_RIGHT_PANE->isChecked());
    DCConfig::Instance()->SetEnableUserCommand(CheckBox_ENABLE_USERCOMMAND_SUPPORT->isChecked());
    DCConfig::Instance()->SetUserCommandSubmenu(CheckBox_USER_COMMAND_SUBMENU->isChecked());

    switch (ComboBox_CHAT_MAGNETS->currentIndex()) {
        case 0:
            DCConfig::Instance()->SetMagnetAction(eMagnetPrompt, eChatMagnet);
            break;
        case 1:
            DCConfig::Instance()->SetMagnetAction(eMagnetSearch, eChatMagnet);
            break;
        case 2:
            DCConfig::Instance()->SetMagnetAction(eMagnetNothing, eChatMagnet);
            break;
        default:
            break;
    }
}

/** */
void DCOptions::SaveSharedFolders() {
    CList<DCConfigShareFolder> sharedfolders;
    DCConfigShareFolder * csf;

    // save shared folders
    sharedfolders.Clear();

    QTreeWidgetItemIterator it(TreeWidget_SHAREDFOLDERS);

    for (; (*it); ++it) {
        csf = new DCConfigShareFolder();
        csf->m_sPath = (*it)->text(0).toAscii().constData();
        csf->m_sAlias = (*it)->text(1).toAscii().constData();
        sharedfolders.Add(csf);
    }

    DCConfig::Instance()->SetSharedFolders(&sharedfolders);
}

void DCOptions::SaveUserChatCommands() {
    QList<DC_UserChatCommand*> commands;
    DC_UserChatCommand * ucc;

    QTreeWidgetItemIterator it(TreeWidget_CHAT_COMMANDS);

    for (; (*it); ++it) {
        ucc = new DC_UserChatCommand();
        ucc->m_sName = (*it)->text(0);
        ucc->m_sCommand = (*it)->text(1);

        commands.append(ucc);
    }

    /* transfer ownership to DCConfig::Instance() */
    DCConfig::Instance()->SetUserChatCommands(&commands);
}

void DCOptions::SaveAutoResponses() {
    QList<DC_AutoResponseObject*> autoresponses;
    DC_AutoResponseObject * aro = 0;

    QTreeWidgetItemIterator it(TreeWidget_AUTO_RESPONSES);
    for (; (*it); ++it) {
        aro = new DC_AutoResponseObject();
        aro->m_sTrigger = (*it)->text(0);
        if ((*it)->text(1) == tr("Yes")) {
            aro->m_bCaseSensitive = true;
        } else {
            aro->m_bCaseSensitive = false;
        }
        aro->m_sResponse = (*it)->text(2);

        autoresponses.append(aro);
    }

    /* transfer ownership to DCConfig::Instance() */
    DCConfig::Instance()->SetAutoResponses(&autoresponses);
}

/** */
void DCOptions::slotCreateShareList() {
    /* need to save these settings for them to be used during the refresh */
    DCConfig::Instance()->SetDontShareDotFiles(CheckBox_DONTSHAREDOTFILES->isChecked());
    DCConfig::Instance()->SetDisableHashList(CheckBox_DISABLEHASHLIST->isChecked());

    SaveSharedFolders();

    if (CFileManager::Instance()) {
        CFileManager::Instance()->CreateShareList();
    }
}

/** */
void DCOptions::slotShareListInfo() {
    QString s = tr("Compressed list size (HE3/BZ/XML): ") +
            QString().setNum(CFileManager::Instance()->GetShareBufferSize(esbtHE3)) + "/" +
            QString().setNum(CFileManager::Instance()->GetShareBufferSize(esbtBZ)) + "/" +
            QString().setNum(CFileManager::Instance()->GetShareBufferSize(esbtXMLBZ)) + " " +
            tr("bytes") + "\n" +
            tr("Total shared: ") +
            DCGuiUtils::GetSizeString(CFileManager::Instance()->GetShareSize());

    QMessageBox::information(this, tr("Share List Info"), s);
}

/** */
void DCOptions::slotSetTheme() {
    if (DCConfig::Instance()->GetThemeSupport()) {
        QString s = ComboBox_THEME->currentText();

        if (!s.isEmpty()) {
            QApplication::setStyle(s);
            m_sTestedTheme = s;
        }
    }
}

/** */
void DCOptions::slotBrowseLanguageFile() {
    QString file = QFileDialog::getOpenFileName(this, tr("Select language file"), LineEdit_LANGUAGEFILE->text(), "Language File (*.qm)");

    if (!file.isEmpty()) {
        LineEdit_LANGUAGEFILE->setText(file);
    }
}

eMenuItems DCOptions::getItemForFile(QString file) {
    if (file == "eiskaltdc.be.qm")
        return emiLANGUAGE_BELARUSIAN;
    else if (file == "eiskaltdc.bs.qm")
        return emiLANGUAGE_BOSNIAN;
    else if (file == "eiskaltdc.pt_br.qm")
        return emiLANGUAGE_BRAZILIAN;
    else if (file == "eiskaltdc.cs.qm")
        return emiLANGUAGE_CZECH;
    else if (file == "eiskaltdc.da.qm")
        return emiLANGUAGE_DANISH;
    else if (file == "eiskaltdc.nl.qm")
        return emiLANGUAGE_DUTCH;
    else if (file == "eiskaltdc.fi.qm")
        return emiLANGUAGE_FINNISH;
    else if (file == "eiskaltdc.fr.qm")
        return emiLANGUAGE_FRENCH;
    else if (file == "eiskaltdc.de.qm")
        return emiLANGUAGE_GERMAN;
    else if (file == "eiskaltdc.el.qm")
        return emiLANGUAGE_GREEK;
    else if (file == "eiskaltdc.en.qm")
        return emiLANGUAGE_ENGLISH;
    else if (file == "eiskaltdc.hu.qm")
        return emiLANGUAGE_HUNGARIAN;
    else if (file == "eiskaltdc.is.qm")
        return emiLANGUAGE_ICELANDIC;
    else if (file == "eiskaltdc.it.qm")
        return emiLANGUAGE_ITALIAN;
    else if (file == "eiskaltdc.lv.qm")
        return emiLANGUAGE_LATVIAN;
    else if (file == "eiskaltdc.nb.qm")
        return emiLANGUAGE_NORWEGIAN;
    else if (file == "eiskaltdc.pl.qm")
        return emiLANGUAGE_POLISH;
    else if (file == "eiskaltdc.ro.qm")
        return emiLANGUAGE_ROMANIAN;
    else if (file == "eiskaltdc.ru.qm")
        return emiLANGUAGE_RUSSIAN;
    else if (file == "eiskaltdc.sr.qm")
        return emiLANGUAGE_SERBIAN_CYRILLIC;
    else if (file == "eiskaltdc.sr@latin.qm")
        return emiLANGUAGE_SERBIAN_LATIN;
    else if (file == "eiskaltdc.es.qm")
        return emiLANGUAGE_SPANISH;
    else if (file == "eiskaltdc.sv.qm")
        return emiLANGUAGE_SWEDISH;

    return emiLANGUAGE_AUTOLANG;
}

/** */
void DCOptions::slotSelectLanguage() {
    QDir dir(DCConfig::Instance()->GetValknutDataPath() + QString(DIRSEPARATOR) + QString("translation") + QString(DIRSEPARATOR));

    if (!dir.exists())
        return;

    QFileInfoList list = dir.entryInfoList(QStringList() << "*.qm", QDir::Files);

    QMenu *m = new QMenu(this);

    QAction *auto_l = DCMenuHandler::addAction(m, emiLANGUAGE_AUTOLANG);
    auto_l->setStatusTip("");

    for (int i = 0; i < list.size(); i++) {
        QAction *act = DCMenuHandler::addAction(m, getItemForFile(list.at(i).fileName()));
        act->setStatusTip(list.at(i).absoluteFilePath());
    }

    QAction * choosen = m->exec(QCursor::pos());

    if (choosen == 0)
        return;
    else
        LineEdit_LANGUAGEFILE->setText(choosen->statusTip());

    delete m;
}

/** */
void DCOptions::slotBrowseAppFont() {
    bool ok;
    QFont font = QFontDialog::getFont(&ok, QApplication::font(), this);
    if (ok) {
        LineEdit_APPFONT->setText(font.toString());
    }
}

/** */
void DCOptions::slotAddHubListUrl() {
    bool ok = false;
    QString url = QInputDialog::getText(
            this,
            tr("HubList URL"),
            tr("Please enter a url"),
            QLineEdit::Normal,
            QString::null,
            &ok
            );

    if (ok) {
        QListWidgetItem * item = new QListWidgetItem(url, ListWidget_HUBLISTURL);
        item->setCheckState(Qt::Checked);
    }
}

/** */
void DCOptions::slotEditHubListUrl() {
    editHubListUrl(ListWidget_HUBLISTURL->currentItem());
}

/** */
void DCOptions::editHubListUrl(QListWidgetItem * item) {
    if (!item)
        return;

    bool ok = false;
    QString url = QInputDialog::getText(
            this,
            tr("HubList URL"),
            tr("Edit url"),
            QLineEdit::Normal,
            item->text(),
            &ok
            );

    if (ok) {
        item->setText(url);
    }
}

/** */
void DCOptions::slotRemoveHubListUrl() {
    QListWidgetItem * item = ListWidget_HUBLISTURL->currentItem();

    if (item) {
        delete item;
    }
}

/** */
void DCOptions::slotDoubleClickedHubListUrl(QListWidgetItem * item) {
    if (item) // always true since signal is only emitted on valid items
    {
        editHubListUrl(item);
    } else {
        slotAddHubListUrl();
    }
}

/** */
void DCOptions::slotContextMenuHubListUrl(const QPoint & pos) {
    QMenu * m = new QMenu(this);
    QListWidgetItem * item = ListWidget_HUBLISTURL->itemAt(pos);
    bool enabled = (item != 0);

    QAction * add = DCMenuHandler::addAction(m, emiADD);
    QAction * edit = DCMenuHandler::addAction(m, emiEDIT, enabled);
    QAction * remove = DCMenuHandler::addAction(m, emiREMOVE, enabled);

    QAction * chosen = m->exec(QCursor::pos());

    delete m;

    if (chosen == 0) {
        return;
    } else if (chosen == add) {
        slotAddHubListUrl();
    } else if (chosen == edit) {
        editHubListUrl(item);
    } else if (chosen == remove) {
        delete item;
    }
}

/** */
void DCOptions::slotHubListUrlsSelectionChanged() {
    if (ListWidget_HUBLISTURL->selectedItems().size() == 1) {
        ToolButton_EDITHUBLISTURL->setEnabled(true);
        ToolButton_REMOVEHUBLISTURL->setEnabled(true);
    } else {
        ToolButton_EDITHUBLISTURL->setEnabled(false);
        ToolButton_REMOVEHUBLISTURL->setEnabled(false);
    }
}

/** */
void DCOptions::slotTreeWidgetOptionTreeCurrentChanged(QTreeWidgetItem * item, QTreeWidgetItem * /* previous */) {
    if (item == plviIdentify) {
        stackedWidget->setCurrentIndex(TAB_IDENTIFY);
    } else if (item == plviTransfer) {
        stackedWidget->setCurrentIndex(TAB_TRANSFER);
        TabWidget_TRANSFER->setCurrentIndex(TAB_TRANSFER_SHARES);
    } else if (item == plviTransferShares) {
        stackedWidget->setCurrentIndex(TAB_TRANSFER);
        TabWidget_TRANSFER->setCurrentIndex(TAB_TRANSFER_SHARES);
    } else if (item == plviTransferDownloads) {
        stackedWidget->setCurrentIndex(TAB_TRANSFER);
        TabWidget_TRANSFER->setCurrentIndex(TAB_TRANSFER_DOWNLOADS);
    } else if (item == plviTransferUploads) {
        stackedWidget->setCurrentIndex(TAB_TRANSFER);
        TabWidget_TRANSFER->setCurrentIndex(TAB_TRANSFER_UPLOADS);
    } else if (item == plviTransferSettings) {
        stackedWidget->setCurrentIndex(TAB_TRANSFER);
        TabWidget_TRANSFER->setCurrentIndex(TAB_TRANSFER_SETTINGS);
    } else if (item == plviConnection) {
        stackedWidget->setCurrentIndex(TAB_CONNECTION);
        TabWidget_CONNECTION->setCurrentIndex(TAB_CONNECTION_MODE);
    } else if (item == plviConnectionMode) {
        stackedWidget->setCurrentIndex(TAB_CONNECTION);
        TabWidget_CONNECTION->setCurrentIndex(TAB_CONNECTION_MODE);
    } else if (item == plviConnectionSettings) {
        stackedWidget->setCurrentIndex(TAB_CONNECTION);
        TabWidget_CONNECTION->setCurrentIndex(TAB_CONNECTION_SETTINGS);
    } else if (item == plviGUI) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_GENERAL);
    } else if (item == plviGUIClient) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_CLIENT);
    } else if (item == plviGUIMenus) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_MENUS);
    } else if (item == plviGUIChat) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_CHAT);
    } else if (item == plviGUIColors) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_COLORS);
    } else if (item == plviGUICommands) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_COMMANDS);
    } else if (item == plviGUITransfer) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_TRANSFER);
    } else if (item == plviGUIGeneral) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_GENERAL);
    } else if (item == plviGUIIcons) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_ICONS);
    } else if (item == plviGUIFilelistBrowser) {
        stackedWidget->setCurrentIndex(TAB_GUI);
        TabWidget_GUI->setCurrentIndex(TAB_GUI_FILELIST);
    } else if (item == plviSound) {
        stackedWidget->setCurrentIndex(TAB_SOUND);
    } else if (item == plviLog) {
        stackedWidget->setCurrentIndex(TAB_LOG);
    } else if (item == plviHubLists) {
        stackedWidget->setCurrentIndex(TAB_HUBLISTS);
    } else if (item == plviSecurity) {
        stackedWidget->setCurrentIndex(TAB_SECURITY);
    } else if (item == plviAutoResponse) {
        stackedWidget->setCurrentIndex(TAB_AUTO_RESPONSES);
    } else if (item == plviOther) {
        stackedWidget->setCurrentIndex(TAB_OTHER);
    }
}

/** */
void DCOptions::slotTabWidgetDCGUICurrentChanged(int index) {
    disconnectOptionsTreeWidget();

    switch (index) {
        case TAB_IDENTIFY:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviIdentify);
            break;
        }
        case TAB_TRANSFER:
        {
            slotTabWidgetTransferCurrentChanged(TabWidget_TRANSFER->currentIndex());
            break;
        }
        case TAB_CONNECTION:
        {
            slotTabWidgetConnectionCurrentChanged(TabWidget_CONNECTION->currentIndex());
            break;
        }
        case TAB_GUI:
        {
            slotTabWidgetGUICurrentChanged(TabWidget_GUI->currentIndex());
            break;
        }
        case TAB_SOUND:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviSound);
            break;
        }
        case TAB_LOG:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviLog);
            break;
        }
        case TAB_HUBLISTS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviHubLists);
            break;
        }
        case TAB_SECURITY:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviSecurity);
            break;
        }
        case TAB_AUTO_RESPONSES:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviAutoResponse);
            break;
        }
        case TAB_OTHER:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviOther);
            break;
        }
        default:
        {
            break;
        }
    }

    connectOptionsTreeWidget();
}

/** */
void DCOptions::slotTabWidgetTransferCurrentChanged(int index) {
    disconnectOptionsTreeWidget();

    switch (index) {
        case TAB_TRANSFER_SHARES:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviTransferShares);
            break;
        }
        case TAB_TRANSFER_DOWNLOADS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviTransferDownloads);
            break;
        }
        case TAB_TRANSFER_UPLOADS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviTransferUploads);
            break;
        }
        case TAB_TRANSFER_SETTINGS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviTransferSettings);
            break;
        }
        default:
        {
            break;
        }
    }

    connectOptionsTreeWidget();
}

/** */
void DCOptions::slotTabWidgetConnectionCurrentChanged(int index) {
    disconnectOptionsTreeWidget();

    switch (index) {
        case TAB_CONNECTION_MODE:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviConnectionMode);
            break;
        }
        case TAB_CONNECTION_SETTINGS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviConnectionSettings);
            break;
        }
        default:
        {
            break;
        }
    }

    connectOptionsTreeWidget();
}

/** */
void DCOptions::slotTabWidgetGUICurrentChanged(int index) {
    disconnectOptionsTreeWidget();

    switch (index) {
        case TAB_GUI_GENERAL:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIGeneral);
            break;
        }
        case TAB_GUI_TRANSFER:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUITransfer);
            break;
        }
        case TAB_GUI_CHAT:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIChat);
            break;
        }
        case TAB_GUI_COLORS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIColors);
            break;
        }
        case TAB_GUI_COMMANDS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUICommands);
            break;
        }
        case TAB_GUI_MENUS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIMenus);
            break;
        }
        case TAB_GUI_CLIENT:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIClient);
            break;
        }
        case TAB_GUI_ICONS:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIIcons);
            break;
        }
        case TAB_GUI_FILELIST:
        {
            TreeWidget_OPTIONTREE->setCurrentItem(plviGUIFilelistBrowser);
            break;
        }
        default:
        {
            break;
        }
    }

    connectOptionsTreeWidget();
}

/** */
void DCOptions::slotAddUserMenuCommand() {
    DCUserCommandEditor * editor = new DCUserCommandEditor(this);

    if (editor->exec() == QDialog::Accepted) {
        DC_UserMenuCommand * umc = editor->GetUMC();
        usercommands[usercommands.size()] = umc;

        QTreeWidgetItem * item = new QTreeWidgetItem(TreeWidget_MENU_COMMANDS);
        item->setText(0, umc->m_sName);
        item->setText(1, umc->m_sCommand);
    }

    delete editor;
}

/** */
void DCOptions::slotEditUserMenuCommand() {
    QTreeWidgetItem * item = TreeWidget_MENU_COMMANDS->currentItem();

    if (item == 0) {
        return;
    }

    QModelIndex index = TreeWidget_MENU_COMMANDS->selectionModel()->currentIndex();

    if (!index.isValid()) {
        return;
    }

    const int key = index.row();

    DC_UserMenuCommand * umc = usercommands.value(key);

    if (!umc) {
        return;
    }

    DCUserCommandEditor * editor = new DCUserCommandEditor(this);
    editor->SetUMC(umc);

    if (editor->exec() == QDialog::Accepted) {
        usercommands.remove(key);

        delete umc;

        umc = editor->GetUMC();

        usercommands[ key ] = umc;

        item->setText(0, umc->m_sName);
        item->setText(1, umc->m_sCommand);
    }

    delete editor;
}

/** */
void DCOptions::slotRemoveUserMenuCommand() {
    QTreeWidgetItem * item = TreeWidget_MENU_COMMANDS->currentItem();

    if (item == 0) {
        return;
    }

    QModelIndex index = TreeWidget_MENU_COMMANDS->selectionModel()->currentIndex();

    if (!index.isValid()) {
        return;
    }

    int ret = QMessageBox::question(
            this,
            tr("Delete menu command?"),
            tr("Delete \"") + item->text(0) + QString("\"?"),
            QMessageBox::Yes | QMessageBox::No,
            QMessageBox::No
            );

    if (ret == QMessageBox::Yes) {
        delete usercommands.take(index.row());

        delete item;

        // fix numbering
        QList<DC_UserMenuCommand*> remaining = usercommands.values();
        usercommands.clear();
        for (int i = 0; i < remaining.size(); i++) {
            usercommands[i] = remaining[i];
        }
    }
}

/** */
void DCOptions::slotUpUserMenuCommand() {
    QModelIndex index = TreeWidget_MENU_COMMANDS->selectionModel()->currentIndex();

    if (!index.isValid()) {
        return;
    }

    int row = index.row();

    if (row == 0) {
        return;
    }

    if (!usercommands.contains(row) || !usercommands.contains(row - 1)) {
        return;
    }

    DC_UserMenuCommand * umc1 = usercommands.take(row);
    DC_UserMenuCommand * umc2 = usercommands.take(row - 1);

    usercommands[ row - 1 ] = umc1;
    usercommands[ row ] = umc2;

    QTreeWidgetItem * item1 = TreeWidget_MENU_COMMANDS->takeTopLevelItem(row);

    TreeWidget_MENU_COMMANDS->insertTopLevelItem(row - 1, item1);
    TreeWidget_MENU_COMMANDS->setCurrentItem(item1);
}

/** */
void DCOptions::slotDownUserMenuCommand() {
    QModelIndex index = TreeWidget_MENU_COMMANDS->selectionModel()->currentIndex();

    if (!index.isValid()) {
        return;
    }

    int row = index.row();

    if (row == TreeWidget_MENU_COMMANDS->topLevelItemCount() - 1) {
        return;
    }

    if (!usercommands.contains(row) || !usercommands.contains(row + 1)) {
        return;
    }

    DC_UserMenuCommand * umc1 = usercommands.take(row);
    DC_UserMenuCommand * umc2 = usercommands.take(row + 1);

    usercommands[ row + 1 ] = umc1;
    usercommands[ row ] = umc2;

    QTreeWidgetItem * item1 = TreeWidget_MENU_COMMANDS->takeTopLevelItem(row);

    TreeWidget_MENU_COMMANDS->insertTopLevelItem(row + 1, item1);
    TreeWidget_MENU_COMMANDS->setCurrentItem(item1);
}

/** */
void DCOptions::slotUserMenuCommandsSelectionChanged() {
    QList<QTreeWidgetItem*> selecteditems = TreeWidget_MENU_COMMANDS->selectedItems();
    if (selecteditems.size() != 1) {
        ToolButton_EDIT_USER_MENU_COMMAND->setEnabled(false);
        ToolButton_REMOVE_USER_MENU_COMMAND->setEnabled(false);
        ToolButton_UP_USER_MENU_COMMAND->setEnabled(false);
        ToolButton_DOWN_USER_MENU_COMMAND->setEnabled(false);
    } else {
        QTreeWidgetItem * selected = selecteditems.first();

        ToolButton_EDIT_USER_MENU_COMMAND->setEnabled(true);
        ToolButton_REMOVE_USER_MENU_COMMAND->setEnabled(true);

        int row = TreeWidget_MENU_COMMANDS->indexOfTopLevelItem(selected);

        if (row == 0) {
            ToolButton_UP_USER_MENU_COMMAND->setEnabled(false);
        } else {
            ToolButton_UP_USER_MENU_COMMAND->setEnabled(true);
        }

        if (row == TreeWidget_MENU_COMMANDS->topLevelItemCount() - 1) {
            ToolButton_DOWN_USER_MENU_COMMAND->setEnabled(false);
        } else {
            ToolButton_DOWN_USER_MENU_COMMAND->setEnabled(true);
        }
    }
}

/** */
void DCOptions::slotUserMenuCommandsDoubleClicked(QTreeWidgetItem * item, int /* column */) {
    if (item) {
        TreeWidget_MENU_COMMANDS->setCurrentItem(item);
        slotEditUserMenuCommand();
    } else {
        slotAddUserMenuCommand();
    }
}

/** */
void DCOptions::slotContextMenuUserChatCommands(const QPoint & pos) {
    QTreeWidgetItem * item = TreeWidget_CHAT_COMMANDS->itemAt(pos);
    bool enabled = (item != 0);

    QMenu * m = new QMenu(this);

    QAction * add = DCMenuHandler::addAction(m, emiADD);
    QAction * edit = DCMenuHandler::addAction(m, emiEDIT, enabled);
    QAction * remove = DCMenuHandler::addAction(m, emiREMOVE, enabled);

    QAction * chosen = m->exec(QCursor::pos());

    delete m;

    if (chosen == 0) {
        return;
    } else if (chosen == add) {
        QTreeWidgetItem * newitem = new QTreeWidgetItem(TreeWidget_CHAT_COMMANDS);
        newitem->setText(0, "/s");
        newitem->setText(1, "/sh somescript.sh");
        newitem->setFlags(newitem->flags() | Qt::ItemIsEditable);
    } else if (chosen == remove) {
        delete item;
    } else if (chosen == edit) {
        TreeWidget_CHAT_COMMANDS->editItem(
                item,
                TreeWidget_CHAT_COMMANDS->columnAt(pos.x())
                );
    }
}

/** */
void DCOptions::slotContextMenuAutoResponses(const QPoint & pos) {
    QTreeWidgetItem * item = TreeWidget_AUTO_RESPONSES->itemAt(pos);
    bool enabled = (item != 0);

    QMenu * m = new QMenu(this);

    QAction * add = DCMenuHandler::addAction(m, emiADD);
    QAction * edit = DCMenuHandler::addAction(m, emiEDIT, enabled);
    QAction * remove = DCMenuHandler::addAction(m, emiREMOVE, enabled);
    QAction * cs_yes = m->addAction(tr("Case sensitive"));
    cs_yes->setEnabled(enabled);
    QAction * cs_no = m->addAction(tr("Case insensitive"));
    cs_no->setEnabled(enabled);

    QAction * chosen = m->exec(QCursor::pos());

    delete m;

    if (chosen == 0) {
        return;
    } else if (chosen == add) {
        QTreeWidgetItem * newitem = new QTreeWidgetItem(TreeWidget_AUTO_RESPONSES);
        newitem->setText(0, tr("-trigger"));
        newitem->setText(1, tr("No"));
        newitem->setText(2, tr("response"));
        newitem->setFlags(newitem->flags() | Qt::ItemIsEditable);
    } else if (chosen == edit) {
        int column = TreeWidget_AUTO_RESPONSES->columnAt(pos.x());
        if ((column == 0) || (column == 2)) {
            TreeWidget_AUTO_RESPONSES->editItem(
                    item,
                    column
                    );
        }
    } else if (chosen == remove) {
        delete item;
    } else if (chosen == cs_yes) {
        item->setText(1, tr("Yes"));
    } else if (chosen == cs_no) {
        item->setText(1, tr("No"));
    }
}

/** */
void DCOptions::setupIconThemeComboBoxes() {
    ComboBox_APPLICATION_ICONS->clear();
    ComboBox_USERLIST_ICONS->clear();
    ComboBox_EMOTICONS->clear();

    setupIconThemeComboBox(ComboBox_APPLICATION_ICONS, "appl");
    setupIconThemeComboBox(ComboBox_USERLIST_ICONS, "user");
    setupIconThemeComboBox(ComboBox_EMOTICONS, "emot");
}

/** */
void DCOptions::setupIconThemeComboBox(QComboBox * box, QString icontype) {
    QDir dir;
    dir.setPath(DCConfig::Instance()->GetValknutDataPath() + "/icons/" + icontype + "/");
    dir.setFilter(QDir::Dirs | QDir::Readable | QDir::Executable);
    dir.setSorting(QDir::Name);

    const QFileInfoList iconslist = dir.entryInfoList();
    if (iconslist.size() > 0) {
        for (int i = 0; i < iconslist.size(); ++i) {
            QFileInfo fi = iconslist.at(i);

            if ((fi.fileName() == ".") || (fi.fileName() == "..")) {
                // skip
            } else {
                box->addItem(fi.fileName());
            }
        }
    }
}

/** */
void DCOptions::slotGenerateKeyCert() {
    QProcess * proc1 = 0;
    QProcess * proc2 = 0;
    QStringList args1;
    QStringList args2;
    QString keyname = LineEdit_TRANSFERKEY->text();
    QString certname = LineEdit_TRANSFERCERT->text();
    QFile key;
    QFile cert;
    QDir keypath;
    QDir certpath;

    PushButton_GENERATE_CERT->setEnabled(false);

    if (keyname.isEmpty()) {
        keyname = QString(DCConfig::Instance()->GetConfigPath().Data()) + QString("ssl/valknut.key");
    }

    if (certname.isEmpty()) {
        certname = QString(DCConfig::Instance()->GetConfigPath().Data()) + QString("ssl/valknut.cert");
    }

    keyname.replace("//", "/");
    certname.replace("//", "/");

    key.setFileName(keyname);
    cert.setFileName(certname);

    if (key.exists() || cert.exists()) {
        int ret = QMessageBox::question(
                this,
                tr("Overwrite?"),
                tr("Replace existing key/cert?"),
                QMessageBox::Yes | QMessageBox::No,
                QMessageBox::No
                );

        if (ret == QMessageBox::No) {
            PushButton_GENERATE_CERT->setEnabled(true);
            return;
        }
    }

    keypath.setPath(QFileInfo(keyname).path());
    certpath.setPath(QFileInfo(certname).path());

    if (keypath.isRelative()) {
        keyname.prepend(QDir::separator());
        keyname.prepend(QDir::currentPath());
        keypath.setPath(QFileInfo(keyname).absolutePath());
    }

    if (certpath.isRelative()) {
        certname.prepend(QDir::separator());
        certname.prepend(QDir::currentPath());
        certpath.setPath(QFileInfo(certname).absolutePath());
    }

    if (keypath.exists() == false) {
        if (keypath.mkdir(keypath.path()) == false) {
            QMessageBox::critical(
                    this,
                    tr("Could not create folder for key"),
                    tr("Could not create ") + keypath.path()
                    );
            PushButton_GENERATE_CERT->setEnabled(true);
            return;
        }
    }

    if (certpath.exists() == false) {
        if (certpath.mkdir(certpath.path()) == false) {
            QMessageBox::critical(
                    this,
                    tr("Could not create folder for cert"),
                    tr("Could not create ") + certpath.path()
                    );
            PushButton_GENERATE_CERT->setEnabled(true);
            return;
        }
    }

    proc1 = new QProcess();
    proc1->setWorkingDirectory(keypath.path());

    args1 << "genrsa";
    args1 << "-out";
    args1 << keyname;
    args1 << "2048";

    proc1->start("openssl", args1);
    proc1->waitForFinished(5000);

    if (proc1->state() != QProcess::NotRunning) {
        proc1->terminate();
        proc1->waitForFinished(1000);
        if (proc1->state() != QProcess::NotRunning) {
            proc1->kill();
        }
    }

    if ((proc1->exitStatus() == QProcess::CrashExit) || (proc1->exitCode() != 0)) {
        QMessageBox::critical(
                this,
                tr("Error occurred while running openssl 1"),
                QString(proc1->readAllStandardError()) + "\n\n" + tr("Make sure the openssl program is in your PATH.")
                );
        delete proc1;
        PushButton_GENERATE_CERT->setEnabled(true);
        return;
    }

    delete proc1;

    proc2 = new QProcess(this);
    proc2->setWorkingDirectory(certpath.path());

    args2 << "req";
    args2 << "-x509";
    args2 << "-new";
    args2 << "-batch";
    args2 << "-days";
    args2 << "3650";
    args2 << "-key";
    args2 << keyname;
    args2 << "-out";
    args2 << certname;
    args2 << "-subj";
    args2 << QString("/CN=EiskaltDC-") + LineEdit_NICK->text();

    proc2->start("openssl", args2);
    proc2->waitForFinished(5000);

    if (proc2->state() != QProcess::NotRunning) {
        proc2->terminate();
        proc2->waitForFinished(1000);
        if (proc2->state() != QProcess::NotRunning) {
            proc2->kill();
        }
    }

    if ((proc2->exitStatus() == QProcess::CrashExit) || (proc2->exitCode() != 0)) {
        QMessageBox::critical(
                this,
                tr("Error occurred while running openssl 2"),
                QString(proc2->readAllStandardError()) + "\n\n" + tr("Make sure the openssl program is in your PATH.")
                );
        delete proc2;
        PushButton_GENERATE_CERT->setEnabled(true);
        return;
    }

    delete proc2;

    LineEdit_TRANSFERKEY->setText(keyname);
    LineEdit_TRANSFERCERT->setText(certname);

    // set them even if dialog is cancelled since files have been created
    DCConfig::Instance()->SetTransferKey(keyname.toAscii().constData());
    DCConfig::Instance()->SetTransferCert(certname.toAscii().constData());

    PushButton_GENERATE_CERT->setEnabled(true);
}

void DCOptions::showEvent(QShowEvent *e) {
    QTreeWidgetItem *it = plviIdentify;
    QFontMetrics t_fontMetrics(TreeWidget_OPTIONTREE->font());
    int max_len = 0;

    while (it) {
        QString it_text = it->text(0);
        int it_text_w = t_fontMetrics.width(it_text);

        max_len = max_len < it_text_w ? it_text_w : max_len;

        it = TreeWidget_OPTIONTREE->itemBelow(it);
    }

    TreeWidget_OPTIONTREE->setMaximumWidth(max_len + (t_fontMetrics.width("_")*10));

    e->accept();
}

void DCOptions::slotTrayMessageType() {
    TrayMessageType t_type = DCConfig::Instance()->GetTrayMessageType();

    bool checked = checkBox_ENABLENOTIFY->isChecked();

    checkBox_PRIVATE->setEnabled(checked);
    checkBox_NICKINCHAT->setEnabled(checked);
    checkBox_CONNECTIONLOST->setEnabled(checked);
    checkBox_WNDACTV->setEnabled(checked);
    checkBox_WNDVSBL->setEnabled(checked);

    if (checked)
        USET_TRAY_MSG_NONE(t_type);
    else
        SET_TRAY_MSG_NONE(t_type);

    if (checkBox_CONNECTIONLOST->isChecked())
        SET_TRAY_MSG_DISC(t_type);
    else
        USET_TRAY_MSG_DISC(t_type);

    if (checkBox_NICKINCHAT->isChecked())
        SET_TRAY_MSG_NICK(t_type);
    else
        USET_TRAY_MSG_NICK(t_type);

    if (checkBox_PRIVATE->isChecked())
        SET_TRAY_MSG_PRIV(t_type);
    else
        USET_TRAY_MSG_PRIV(t_type);

    if (checkBox_WNDACTV->isChecked())
        SET_TRAY_WND_ACTV(t_type);
    else
        USET_TRAY_WND_ACTV(t_type);

    if (checkBox_WNDVSBL->isChecked())
        SET_TRAY_WND_VSBL(t_type);
    else
        USET_TRAY_WND_VSBL(t_type);

    DCConfig::Instance()->SetTrayMessageType(t_type);
}

void DCOptions::slotAddDownloadAlias(){
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select share folder"));

    if (!dir.isEmpty()) {
	if (treeWidget_DOWNLOADALIASES->findItems(dir, Qt::MatchExactly, 1).size() == 0) {

	    bool ok = false;
	    QString dir_alias = QInputDialog::getText(this, tr("Select directory"), tr("Alias"),
						      QLineEdit::Normal,
						      QDir(dir).dirName(),
						      &ok);
	    if (!ok)
		return;

	    if (dir_alias.isEmpty() || dir_alias.isNull() ||
		(dir_alias.indexOf("\\W") >= 0))
	    {
		QMessageBox msg_box(QMessageBox::Critical,
				    tr("Error"),
				    tr("Special symbols are not alowed"),
				    QMessageBox::Ok);
		msg_box.exec();

		return;
	    }

	    if (treeWidget_DOWNLOADALIASES->findItems(dir_alias, Qt::MatchExactly, 0).size() != 0){
		QMessageBox msg_box(QMessageBox::Critical,
				    tr("Error"),
				    tr("Alias already exists"),
				    QMessageBox::Ok);
		msg_box.exec();

		return;
	    }

	    DCDownloadAlias *alias = new DCDownloadAlias;
	    alias->alias = dir_alias;
	    alias->path  = dir;

	    QList<DCDownloadAlias*> alias_list = DCConfig::Instance()->GetDownloadAliases();
	    alias_list << alias;

	    DCConfig::Instance()->SetDownloadAliases(alias_list);

	    QTreeWidgetItem * item = new QTreeWidgetItem(treeWidget_DOWNLOADALIASES);
	    item->setText(0, dir_alias);
	    item->setText(1, dir);
	}
    }
}

void DCOptions::slotRemDownloadAlias(){
    QTreeWidgetItem *it = treeWidget_DOWNLOADALIASES->currentItem();

    if (!it)
	return;

    QList<DCDownloadAlias*> alias_list = DCConfig::Instance()->GetDownloadAliases();

    for (int i = 0; i < alias_list.size(); i++){
	DCDownloadAlias *da =  alias_list.at(i);

	if (da->alias == it->text(0))
	{
	    delete da;
	    alias_list.removeAt(i);

	    QTreeWidgetItemIterator it(treeWidget_DOWNLOADALIASES, QTreeWidgetItemIterator::NotHidden);

	    while (*it) {
		    if (*it)
			delete *it;
		    ++it;
	    }

	    treeWidget_DOWNLOADALIASES->clear();

	    DCConfig::Instance()->SetDownloadAliases(alias_list);

	    loadDownloadAliases();

	    return;
	}
    }
}

void DCOptions::loadDownloadAliases(){

    QList<DCDownloadAlias*> alias_list = DCConfig::Instance()->GetDownloadAliases();

    for (int i = 0; i < alias_list.size(); i++){
	QTreeWidgetItem * item = new QTreeWidgetItem(treeWidget_DOWNLOADALIASES);
	item->setText(0, alias_list.at(i)->alias);
	item->setText(1, alias_list.at(i)->path);
    }
}
