void KEquityPriceUpdateDlg::storePrices()
{
  // update the new prices into the equities

  MyMoneyFile* file = MyMoneyFile::instance();
  QList<MyMoneySecurity> equities = file->securityList();

  QTreeWidgetItem* item = 0;
  MyMoneyFileTransaction ft;
  QString name;

  try {
    for (int i = 0; i < lvEquityList->invisibleRootItem()->childCount(); ++i) {
      item = lvEquityList->invisibleRootItem()->child(i);
      // turn on signals before we modify the last entry in the list
      MyMoneyFile::instance()->blockSignals(i < lvEquityList->invisibleRootItem()->childCount() - 1);

      MyMoneyMoney rate(item->text(PRICE_COL));
      if (!rate.isZero()) {
        QString id = item->text(ID_COL).toUtf8();

        // if the ID has a space, then this is TWO ID's, so it's a currency quote
        if (QString(id).contains(" ")) {
          QStringList ids = id.split(' ', QString::SkipEmptyParts);
          QString fromid = ids[0].toUtf8();
          QString toid = ids[1].toUtf8();
          name = QString("%1 --> %2").arg(fromid).arg(toid);
          MyMoneyPrice price(fromid, toid, QDate().fromString(item->text(DATE_COL), Qt::ISODate), rate, item->text(SOURCE_COL));
          file->addPrice(price);
        } else
          // otherwise, it's a security quote
        {
          MyMoneySecurity security = MyMoneyFile::instance()->security(id);
          name = security.name();
          MyMoneyPrice price(id, security.tradingCurrency(), QDate().fromString(item->text(DATE_COL), Qt::ISODate), rate, item->text(SOURCE_COL));

          // TODO (Ace) Better handling of the case where there is already a price
          // for this date.  Currently, it just overrides the old value.  Really it
          // should check to see if the price is the same and prompt the user.
          MyMoneyFile::instance()->addPrice(price);
        }

      }
    }
    ft.commit();

  } catch (const MyMoneyException &) {
    qDebug("Unable to add price information for %s", qPrintable(name));
  }
}
KEquityPriceUpdateDlg::KEquityPriceUpdateDlg(QWidget *parent, const QString& securityId) :
    KEquityPriceUpdateDlgDecl(parent),
    m_fUpdateAll(false)
{
  QStringList headerList;
  headerList << i18n("Symbol") << i18nc("Equity name", "Name")
  << i18n("Price") << i18n("Date");

  lvEquityList->header()->setSortIndicator(0, Qt::AscendingOrder);
  lvEquityList->setColumnWidth(NAME_COL, 125);

  // This is a "get it up and running" hack.  Will replace this in the future.
  headerList << i18nc("Internal identifier", "ID")
  << i18nc("Online quote source", "Source");
  lvEquityList->setColumnWidth(ID_COL, 0);

  lvEquityList->setHeaderLabels(headerList);

  lvEquityList->setSelectionMode(QAbstractItemView::MultiSelection);
  lvEquityList->setAllColumnsShowFocus(true);

  btnUpdateAll->setEnabled(false);

  btnOK->setGuiItem(KStandardGuiItem::ok());
  btnCancel->setGuiItem(KStandardGuiItem::cancel());

  MyMoneyFile* file = MyMoneyFile::instance();

  //
  // Add each price pair that we know about
  //

  // send in securityId == "XXX YYY" to get a single-shot update for XXX to YYY.
  // for consistency reasons, this accepts the same delimiters as WebPriceQuote::launch()
  QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
  MyMoneySecurityPair currencyIds;
  if (splitrx.indexIn(securityId) != -1) {
    currencyIds = MyMoneySecurityPair(splitrx.cap(1).toUtf8(), splitrx.cap(2).toUtf8());
  }

  MyMoneyPriceList prices = file->priceList();
  for (MyMoneyPriceList::ConstIterator it_price = prices.constBegin(); it_price != prices.constEnd(); ++it_price) {
    const MyMoneySecurityPair& pair = it_price.key();
    if (file->security(pair.first).isCurrency() && (securityId.isEmpty() || (pair == currencyIds))) {
      const MyMoneyPriceEntries& entries = (*it_price);
      if (entries.count() > 0 && entries.begin().key() <= QDate::currentDate()) {
        addPricePair(pair);
        btnUpdateAll->setEnabled(true);
      }
    }
  }

  //
  // Add each investment
  //

  QList<MyMoneySecurity> securities = file->securityList();
  for (QList<MyMoneySecurity>::const_iterator it = securities.constBegin(); it != securities.constEnd(); ++it) {
    if (!(*it).isCurrency()
        && (securityId.isEmpty() || ((*it).id() == securityId))
        && !(*it).value("kmm-online-source").isEmpty()
       ) {
      addInvestment(*it);
      btnUpdateAll->setEnabled(true);
    }
  }

  // if list is empty, add the request price pair
  if (lvEquityList->invisibleRootItem()->childCount() == 0) {
    addPricePair(currencyIds, true);
  }

  connect(btnOK, SIGNAL(clicked()), this, SLOT(accept()));
  connect(btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
  connect(btnUpdateSelected, SIGNAL(clicked()), this, SLOT(slotUpdateSelectedClicked()));
  connect(btnUpdateAll, SIGNAL(clicked()), this, SLOT(slotUpdateAllClicked()));

  connect(&m_webQuote, SIGNAL(quote(QString,QString,QDate,double)),
          this, SLOT(slotReceivedQuote(QString,QString,QDate,double)));
  connect(&m_webQuote, SIGNAL(failed(QString,QString)),
          this, SLOT(slotQuoteFailed(QString,QString)));
  connect(&m_webQuote, SIGNAL(status(QString)),
          this, SLOT(logStatusMessage(QString)));
  connect(&m_webQuote, SIGNAL(error(QString)),
          this, SLOT(logErrorMessage(QString)));

  connect(lvEquityList, SIGNAL(itemSelectionChanged()), this, SLOT(slotUpdateSelection()));

  // Not implemented yet.
  btnConfigure->hide();
  //connect(btnConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureClicked()));

  if (!securityId.isEmpty()) {
    btnUpdateSelected->hide();
    btnUpdateAll->hide();
    // delete layout1;

    QTimer::singleShot(100, this, SLOT(slotUpdateAllClicked()));
  }

  // Hide OK button until we have received the first update
  btnOK->setEnabled(false);

  slotUpdateSelection();

  // previous versions of this dialog allowed to store a "Don't ask again" switch.
  // Since we don't support it anymore, we just get rid of it
  KSharedConfigPtr config = KGlobal::config();
  KConfigGroup grp = config->group("Notification Messages");
  grp.deleteEntry("KEquityPriceUpdateDlg::slotQuoteFailed::Price Update Failed");
}
void KInstitutionsView::loadAccounts(void)
{
  QMap<QString, bool> isOpen;

  ::timetrace("start load institutions view");
  // remember the id of the current selected item
  KMyMoneyAccountTreeBaseItem *item = m_accountTree->selectedItem();
  QString selectedItemId = (item) ? item->id() : QString();

  // keep a map of all 'expanded' accounts
  QListViewItemIterator it_lvi(m_accountTree);
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item && item->isOpen()) {
      isOpen[item->id()] = true;
    }
    ++it_lvi;
  }

  // remember the upper left corner of the viewport
  QPoint startPoint = m_accountTree->viewportToContents(QPoint(0, 0));

  // turn off updates to avoid flickering during reload
  m_accountTree->setUpdatesEnabled(false);

  // clear the current contents and recreate it
  m_accountTree->clear();
  m_accountMap.clear();
  m_securityMap.clear();
  m_transactionCountMap.clear();

  MyMoneyFile* file = MyMoneyFile::instance();

  QValueList<MyMoneyAccount> alist;
  file->accountList(alist);
  QValueList<MyMoneyAccount>::const_iterator it_a;
  for(it_a = alist.begin(); it_a != alist.end(); ++it_a) {
    m_accountMap[(*it_a).id()] = *it_a;
  }

  // we need to make sure we show stock accounts
  // under the right institution (the one of the parent account)
  QMap<QString, MyMoneyAccount>::iterator it_am;
  for(it_am = m_accountMap.begin(); it_am != m_accountMap.end(); ++it_am) {
    if((*it_am).isInvest()) {
      (*it_am).setInstitutionId(m_accountMap[(*it_am).parentAccountId()].institutionId());
    }
  }

  QValueList<MyMoneySecurity> slist = file->currencyList();
  slist += file->securityList();
  QValueList<MyMoneySecurity>::const_iterator it_s;
  for(it_s = slist.begin(); it_s != slist.end(); ++it_s) {
    m_securityMap[(*it_s).id()] = *it_s;
  }

  m_transactionCountMap = file->transactionCountMap();

  m_accountTree->setBaseCurrency(file->baseCurrency());

  // create the items
  try {
    const MyMoneySecurity& security = file->baseCurrency();
    m_accountTree->setBaseCurrency(security);

    MyMoneyInstitution none;
    none.setName(i18n("Accounts with no institution assigned"));
    KMyMoneyAccountTreeItem* noInstitutionItem = new KMyMoneyAccountTreeItem(m_accountTree, none);
    noInstitutionItem->setPixmap(0,none.pixmap());
    loadSubAccounts(noInstitutionItem, QString());

    // hide it, if unused
    noInstitutionItem->setVisible(noInstitutionItem->childCount() != 0);
    
    bool showClosedAccounts = kmymoney2->toggleAction("view_show_all_accounts")->isChecked()
      || !KMyMoneyGlobalSettings::hideClosedAccounts();

    QValueList<MyMoneyInstitution> list = file->institutionList();
    QValueList<MyMoneyInstitution>::const_iterator it_i;
    for(it_i = list.begin(); it_i != list.end(); ++it_i) {
      KMyMoneyAccountTreeItem* item = new KMyMoneyAccountTreeItem(m_accountTree, *it_i);
      item->setPixmap(0, none.pixmap());
      loadSubAccounts(item, (*it_i).id());
      if(!showClosedAccounts)
        item->setVisible(item->childCount() != 0);
    }

  } catch(MyMoneyException *e) {
    kdDebug(2) << "Problem in institutions view: " << e->what();
    delete e;
  }

  // scan through the list of accounts and re-expand those that were
  // expanded and re-select the one that was probably selected before
  it_lvi = QListViewItemIterator(m_accountTree);
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item) {
      if(item->id() == selectedItemId)
        m_accountTree->setSelected(item, true);
      if(isOpen.find(item->id()) != isOpen.end())
        item->setOpen(true);
    }
    ++it_lvi;
  }

  // reposition viewport
  m_accountTree->setContentsPos(startPoint.x(), startPoint.y());

  // turn updates back on
  m_accountTree->setUpdatesEnabled(true);
  m_accountTree->repaintContents();

  ::timetrace("done load institutions view");
}