/****************************************************************************
** Dooble - The Secure Internet Web Browser
**
** Copyright (c) 2008, 2009, 2010 Alexis Megas,
** Gunther van Dooble, and the Dooble Team.
** All rights reserved.
**
** License: GPL2 only:
** 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; version 2 of the License only.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
** or see here: http://www.gnu.org/licenses/gpl.html
**
** For the WebKit library, please see: http://webkit.org.
**
** THE CODE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS APPLICATION, EVEN IF ADVISED
** OF THE POSSIBILITY OF SUCH DAMAGE.
**
** Please report all praise, requests, bugs, and problems to the project
** team and administrators: http://sf.net/projects/dooble.
**
** You can find us listed at our project page. New team members are welcome.
** The name of the authors should not be used to endorse or promote products
** derived from Dooble without specific prior written permission.
** If you use this code for other projects, please let us know.
**
** Web sites:
**   http://sf.net/projects/dooble
**   http://dooble.sf.net
****************************************************************************/

#include <QDir>
#include <QMap>
#include <QUrl>
#include <QLocale>
#include <QSettings>
#include <QFileDialog>
#include <QWebSettings>
#include <QDesktopServices>

#include "dooble.h"
#include "dsettings.h"

dsettings::dsettings():QDialog()
{
  ui.setupUi(this);

  foreach(QPushButton *button, ui.buttonBox->findChildren<QPushButton *>())
    button->setIcon(QIcon());

#ifdef Q_WS_MAC
  setAttribute(Qt::WA_MacMetalStyle, true);
#endif
  ui.popupExceptionsPushButton->setEnabled(false);

  QSettings settings;

  if(!dooble::s_settings.contains("iconSet"))
    {
      settings.setValue("iconSet",
			QString("%1/%2").arg(QDir::currentPath()).
			arg("Icons/nuovext/configuration.cfg"));
      dooble::s_settings["iconSet"] =
	QString("%1/%2").arg(QDir::currentPath()).
	arg("Icons/nuovext/configuration.cfg");
    }

  if(!dooble::s_settings.contains("settingsWindow/iconSet1"))
    {
      settings.setValue("settingsWindow/iconSet1", settings.value("iconSet"));
      dooble::s_settings["settingsWindow/iconSet1"] =
	dooble::s_settings["iconSet"];
    }

  QSettings cfgSettings(dooble::s_settings.value("iconSet").toString(),
			QSettings::IniFormat);

  setWindowIcon
    (QIcon(cfgSettings.value("settingsWindow/windowIcon").toString()));
  setSizeGripEnabled(true);
  connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)),
	  this, SLOT(slotClicked(QAbstractButton *)));
  connect(ui.chooseIconSetPushButton, SIGNAL(clicked(void)),
	  this, SLOT(slotSelectIconCfgFile(void)));
  connect(ui.chooseMyRetrievedFilesPushButton, SIGNAL(clicked(void)),
	  this, SLOT(slotChooseMyRetrievedFilesDirectory(void)));
  connect(ui.fontComboBox, SIGNAL(currentIndexChanged(const QString &)),
	  this, SLOT(slotFontChanged(const QString &)));
  connect(ui.defaultFontCombinationBox,
	  SIGNAL(currentIndexChanged(const QString &)),
	  this, SLOT(slotWebFontChanged(const QString &)));
  connect(ui.fixedFontCombinationBox,
	  SIGNAL(currentIndexChanged(const QString &)),
	  this, SLOT(slotWebFontChanged(const QString &)));
  connect(ui.historyCheckBox,
	  SIGNAL(clicked(bool)),
	  ui.historySpinBox,
	  SLOT(setEnabled(bool)));
  connect(ui.cookieTimerComboBox,
	  SIGNAL(currentIndexChanged(int)),
	  this,
	  SLOT(slotCookieTimerTimeChanged(int)));
  connect(ui.cookieTimerCheckBox,
	  SIGNAL(clicked(bool)),
	  ui.cookieTimerComboBox,
	  SLOT(setEnabled(bool)));
  connect(ui.cookieTimerCheckBox,
	  SIGNAL(clicked(bool)),
	  ui.cookieTimerSpinBox,
	  SLOT(setEnabled(bool)));

  /*
  ** As long as the tab order of the buttons is correct, this trick
  ** will always work.
  */

  int idx = 0;

  foreach(QToolButton *button, ui.tabFrame->findChildren<QToolButton *> ())
    {
      connect(button,
	      SIGNAL(clicked(bool)),
	      this,
	      SLOT(slotChangePage(bool)));
      button->setProperty("page", idx);
      idx += 1;
    }

  ui.doobleSearchLineEdit->setText
    (QUrl::fromLocalFile(QString("%1/Tab/Default/search.html").arg
			 (QDir::currentPath())).toString());
  settings.setValue("settingsWindow/url12",
		    ui.doobleSearchLineEdit->text().trimmed());
  dooble::s_settings["settingsWindow/url12"] =
    ui.doobleSearchLineEdit->text().trimmed();

  if(!dooble::s_settings.contains("settingsWindow/myRetrievedFiles"))
    {
      QString path = QDesktopServices::storageLocation
	(QDesktopServices::DesktopLocation);

      if(path.isEmpty() || !QFile::exists(path) ||
	 !QFileInfo(path).isReadable())
	path = QDir::homePath();

      settings.setValue("settingsWindow/myRetrievedFiles", path);
      dooble::s_settings["settingsWindow/myRetrievedFiles"] = path;
    }

  ui.myRetrievedFilesLineEdit->setText
    (dooble::s_settings.value("settingsWindow/myRetrievedFiles").toString());
  slotSetIcons();
  slotCookieTimerTimeChanged(0);
}

dsettings::~dsettings()
{
}

void dsettings::exec(QWidget *parent)
{
  ui.url01lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url1", "").toString().trimmed());
  ui.url02lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url2", "").toString().trimmed());
  ui.url03lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url3", "").toString().trimmed());
  ui.url04lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url4", "").toString().trimmed());
  ui.url05lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url5", "").toString().trimmed());
  ui.url06lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url6", "").toString().trimmed());
  ui.url07lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url7", "").toString().trimmed());
  ui.url08lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url8", "").toString().trimmed());
  ui.url09lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url9", "").toString().trimmed());
  ui.url10lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url10",
			      "").toString().trimmed());
  ui.url11lineEdit->setText
    (dooble::s_settings.value("settingsWindow/url11",
			      "").toString().trimmed());
  ui.displayDesktopCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/displayDesktopCheckBox",
			      false).toBool());
  ui.proceedToNewTabCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/proceedToNewTab",
			      true).toBool());
  ui.openInNewTabsCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/openInNewTab", true).toBool());
  ui.addTabWithDoubleClick->setChecked
    (dooble::s_settings.value("settingsWindow/addTabWithDoubleClick",
			      true).toBool());
  ui.pluginsCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/enablePlugins", true).toBool());
  ui.browsingProxyGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/proxyEnabled", false).toBool());
  ui.ftpProxyGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/ftpProxyEnabled",
			      false).toBool());
  ui.browsingFtpProxyGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/ftpBrowsingProxyEnabled",
			      false).toBool());
  ui.httpProxyGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/httpProxyEnabled", false).
     toBool());
  ui.proxyType->setCurrentIndex
    (ui.proxyType->findText
     (dooble::s_settings.value("settingsWindow/proxyType",
			       "Socks5").toString().trimmed()));
  ui.proxyHostName->setText
    (dooble::s_settings.value("settingsWindow/proxyHost",
			      "").toString().trimmed());
  ui.proxyPort->setValue(dooble::s_settings.value("settingsWindow/proxyPort",
						  1080).toInt());
  ui.proxyUserName->setText
    (dooble::s_settings.value("settingsWindow/proxyUser",
			      "").toString().trimmed());
  ui.proxyPassword->setText(dooble::s_settings.value
			    ("settingsWindow/proxyPassword",
			     "").toString().trimmed());
  ui.i2pProxyGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/i2pProxyEnabled",
			      true).toBool());
  ui.i2pProxyType->setCurrentIndex
    (ui.i2pProxyType->findText
     (dooble::s_settings.value("settingsWindow/i2pProxyType",
			       "Http").toString().trimmed()));
  ui.i2pProxyHostName->setText(dooble::s_settings.value
			       ("settingsWindow/i2pProxyHost",
				"127.0.0.1").toString().trimmed());
  ui.i2pProxyPort->setValue(dooble::s_settings.value
			    ("settingsWindow/i2pProxyPort",
			     4444).toInt());
  ui.i2pProxyGroupBox_2->setChecked
    (dooble::s_settings.value("settingsWindow/di2pProxyEnabled",
			      true).toBool());
  ui.i2pProxyType_2->setCurrentIndex
    (ui.i2pProxyType_2->findText
     (dooble::s_settings.value("settingsWindow/di2pProxyType",
			       "Http").toString().trimmed()));
  ui.i2pProxyHostName_2->setText(dooble::s_settings.value
				 ("settingsWindow/di2pProxyHost",
				  "127.0.0.1").toString().trimmed());
  ui.i2pProxyPort_2->setValue(dooble::s_settings.value
			      ("settingsWindow/di2pProxyPort",
			       4444).toInt());
  ui.ftpProxyHostName->setText
    (dooble::s_settings.value("settingsWindow/ftpProxyHost",
			      "").toString().trimmed());
  ui.ftpProxyPort->setValue
    (dooble::s_settings.value("settingsWindow/ftpProxyPort",
			      21).toInt());
  ui.browsingFtpProxyHostName->setText
    (dooble::s_settings.value("settingsWindow/ftpBrowsingProxyHost",
			      "").toString().trimmed());
  ui.browsingFtpProxyPort->setValue
    (dooble::s_settings.value("settingsWindow/ftpBrowsingProxyPort",
			      21).toInt());
  ui.httpProxyType->setCurrentIndex
    (ui.proxyType->findText
     (dooble::s_settings.value("settingsWindow/httpProxyType",
			       "Socks5").toString().trimmed()));
  ui.httpProxyHostName->setText
    (dooble::s_settings.value("settingsWindow/httpProxyHost",
			      "").toString().trimmed());
  ui.httpProxyPort->setValue
    (dooble::s_settings.value("settingsWindow/httpProxyPort",
			      1080).toInt());
  ui.httpProxyUserName->setText
    (dooble::s_settings.value("settingsWindow/httpProxyUser",
			      "").toString().trimmed());
  ui.httpProxyPassword->setText
    (dooble::s_settings.value("settingsWindow/httpProxyPassword",
			      "").toString().trimmed());

  if(!dooble::s_settings.value("settingsWindow/url12",
			       "").toString().isEmpty())
    ui.doobleSearchLineEdit->setText
      (dooble::s_settings.value("settingsWindow/url12", "").
       toString().trimmed());

  ui.automaticallyLoadImagesCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/automaticallyLoadImages",
			      true).toBool());
  ui.openUserWindowsInNewProcessesCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/openUserWindowsInNewProcesses",
			      false).toBool());
  ui.closeViaMiddleCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/closeViaMiddle", true).toBool());

  QStringList allKeys(dooble::s_settings.keys());
  QMap<QString, QString> itemsMap;

  for(int i = 0; i < allKeys.size(); i++)
    if(allKeys[i].contains("iconSet"))
      {
	if(!QFileInfo(dooble::s_settings.value
		      (allKeys[i]).toString()).exists())
	  {
	    /*
	    ** Remove the setting from the configuration file.
	    */

	    dooble::s_settings.remove(allKeys[i]);
	    continue;
	  }

	QSettings settings
	  (dooble::s_settings.value(allKeys[i]).toString(),
	   QSettings::IniFormat);

	settings.beginGroup("Description");
	itemsMap[settings.value("Name").toString()] =
	  dooble::s_settings.value(allKeys[i]).toString();
      }

  allKeys.clear();
  ui.iconSetComboBox->clear();

  QSettings settings
    (dooble::s_settings.value("iconSet").toString(), QSettings::IniFormat);

  settings.beginGroup("Description");

  for(int i = 0; i < itemsMap.size(); i++)
    {
      ui.iconSetComboBox->addItem(itemsMap.keys()[i],
				  itemsMap.values()[i]);

      if(settings.value("Name").toString() == itemsMap.keys()[i])
	ui.iconSetComboBox->setCurrentIndex(i);
    }

  itemsMap.clear();
  ui.javaCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/javaEnabled", false).toBool());
  ui.javascriptGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/javascriptEnabled", true).
     toBool());
  ui.jsAllowNewWindowsCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/javascriptAllowNewWindows",
			      false).toBool());
  ui.cookieGroupBox->setChecked
    (dooble::s_settings.value("settingsWindow/cookiesEnabled", true).toBool());
  ui.blockPopupsCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/blockPopups", false).toBool());
  ui.languageComboBox->clear();

  QFont font;

  if(font.fromString(dooble::s_settings.value("settingsWindow/globalFont", "").
		     toString()) &&
     !font.family().isEmpty())
    {
      if(ui.fontComboBox->findText(font.family()) > -1)
	ui.fontComboBox->setCurrentIndex
	  (ui.fontComboBox->findText(font.family()));
      else
	ui.fontComboBox->setCurrentIndex(0);

      updateFontWidgets(font.family(), ui.fontSizeComboBox);

      QString globalFontSize(QString::number(font.pointSize()));

      if(ui.fontSizeComboBox->findText(globalFontSize) > -1)
	ui.fontSizeComboBox->setCurrentIndex
	  (ui.fontSizeComboBox->findText(globalFontSize));
      else
	ui.fontSizeComboBox->setCurrentIndex(0);
    }
  else
    {
      QString text("");
      QString fontSize("");

#ifdef Q_WS_MAC
      text = "Times";
      fontSize = "10";
#elif defined Q_WS_WIN
      text = "Arial";
      fontSize = "12";
#else
      text = "Serif";
      fontSize = "9";
#endif

      if(ui.fontComboBox->findText(text) > -1)
	ui.fontComboBox->setCurrentIndex
	  (ui.fontComboBox->findText(text));
      else
	ui.fontComboBox->setCurrentIndex(0);

      updateFontWidgets(ui.fontComboBox->currentText(),
			ui.fontSizeComboBox);

      if(ui.fontSizeComboBox->findText(fontSize) > -1)
	ui.fontSizeComboBox->setCurrentIndex
	  (ui.fontSizeComboBox->findText(fontSize));
      else
	ui.fontSizeComboBox->setCurrentIndex(0);
    }

  if(font.fromString(dooble::s_settings.value
		     ("settingsWindow/standardWebFont", "").
		     toString()) &&
     !font.family().isEmpty())
    {
      if(ui.defaultFontCombinationBox->findText(font.family()) > -1)
	ui.defaultFontCombinationBox->setCurrentIndex
	  (ui.defaultFontCombinationBox->findText(font.family()));
      else
	ui.defaultFontCombinationBox->setCurrentIndex(0);

      updateFontWidgets(font.family(), ui.defaultFontSizeCombinationBox);

      QString fontSize(QString::number(font.pointSize()));

      if(ui.defaultFontSizeCombinationBox->findText(fontSize) > -1)
	ui.defaultFontSizeCombinationBox->setCurrentIndex
	  (ui.defaultFontSizeCombinationBox->findText(fontSize));
      else
	ui.defaultFontSizeCombinationBox->setCurrentIndex(0);
    }
  else
    {
      QString text("");
      QString fontSize("");

#ifdef Q_WS_MAC
      text = "Times";
      fontSize = "16";
#elif defined Q_WS_WIN
      text = "Serif";
      fontSize = "16";
#else
      text = "Serif";
      fontSize = "16";
#endif

      if(ui.defaultFontCombinationBox->findText(text) > -1)
	ui.defaultFontCombinationBox->setCurrentIndex
	  (ui.defaultFontCombinationBox->findText(text));
      else
	ui.defaultFontCombinationBox->setCurrentIndex(0);

      updateFontWidgets(ui.defaultFontCombinationBox->currentText(),
			ui.defaultFontSizeCombinationBox);

      if(ui.defaultFontSizeCombinationBox->findText(fontSize) > -1)
	ui.defaultFontSizeCombinationBox->setCurrentIndex
	  (ui.defaultFontSizeCombinationBox->findText(fontSize));
      else
	ui.defaultFontSizeCombinationBox->setCurrentIndex(0);
    }

  if(font.fromString
     (dooble::s_settings.value("settingsWindow/cursiveWebFont", "").
      toString()) &&
     !font.family().isEmpty())
    {
      if(ui.cursiveFontCombinationBox->findText(font.family()) > -1)
	ui.cursiveFontCombinationBox->setCurrentIndex
	  (ui.cursiveFontCombinationBox->findText(font.family()));
      else
	ui.cursiveFontCombinationBox->setCurrentIndex(0);
    }
  else
    {
      if(ui.cursiveFontCombinationBox->
	 findText("Serif") > -1)
	ui.cursiveFontCombinationBox->setCurrentIndex
	  (ui.cursiveFontCombinationBox->
	   findText("Serif"));
      else
	ui.cursiveFontCombinationBox->setCurrentIndex(0);
    }

  if(font.fromString
     (dooble::s_settings.value("settingsWindow/fantasyWebFont", "").
      toString()) &&
     !font.family().isEmpty())
    {
      if(ui.fantasyFontCombinationBox->findText(font.family()) > -1)
	ui.fantasyFontCombinationBox->setCurrentIndex
	  (ui.fantasyFontCombinationBox->findText(font.family()));
      else
	ui.fantasyFontCombinationBox->setCurrentIndex(0);
    }
  else
    {
      if(ui.fantasyFontCombinationBox->
	 findText("Serif") > -1)
	ui.fantasyFontCombinationBox->setCurrentIndex
	  (ui.fantasyFontCombinationBox->
	   findText("Serif"));
      else
	ui.fantasyFontCombinationBox->setCurrentIndex(0);
    }

  if(font.fromString
     (dooble::s_settings.value("settingsWindow/fixedWebFont", "").
      toString()) &&
     !font.family().isEmpty())
    {
      if(ui.fixedFontCombinationBox->findText(font.family()) > -1)
	ui.fixedFontCombinationBox->setCurrentIndex
	  (ui.fixedFontCombinationBox->findText(font.family()));
      else
	ui.fixedFontCombinationBox->setCurrentIndex(0);

      updateFontWidgets(font.family(), ui.fixedFontSizeCombinationBox);

      QString fontSize(QString::number(font.pointSize()));

      if(ui.fixedFontSizeCombinationBox->findText(fontSize) > -1)
	ui.fixedFontSizeCombinationBox->setCurrentIndex
	  (ui.fixedFontSizeCombinationBox->findText(fontSize));
      else
	ui.fixedFontSizeCombinationBox->setCurrentIndex(0);
    }
  else
    {
      int index = -1;
      QString text("");
      QString fontSize("");

#ifdef Q_WS_MAC
      text = "Courier";
      fontSize = "13";
#elif defined Q_WS_WIN
      text = "Courier New";
      fontSize = "16";
#else
      text = "Courier";
      fontSize = "10";
#endif

      if((index = ui.fixedFontCombinationBox->
	  findText(text, Qt::MatchContains)) > -1)
	ui.fixedFontCombinationBox->setCurrentIndex(index);
      else
	ui.fixedFontCombinationBox->setCurrentIndex(0);

      updateFontWidgets(ui.fixedFontCombinationBox->currentText(),
			ui.fixedFontSizeCombinationBox);

      if(ui.fixedFontSizeCombinationBox->findText(fontSize) > -1)
	ui.fixedFontSizeCombinationBox->setCurrentIndex
	  (ui.fixedFontSizeCombinationBox->findText(fontSize));
      else
	ui.fixedFontSizeCombinationBox->setCurrentIndex(0);
    }

  if(font.fromString
     (dooble::s_settings.value("settingsWindow/sansSerifWebFont", "").
      toString()) &&
     !font.family().isEmpty())
    {
      if(ui.sansSerifFontCombinationBox->findText(font.family()) > -1)
	ui.sansSerifFontCombinationBox->setCurrentIndex
	  (ui.sansSerifFontCombinationBox->findText(font.family()));
      else
	ui.sansSerifFontCombinationBox->setCurrentIndex(0);
    }
  else
    {
      QString text("");

#ifdef Q_WS_MAC
      text = "Helvetica";
#elif defined Q_WS_WIN
      text = "Arial";
#else
      text = "Sans Serif";
#endif

      if(ui.sansSerifFontCombinationBox->
	 findText(text) > -1)
	ui.sansSerifFontCombinationBox->setCurrentIndex
	  (ui.sansSerifFontCombinationBox->
	   findText(text));
      else
	ui.sansSerifFontCombinationBox->setCurrentIndex(0);
    }

  if(font.fromString
     (dooble::s_settings.value("settingsWindow/serifWebFont", "").
      toString()) && !font.family().isEmpty())
    {
      if(ui.serifFontCombinationBox->findText(font.family()) > -1)
	ui.serifFontCombinationBox->setCurrentIndex
	  (ui.serifFontCombinationBox->findText(font.family()));
      else
	ui.serifFontCombinationBox->setCurrentIndex(0);
    }
  else
    {
      QString text("");

#ifdef Q_WS_MAC
      text = "Times";
#elif defined Q_WS_WIN
      text = "Times New Roman";
#else
      text = "Serif";
#endif

      if(ui.serifFontCombinationBox->
	 findText(text) > -1)
	ui.serifFontCombinationBox->setCurrentIndex
	  (ui.serifFontCombinationBox->findText(text));
      else
	ui.serifFontCombinationBox->setCurrentIndex(0);
    }

  QString size = dooble::s_settings.value
    ("settingsWindow/minimumWebFontSize", "9").toString();

  if(ui.minimumFontSizeCombinationBox->findText(size) > -1)
    ui.minimumFontSizeCombinationBox->setCurrentIndex
      (ui.minimumFontSizeCombinationBox->findText(size));
  else
    ui.minimumFontSizeCombinationBox->setCurrentIndex(0);

  ui.jsAcceptGeometryRequestsCheckBox->setChecked
    (dooble::s_settings.value
     ("settingsWindow/javascriptAcceptGeometryChangeRequests",
      false).toBool());
  ui.historyCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/rememberHistory",
			      false).toBool());
  ui.downloadCheckBox->setChecked
    (dooble::s_settings.value
     ("settingsWindow/rememberDownloads", false).toBool());
  ui.historySpinBox->setValue
    (dooble::s_settings.value("settingsWindow/historyDays", 1).toInt());
  ui.historySpinBox->setEnabled(ui.historyCheckBox->isChecked());
  ui.jsHideMenuBarCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/javascriptAllowMenuBarHiding",
			      false).toBool());
  ui.jsHideStatusBarCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/javascriptAllowStatusBarHiding",
			      false).toBool());
  ui.jsHideToolBarCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/javascriptAllowToolBarHiding",
			      false).toBool());
  ui.alwaysShowTabBarCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/alwaysShowTabBar",
			      true).toBool());
  ui.spatialNavigationCheckBox->setChecked
    (dooble::s_settings.value("settingsWindow/spatialNavigation",
			      false).toBool());

  if(dooble::s_settings.value("settingsWindow/cookiesShouldBe",
			      0).toInt() == 0)
    ui.cookieComboBox->setCurrentIndex(0);
  else if(dooble::s_settings.value("settingsWindow/cookiesShouldBe",
				   0).toInt() == 1)
    ui.cookieComboBox->setCurrentIndex(1);
  else if(dooble::s_settings.value("settingsWindow/cookiesShouldBe",
				   0).toInt() == 2)
    ui.cookieComboBox->setCurrentIndex(2);
  else
    ui.cookieComboBox->setCurrentIndex(0);

  QLocale locale;

  ui.languageComboBox->addItem(locale.languageToString(locale.language()));

  foreach(QToolButton *button, ui.tabFrame->findChildren<QToolButton *> ())
    if(button->property("page").toInt() == 
       dooble::s_settings.value("settingsWindow/currentPage", 0).toInt())
      {
	button->click();
	break;
      }

  if(dooble::s_settings.value("settingsWindow/cookieTimerEnabled",
			      false).toBool())
    if(!(ui.cookieTimerCheckBox->checkState() == Qt::Checked))
      ui.cookieTimerCheckBox->click();

  ui.cookieTimerSpinBox->setValue
    (dooble::s_settings.value("settingsWindow/cookieTimerInterval",
			      1).toInt());
  ui.cookieTimerComboBox->setCurrentIndex
    (dooble::s_settings.value("settingsWindow/cookieTimerUnit", 0).toInt());
  setParent(parent, Qt::Dialog);
  QDialog::exec();
}

void dsettings::slotClicked(QAbstractButton *button)
{
  if(ui.buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
    {
      QSettings settings;

      settings.setValue
	("iconSet",
	 ui.iconSetComboBox->itemData(ui.iconSetComboBox->currentIndex()).
	 toString());
      dooble::s_settings["iconSet"] =
	ui.iconSetComboBox->itemData(ui.iconSetComboBox->currentIndex()).
	toString();
      settings.setValue("settingsWindow/size", geometry().size());
      settings.setValue("settingsWindow/url1",
			ui.url01lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url2",
			ui.url02lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url3",
			ui.url03lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url4",
			ui.url04lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url5",
			ui.url05lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url6",
			ui.url06lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url7",
			ui.url07lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url8",
			ui.url08lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url9",
			ui.url09lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url10",
			ui.url10lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url11",
			ui.url11lineEdit->text().trimmed());
      settings.setValue("settingsWindow/url12",
			ui.doobleSearchLineEdit->text().trimmed());
      settings.setValue("settingsWindow/myRetrievedFiles",
			ui.myRetrievedFilesLineEdit->text().trimmed());
      settings.setValue("settingsWindow/javaEnabled",
			ui.javaCheckBox->isChecked());
      settings.setValue("settingsWindow/javascriptEnabled",
			ui.javascriptGroupBox->isChecked());
      settings.setValue("settingsWindow/javascriptAllowNewWindows",
			ui.jsAllowNewWindowsCheckBox->isChecked());
      settings.setValue("settingsWindow/displayDesktopCheckBox",
			ui.displayDesktopCheckBox->isChecked());
      settings.setValue("settingsWindow/proceedToNewTab",
			ui.proceedToNewTabCheckBox->isChecked());
      settings.setValue("settingsWindow/openInNewTab",
			ui.openInNewTabsCheckBox->isChecked());
      settings.setValue("settingsWindow/proxyEnabled",
			ui.browsingProxyGroupBox->isChecked());
      settings.setValue("settingsWindow/proxyType",
			ui.proxyType->currentText().trimmed());
      settings.setValue("settingsWindow/proxyHost",
			ui.proxyHostName->text().trimmed());
      settings.setValue("settingsWindow/proxyPort",
			ui.proxyPort->value());
      settings.setValue("settingsWindow/proxyUser",
			ui.proxyUserName->text().trimmed());
      settings.setValue("settingsWindow/proxyPassword",
			ui.proxyPassword->text().trimmed());
      settings.setValue("settingsWindow/i2pProxyEnabled",
			ui.i2pProxyGroupBox->isChecked());
      settings.setValue("settingsWindow/i2pProxyType",
			ui.i2pProxyType->currentText().trimmed());
      settings.setValue("settingsWindow/i2pProxyHost",
			ui.i2pProxyHostName->text().trimmed());
      settings.setValue("settingsWindow/i2pProxyPort",
			ui.i2pProxyPort->value());
      settings.setValue("settingsWindow/di2pProxyEnabled",
			ui.i2pProxyGroupBox_2->isChecked());
      settings.setValue("settingsWindow/di2pProxyType",
			ui.i2pProxyType_2->currentText().trimmed());
      settings.setValue("settingsWindow/di2pProxyHost",
			ui.i2pProxyHostName_2->text().trimmed());
      settings.setValue("settingsWindow/di2pProxyPort",
			ui.i2pProxyPort_2->value());
      settings.setValue("settingsWindow/ftpProxyEnabled",
			ui.ftpProxyGroupBox->isChecked());
      settings.setValue("settingsWindow/ftpProxyHost",
			ui.ftpProxyHostName->text().trimmed());
      settings.setValue("settingsWindow/ftpProxyPort",
			ui.ftpProxyPort->value());
      settings.setValue("settingsWindow/ftpBrowsingProxyEnabled",
			ui.browsingFtpProxyGroupBox->isChecked());
      settings.setValue("settingsWindow/ftpBrowsingProxyHost",
			ui.browsingFtpProxyHostName->text().trimmed());
      settings.setValue("settingsWindow/ftpBrowsingProxyPort",
			ui.browsingFtpProxyPort->value());
      settings.setValue("settingsWindow/httpProxyEnabled",
			ui.httpProxyGroupBox->isChecked());
      settings.setValue("settingsWindow/httpProxyType",
			ui.httpProxyType->currentText().trimmed());
      settings.setValue("settingsWindow/httpProxyHost",
			ui.httpProxyHostName->text().trimmed());
      settings.setValue("settingsWindow/httpProxyPort",
			ui.httpProxyPort->value());
      settings.setValue("settingsWindow/httpProxyUser",
			ui.httpProxyUserName->text().trimmed());
      settings.setValue("settingsWindow/httpProxyPassword",
			ui.httpProxyPassword->text().trimmed());
      settings.setValue("settingsWindow/automaticallyLoadImages",
			ui.automaticallyLoadImagesCheckBox->isChecked());
      settings.setValue("settingsWindow/enablePlugins",
			ui.pluginsCheckBox->isChecked());
      settings.setValue("settingsWindow/addTabWithDoubleClick",
			ui.addTabWithDoubleClick->isChecked());
      settings.setValue("settingsWindow/openUserWindowsInNewProcesses",
			ui.openUserWindowsInNewProcessesCheckBox->
			isChecked());
      settings.setValue("settingsWindow/closeViaMiddle",
			ui.closeViaMiddleCheckBox->isChecked());
      settings.setValue("settingsWindow/cookiesEnabled",
			ui.cookieGroupBox->isChecked());
      settings.setValue("settingsWindow/blockPopups",
			ui.blockPopupsCheckBox->isChecked());
      settings.setValue("settingsWindow/cursiveWebFont",
			ui.cursiveFontCombinationBox->
			currentFont().toString());
      settings.setValue("settingsWindow/fantasyWebFont",
			ui.fantasyFontCombinationBox->
			currentFont().toString());
      settings.setValue("settingsWindow/sansSerifWebFont",
			ui.sansSerifFontCombinationBox->
			currentFont().toString());
      settings.setValue("settingsWindow/serifWebFont",
			ui.serifFontCombinationBox->
			currentFont().toString());
      settings.setValue("settingsWindow/minimumWebFontSize",
			ui.minimumFontSizeCombinationBox->
			currentText().toInt());
      settings.setValue
	("settingsWindow/javascriptAcceptGeometryChangeRequests",
	 ui.jsAcceptGeometryRequestsCheckBox->isChecked());
      settings.setValue("settingsWindow/rememberHistory",
			ui.historyCheckBox->isChecked());
      settings.setValue("settingsWindow/rememberDownloads",
			ui.downloadCheckBox->isChecked());
      settings.setValue("settingsWindow/historyDays",
			ui.historySpinBox->value());
      settings.setValue("settingsWindow/javascriptAllowMenuBarHiding",
			ui.jsHideMenuBarCheckBox->isChecked());
      settings.setValue("settingsWindow/javascriptAllowStatusBarHiding",
			ui.jsHideStatusBarCheckBox->isChecked());
      settings.setValue("settingsWindow/javascriptAllowToolBarHiding",
			ui.jsHideToolBarCheckBox->isChecked());
      settings.setValue("settingsWindow/alwaysShowTabBar",
			ui.alwaysShowTabBarCheckBox->isChecked());
      settings.setValue("settingsWindow/spatialNavigation",
			ui.spatialNavigationCheckBox->isChecked());
      settings.setValue("settingsWindow/cookiesShouldBe",
			ui.cookieComboBox->currentIndex());

      QFont font;

      font = ui.fixedFontCombinationBox->currentFont();
      font.setPointSize(ui.fixedFontSizeCombinationBox->
			currentText().toInt());
      font.setWeight(QFont::Normal);
      settings.setValue("settingsWindow/fixedWebFont", font.toString());
      font = ui.fontComboBox->currentFont();
      font.setPointSize(ui.fontSizeComboBox->currentText().toInt());
      font.setWeight(QFont::Normal);
      QApplication::setFont(font);
      settings.setValue("settingsWindow/globalFont", font.toString());
      font = ui.defaultFontCombinationBox->currentFont();
      font.setPointSize(ui.defaultFontSizeCombinationBox->
			currentText().toInt());
      font.setWeight(QFont::Normal);
      settings.setValue("settingsWindow/standardWebFont", font.toString());
      settings.setValue("settingsWindow/currentPage",
			ui.stackedWidget->currentIndex());
      settings.setValue("settingsWindow/cookieTimerEnabled",
			ui.cookieTimerCheckBox->isChecked());
      settings.setValue("settingsWindow/cookieTimerInterval",
			ui.cookieTimerSpinBox->value());
      settings.setValue("settingsWindow/cookieTimerUnit",
			ui.cookieTimerComboBox->currentIndex());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::JavaEnabled,
	 ui.javaCheckBox->isChecked());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::JavascriptEnabled,
	 ui.javascriptGroupBox->isChecked());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::JavascriptCanOpenWindows,
	 ui.jsAllowNewWindowsCheckBox->isChecked() &&
	 ui.javascriptGroupBox->isChecked());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::AutoLoadImages,
	 ui.automaticallyLoadImagesCheckBox->isChecked());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::PluginsEnabled,
	 ui.pluginsCheckBox->isChecked());
      QWebSettings::globalSettings()->setFontFamily
	(QWebSettings::StandardFont,
	 ui.defaultFontSizeCombinationBox->currentText());
      QWebSettings::globalSettings()->setFontSize
	(QWebSettings::DefaultFontSize,
	 ui.defaultFontSizeCombinationBox->currentText().toInt());
      QWebSettings::globalSettings()->setFontFamily
	(QWebSettings::CursiveFont,
	 ui.cursiveFontCombinationBox->currentFont().family());
      QWebSettings::globalSettings()->setFontFamily
	(QWebSettings::FantasyFont,
	 ui.fantasyFontCombinationBox->currentFont().family());
      QWebSettings::globalSettings()->setFontFamily
	(QWebSettings::FixedFont,
	 ui.fixedFontCombinationBox->currentFont().family());
      QWebSettings::globalSettings()->setFontSize
	(QWebSettings::DefaultFixedFontSize,
	 ui.fixedFontSizeCombinationBox->currentText().toInt());
      QWebSettings::globalSettings()->setFontFamily
	(QWebSettings::SansSerifFont,
	 ui.sansSerifFontCombinationBox->currentFont().family());
      QWebSettings::globalSettings()->setFontFamily
	(QWebSettings::SerifFont,
	 ui.serifFontCombinationBox->currentFont().family());
      QWebSettings::globalSettings()->setFontSize
	(QWebSettings::MinimumFontSize,
	 ui.minimumFontSizeCombinationBox->currentText().toInt());
      QWebSettings::globalSettings()->setAttribute
	(QWebSettings::SpatialNavigationEnabled,
	 ui.spatialNavigationCheckBox->isChecked());

      /*
      ** Populate the dooble::s_settings container.
      */

      for(int i = 0; i < settings.allKeys().size(); i++)
	dooble::s_settings[settings.allKeys().at(i)] =
	  settings.value(settings.allKeys().at(i));

      for(int i = 0; i < ui.iconSetComboBox->count(); i++)
	{
	  settings.setValue(QString("settingsWindow/iconSet%1").arg(i + 1),
			    ui.iconSetComboBox->itemData(i));
	  dooble::s_settings[QString("settingsWindow/iconSet%1").arg(i + 1)] =
	    ui.iconSetComboBox->itemData(i);
	}

      emit showTabBar(ui.alwaysShowTabBarCheckBox->isChecked());
      emit fontChanged(QApplication::font());
      emit iconsChanged();
      emit cookieTimerChanged();
      slotSetIcons();
    }

  setVisible(false);
}

void dsettings::keyPressEvent(QKeyEvent *event)
{
  if(event && event->key() == Qt::Key_Escape)
    setVisible(false);

  QDialog::keyPressEvent(event);
}

void dsettings::slotSelectIconCfgFile(void)
{
  QFileDialog fileDialog(this);

#ifdef Q_WS_MAC
  fileDialog.setAttribute(Qt::WA_MacMetalStyle, true);
#endif
  fileDialog.setWindowTitle(tr("Dooble Web Browser: Theme "
			       "Selection"));

  if(dooble::s_settings.contains("settingsWindow/themesPath"))
    {
      if(QFile::exists(dooble::s_settings.value("settingsWindow/themesPath").
		       toString()))
	fileDialog.setDirectory
	  (dooble::s_settings.value("settingsWindow/themesPath").toString());
      else
	fileDialog.setDirectory(QDir::homePath());
    }
  else
    fileDialog.setDirectory(QDir::homePath());

  fileDialog.setFileMode(QFileDialog::ExistingFile);
  fileDialog.setLabelText(QFileDialog::Accept, tr("&Select"));
  fileDialog.setNameFilter(tr("Theme Configuration File (*.cfg)"));

  if(fileDialog.exec() == QDialog::Accepted)
    {
      QStringList list(fileDialog.selectedFiles());

      if(!list.isEmpty())
	{
	  QDir dir(fileDialog.directory());
	  QSettings settings;

	  if(dir.cdUp())
	    {
	      settings.setValue("settingsWindow/themesPath",
				dir.absolutePath());
	      dooble::s_settings["settingsWindow/themesPath"] =
		dir.absolutePath();
	    }
	  else
	    {
	      settings.setValue("settingsWindow/themesPath",
				QDir::homePath());
	      dooble::s_settings["settingsWindow/themesPath"] =
		QDir::homePath();
	    }

	  bool itemInserted = false;
	  QSettings cfgSettings(list[0],
				QSettings::IniFormat);

	  cfgSettings.beginGroup("Description");

	  for(int i = 0; i < ui.iconSetComboBox->count(); i++)
	    if(cfgSettings.value("Name").toString() <
	       ui.iconSetComboBox->itemText(i))
	      {
		itemInserted = true;
		ui.iconSetComboBox->insertItem
		  (i, cfgSettings.value("Name").toString(),
		   list[0]);
		ui.iconSetComboBox->setCurrentIndex(i);
		break;
	      }
	    else if(cfgSettings.value("Name").toString() ==
		    ui.iconSetComboBox->itemText(i))
	      {
		itemInserted = true;
		ui.iconSetComboBox->setCurrentIndex(i);
		break;
	      }

	  if(!itemInserted)
	    {
	      ui.iconSetComboBox->addItem
		(cfgSettings.value("Name").toString(),
		 list[0]);
	      ui.iconSetComboBox->setCurrentIndex
		(ui.iconSetComboBox->count() - 1);
	    }

	  list.clear();
	}
    }
}

void dsettings::slotChooseMyRetrievedFilesDirectory(void)
{
  QFileDialog fileDialog(this);

#ifdef Q_WS_MAC
  fileDialog.setAttribute(Qt::WA_MacMetalStyle, true);
#endif
  fileDialog.setWindowTitle
    (tr("Dooble Web Browser: My Retrieved Files Directory Selection"));
  fileDialog.setFileMode(QFileDialog::Directory);
  fileDialog.setDirectory(QDir::homePath());
  fileDialog.setLabelText(QFileDialog::Accept, tr("&Open"));
  fileDialog.setAcceptMode(QFileDialog::AcceptOpen);

  if(fileDialog.exec() == QDialog::Accepted)
    {
      QStringList list(fileDialog.selectedFiles());

      if(!list.isEmpty())
	{
	  ui.myRetrievedFilesLineEdit->setText(list[0]);
	  list.clear();
	}
    }
}

void dsettings::slotAddBlockUrl(void)
{
}

void dsettings::updateFontWidgets(const QString &fontName,
				  QComboBox *fontSizeWidget)
{
  if(fontName.isEmpty() || !fontSizeWidget)
    return;

  fontSizeWidget->clear();

  QList<int> fontSizes;
  QFontDatabase fontDatabase;

  fontSizes = fontDatabase.pointSizes(fontName);

  for(int i = 0; i < fontSizes.size(); i++)
    fontSizeWidget->addItem(QString::number(fontSizes.at(i)));
}

void dsettings::slotFontChanged(const QString &text)
{
  if(text.isEmpty())
    return;

  updateFontWidgets(text, ui.fontSizeComboBox);
}

void dsettings::slotWebFontChanged(const QString &text)
{
  if(text.isEmpty())
    return;

  QComboBox *comboBox = qobject_cast<QComboBox *> (sender());

  if(!comboBox)
    return;

  if(comboBox == ui.defaultFontCombinationBox)
    updateFontWidgets(text, ui.defaultFontSizeCombinationBox);
  else if(comboBox == ui.fixedFontCombinationBox)
    updateFontWidgets(text, ui.fixedFontSizeCombinationBox);
}

void dsettings::slotSetIcons(void)
{
  QSettings settings
    (dooble::s_settings.value("iconSet").toString(),
     QSettings::IniFormat);

  foreach(QPushButton *button,
	  ui.buttonBox->findChildren<QPushButton *>())
    if(ui.buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
      button->setIcon
	(QIcon(settings.value("okButtonIcon").toString()));
    else
      button->setIcon
	(QIcon(settings.value("cancelButtonIcon").toString()));

  ui.displayButton->setIcon
    (QIcon(settings.value("settingsWindow/displayButtonIcon").toString()));
  ui.historyButton->setIcon
    (QIcon(settings.value("settingsWindow/historyButtonIcon").toString()));
  ui.homeButton->setIcon
    (QIcon(settings.value("settingsWindow/homeButtonIcon").toString()));
  ui.proxyButton->setIcon
    (QIcon(settings.value("settingsWindow/proxyButtonIcon").toString()));
  ui.securityButton->setIcon
    (QIcon(settings.value("settingsWindow/securityButtonIcon").toString()));
  ui.tabsButton->setIcon
    (QIcon(settings.value("settingsWindow/tabsButtonIcon").toString()));
  ui.webkitButton->setIcon
    (QIcon(settings.value("settingsWindow/webkitButtonIcon").toString()));
  ui.windowsButton->setIcon
    (QIcon(settings.value("settingsWindow/windowsButtonIcon").toString()));

  int h = 0;
  int w = 0;

  foreach(QToolButton *button, ui.tabFrame->findChildren<QToolButton *> ())
    {
      if(button->sizeHint().width() > w)
	w = button->sizeHint().width();

      if(button->sizeHint().height() > h)
	h = button->sizeHint().height();
    }

  foreach(QToolButton *button, ui.tabFrame->findChildren<QToolButton *> ())
    button->setMinimumSize(w, h);
}

void dsettings::slotChangePage(bool checked)
{
  QToolButton *button = qobject_cast<QToolButton *> (sender());

  if(!button)
    return;
  else if(!checked)
    {
      button->setFocus();
      button->setChecked(true);
      return;
    }

  foreach(QToolButton *btn, ui.tabFrame->findChildren<QToolButton *> ())
    if(btn != button)
      btn->setChecked(!checked);
    else
      btn->setChecked(checked);

  button->setFocus();
  ui.stackedWidget->setCurrentIndex(button->property("page").toInt());
}

void dsettings::slotCookieTimerTimeChanged(int index)
{
  int value = ui.cookieTimerSpinBox->value();

  if(index == 0)
    {
      ui.cookieTimerSpinBox->setMinimum(1);
      ui.cookieTimerSpinBox->setMaximum(60);
    }
  else
    {
      ui.cookieTimerSpinBox->setMinimum(1);
      ui.cookieTimerSpinBox->setMaximum(3600);
    }

  ui.cookieTimerSpinBox->setValue(value);
}
