/*
 * This file is part of the xTuple ERP: PostBooks Edition, a free and
 * open source Enterprise Resource Planning software suite,
 * Copyright (c) 1999-2009 by OpenMFG LLC, d/b/a xTuple.
 * It is licensed to you under the Common Public Attribution License
 * version 1.0, the full text of which (including xTuple-specific Exhibits)
 * is available at www.xtuple.com/CPAL.  By using this software, you agree
 * to be bound by its terms.
 */

#include "todoList.h"

#include "xdialog.h"
#include <QMenu>
#include <QMessageBox>
#include <QSqlError>
#include <QVariant>
#include <metasql.h>
#include <openreports.h>

#include "todoItem.h"
#include "incident.h"
#include "dspCustomerInformation.h"
#include "project.h"
#include "storedProcErrorLookup.h"
#include "task.h"

todoList::todoList(QWidget* parent, const char* name, Qt::WFlags fl)
    : XWidget(parent, name, fl)
{
  setupUi(this);

  _dueDates->setStartNull(tr("Earliest"), omfgThis->startOfTime(), TRUE);
  _dueDates->setEndNull(tr("Latest"),	  omfgThis->endOfTime(),   TRUE);
  _startDates->setStartNull(tr("Earliest"), omfgThis->startOfTime(), TRUE);
  _startDates->setEndNull(tr("Latest"),	  omfgThis->endOfTime(),   TRUE);

  _usr->setEnabled(_privileges->check("MaintainOtherTodoLists"));
  _usr->setType(ParameterGroup::User);
  q.prepare("SELECT usr_id, current_user "
	    "FROM usr "
	    "WHERE (usr_username=CURRENT_USER);");
  q.exec();
  if (q.first())
  {
    _myUsername = q.value("current_user").toInt();
    _usr->setId(q.value("usr_id").toInt());
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    close();
  }

  connect(_autoUpdate,	SIGNAL(toggled(bool)),	this,	SLOT(sHandleAutoUpdate(bool)));
  connect(_close,	SIGNAL(clicked()),	this,	SLOT(sClose()));
  connect(_completed,	SIGNAL(toggled(bool)),	this,	SLOT(sFillList()));
  connect(_delete,	SIGNAL(clicked()),	this,	SLOT(sDelete()));
  connect(_dueDates,	SIGNAL(updated()),	this,   SLOT(sFillList()));
  connect(_startDates,	SIGNAL(updated()),	this,   SLOT(sFillList()));
  connect(_incidents,	SIGNAL(toggled(bool)),	this,	SLOT(sFillList()));
  connect(_projects,	SIGNAL(toggled(bool)),	this,	SLOT(sFillList()));
  connect(_new,		SIGNAL(clicked()),	this,	SLOT(sNew()));
  connect(_print,	SIGNAL(clicked()),	this,	SLOT(sPrint()));
  connect(_todoList,	SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
  connect(_todoList,	SIGNAL(populateMenu(QMenu*, QTreeWidgetItem*, int)),
	    this,	SLOT(sPopulateMenu(QMenu*)));
  connect(_todoList,	SIGNAL(itemSelectionChanged()),	this,	SLOT(handlePrivs()));
  connect(_usr,		SIGNAL(updated()),	this,	SLOT(sFillList()));
  connect(_usr,		SIGNAL(updated()),	this,	SLOT(handlePrivs()));
  connect(_edit,	SIGNAL(clicked()),	this,	SLOT(sEdit()));
  connect(_view,	SIGNAL(clicked()),	this,	SLOT(sView()));
  connect(_duedateGroup, SIGNAL(toggled(bool)), this, SLOT(sFillList()));
  connect(_startdateGroup, SIGNAL(toggled(bool)), this, SLOT(sFillList()));

  _todoList->addColumn(tr("Type"),    _statusColumn,  Qt::AlignCenter, true, "type");
  _todoList->addColumn(tr("Seq"),        _seqColumn,  Qt::AlignRight,  false, "seq");
  _todoList->addColumn(tr("Priority"),  _userColumn,  Qt::AlignLeft,   true, "priority");
  _todoList->addColumn(tr("User"),      _userColumn,  Qt::AlignLeft,   true, "usr");
  _todoList->addColumn(tr("Name"),              100,  Qt::AlignLeft,   true, "name");
  _todoList->addColumn(tr("Description"),        -1,  Qt::AlignLeft,   true, "descrip");
  _todoList->addColumn(tr("Status"),  _statusColumn,  Qt::AlignLeft,   true, "status");
  _todoList->addColumn(tr("Start Date"),_dateColumn, Qt::AlignLeft,   false, "start");
  _todoList->addColumn(tr("Due Date"),  _dateColumn,  Qt::AlignLeft,   true, "due");
  _todoList->addColumn(tr("Parent#"),   _orderColumn,  Qt::AlignLeft,  true, "number");
  _todoList->addColumn(tr("Customer"), _orderColumn,  Qt::AlignLeft,   true, "cust");
  _todoList->addColumn(tr("Owner"),     _userColumn,  Qt::AlignLeft,   false,"owner");

  if (_preferences->boolean("XCheckBox/forgetful"))
    _incidents->setChecked(true);

  handlePrivs();
  sFillList();
  sHandleAutoUpdate(_autoUpdate->isChecked());
}

void todoList::languageChange()
{
    retranslateUi(this);
}

void todoList::sPopulateMenu(QMenu *pMenu)
{
  int menuItem; 

  if (_todoList->currentItem()->altId() == 1)
  {
    bool editPriv =
	(_myUsername == _todoList->currentItem()->text(3) && _privileges->check("MaintainPersonalTodoList")) ||
	(_myUsername != _todoList->currentItem()->text(3) && _privileges->check("MaintainOtherTodoLists"));

    bool viewPriv =
	(_myUsername == _todoList->currentItem()->text(3) && _privileges->check("ViewPersonalTodoList")) ||
	(_myUsername != _todoList->currentItem()->text(3) && _privileges->check("ViewOtherTodoLists"));

    menuItem = pMenu->insertItem(tr("New To-do..."), this, SLOT(sNew()), 0);
    pMenu->setItemEnabled(menuItem, editPriv);

    menuItem = pMenu->insertItem(tr("Edit To-do..."), this, SLOT(sEdit()), 0);
    pMenu->setItemEnabled(menuItem, editPriv);

    menuItem = pMenu->insertItem(tr("View To-Do..."), this, SLOT(sView()), 0);
    pMenu->setItemEnabled(menuItem, viewPriv);

    menuItem = pMenu->insertItem(tr("Delete To-Do"), this, SLOT(sDelete()), 0);
    pMenu->setItemEnabled(menuItem, editPriv);
  }

  if (_todoList->altId() == 1 && !_todoList->currentItem()->text(9).isEmpty())
    pMenu->addSeparator();
  
  if ((_todoList->altId() == 1 && !_todoList->currentItem()->text(9).isEmpty()) ||
       _todoList->altId() == 2)
  {
    menuItem = pMenu->insertItem(tr("Edit Incident"), this, SLOT(sEditIncident()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("MaintainIncidents"));
    menuItem = pMenu->insertItem(tr("View Incident"), this, SLOT(sViewIncident()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("ViewIncidents") ||
				    _privileges->check("MaintainIncidents"));
  }
  
  if (_todoList->altId() == 3)
  {
    menuItem = pMenu->insertItem(tr("Edit Task"), this, SLOT(sEditTask()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("MaintainProjects"));
    menuItem = pMenu->insertItem(tr("View Task"), this, SLOT(sViewTask()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("ViewProjects") ||
      _privileges->check("MaintainProjects"));
    pMenu->addSeparator();
  }
    
  if (_todoList->altId() >= 3)  
  {
    menuItem = pMenu->insertItem(tr("Edit Project"), this, SLOT(sEditProject()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("MaintainProjects"));
    menuItem = pMenu->insertItem(tr("View Project"), this, SLOT(sViewProject()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("ViewProjects") ||
      _privileges->check("MaintainProjects"));
  }

  if (!_todoList->currentItem()->text(10).isEmpty())
  {
    pMenu->addSeparator();
    menuItem = pMenu->insertItem(tr("Customer Workbench"), this, SLOT(sCustomerInfo()), 0);
    pMenu->setItemEnabled(menuItem, _privileges->check("MaintainCustomerMasters"));
  }
}

enum SetResponse todoList::set(const ParameterList& pParams)
{
  QVariant param;
  bool	   valid;

  param = pParams.value("usr_id", &valid);
  if (valid)
  {
    _usr->setId(param.toInt());
    handlePrivs();
    sFillList();
  }

  return NoError;
}

void todoList::handlePrivs()
{
  //bool editNewPriv  = false;
  bool editTodoPriv = false;
  bool viewTodoPriv = false;

  if (! _todoList->currentItem())
  {
  }
  else if (_todoList->altId() == 1)
  {
    editTodoPriv =
      (_myUsername == _todoList->currentItem()->text(3) && _privileges->check("MaintainPersonalTodoList")) ||
      (_privileges->check("MaintainOtherTodoLists"));

    viewTodoPriv =
      (_myUsername == _todoList->currentItem()->text(3) && _privileges->check("ViewPersonalTodoList")) ||
      (_privileges->check("ViewOtherTodoLists"));
  }
  else if (_todoList->altId() == 2)
  {
    editTodoPriv = _privileges->check("MaintainIncidents");
    viewTodoPriv = (_privileges->check("ViewIncidents") ||
				            _privileges->check("MaintainIncidents"));
  }
  else if (_todoList->altId() >= 3)
  {
    editTodoPriv = _privileges->check("MaintainProjects");
    viewTodoPriv = (_privileges->check("ViewProjects") ||
				            _privileges->check("MaintainProjects"));
  }

  _usr->setEnabled(_privileges->check("MaintainOtherTodoLists") ||
		   _privileges->check("ViewOtherTodoLists"));
  _new->setEnabled(_privileges->check("MaintainOtherTodoLists") ||
                   _privileges->check("ViewOtherTodoLists"));
  _edit->setEnabled(editTodoPriv && _todoList->id() > 0);
  _view->setEnabled((editTodoPriv || viewTodoPriv) && _todoList->id() > 0);
  _delete->setEnabled(editTodoPriv && _todoList->id() > 0 && _todoList->altId() != 2);

  if (editTodoPriv)
  {
    disconnect(_todoList,SIGNAL(itemSelected(int)),_view, SLOT(animateClick()));
    connect(_todoList,	SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
  }
  else if (viewTodoPriv)
  {
    disconnect(_todoList,SIGNAL(itemSelected(int)),_edit, SLOT(animateClick()));
    connect(_todoList,	SIGNAL(itemSelected(int)), _view, SLOT(animateClick()));
  }
}

void todoList::sClose()
{
  close();
}

void todoList::sNew()
{
  ParameterList params;
  params.append("mode", "new");
  if (_usr->isSelected())
    params.append("usr_username", _myUsername);

  todoItem newdlg(this, "", TRUE);
  newdlg.set(params);

  if (newdlg.exec() != XDialog::Rejected)
    sFillList();
}

void todoList::sEdit()
{
  if (_todoList->altId() ==2)
    sEditIncident();
  else if (_todoList->altId() == 3)
    sEditTask();
  else if (_todoList->altId() == 4)
    sEditProject();
  else
  {
    ParameterList params;
    params.append("mode", "edit");
    params.append("todoitem_id", _todoList->id());

    todoItem newdlg(this, "", TRUE);
    newdlg.set(params);

    if (newdlg.exec() != XDialog::Rejected)
      sFillList();
  }
}

void todoList::sView()
{
  if (_todoList->altId() ==2)
    sViewIncident();
  else if (_todoList->altId() == 3)
    sViewTask();
  else if (_todoList->altId() == 4)
    sViewProject();
  else
  {
    ParameterList params;
    params.append("mode", "view");
    params.append("todoitem_id", _todoList->id());

    todoItem newdlg(this, "", TRUE);
    newdlg.set(params);

    newdlg.exec();
  }
}

void todoList::sDelete()
{
  if ( QMessageBox::warning(this, tr("Delete List Item?"),
                            tr("<p>Are you sure that you want to completely "
			       "delete the selected item?"),
			    QMessageBox::Yes,
			    QMessageBox::No | QMessageBox::Default) == QMessageBox::Yes)
  {
    if (_todoList->altId() == 1)
      q.prepare("SELECT deleteTodoItem(:todoitem_id) AS result;");
    else if (_todoList->altId() == 3)
      q.prepare("DELETE FROM prjtask"
                " WHERE (prjtask_id=:todoitem_id); ");
    else if (_todoList->altId() == 4)
      q.prepare("SELECT deleteProject(:todoitem_id) AS result");
    else
      return;
    q.bindValue(":todoitem_id", _todoList->id());
    q.exec();
    if (q.first())
    {
      int result = q.value("result").toInt();
      if (result < 0)
      {
        systemError(this, storedProcErrorLookup("deleteTodoItem", result));
        return;
      }
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    sFillList();
  }
}

void todoList::setParams(ParameterList &params)
{
  if (_completed->isChecked())
    params.append("completed");
  if (_incidents->isChecked())
    params.append("incidents");
  if (_projects->isChecked())
    params.append("projects");
  _usr->appendValue(params);
  if (_duedateGroup->isChecked())
  {
    params.append("dueStartDate", _dueDates->startDate());
    params.append("dueEndDate",   _dueDates->endDate());
  }
  if (_startdateGroup->isChecked())
  {
    params.append("startStartDate", _startDates->startDate());
    params.append("startEndDate",   _startDates->endDate());
  }
  params.append("todo", tr("To-do"));
  params.append("incident", tr("Incident"));
  params.append("task", tr("Task"));
  params.append("project", tr("Project"));
}

void todoList::sPrint()
{
  ParameterList params;
  setParams(params);

  orReport report("TodoList", params);
  if (report.isValid())
    report.print();
  else
    report.reportError(this);
}

void todoList::sFillList()
{
  QString sql = "SELECT todoitem_id AS id, 1 AS altId, todoitem_owner_username AS owner, "
		"       <? value(\"todo\") ?> AS type, incdtpriority_order AS seq, incdtpriority_name AS priority, "
		"       todoitem_name AS name, "
		"       firstLine(todoitem_description) AS descrip, "
    "       todoitem_status AS status, todoitem_start_date as start, "
		"       todoitem_due_date AS due, formatDate(todoitem_due_date) AS f_due, "
		"       usr_username AS usr, CAST(incdt_number AS text) AS number, cust_number AS cust, "
    "       CASE WHEN (todoitem_status != 'C'AND "
    "                  todoitem_due_date < CURRENT_DATE) THEN 'expired'"
    "            WHEN (todoitem_status != 'C'AND "
    "                  todoitem_due_date > CURRENT_DATE) THEN 'future'"
    "       END AS due_qtforegroundrole "
		"FROM usr, todoitem LEFT OUTER JOIN incdt ON (incdt_id=todoitem_incdt_id) "
		"                   LEFT OUTER JOIN crmacct ON (crmacct_id=todoitem_crmacct_id) "
		"                   LEFT OUTER JOIN cust ON (cust_id=crmacct_cust_id) "
    "                   LEFT OUTER JOIN incdtpriority ON (incdtpriority_id=todoitem_priority_id) "
		"WHERE ( (todoitem_usr_id=usr_id)"
    "  <? if exists(\"startStartDate\") ?> "
    "  AND (todoitem_start_date BETWEEN <? value(\"startStartDate\") ?>"
		"                             AND <? value(\"startEndDate\") ?>)"
    "  <? endif ?>"
    "  <? if exists(\"dueStartDate\") ?> "
		"  AND   (todoitem_due_date BETWEEN <? value(\"dueStartDate\") ?> "
		"                               AND <? value(\"dueEndDate\") ?>) "
  	"  <? endif ?>"
		"  <? if not exists(\"completed\") ?>"
		"  AND   (todoitem_status != 'C')"
		"  <? endif ?>"
		"  <? if exists(\"usr_id\") ?> "
		"  AND (usr_id=<? value(\"usr_id\") ?>) "
		"  <? elseif exists(\"usr_pattern\" ?>"
		"  AND (usr_username ~ <? value(\"usr_pattern\") ?>) "
		"  <? endif ?>"
		"  <? if not exists(\"completed\") ?>AND (todoitem_active) <? endif ?>"
		"       ) "
		"<? if exists(\"incidents\")?>"
    "<? if not exists(\"dueStartDate\") ?> "
		"UNION "
		"SELECT incdt_id AS id, 2 AS altId, incdt_owner_username AS owner, "
		"       <? value(\"incident\") ?> AS type, incdtpriority_order AS seq, incdtpriority_name AS priority, "
		"       incdt_summary AS name, "
		"       firstLine(incdt_descrip) AS descrip, "
    "       incdt_status AS status, CAST(incdt_timestamp AS date) AS start, "
		"       null AS due, null AS f_due, "
		"       incdt_assigned_username AS usr, CAST(incdt_number AS text) AS number, cust_number AS cust, "
                "       NULL AS due_qtforegroundrole "
		"FROM incdt LEFT OUTER JOIN usr ON (usr_username=incdt_assigned_username)"
		"           LEFT OUTER JOIN crmacct ON (crmacct_id=incdt_crmacct_id) "
		"           LEFT OUTER JOIN cust ON (cust_id=crmacct_cust_id) "
    "           LEFT OUTER JOIN incdtpriority ON (incdtpriority_id=incdt_incdtpriority_id) "
		"WHERE ((true) "
    "  <? if exists(\"startStartDate\") ?> "
    "  AND (incdt_timestamp BETWEEN <? value(\"startStartDate\") ?>"
		"                            AND <? value(\"startEndDate\") ?>)"
    "  <? endif ?>"
		"  <? if not exists(\"completed\") ?> "
		"  AND (incdt_status != 'L')"
		"  <? endif ?>"
		"  <? if exists(\"usr_id\") ?> "
		"  AND (usr_id=<? value(\"usr_id\") ?>) "
		"  <? elseif exists(\"usr_pattern\" ?>"
		"  AND (usr_username ~ <? value(\"usr_pattern\") ?>) "
		"  <? endif ?>"
		"       ) "
		"<? endif ?>"
    "<? endif ?>"
		"<? if exists(\"projects\")?>"
		"UNION "
		"SELECT prjtask_id AS id, 3 AS altId, prjtask_owner_username AS owner, "
		"       <? value(\"task\") ?> AS type, NULL AS seq, NULL AS priority, "
		"       prjtask_number || '-' || prjtask_name AS name, "
		"       firstLine(prjtask_descrip) AS descrip, "
		"       prjtask_status AS status,  prjtask_start_date AS start, "
    "       prjtask_due_date AS due, formatDate(prjtask_due_date) AS f_due, "
		"       usr_username AS usr, prj_number, '' AS cust, "
    "       CASE WHEN (prjtask_status != 'C'AND "
    "                  prjtask_due_date < CURRENT_DATE) THEN 'expired'"
    "            WHEN (prjtask_status != 'C'AND "
    "                  prjtask_due_date > CURRENT_DATE) THEN 'future'"
    "       END AS due_qtforegroundrole "
		"FROM prj, prjtask LEFT OUTER JOIN usr ON (usr_id=prjtask_usr_id)"
		"WHERE ((prj_id=prjtask_prj_id) "
    "  <? if exists(\"startStartDate\") ?> "
    "  AND (prjtask_start_date BETWEEN <? value(\"startStartDate\") ?>"
		"                             AND <? value(\"startEndDate\") ?>)"
    "  <? endif ?>"
    "  <? if exists(\"dueStartDate\") ?> "
    "  AND (prjtask_due_date BETWEEN <? value(\"dueStartDate\") ?>"
		"                             AND <? value(\"dueEndDate\") ?>)"
    "  <? endif ?>"
		"  <? if not exists(\"completed\") ?> "
		"  AND (prjtask_status != 'C')"
		"  <? endif ?>"
		"  <? if exists(\"usr_id\") ?> "
		"  AND (usr_id=<? value(\"usr_id\") ?>) "
		"  <? elseif exists(\"usr_pattern\" ?>"
		"  AND (usr_username ~ <? value(\"usr_pattern\") ?>) "
		"  <? endif ?>"
		"       ) "
  	"UNION "
		"SELECT prj_id AS id, 4 AS altId, prj_owner_username AS owner, "
		"       <? value(\"project\") ?> AS type, NULL AS seq, NULL AS priority, "
		"       prj_number || '-' || prj_name AS name, "
		"       firstLine(prj_descrip) AS descrip, "
		"       prj_status AS status,  prj_start_date AS start, "
    "       prj_due_date AS due, formatDate(prj_due_date) AS f_due, "
		"       usr_username AS usr, NULL AS number, '' AS cust, "
    "       CASE WHEN (prj_status != 'C'AND "
    "                  prj_due_date < CURRENT_DATE) THEN 'expired'"
    "            WHEN (prj_status != 'C'AND "
    "                  prj_due_date > CURRENT_DATE) THEN 'future'"
    "       END AS due_qtforegroundrole "
		"FROM prj LEFT OUTER JOIN usr ON (usr_id=prj_usr_id)"
		"WHERE ((true) "
    "  <? if exists(\"startStartDate\") ?> "
    "  AND (prj_start_date BETWEEN <? value(\"startStartDate\") ?>"
		"                             AND <? value(\"startEndDate\") ?>)"
    "  <? endif ?>"
    "  <? if exists(\"dueStartDate\") ?> "
    "  AND (prj_due_date BETWEEN <? value(\"dueStartDate\") ?>"
		"                             AND <? value(\"dueEndDate\") ?>)"
    "  <? endif ?>"
		"  <? if not exists(\"completed\") ?> "
		"  AND (prj_status != 'C')"
		"  <? endif ?>"
		"  <? if exists(\"usr_id\") ?> "
		"  AND (usr_id=<? value(\"usr_id\") ?>) "
		"  <? elseif exists(\"usr_pattern\" ?>"
		"  AND (usr_username ~ <? value(\"usr_pattern\") ?>) "
		"  <? endif ?>"
		"       ) "
		"<? endif ?>"
		"ORDER BY due, seq, usr;";

  ParameterList params;
  setParams(params);

  MetaSQLQuery mql(sql);
  XSqlQuery itemQ = mql.toQuery(params);

  _todoList->populate(itemQ, true);

  if (itemQ.lastError().type() != QSqlError::NoError)
  {
    systemError(this, itemQ.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  handlePrivs();

  _total->setText(QString::number(_todoList->topLevelItemCount()));
}

void todoList::sHandleAutoUpdate(bool pAutoUpdate)
{
  if (pAutoUpdate)
    connect(omfgThis, SIGNAL(tick()), this, SLOT(sFillList()));
  else
    disconnect(omfgThis, SIGNAL(tick()), this, SLOT(sFillList()));
}

int todoList::getIncidentId()
{
  int returnVal = -1;

  if (_todoList->currentItem()->altId() == 2)
    returnVal = _todoList->id();
  else if (! _todoList->currentItem()->text(9).isEmpty())
  {
    XSqlQuery incdt;
    incdt.prepare("SELECT incdt_id FROM incdt WHERE (incdt_number=:number);");
    incdt.bindValue(":number", _todoList->currentItem()->text(9).toInt());
    if (incdt.exec() && incdt.first())
     returnVal = incdt.value("incdt_id").toInt();
    else if (incdt.lastError().type() != QSqlError::NoError)
      systemError(this, incdt.lastError().databaseText(), __FILE__, __LINE__);
  }

  return returnVal;
}

int todoList::getProjectId()
{
  int returnVal = -1;

  if (_todoList->currentItem()->altId() == 4)
    returnVal = _todoList->id();
  else if (_todoList->currentItem()->altId() == 3)
  {
    XSqlQuery prj;
    prj.prepare("SELECT prjtask_prj_id FROM prjtask WHERE (prjtask_id=:prjtask_id);");
    prj.bindValue(":prjtask_id", _todoList->id());
    if (prj.exec() && prj.first())
     returnVal = prj.value("prjtask_prj_id").toInt();
    else if (prj.lastError().type() != QSqlError::NoError)
     systemError(this, prj.lastError().databaseText(), __FILE__, __LINE__);
  }
  else if (! _todoList->currentItem()->text(9).isEmpty())
  {
    XSqlQuery prj;
    prj.prepare("SELECT prj_id FROM prj WHERE (prj_number=:number);");
    prj.bindValue(":number", _todoList->currentItem()->text(9));
    if (prj.exec() && prj.first())
     returnVal = prj.value("prj_id").toInt();
    else if (prj.lastError().type() != QSqlError::NoError)
     systemError(this, prj.lastError().databaseText(), __FILE__, __LINE__);
  }
  return returnVal;
}

void todoList::sEditIncident()
{

  ParameterList params;
  params.append("mode", "edit");
  params.append("incdt_id", getIncidentId());

  incident newdlg(this, "", TRUE);
  newdlg.set(params);

  if (newdlg.exec() != XDialog::Rejected)
    sFillList();
}

void todoList::sViewIncident()
{
  ParameterList params;
  params.append("mode", "view");
  params.append("incdt_id", getIncidentId());

  incident newdlg(this, "", TRUE);
  newdlg.set(params);

  newdlg.exec();
}

void todoList::sEditProject()
{

  ParameterList params;
  params.append("mode", "edit");
  params.append("prj_id", getProjectId());

  project newdlg(this, "", TRUE);
  newdlg.set(params);

  if (newdlg.exec() != XDialog::Rejected)
    sFillList();
}

void todoList::sViewProject()
{
  ParameterList params;
  params.append("mode", "view");
  params.append("prj_id", getProjectId());

  project newdlg(this, "", TRUE);
  newdlg.set(params);

  newdlg.exec();
}

void todoList::sEditTask()
{

  ParameterList params;
  params.append("mode", "edit");
  params.append("prjtask_id", _todoList->id());

  task newdlg(this, "", TRUE);
  newdlg.set(params);

  if (newdlg.exec() != XDialog::Rejected)
    sFillList();
}

void todoList::sViewTask()
{
  ParameterList params;
  params.append("mode", "view");
  params.append("prjtask_id", _todoList->id());

  task newdlg(this, "", TRUE);
  newdlg.set(params);

  newdlg.exec();
}

void todoList::sCustomerInfo()
{
  XSqlQuery cust;
  cust.prepare("SELECT cust_id FROM cust WHERE (cust_number=:number);");
  cust.bindValue(":number", _todoList->currentItem()->text(10));
  if (cust.exec() && cust.first())
  {
    ParameterList params;
    params.append("cust_id", cust.value("cust_id").toInt());

    dspCustomerInformation *newdlg = new dspCustomerInformation();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg);
  }
  else if (cust.lastError().type() != QSqlError::NoError)
    systemError(this, cust.lastError().databaseText(), __FILE__, __LINE__);

}


