// ProjectDlg.cpp : implementation file
//

#include "stdafx.h"

#include "ProjectDlg.h"
#include "TransactionListDlg.h"

#include <apl_api.h>
#include <aplguiex.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CProjectDlg dialog


CProjectDlg::CProjectDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CProjectDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CProjectDlg)
	m_id = _T("");
	//m_time_begin_fact = COleDateTime::GetCurrentTime();
	//m_time_begin_planned = COleDateTime::GetCurrentTime();
	//m_time_end_fact = COleDateTime::GetCurrentTime();
	//m_time_end_planned = COleDateTime::GetCurrentTime();
	m_sName = _T("");
	//}}AFX_DATA_INIT
	m_project=0;
	m_labor_unit=0;
	m_project_mgr=0;
	m_api=0;
	m_parent=0;
	m_kurator=0;
	m_cur_state=_T("");
	m_read_only=false;
	m_can_check_out=true;
	m_read_only_ver=false;
	m_customer=0;
	//m_labor_unit_actual=0;
	m_prd_labor_unit_planned=0;
	m_prd_labor_unit_actual=0;
	m_labor_of_item_unit=0;
	m_bHaveChildren=false;
	m_check_dates=0;
	m_forbid_overproducing=0;
	m_auto_complete=0;
	m_auto_complete_parent=0;
	m_max_actual_date_end=_T(""),m_min_actual_date_begin=_T("");
	m_max_planned_date_end=_T(""),m_min_planned_date_begin=_T("");

	m_odt_min_planed.SetStatus(COleDateTime::null);
	m_odt_max_planed.SetStatus(COleDateTime::null);

	m_bNeedUndoCheckout=false;

	m_forbinen_future_fact_dates=0;
}


void CProjectDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CProjectDlg)
	DDX_Control(pDX, IDC_DATE_CONTROL, m_date_control_ctrl);
	DDX_Control(pDX, IDC_DLIT_PLAN, m_dlit_plan_ctrl);
	DDX_Control(pDX, IDC_DLIT_ACTUAL, m_dlit_actual_ctrl);
	DDX_Control(pDX, IDC_SELECT_LABOR_OF_ITEM_UNIT, m_select_labor_of_item_unit_btn);
	//DDX_Control(pDX, IDC_SELECT_ACTUAL_LABOR_UNIT, m_select_actual_labor_unit_btn);
	DDX_Control(pDX, IDC_PRD_AMOUT_PLANNED, m_prd_amount_planned_ctrl);
	DDX_Control(pDX, IDC_PRD_AMOUT_ACTUAL, m_prd_amount_actual_ctrl);
	DDX_Control(pDX, IDC_LABOR_OF_ITEM_UNIT, m_labor_of_item_unit_ctrl);
	DDX_Control(pDX, IDC_LABOR_OF_ITEM, m_labor_of_item_ctrl);
	DDX_Control(pDX, IDC_CALC_BY_AMOUNT, m_calc_by_amount_ctrl);
	//DDX_Control(pDX, IDC_ACTUAL_LABOR_UNIT, m_actual_labor_unit_ctrl);
	DDX_Control(pDX, IDC_ACTUAL_LABOR, m_actual_labor_ctrl);
	DDX_Control(pDX, IDC_SELECT_CUSTOMER, m_select_customer_btn);
	DDX_Control(pDX, IDC_CUSTOMER, m_customer_ctrl);
	DDX_Control(pDX, IDC_PROJECT_ICON, m_st_project_name);
	DDX_Control(pDX, IDC_DATE_BEGIN_PLANNED, m_date_begin_planned_ctrl);
	DDX_Control(pDX, IDC_CHECK_IN, m_check_in_ctrl);
	DDX_Control(pDX, IDC_CHECK_OUT, m_check_out_ctrl);
	DDX_Control(pDX, IDC_UNDO_CHECK_OUT, m_undo_check_out_ctrl);
	DDX_Control(pDX, IDC_PROJECT_TYPE, m_project_type_ctrl);
	DDX_Control(pDX, IDC_CHECK_PLANNED_END, m_check_planned_end_ctrl);
	DDX_Control(pDX, IDC_CHECK_PLANNED_BEGIN, m_check_planned_begin_ctrl);
	DDX_Control(pDX, IDC_STATE, m_state_ctrl);
	DDX_Control(pDX, IDC_SELECT_LABOR_UNIT, m_select_labunit_btn);
	DDX_Control(pDX, IDC_SELECT_EXECUTORS, m_select_executors_btn);
	DDX_Control(pDX, IDC_SELECT_KURATOR, m_select_kurator_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDC_KURATOR, m_kurator_ctrl);
	DDX_Control(pDX, IDC_CHECK_FACT_END, m_check_fact_end_ctrl);
	DDX_Control(pDX, IDC_CHECK_FACT_BEGIN, m_check_fact_begin_ctrl);
	DDX_Control(pDX, IDC_EXECUTORS, m_executors_ctrl);
	DDX_Control(pDX, IDC_DATE_END_PLANNED, m_date_end_planned_ctrl);
	DDX_Control(pDX, IDC_DATE_END_FACT, m_date_end_fact_ctrl);
	DDX_Control(pDX, IDC_DATE_BEGIN_FACT, m_date_begin_fact_ctrl);
	DDX_Control(pDX, IDC_DESCR, m_descr_ctrl);
	DDX_Control(pDX, IDC_NAME, m_name_ctrl);
	DDX_Control(pDX, IDC_ID, m_id_ctrl);
	DDX_Control(pDX, IDC_TIME_END_PLANNED, m_time_end_planned_ctrl);
	DDX_Control(pDX, IDC_TIME_END_FACT, m_time_end_fact_ctrl);
	DDX_Control(pDX, IDC_TIME_BEGIN_PLANNED, m_time_begin_planned_ctrl);
	DDX_Control(pDX, IDC_TIME_BEGIN_FACT, m_time_begin_fact_ctrl);
	DDX_Control(pDX, IDC_PERSENTAGE, m_persentage_ctrl);
	DDX_Control(pDX, IDC_LABOR, m_labor_value_ctrl);
	DDX_Control(pDX, IDC_LABOR_UNIT, m_labor_unit_ctrl);
	DDX_Text(pDX, IDC_ID, m_id);
	//DDX_DateTimeCtrl(pDX, IDC_TIME_BEGIN_FACT, m_time_begin_fact);
	//DDX_DateTimeCtrl(pDX, IDC_TIME_BEGIN_PLANNED, m_time_begin_planned);
	//DDX_DateTimeCtrl(pDX, IDC_TIME_END_FACT, m_time_end_fact);
	//DDX_DateTimeCtrl(pDX, IDC_TIME_END_PLANNED, m_time_end_planned);
	DDX_Text(pDX, IDC_NAME, m_sName);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_PRD_AMOUT_UNIT, m_prd_amount_unit_ctrl);
	DDX_Control(pDX, IDC_NUMBER, m_number_ctrl);
	DDX_Control(pDX, IDC_DELETE_CUSTOMER, m_delete_cust_btn);
	DDX_Control(pDX, IDC_DELETE_KURATOR, m_delete_kur_btn);
	DDX_Control(pDX, IDC_CHECK_PLANNED_DURATION, m_check_planed_duration_set_btn);
	DDX_Control(pDX, IDC_PRJ_REL_LIST, m_prj_rel_list);
	DDX_Control(pDX, IDC_IDC_ACTUAL_LABOR_DATE, m_actual_labor_date_ctrl);
	DDX_Control(pDX, IDC_COEXECUTORS, m_coexecutors_ctrl);
	DDX_Control(pDX, IDC_SELECT_COEXECUTORS, m_select_coexecutors_btn);
	DDX_Control(pDX, IDC_NOTES, m_notes_btn);
	DDX_Control(pDX, IDC_COCUSTOMERS, m_cosustomers_ctrl);
	DDX_Control(pDX, IDC_SELECT_COCUSTOMERS, m_select_cocostomers_btn);
	DDX_Control(pDX, IDC_AUTO_END_EDIT, m_auto_end_edit_ctrl);
}


BEGIN_MESSAGE_MAP(CProjectDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CProjectDlg)
	ON_BN_CLICKED(IDC_SELECT_LABOR_UNIT, OnSelectLaborUnit)
	ON_BN_CLICKED(IDC_SELECT_EXECUTORS, OnSelectExecutors)
	ON_BN_CLICKED(IDC_CHECK_FACT_BEGIN, OnCheckFactBegin)
	ON_BN_CLICKED(IDC_CHECK_FACT_END, OnCheckFactEnd)
	ON_BN_CLICKED(IDC_SELECT_KURATOR, OnSelectKurator)
	ON_CBN_SELCHANGE(IDC_STATE, OnSelchangeState)
	ON_BN_CLICKED(IDC_CHECK_PLANNED_BEGIN, OnCheckPlannedBegin)
	ON_BN_CLICKED(IDC_CHECK_PLANNED_END, OnCheckPlannedEnd)
	ON_BN_CLICKED(IDC_CHECK_OUT, OnCheckOut)
	ON_BN_CLICKED(IDC_CHECK_IN, OnCheckIn)
	ON_BN_CLICKED(IDC_UNDO_CHECK_OUT, OnUndoCheckOut)
	ON_BN_CLICKED(IDC_SELECT_CUSTOMER, OnSelectCustomer)
	ON_BN_CLICKED(IDC_CALC_BY_AMOUNT, OnCalcByAmount)
	ON_BN_CLICKED(IDC_SELECT_LABOR_OF_ITEM_UNIT, OnSelectLaborOfItemUnit)
	//ON_BN_CLICKED(IDC_SELECT_ACTUAL_LABOR_UNIT, OnSelectActualLaborUnit)
	ON_EN_CHANGE(IDC_PRD_AMOUT_PLANNED, OnChangePrdAmoutPlanned)
	ON_EN_CHANGE(IDC_LABOR_OF_ITEM, OnChangeLaborOfItem)
	ON_EN_CHANGE(IDC_PRD_AMOUT_ACTUAL, OnChangePrdAmoutActual)
	ON_EN_CHANGE(IDC_LABOR, OnChangeLabor)
	ON_EN_CHANGE(IDC_ACTUAL_LABOR, OnChangeActualLabor)
	ON_CBN_SELCHANGE(IDC_DATE_CONTROL, OnSelchangeDateControl)
	ON_EN_CHANGE(IDC_DLIT_PLAN, OnChangeDlitPlan)
	ON_EN_CHANGE(IDC_DLIT_ACTUAL, OnChangeDlitActual)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATE_BEGIN_FACT, OnDatetimechangeDateBeginFact)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATE_END_FACT, OnDatetimechangeDateEndFact)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATE_BEGIN_PLANNED, OnDatetimechangeDateBeginPlanned)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATE_END_PLANNED, OnDatetimechangeDateEndPlanned)
	ON_BN_CLICKED(IDC_TRANSACTIONS, OnTransactions)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_DELETE_CUSTOMER, &CProjectDlg::OnBnClickedDeleteCustomer)
	ON_BN_CLICKED(IDC_DELETE_KURATOR, &CProjectDlg::OnBnClickedDeleteKurator)
	ON_BN_CLICKED(IDC_DEL_LABOR_UNIT, &CProjectDlg::OnBnClickedDelLaborUnit)
	ON_BN_CLICKED(IDC_CHECK_PLANNED_DURATION, &CProjectDlg::OnBnClickedCheckPlannedDuration)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_TIME_BEGIN_PLANNED, &CProjectDlg::OnDtnDatetimechangeTimeBeginPlanned)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_TIME_END_PLANNED, &CProjectDlg::OnDtnDatetimechangeTimeEndPlanned)
	ON_NOTIFY(NM_DBLCLK, IDC_PRJ_REL_LIST, &CProjectDlg::OnNMDblclkPrjRelList)
	ON_BN_CLICKED(IDC_SELECT_COEXECUTORS, &CProjectDlg::OnBnClickedSelectCoexecutors)
	ON_BN_CLICKED(IDC_NOTES, &CProjectDlg::OnBnClickedNotes)
	ON_BN_CLICKED(IDC_SELECT_COCUSTOMERS, &CProjectDlg::OnBnClickedSelectCocustomers)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_TIME_END_FACT, &CProjectDlg::OnDtnDatetimechangeTimeEndFact)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_TIME_BEGIN_FACT, &CProjectDlg::OnDtnDatetimechangeTimeBeginFact)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_IDC_ACTUAL_LABOR_DATE, &CProjectDlg::OnDtnDatetimechangeIdcActualLaborDate)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CProjectDlg message handlers
BOOL CProjectDlg::PreTranslateMessage(MSG* pMsg)
{
	// TODO: Add your specialized code here and/or call the base class
	m_toolTipCtrl.RelayEvent(pMsg); 

	if(pMsg)
	{
		if(pMsg->message==WM_RBUTTONDOWN)
		{
			if(pMsg->hwnd==m_prj_rel_list.m_hWnd)
			{
				PrjRbuttonDown(pMsg); return TRUE;
			}
		}
	}


	return CaplResizableDialog::PreTranslateMessage(pMsg);
}


BOOL CProjectDlg::OnInitDialog() 
{
	if(m_project_mgr==0)
		return FALSE;
	m_api=m_project_mgr->m_api;
	CaplResizableDialog::OnInitDialog();
	if(m_api==NULL)
	{
		EndDialog(0);
		return FALSE;
	}

	m_date_control_ctrl.ResetContent();
	m_date_control_ctrl.InsertString(0,APL_T("Не учитывать"));
	m_date_control_ctrl.InsertString(1,APL_T("Определять по входящим"));
	m_date_control_ctrl.InsertString(2,APL_T("Ограничивать входящие"));

	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(&(m_api->m_data));

	m_auto_end_edit_ctrl.SetCheck(TRUE);

	m_prj_rel_list.SetExtendedStyle(m_prj_rel_list.GetExtendedStyle()|LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES);
	m_prj_rel_list.InsertColumn(0, APL_T("Тип связи"), LVCFMT_LEFT, 100);
	m_prj_rel_list.InsertColumn(1, APL_T("Параметры связи"), LVCFMT_LEFT, 50);
	m_prj_rel_list.InsertColumn(2, APL_T("Обозначение проекта"), LVCFMT_LEFT, 130);
	m_prj_rel_list.InsertColumn(3, APL_T("Наименование проекта"), LVCFMT_LEFT, 200);
	m_prj_rel_list.InsertColumn(4, APL_T("Тип проекта"), LVCFMT_LEFT, 190);

	COLORMAP  cm;
	cm.from=RGB(192,192,192);
	cm.to=GetSysColor(COLOR_BTNFACE);

	

	if(aplGetBitPerPixel(this)>8)
		//m_name_bmp.LoadMappedBitmap(IDB_PRJ_BMP_COLOR,0,&cm,1);
		aplLoadMappedBitmap(m_name_bmp,IDB_PRJ_BMP_COLOR,RGB(0,0,0),GetSysColor(COLOR_BTNFACE),50);
	else
		m_name_bmp.LoadMappedBitmap(IDB_PROJECT_ICON_BMP,0,&cm,1);

	HBITMAP hBmpOld=m_st_project_name.SetBitmap(HBITMAP(m_name_bmp));	
	::DeleteObject(hBmpOld);

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_ok_btn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_ok_btn.SetFlat(FALSE);

	m_check_out_ctrl.SetFlat(false);
	m_check_in_ctrl.SetFlat(false);
	m_undo_check_out_ctrl.SetFlat(false);

	m_notes_btn.SetIcon(GetAplTableIco(APL_TABLE_NOTE_NOTE));
	m_notes_btn.SetFlat(FALSE);

	int color_mode=0;
	if(aplGetBitPerPixel(this)>8) color_mode=1;
	
	m_check_out_ctrl.SetIcon(GetAplCheckIco(APL_ICON_CHECKOUT,color_mode)); 
	m_check_in_ctrl.SetIcon(GetAplCheckIco(APL_ICON_CHECKIN,color_mode)); 
	m_undo_check_out_ctrl.SetIcon(GetAplCheckIco(APL_ICON_UNDOCHECKOUT,color_mode)); 

	RECT r1;
	m_undo_check_out_ctrl.GetWindowRect(&r1);
	ScreenToClient(&r1);
	m_check_out_ctrl.MoveWindow(&r1);

	AddAnchor(IDOK,BOTTOM_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_CHECK_OUT,TOP_RIGHT);
	AddAnchor(IDC_CHECK_IN,TOP_RIGHT);
	AddAnchor(IDC_UNDO_CHECK_OUT,TOP_RIGHT);

	m_check_out_ctrl.SetTooltipText(APL_T("Взять на редактирование"));
	m_check_in_ctrl.SetTooltipText(APL_T("Завершить редактирование"));
	m_undo_check_out_ctrl.SetTooltipText(APL_T("Отменить редактирование")); 

	m_toolTipCtrl.Create(this);
	m_toolTipCtrl.AddTool(&m_actual_labor_ctrl,APL_T("Трудоемкость затраченная на текущий момент. Используется при расчете % выполнения и прогнозируемой даты завершения."));
	m_toolTipCtrl.AddTool(&m_persentage_ctrl, APL_T("Вычисляется как отношение фактической трудоемкости к плановой."));
	m_toolTipCtrl.AddTool(&m_actual_labor_date_ctrl, APL_T("Дата, на которую актуальна указанная затраченная трудоемкость. (Используется при расчете прогнозируемой даты завершения."));
	EnableToolTips();

	// Ед. изм.
	aplExtent ext_unit;
	m_project_mgr->m_api->m_unit_exch_mgr.GetPrdUnits(ext_unit);
	int i;
	CString buf;
	int k=m_prd_amount_unit_ctrl.AddString(_T(""));
	m_prd_amount_unit_ctrl.SetItemData(k,0);

	for(i=0;i<ext_unit.Size;i++)
	{
		m_project_mgr->m_api->m_charact_mgr.GetUnitName(ext_unit[i],buf);
		int k=m_prd_amount_unit_ctrl.AddString(buf);
		m_prd_amount_unit_ctrl.SetItemData(k,(UINT)ext_unit[i]);
	}
	m_prd_amount_unit_ctrl.SelectString(0,_T(""));
	
	// Типы проектов
	aplExtent ext;
	int j=m_project_type_ctrl.AddString(_T(""));
	m_project_type_ctrl.SetItemData(j,0);
	m_project_type_ctrl.SetCurSel(j);
	m_project_mgr->m_data->GetEntityExtent(m_project_mgr->e_project_type,ext);
	for(int i=0;i<ext.Size;i++)
	{
		m_project_mgr->m_data->GetAttr(ext[i],m_project_mgr->a_project_type_name,buf);
		j=m_project_type_ctrl.AddString(buf);
		m_project_type_ctrl.SetItemData(j,(long)ext[i]);
	}
	
	if(m_project) 
	{
		CalcMaxMinSubDates();
		SetFromInst();
		SetReadOnlyItems();
		SetStates();
	}
	else SetDefaults();
	m_project_mgr->m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("Проекты\\Иерархический контроль сроков"),m_check_dates,1);
	m_project_mgr->m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("Проекты\\Запретить перевыполнение плана"),m_forbid_overproducing,1);
	m_project_mgr->m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("Проекты\\Присваивать статус 'завершен' при достижении 100%"),m_auto_complete,1);
	m_project_mgr->m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("Проекты\\Автоматически присваивать статус 'завершен' проектам-родителям"),m_auto_complete_parent,1);


	if(m_odt_min_planed.GetStatus()!=COleDateTime::null)
	{
		buf=m_odt_min_planed.Format(APL_T("Минимальная дата: %d.%m.%Y  %H:%M:%S"));
		m_toolTipCtrl.AddTool(&m_date_begin_planned_ctrl, buf);
	}
	if(m_odt_max_planed.GetStatus()!=COleDateTime::null)
	{
		buf=m_odt_max_planed.Format(APL_T("Максимальная дата: %d.%m.%Y  %H:%M:%S"));
		m_toolTipCtrl.AddTool(&m_date_end_planned_ctrl, buf);
	}

	m_project_mgr->m_api->m_options_mgr.GetOptionValueBN(APL_NO_T("Проекты\\Запретить ввод фактической даты будущей датой"),m_forbinen_future_fact_dates, 0);


	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CProjectDlg::UpdateRelation(int item)
{
	CaplInstance *cur_project=m_project;
	if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);
	
	if(item>=0)
	{
		// Обновляем конекретный Item
		CaplInstance *rel_prj, *prj_type, *rel;
		rel=(CaplInstance *)m_prj_rel_list.GetItemData(item);
		bool bDel=false;
		if(rel==0)bDel=true;
		else if(rel->GetId()==0)bDel=true;
		
		if(bDel) 
		{
			m_prj_rel_list.DeleteItem(item);
			return;
		}
		CString buf;
		m_api->m_data.GetAttr(rel,m_project_mgr->a_project_seq_prev,rel_prj);
		if(rel_prj!=cur_project) buf=APL_T("Предыдущий");
		else buf=APL_T("Следующий");
		m_prj_rel_list.SetItemText(item,0,buf);

		m_api->m_data.GetAttr(rel_prj,m_project_mgr->a_project_id,buf);
		m_prj_rel_list.SetItemText(item,2,buf);
		m_api->m_data.GetAttr(rel_prj,m_project_mgr->a_project_name,buf);
		m_prj_rel_list.SetItemText(item,3,buf);
		m_api->m_data.GetAttr(rel_prj,m_project_mgr->a_project_type,prj_type);
		if(prj_type)
		{
			m_api->m_data.GetAttr(prj_type,m_project_mgr->a_project_type_name,buf);
			m_prj_rel_list.SetItemText(item,4,buf);
		}
		return;
	}

	// Обновляем все
	m_prj_rel_list.DeleteAllItems();
	int i;
	CString buf;
	CaplInstance *rel_prj,*prj_type;
	aplExtent ext_rel;
	m_project_mgr->GetProjectSequenceRelation(cur_project,ext_rel,false);
	for(i=0;i<ext_rel.GetSize();i++)
	{
		m_api->m_data.GetAttr(ext_rel[i],m_project_mgr->a_project_seq_prev,rel_prj);
		if(rel_prj!=cur_project) buf=APL_T("Предыдущий");
		else 
		{
			buf=APL_T("Следующий");
			m_api->m_data.GetAttr(ext_rel[i],m_project_mgr->a_project_seq_next,rel_prj);
		}
		if(rel_prj && rel_prj->GetId()>0 &&  rel_prj->GetAccessmode()<=aplRO)
		{
			int item=m_prj_rel_list.InsertItem(i,buf);
			m_prj_rel_list.SetItemData(item,(int)ext_rel[i]);
			m_api->m_data.GetAttr(rel_prj,m_project_mgr->a_project_id,buf);
			m_prj_rel_list.SetItemText(item,2,buf);
			m_api->m_data.GetAttr(rel_prj,m_project_mgr->a_project_name,buf);
			m_prj_rel_list.SetItemText(item,3,buf);
			m_api->m_data.GetAttr(rel_prj,m_project_mgr->a_project_type,prj_type);
			if(prj_type)
			{
				m_api->m_data.GetAttr(prj_type,m_project_mgr->a_project_type_name,buf);
				m_prj_rel_list.SetItemText(item,4,buf);
			}
		}
	}


	
}


void CProjectDlg::SetFromInst()
{
	CString buf=_T(""),id=_T(""),name=_T(""),descr=_T(""),number=_T(""),date_begin=_T(""),date_end=_T(""),date_end2=_T(""),num_prj, labor_useness_actual_date_s=_T("");
	CString control_type;
	double num=0,prd_amount_planned=0,persentage=0,planed_duration=0;
	CaplAggr aggr;
	CaplInstance *labor=0,*labor_actual=0,*labor_of_item=0,*type=0,*inst=0;
	bool calc_by_amount;
	int date_set_mask=0;
	CaplInstance *cur_project=m_project;
	if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project))
	{
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_id,id);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_name,name);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_descr,descr);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_number,number);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_type,type);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_control_type,control_type);
		if(control_type==APL_T("Не контролировать")) control_type=APL_T("Не учитывать"); //Учет переименования
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_customer,m_customer);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_labor_useness,labor);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_kurator,m_kurator);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_executors,m_executors);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_co_executors,m_co_executors);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_co_customers,m_co_customers);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_date_planned_begin,date_begin);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_date_planned_end,date_end);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_date_planned_end2,date_end2);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_date_planned_end2,date_end2);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_date_planned_duration,planed_duration);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_date_set_mask,date_set_mask);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_number,num_prj);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_labor_of_item,labor_of_item);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_prd_amount_planned,prd_amount_planned);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_calc_by_amount,calc_by_amount);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_persentage,persentage);

		CaplInstance *unit=0;
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_prd_amount_unit,unit);
		
		int i;
		for(i=0;i<m_prd_amount_unit_ctrl.GetCount();i++)
		{
			if (((DWORD)unit)==m_prd_amount_unit_ctrl.GetItemData(i))
			{
				m_prd_amount_unit_ctrl.SetCurSel(i);
				break;
			}
		}
		m_check_in_ctrl.ShowWindow(SW_HIDE);
		m_undo_check_out_ctrl.ShowWindow(SW_HIDE);
		m_auto_end_edit_ctrl.ShowWindow(SW_HIDE);
		SetWindowText(APL_T("Проект"));
	}
	else if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
	{
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_id,id);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_name,name);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_number,number);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_descr,descr);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_type,type);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_control_type,control_type);
		if(control_type==APL_T("Не контролировать")) control_type=APL_T("Не учитывать"); //Учет переименования
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_customer,m_customer);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_labor_useness,labor);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_kurator,m_kurator);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_executors,m_executors);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_co_executors,m_co_executors);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_co_customers,m_co_customers);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_date_planned_begin,date_begin);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_date_planned_end,date_end);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_date_planned_end2,date_end2);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_date_planned_duration,planed_duration);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_date_set_mask,date_set_mask);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_number,num_prj);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_labor_of_item,labor_of_item);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_prd_amount_planned,prd_amount_planned);
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_calc_by_amount,calc_by_amount);

		// 20.03.2023  Убрано использование a_project_adm_ver_persentage  чтобы не было путаницы
		//m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_persentage,persentage);
		m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_persentage,persentage);

		CaplInstance *unit=0;
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_prd_amount_unit,unit);
		
		int i;
		for(i=0;i<m_prd_amount_unit_ctrl.GetCount();i++)
		{
			if (((DWORD)unit)==m_prd_amount_unit_ctrl.GetItemData(i))
			{
				m_prd_amount_unit_ctrl.SetCurSel(i);
				break;
			}
		}
		m_check_out_ctrl.ShowWindow(SW_HIDE);
		SetWindowText(APL_T("Версия проекта"));
	}

	if(!cur_project) return;
	m_project_mgr->GetPrjDateRestrictions(cur_project,m_odt_min_planed,m_odt_max_planed,false);

	//m_bHaveChildren=m_project_mgr->IsProjectHaveChildren(cur_project,false);

	m_id_ctrl.SetWindowText(id);
	m_name_ctrl.SetWindowText(name);
	m_descr_ctrl.SetWindowText(descr);
	m_number_ctrl.SetWindowText(number);
	UpdateKuratorCtrl();
	UpdateExecutorsCtrl();
	UpdateCoExecutorsCtrl();
	UpdateCustomerCtrl();
	UpdateCoCutomersCtrl();
	
	//объем выпуска плановый
	buf.Format(_T("%g"),prd_amount_planned);
	m_prd_amount_planned_ctrl.SetWindowText(buf);

	//трудоемкость
	m_labor_value_ctrl.SetWindowText(_T("0"));
	if(labor)
	{
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_value,num);
		buf.Format(_T("%g"),num);
		if(buf==_T("")) buf==_T("0");
		m_labor_value_ctrl.SetWindowText(buf);
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_unit,m_labor_unit);
		UpdateLaborUnitCtrl();
	}
	//фактическая трудоемкость
	m_actual_labor_ctrl.SetWindowText(_T("0"));
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_labor_useness_actual,labor_actual);
	if(labor_actual)
	{
		m_project_mgr->m_data->GetAttr(labor_actual,m_project_mgr->a_labor_value,num);
		buf.Format(_T("%g"),num);
		if(buf==_T("")) buf==_T("0");
		m_actual_labor_ctrl.SetWindowText(buf);
		//m_project_mgr->m_data->GetAttr(labor_actual,m_project_mgr->a_labor_unit,m_labor_unit_actual);
		//UpdateActualLaborUnitCtrl();
	}
	
	COleDateTime odt_labor_useness_actual_date;
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_labor_useness_actual_date,labor_useness_actual_date_s);
	if(labor_useness_actual_date_s==_T(""))	odt_labor_useness_actual_date.SetDateTime(1900,1,1,0,0,0);	
	else aplString2Date(labor_useness_actual_date_s,odt_labor_useness_actual_date);
	m_actual_labor_date_ctrl.SetTime(odt_labor_useness_actual_date);
	
	//трудоемкость на единицу
	m_labor_of_item_ctrl.SetWindowText(_T("0"));
	if(labor_of_item)
	{
		m_project_mgr->m_data->GetAttr(labor_of_item,m_project_mgr->a_labor_value,num);
		buf.Format(_T("%g"),num);
		if(buf==_T("")) buf==_T("0");
		m_labor_of_item_ctrl.SetWindowText(buf);
		m_project_mgr->m_data->GetAttr(labor_of_item,m_project_mgr->a_labor_unit,m_labor_of_item_unit);
		UpdateLaborOfItemUnitCtrl();
	}
	//объем выпуска фактический
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_prd_amount_actual,num);
	buf.Format(_T("%g"),num);
	if(buf==_T("")) buf==_T("0");
	m_prd_amount_actual_ctrl.SetWindowText(buf);

	if(calc_by_amount)
	{
		m_calc_by_amount_ctrl.SetCheck(TRUE);

		m_labor_value_ctrl.SetReadOnly(TRUE);
		m_select_labunit_btn.EnableWindow(FALSE);
		GetDlgItem(IDC_DEL_LABOR_UNIT)->EnableWindow(FALSE);

		m_actual_labor_ctrl.SetReadOnly(TRUE);
		//m_select_actual_labor_unit_btn.EnableWindow(FALSE);
		//m_actual_labor_date_ctrl.EnableWindow(FALSE);

	}
	else m_calc_by_amount_ctrl.SetCheck(FALSE);

	//процент выполнения
	buf.Format(_T("%.1f"),persentage);
	if(buf==_T("")) buf==_T("0");
	m_persentage_ctrl.SetWindowText(buf);
	//даты
	m_dlit_actual_ctrl.SetWindowText(_T("0"));
	m_dlit_plan_ctrl.SetWindowText(_T("0"));

	COleDateTime dt;

	if(date_begin!=_T("")) aplString2Date(date_begin,dt);
	else dt.SetDateTime(1900,1,1,0,0,0);

	if(dt.GetStatus()!=COleDateTime::valid) { dt.SetDateTime(1900,1,1,0,0,0); date_begin=_T("");}
	m_date_begin_planned_ctrl.SetTime(dt);	
	m_time_begin_planned_ctrl.SetTime(dt);


	if(date_end!=_T(""))aplString2Date(date_end,dt);
	else dt.SetDateTime(1900,1,1,23,59,59);

	if(dt.GetStatus()!=COleDateTime::valid) { dt.SetDateTime(1900,1,1,23,59,59); date_end=_T("");}
	m_date_end_planned_ctrl.SetTime(dt);	
	m_time_end_planned_ctrl.SetTime(dt);

	if(planed_duration==0&& (0==(date_set_mask & 4)))  buf=_T("");
	else buf=_T("");buf.Format(_T("%.4g"),planed_duration);
	m_dlit_plan_ctrl.SetWindowText(buf);

	// определяем галочки
	if(0==date_set_mask)
	{
		//старый проект без масок или ничего не задано
		if(date_begin!=_T("")) m_check_planned_begin_ctrl.SetCheck(1); else m_check_planned_begin_ctrl.SetCheck(0);
		if(date_end!=_T(""))   m_check_planned_end_ctrl.SetCheck(1);   else m_check_planned_end_ctrl.SetCheck(0);
	}
	else
	{
		if(0!=(date_set_mask & 1))m_check_planned_begin_ctrl.SetCheck(1); else m_check_planned_begin_ctrl.SetCheck(0);
		if(0!=(date_set_mask & 2))m_check_planned_end_ctrl.SetCheck(1);   else m_check_planned_end_ctrl.SetCheck(0);
		if(0!=(date_set_mask & 4))m_check_planed_duration_set_btn.SetCheck(1); else m_check_planed_duration_set_btn.SetCheck(0);
	}

	RecalcPlanDate();

	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_actual_begin,buf);
	if(buf!=_T(""))
	{
		aplString2Date(buf,dt);
		if(dt.GetStatus()==COleDateTime::valid)
		{
			m_check_fact_begin_ctrl.SetCheck(1);
			m_date_begin_fact_ctrl.SetTime(dt);	
			m_time_begin_fact_ctrl.SetTime(dt);
		}
	}
	OnCheckFactBegin();
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_actual_end,buf);
	if(buf!=_T(""))
	{
		aplString2Date(buf,dt);
		if(dt.GetStatus()==COleDateTime::valid)
		{
			m_check_fact_end_ctrl.SetCheck(1);
			m_date_end_fact_ctrl.SetTime(dt);	
			m_time_end_fact_ctrl.SetTime(dt);
		}
	}
	OnCheckFactEnd();
	
	//тип
	long j;
	if(type!=0)
	{
		for(int i=0;i<m_project_type_ctrl.GetCount();i++)
		{
			j=m_project_type_ctrl.GetItemData(i);
			if(j==(long)type) { m_project_type_ctrl.SetCurSel(i); break;	}
		}
	}

	//номер проекта
	m_number_ctrl.SetWindowText(num_prj);

	//состояние
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_state,m_cur_state);
	if(m_cur_state==_T("")) m_cur_state=APL_T("планирование");

	if(control_type==_T(""))	control_type=APL_NO_T("Не учитывать");
	else if(control_type==APL_NO_T("По умолчанию"))	control_type=APL_NO_T("Не учитывать");
	else if(control_type==APL_NO_T("Не контролировать"))	control_type=APL_NO_T("Не учитывать"); //для учета переименования
	
	if(CaplTranslate::IsNeedTranslate()) control_type=CaplTranslate::Translate(control_type);
	
	m_date_control_ctrl.SelectString(-1,control_type);
	OnSelchangeDateControl(); 


	// Записываем связи
	UpdateRelation(-1);
}

void CProjectDlg::SetReadOnlyItems()
{
	if(m_project)
	{
		if(m_read_only)
		{
			m_id_ctrl.SetReadOnly(TRUE);
			m_name_ctrl.SetReadOnly(TRUE);
			m_descr_ctrl.SetReadOnly(TRUE);
			m_number_ctrl.SetReadOnly(TRUE);
			m_select_kurator_btn.EnableWindow(FALSE);
			m_delete_kur_btn.EnableWindow(FALSE);
			m_select_executors_btn.EnableWindow(FALSE);
			m_select_cocostomers_btn.EnableWindow(FALSE);
			m_select_coexecutors_btn.EnableWindow(FALSE);
			m_check_planned_end_ctrl.EnableWindow(FALSE);
			m_check_planned_begin_ctrl.EnableWindow(FALSE);
			m_check_planed_duration_set_btn.EnableWindow(FALSE);
			m_date_begin_planned_ctrl.EnableWindow(FALSE);
			m_time_begin_planned_ctrl.EnableWindow(FALSE);
			m_date_end_planned_ctrl.EnableWindow(FALSE);
			m_time_end_planned_ctrl.EnableWindow(FALSE);
			m_dlit_plan_ctrl.EnableWindow(FALSE);
			m_project_type_ctrl.EnableWindow(FALSE);
			m_check_fact_end_ctrl.EnableWindow(FALSE);
			m_check_fact_begin_ctrl.EnableWindow(FALSE);
			m_date_begin_fact_ctrl.EnableWindow(FALSE);
			m_time_begin_fact_ctrl.EnableWindow(FALSE);
			m_date_end_fact_ctrl.EnableWindow(FALSE);
			m_time_end_fact_ctrl.EnableWindow(FALSE);
			m_select_labunit_btn.EnableWindow(FALSE);
			m_date_control_ctrl.EnableWindow(FALSE);
			GetDlgItem(IDC_DEL_LABOR_UNIT)->EnableWindow(FALSE);
			m_labor_value_ctrl.SetReadOnly(TRUE);
			//m_persentage_ctrl.SetReadOnly(TRUE);
			m_state_ctrl.EnableWindow(FALSE);			
	
			m_select_labor_of_item_unit_btn.EnableWindow(FALSE);
			//m_select_actual_labor_unit_btn.EnableWindow(FALSE);
			m_actual_labor_date_ctrl.EnableWindow(FALSE);
			m_prd_amount_planned_ctrl.SetReadOnly(TRUE);
			m_prd_amount_unit_ctrl.EnableWindow(FALSE);
			m_prd_amount_actual_ctrl.SetReadOnly(TRUE);
			m_labor_of_item_ctrl.SetReadOnly(TRUE);
			m_calc_by_amount_ctrl.EnableWindow(FALSE);
			m_actual_labor_ctrl.SetReadOnly(TRUE);
			m_select_customer_btn.EnableWindow(FALSE);
			m_delete_cust_btn.EnableWindow(FALSE);
		
			m_ok_btn.EnableWindow(FALSE);
			m_check_out_ctrl.ShowWindow(SW_HIDE);
			m_check_in_ctrl.ShowWindow(SW_HIDE);
			m_auto_end_edit_ctrl.ShowWindow(SW_HIDE);
			m_undo_check_out_ctrl.ShowWindow(SW_HIDE);		
		}
		else
		{
			m_id_ctrl.SetReadOnly(m_read_only_ver);
			m_name_ctrl.SetReadOnly(m_read_only_ver);
			m_descr_ctrl.SetReadOnly(m_read_only_ver);
			m_number_ctrl.SetReadOnly(m_read_only_ver);
			m_project_type_ctrl.EnableWindow(!m_read_only_ver);
			if(m_calc_by_amount_ctrl.GetCheck()==0)
			{
				m_select_labunit_btn.EnableWindow(!m_read_only_ver);
				GetDlgItem(IDC_DEL_LABOR_UNIT)->EnableWindow(!m_read_only_ver);
				m_labor_value_ctrl.SetReadOnly(m_read_only_ver);
			}
			m_select_customer_btn.EnableWindow(!m_read_only_ver);
			m_delete_cust_btn.EnableWindow(!m_read_only_ver);
			m_select_kurator_btn.EnableWindow(!m_read_only_ver);
			m_delete_kur_btn.EnableWindow(!m_read_only_ver);
			m_select_executors_btn.EnableWindow(!m_read_only_ver);
			m_select_cocostomers_btn.EnableWindow(!m_read_only_ver);
			m_select_coexecutors_btn.EnableWindow(!m_read_only_ver);
			m_check_planned_end_ctrl.EnableWindow(!m_read_only_ver);
			m_check_planned_begin_ctrl.EnableWindow(!m_read_only_ver);			
			m_date_control_ctrl.EnableWindow(!m_read_only_ver);
			m_check_planed_duration_set_btn.EnableWindow(!m_read_only_ver);			
			m_dlit_plan_ctrl.EnableWindow(!m_read_only_ver);	
			m_date_begin_planned_ctrl.EnableWindow(FALSE);
			m_time_begin_planned_ctrl.EnableWindow(FALSE);
			m_date_end_planned_ctrl.EnableWindow(FALSE);
			m_time_end_planned_ctrl.EnableWindow(FALSE);

			int check=m_check_planned_begin_ctrl.GetCheck();
			int check1=m_check_planned_end_ctrl.GetCheck();
			int check2=m_check_planed_duration_set_btn.GetCheck();

			if(!m_read_only_ver)
			{
				if(check)
				{
					m_date_begin_planned_ctrl.EnableWindow(TRUE);
					m_time_begin_planned_ctrl.EnableWindow(TRUE);
				}
				if(check1)
				{
					m_date_end_planned_ctrl.EnableWindow(TRUE);
					m_time_end_planned_ctrl.EnableWindow(TRUE);
				}
				if(check2)
				{
					m_dlit_plan_ctrl.SetReadOnly(FALSE);
				}
			}

			
			m_calc_by_amount_ctrl.EnableWindow(!m_read_only_ver);
			m_select_labor_of_item_unit_btn.EnableWindow(!m_read_only_ver);
			m_prd_amount_planned_ctrl.SetReadOnly(m_read_only_ver);
			
			if(m_read_only_ver)m_prd_amount_unit_ctrl.EnableWindow(FALSE);
			else m_prd_amount_unit_ctrl.EnableWindow(TRUE);

			m_labor_of_item_ctrl.SetReadOnly(m_read_only_ver);
			
			if(m_bHaveChildren)
			{
				m_labor_value_ctrl.SetReadOnly(TRUE);
				m_select_labunit_btn.EnableWindow(FALSE);
				GetDlgItem(IDC_DEL_LABOR_UNIT)->EnableWindow(FALSE);
				m_actual_labor_ctrl.SetReadOnly(TRUE);	
				//m_select_actual_labor_unit_btn.EnableWindow(FALSE);
				m_actual_labor_date_ctrl.EnableWindow(FALSE);
				m_calc_by_amount_ctrl.EnableWindow(FALSE);
				m_labor_of_item_ctrl.SetReadOnly(TRUE);
				m_select_labor_of_item_unit_btn.EnableWindow(FALSE);
				m_prd_amount_planned_ctrl.SetReadOnly(TRUE);
				m_prd_amount_actual_ctrl.SetReadOnly(TRUE);

				CString control_type;
				m_date_control_ctrl.GetWindowText(control_type);

				// Не учитывать;Определять по входящим;Ограничивать входящие;

				if(control_type==APL_T("Определять по входящим")) control_type=APL_NO_T("Определять по входящим");
				else  if(control_type==APL_T("Ограничивать входящие")) control_type=APL_NO_T("Ограничивать входящие");
				else control_type=APL_NO_T("Не учитывать");


				bool b_control_by_content=false;
				if(control_type==APL_NO_T("Определять по входящим")) b_control_by_content=true;
				if(!m_read_only_ver && !b_control_by_content)
				{
					m_check_planned_begin_ctrl.EnableWindow(TRUE);
					m_check_planned_end_ctrl.EnableWindow(TRUE);
					m_check_planed_duration_set_btn.EnableWindow(TRUE);

					if(check)
					{
						m_date_begin_planned_ctrl.EnableWindow(TRUE);
						m_time_begin_planned_ctrl.EnableWindow(TRUE);
					}
					if(check1)
					{
						m_date_end_planned_ctrl.EnableWindow(TRUE);
						m_time_end_planned_ctrl.EnableWindow(TRUE);
					}
					if(check2) 	m_dlit_plan_ctrl.SetReadOnly(FALSE);
				}
				else
				{
					m_date_begin_planned_ctrl.EnableWindow(FALSE);
					m_date_end_planned_ctrl.EnableWindow(FALSE);
					m_time_begin_planned_ctrl.EnableWindow(FALSE);
					m_time_end_planned_ctrl.EnableWindow(FALSE);
					m_check_planned_begin_ctrl.EnableWindow(FALSE);
					m_check_planed_duration_set_btn.EnableWindow(FALSE);
					m_check_planned_end_ctrl.EnableWindow(FALSE);
					m_dlit_plan_ctrl.EnableWindow(FALSE);
				}
				int check=m_check_fact_begin_ctrl.GetCheck();
				int check1=m_check_fact_end_ctrl.GetCheck();
				if(check)
				{
					m_date_begin_fact_ctrl.EnableWindow(!b_control_by_content);
					m_time_begin_fact_ctrl.EnableWindow(!b_control_by_content);
				}
				if(check1)
				{
					m_date_end_fact_ctrl.EnableWindow(!b_control_by_content);
					m_time_end_fact_ctrl.EnableWindow(!b_control_by_content);
				}


				m_check_fact_begin_ctrl.EnableWindow(!b_control_by_content);
				m_check_fact_end_ctrl.EnableWindow(!b_control_by_content);
				if((check==1 && check1==0) || (check==0 && check1==1))
					m_dlit_actual_ctrl.SetReadOnly(b_control_by_content);
				
			}
			if(!m_can_check_out)
			{
				m_check_out_ctrl.ShowWindow(SW_HIDE);
				m_check_in_ctrl.ShowWindow(SW_HIDE);
				m_undo_check_out_ctrl.ShowWindow(SW_HIDE);
				m_auto_end_edit_ctrl.ShowWindow(SW_HIDE);
			}
		}
	}

}

void CProjectDlg::SetDefaults()
{
	UpdateData(FALSE);
	m_prj_rel_list.DeleteAllItems();

	if(m_parent) m_project_mgr->GetPrjDateRestrictions(m_parent,m_odt_min_planed,m_odt_max_planed,true);

	COleDateTime dt = COleDateTime::GetCurrentTime();
	COleDateTime ts(1900,1,1,0,0,0),te(1900,1,1,23,59,59);
	m_date_begin_planned_ctrl.SetTime(dt);
	m_date_end_planned_ctrl.SetTime(dt);
	m_time_begin_planned_ctrl.SetTime(ts);
	m_time_end_planned_ctrl.SetTime(te);
	m_dlit_plan_ctrl.SetWindowText(_T("0"));
	RecalcPlanDate();

	m_time_begin_fact_ctrl.SetTime(ts);
	m_time_end_fact_ctrl.SetTime(ts);
	m_dlit_actual_ctrl.SetWindowText(_T("0"));
	
	m_labor_value_ctrl.SetWindowText(_T("0"));
	m_actual_labor_ctrl.SetWindowText(_T("0"));
	m_labor_of_item_ctrl.SetWindowText(_T("0"));
	m_prd_amount_planned_ctrl.SetWindowText(_T("0"));
	m_prd_amount_actual_ctrl.SetWindowText(_T("0"));
	m_persentage_ctrl.SetWindowText(_T("0"));
	m_cur_state=APL_T("планирование");
	int i=m_state_ctrl.AddString(m_cur_state);
	m_state_ctrl.SetCurSel(i);
	m_state_ctrl.AddString(APL_T("в работе"));
	m_state_ctrl.AddString(APL_T("остановлен"));
	m_state_ctrl.AddString(APL_T("отменен"));
	m_state_ctrl.AddString(APL_T("завершен"));
	m_check_out_ctrl.ShowWindow(SW_HIDE);
	m_check_in_ctrl.ShowWindow(SW_HIDE);
	m_auto_end_edit_ctrl.ShowWindow(SW_HIDE);
	m_undo_check_out_ctrl.ShowWindow(SW_HIDE);
	m_date_control_ctrl.SetCurSel(0);

	if(m_parent)
	{
		CaplAPI* m_api= m_project_mgr->m_api;
		m_api->m_data.GetAttr(m_parent, m_project_mgr->a_project_id, m_id);
		m_api->m_data.GetAttr(m_parent, m_project_mgr->a_project_name, m_sName);

		aplExtent ext_parent_sub_prj;
		if(m_project_mgr->GetAllSubProject(m_parent, ext_parent_sub_prj, false, true, true))
		{
			CString buf;
			buf.Format(_T(".%02i"),ext_parent_sub_prj.GetSize()+1);
			m_id+=buf;
		}

		CString date_begin, date_end;
		COleDateTime odt;

		// Определяем даты родителя
		CaplInstance *ver;
		m_api->m_data.GetAttr(m_parent, m_project_mgr->a_project_locker_adm_version, ver);
		if(0==ver)
		{
			m_project_mgr->m_data->GetAttr(m_parent,m_project_mgr->a_project_date_planned_begin,date_begin);
			m_project_mgr->m_data->GetAttr(m_parent,m_project_mgr->a_project_date_planned_end,date_end);
		}
		else
		{
			m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_begin,date_begin);
			m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_end,date_end);
		}
		
		if(date_begin!=_T(""))
		{
			aplString2Date(date_begin,odt);
			m_time_begin_planned_ctrl.SetTime(odt);
			m_date_begin_planned_ctrl.SetTime(odt);
			m_check_planned_begin_ctrl.SetCheck(1);
			OnCheckPlannedBegin();
		}
		if(date_end!=_T(""))
		{
			aplString2Date(date_end,odt);
			m_time_end_planned_ctrl.SetTime(odt);
			m_date_end_planned_ctrl.SetTime(odt);
			m_check_planned_end_ctrl.SetCheck(1);
			OnCheckPlannedEnd();
		}
		//RecalcPlanDate();
	}

	COleDateTime odt_labor_useness_actual_date;
	odt_labor_useness_actual_date.SetDateTime(1900,1,1,0,0,0);	
	m_actual_labor_date_ctrl.SetTime(odt_labor_useness_actual_date);

	UpdateData(FALSE);
}

void CProjectDlg::SetStates()
{
	int i;
/*	CaplInstance *cur_project=m_project;
	CaplInstance *gk_approval=0;
	CaplInstance *c_status=0;
	if(cur_project)
	{
		if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
			m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);
		m_project_mgr->m_api->m_appr_mgr.FindApprovalStatusBN(APL_T("Утвержден сводный план-график"));
		if(c_status) gk_approval=m_project_mgr->m_api->m_appr_mgr.FindRoleApproval(cur_project,APL_T("Главный конструктор"),c_status);
	}*/
	
	if(m_cur_state==APL_T("планирование"))
	{
		i=m_state_ctrl.AddString(m_cur_state);
		m_state_ctrl.AddString(APL_T("в работе"));
		m_state_ctrl.AddString(APL_T("остановлен"));
		m_state_ctrl.AddString(APL_T("отменен"));
	}
	else if(m_cur_state==APL_T("остановлен"))
	{
		i=m_state_ctrl.AddString(m_cur_state);
		//if(gk_approval) m_state_ctrl.AddString(APL_T("в работе"));
		//else m_state_ctrl.AddString(APL_T("планирование"));
		m_state_ctrl.AddString(APL_T("планирование"));
		m_state_ctrl.AddString(APL_T("в работе"));
	}
	else if(m_cur_state==APL_T("отменен"))
	{
		i=m_state_ctrl.AddString(m_cur_state);
		//if(gk_approval) m_state_ctrl.AddString(APL_T("в работе"));
		//else m_state_ctrl.AddString(APL_T("планирование"));
		m_state_ctrl.AddString(APL_T("планирование"));
		m_state_ctrl.AddString(APL_T("в работе"));
	}
	else if(m_cur_state==APL_T("завершен"))
	{
		i=m_state_ctrl.AddString(m_cur_state);
		m_state_ctrl.AddString(APL_T("в работе"));
	}
	else if(m_cur_state==APL_T("в работе"))
	{
		i=m_state_ctrl.AddString(m_cur_state);
		m_state_ctrl.AddString(APL_T("завершен"));
		m_state_ctrl.AddString(APL_T("отменен"));
		m_state_ctrl.AddString(APL_T("остановлен"));
		m_state_ctrl.AddString(APL_T("планирование"));
	}
	else
		return;
	m_state_ctrl.SetCurSel(i);

}

bool CProjectDlg::SaveChanges()
{
	RecalcPlanDate();
	//Проверка введенных значений

	CString old_id=_T(""),id=_T(""),buf=_T(""),buf1=_T("");
	//id
	m_id_ctrl.GetWindowText(id);
	id.TrimRight();
	id.TrimLeft();
	
	if(id==_T("")) {AfxMessageBox(APL_T("Поле \"Обозначение\" не заполнено !")); return false;}
	
	double persentage=0,labor_value=0,num=0;
	CaplInstance *inst=0; 
	//процент выполнения
	m_persentage_ctrl.GetWindowText(buf1);

	buf1.TrimLeft(); buf1.TrimRight();
	if(!IsRealOrEmpty(buf1))
	{
		AfxMessageBox(APL_T("Процент выполнения должен быть числом!!!"));
		return false;
	}
	persentage=__atof(buf1);
	if(persentage>100 && m_forbid_overproducing)
	{
		AfxMessageBox(APL_T("Процент выполнения должен быть числом от 0 до 100!!!"));
		return false;
	}

	//трудоемкость
	m_labor_value_ctrl.GetWindowText(buf1);
	buf1.TrimLeft(); buf1.TrimRight();
	if(!IsRealOrEmpty(buf1))
	{
		AfxMessageBox(APL_T("Трудоемкость должна быть числом!!!"));
		return false;
	}
	labor_value=__atof(buf1);
	if(labor_value<0)
	{
		AfxMessageBox(APL_T("Трудоемкость должна быть неотрицательным числом!!!"));
		return false;	
	}
	//фактическая трудоемкость
	m_actual_labor_ctrl.GetWindowText(buf1);
	buf1.TrimLeft(); buf1.TrimRight();
	if(!IsRealOrEmpty(buf1))
	{
		AfxMessageBox(APL_T("Фактическая трудоемкость должна быть числом!!!"));
		return false;
	}
	double actual_labor_value=__atof(buf1);
	if(actual_labor_value<0)
	{
		AfxMessageBox(APL_T("Фактическая трудоемкость должна быть неотрицательным числом!!!"));
		return false;	
	}

	//объем продукции плановый 
	m_prd_amount_planned_ctrl.GetWindowText(buf1);
	buf1.TrimLeft(); buf1.TrimRight();
	if(!IsRealOrEmpty(buf1))
	{
		AfxMessageBox(APL_T("Плановый объем продукции должен быть числом!!!"));
		return false;
	}
	double prd_amount_planned=__atof(buf1);
	if(prd_amount_planned<0)
	{
		AfxMessageBox(APL_T("Плановый объем продукции должен быть неотрицательным числом!!!"));
		return false;	
	}
	//объем продукции фактический 
	m_prd_amount_actual_ctrl.GetWindowText(buf1);
	buf1.TrimLeft(); buf1.TrimRight();
	if(!IsRealOrEmpty(buf1))
	{
		AfxMessageBox(APL_T("Фактический объем продукции должен быть числом!!!"));
		return false;
	}
	double prd_amount_actual=__atof(buf1);
	if(prd_amount_actual<0)
	{
		AfxMessageBox(APL_T("Фактический объем продукции должен быть неотрицательным числом!!!"));
		return false;	
	}
	//трудоемкость единицы
	m_labor_of_item_ctrl.GetWindowText(buf1);
	buf1.TrimLeft(); buf1.TrimRight();
	if(!IsRealOrEmpty(buf1))
	{
		AfxMessageBox(APL_T("Трудоемкость единицы продукции должна быть числом!!!"));
		return false;
	}
	double labor_of_item=__atof(buf1);
	if(labor_of_item<0)
	{
		AfxMessageBox(APL_T("Трудоемкость единицы продукции должна быть неотрицательным числом!!!"));
		return false;	
	}
	//даты
	CString control_type;
	m_date_control_ctrl.GetWindowText(control_type);
	COleDateTime d_time,t_time,dt;
	CString planned_date_begin=_T("");
	CString planned_date_end=_T("");
	double planned_dlit=0;

	int date_set_mask=0;
	
	
	int chek1=m_check_planned_begin_ctrl.GetCheck();
	int chek2=m_check_planned_end_ctrl.GetCheck();
	int chek3=m_check_planed_duration_set_btn.GetCheck();

	m_date_begin_planned_ctrl.GetTime(d_time);	
	m_time_begin_planned_ctrl.GetTime(t_time);

	if(d_time.GetYear()==1900 )planned_date_begin=_T("");
	else
	{
		dt.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),
			t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());
		aplDate2String(dt,planned_date_begin);	
	}

	m_date_end_planned_ctrl.GetTime(d_time);	
	m_time_end_planned_ctrl.GetTime(t_time);
	if(d_time.GetYear()==1900 )planned_date_end =_T("");
	else
	{
		dt.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),
			t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());
		aplDate2String(dt,planned_date_end);
	}

	if(planned_date_begin>planned_date_end && planned_date_begin!=_T("") && planned_date_end!=_T(""))
	{
		AfxMessageBox(APL_T("Плановая дата начала не может быть позднее плановой даты окончания!"));
		return false;
	}


	CString planned_dlit_s;
	m_dlit_plan_ctrl.GetWindowText(planned_dlit_s);
	planned_dlit=__atof(planned_dlit_s);

	
	if(chek1==1) date_set_mask|=1;
	if(chek2==1) date_set_mask|=2;
	if(chek3==1) date_set_mask|=4;

	CString actual_dlit_s;
	m_dlit_actual_ctrl.GetWindowText(actual_dlit_s);
	long actual_dlit=_atoi(actual_dlit_s);

	
	CString actual_date_begin=_T(""),actual_date_end=_T("");
	if(m_check_fact_begin_ctrl.GetCheck()==1)
	{
		m_date_begin_fact_ctrl.GetTime(d_time);	
		m_time_begin_fact_ctrl.GetTime(t_time);
		dt.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),
			t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());
		aplDate2String(dt,actual_date_begin);
	}
	if(m_check_fact_end_ctrl.GetCheck()==1)
	{
		m_date_end_fact_ctrl.GetTime(d_time);	
		m_time_end_fact_ctrl.GetTime(t_time);
		dt.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),
			t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());
		aplDate2String(dt,actual_date_end);
	}
	if(actual_date_begin>actual_date_end && actual_date_begin!=_T("") && actual_date_end!=_T(""))
	{
		AfxMessageBox(APL_T("Фактическая дата начала не может быть позденее фактической даты завершения!"));
		return false;
	}

	COleDateTime odt_labor_useness_actual_date;
	CString labor_useness_actual_date_s;
	m_actual_labor_date_ctrl.GetTime(odt_labor_useness_actual_date);
	odt_labor_useness_actual_date.SetDateTime(odt_labor_useness_actual_date.GetYear(),odt_labor_useness_actual_date.GetMonth(),odt_labor_useness_actual_date.GetDay(),23,59,59);

	// Убрано 22.09.2023 по замечаниям Созвездия.
	//if(d_time.GetYear()==1900 )labor_useness_actual_date_s=_T("");
	//..else 
	aplDate2String(odt_labor_useness_actual_date,labor_useness_actual_date_s);


	if(prd_amount_actual>0 && labor_useness_actual_date_s==_T(""))
	{
		AfxMessageBox(APL_T("Не задана дата задания фактической трудоемкости!"));
		m_actual_labor_date_ctrl.SetFocus();
		return false;
	}

	if(prd_amount_actual>0 && actual_date_begin!=_T("") && labor_useness_actual_date_s<actual_date_begin)
	{
		if(!m_bHaveChildren)
		{
			AfxMessageBox(APL_T("Дата задания фактической трудоемкости не может быть меньше фактической даты начала!"));
			m_actual_labor_date_ctrl.SetFocus();
			return false;
		}
	}

	CaplInstance *cur_project=m_project,*ver=0;
	if(m_project)
	{
		if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
		{
			m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);
			ver=m_project;
		}
		else 
		{
			ver=m_project_mgr->CheckMyLock(m_project,false);
		}
		if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_id,old_id);
		else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_id,old_id);
	}

	if(old_id!=id)
	{
		//проверка уникальности id
		if(!m_project_mgr->IsProjectIdUnique(id,cur_project,true))
		{
			return false;
		}
	}
	int i;
	CaplInstance *parent=0;	
	//контроль сроков по родительскому проекту

	CString parent_date_begin=_T(""), parent_date_end=_T("");
	if(cur_project) m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_parent,parent);
	else parent=m_parent;
	CString parent_control_type;
	CString err_string=_T("");
	if(parent) m_project_mgr->m_data->GetAttr(parent,m_project_mgr->a_project_control_type,parent_control_type);


	/*bool b_need_recalc_parent_dates=false;
	if(parent && parent_control_type!=APL_T("Не контролировать"))
	{
		m_project_mgr->m_data->GetAttr(parent,m_project_mgr->a_project_control_type,parent_control_type);
		CaplInstance *parent_lock=m_project_mgr->CheckMyLock(parent,false);
		if(parent_lock)
		{
			m_project_mgr->m_data->GetAttr(parent_lock,m_project_mgr->a_project_adm_ver_date_planned_begin,parent_date_begin);
			m_project_mgr->m_data->GetAttr(parent_lock,m_project_mgr->a_project_adm_ver_date_planned_end,parent_date_end);
		}
		else
		{
			m_project_mgr->m_data->GetAttr(parent,m_project_mgr->a_project_date_planned_begin,parent_date_begin);
			m_project_mgr->m_data->GetAttr(parent,m_project_mgr->a_project_date_planned_end,parent_date_end);
		}
		aplString2Date(parent_date_end,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,parent_date_end);
		aplString2Date(planned_date_end,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,buf);
		if(parent_date_end!=buf)
		{
			if(parent_control_type==APL_NO_T("Определять по входящим"))
			{
				b_need_recalc_parent_dates=true;
			}
			else
			{
				if(parent_date_end!=_T("") && buf!=_T("") && buf>parent_date_end)//плановая дата окончания проекта превышает плановую дату окончания родителя
				{
					aplString2Date(parent_date_end,dt);
					buf1=dt.Format(_T("%d.%m.%Y"));
					err_string= APL_T("Плановая дата окончания проекта превышает плановую дату окончания родителя (");
					err_string+=buf1;
					err_string+=_T(")!");
					if(parent_control_type==APL_T("Ограничивать входящие") || (m_check_dates && parent_control_type==APL_T("По умолчанию")))
					{
						AfxMessageBox(err_string);
						return false;
					}
					else
					{
						err_string+=APL_T("\nПродолжить?");
						if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
							return false;
					}
				}
			}
		}
		aplString2Date(parent_date_begin,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,parent_date_begin);
		aplString2Date(planned_date_begin,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,buf);
		if(parent_date_begin!=buf)
		{
			if(parent_control_type==APL_NO_T("Определять по входящим"))
			{
				b_need_recalc_parent_dates=true;		
			}
			else
			{
				if(parent_date_begin!=_T("") && buf!=_T("") && buf<parent_date_begin)//плановая дата начала проекта меньше плановой даты начала родителя
				{
					aplString2Date(parent_date_begin,dt);
					buf1=dt.Format(_T("%d.%m.%Y"));
					err_string= APL_T("Плановая дата начала проекта меньше плановой даты начала родителя (");
					err_string+=buf1;
					err_string+=_T(")!");
					if(parent_control_type==APL_T("Ограничивать входящие") || (m_check_dates && parent_control_type==APL_T("По умолчанию")))
					{
						AfxMessageBox(err_string);
						return false;
					}
					else
					{
						err_string+=APL_T("\nПродолжить?");
						if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
							return false;
					}
				}
			}
		}
		//фактические даты
		CString actual_parent_date_begin=_T("");
		CString actual_parent_date_end=_T("");
		m_project_mgr->m_data->GetAttr(parent,m_project_mgr->a_project_date_actual_begin,actual_parent_date_begin);
		m_project_mgr->m_data->GetAttr(parent,m_project_mgr->a_project_date_actual_end,actual_parent_date_end);
		
		aplString2Date(actual_parent_date_end,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,actual_parent_date_end);
		aplString2Date(actual_date_end,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,buf);
		if(actual_parent_date_end!=buf)
		{
			if(parent_control_type==APL_NO_T("Определять по входящим"))
			{
				b_need_recalc_parent_dates=true;		
			}
			else
			{
				if(actual_parent_date_end!=_T("") && buf!=_T("") && buf>actual_parent_date_end)//фактич дата окончания проекта превышает плановую дату окончания родителя
				{
					aplString2Date(actual_parent_date_end,dt);
					buf1=dt.Format(_T("%d.%m.%Y"));
					err_string= APL_T("Фактическая дата окончания проекта превышает фактическую дату окончания родителя (");
					err_string+=buf1;
					err_string+=_T(")!");
					if(parent_control_type==APL_T("Ограничивать входящие") || (m_check_dates && parent_control_type==APL_T("По умолчанию")))
					{
						AfxMessageBox(err_string);
						return false;
					}
					else
					{
						err_string+=APL_T("\nПродолжить?");
						if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
							return false;
					}
				}
			}
		}
		aplString2Date(actual_parent_date_begin,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,actual_parent_date_begin);
		aplString2Date(actual_date_begin,dt);
		dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
			0,0,0);
		aplDate2String(dt,buf);
		if(actual_parent_date_begin!=buf)
		{
			if(parent_control_type==APL_NO_T("Определять по входящим"))
			{
				b_need_recalc_parent_dates=true;		
			}
			else
			{
				if(actual_parent_date_begin!=_T("") && buf!=_T("") && buf<actual_parent_date_begin)//фактич дата начала проекта меньше плановой даты начала родителя
				{
					aplString2Date(parent_date_begin,dt);
					buf1=dt.Format(_T("%d.%m.%Y"));
					err_string= APL_T("Фактическая дата начала проекта меньше фактической даты начала родителя (");
					err_string+=buf1;
					err_string+=_T(")!");
					if(parent_control_type==APL_T("Ограничивать входящие") || (m_check_dates && parent_control_type==APL_T("По умолчанию")))
					{
						AfxMessageBox(err_string);
						return false;
					}
					else if(parent_control_type==APL_NO_T("Определять по входящим"))
					{
						b_need_recalc_parent_dates=true;
					}
					else
					{
						err_string+=APL_T("\nПродолжить?");
						if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
							return false;
					}
				}
			}
		}
	}
	int i;
	if(control_type!=APL_T("Не контролировать"))//контроль сроков по подпроектам
	{
		if(m_bHaveChildren)
		{
			aplString2Date(m_min_planned_date_begin,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,m_min_planned_date_begin);
			aplString2Date(planned_date_begin,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,buf);
			if(m_min_planned_date_begin!=_T("") && buf!=_T("") && m_min_planned_date_begin<buf)
			{
				aplString2Date(m_min_planned_date_begin,dt);
				buf1=dt.Format(_T("%d.%m.%Y"));
				err_string= APL_T("Плановая дата начала проекта больше минимальной плановой даты подпроектов! (");
				err_string+=buf1;
				err_string+=_T(")!");
				if(control_type==APL_NO_T("Ограничивать входящие") || (m_check_dates && control_type==APL_T("По умолчанию")))
				{
					AfxMessageBox(err_string);
						return false;
				}
				else if(control_type==APL_NO_T("Определять по входящим"))
				{
					planned_date_begin=m_min_planned_date_begin;
				}
				else
				{
					err_string+=APL_T("\nПродолжить?");
					if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
						return false;
				}
			}
			aplString2Date(m_max_planned_date_end,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,m_max_planned_date_end);
			aplString2Date(planned_date_end,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,buf);
			if(m_max_planned_date_end!=_T("") && buf!=_T("") && m_max_planned_date_end>buf)
			{
				aplString2Date(m_max_planned_date_end,dt);
				buf1=dt.Format(_T("%d.%m.%Y"));
				err_string= APL_T("Плановая дата окончания проекта меньше максимальной плановой даты подпроектов! (");
				err_string+=buf1;
				err_string+=_T(")!");
				if(control_type==APL_T("Ограничивать входящие") || (m_check_dates && control_type==APL_T("По умолчанию")))
				{
					AfxMessageBox(err_string);
						return false;
				}
				else if(control_type==APL_NO_T("Определять по входящим"))
				{
					planned_date_end=m_max_planned_date_end;
				}
				else
				{
					err_string+=APL_T("\nПродолжить?");
					if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
						return false;
				}
			}

			aplString2Date(m_min_actual_date_begin,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,m_min_actual_date_begin);
			aplString2Date(actual_date_begin,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,buf);
			if(m_min_actual_date_begin!=_T("") && buf!=_T("") && m_min_actual_date_begin<buf)
			{
				aplString2Date(m_min_actual_date_begin,dt);
				buf1=dt.Format(_T("%d.%m.%Y"));
				err_string= APL_T("Фактическая дата начала проекта больше минимальной фактической даты подпроектов! (");
				err_string+=buf1;
				err_string+=_T(")!");
				if(control_type==APL_T("Ограничивать входящие") || (m_check_dates && control_type==APL_T("По умолчанию")))
				{
					AfxMessageBox(err_string);
						return false;
				}
				else if(control_type==APL_NO_T("Определять по входящим"))
				{
					actual_date_begin=m_min_actual_date_begin;
				}
				else
				{
					err_string+=APL_T("\nПродолжить?");
					if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
						return false;
				}
			}
			aplString2Date(m_max_actual_date_end,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,m_max_actual_date_end);
			aplString2Date(actual_date_end,dt);
			dt.SetDateTime(dt.GetYear(),dt.GetMonth(),dt.GetDay(),
				0,0,0);
			aplDate2String(dt,buf);
			if(m_max_actual_date_end!=_T("") && buf!=_T("") && m_max_actual_date_end>buf)
			{
				aplString2Date(m_max_actual_date_end,dt);
				buf1=dt.Format(_T("%d.%m.%Y"));
				err_string= APL_T("Фактическая дата окончания проекта меньше максимальной фактической даты подпроектов! (");
				err_string+=buf1;
				err_string+=_T(")!");
				if(control_type==APL_T("Ограничивать входящие") || (m_check_dates && control_type==APL_T("По умолчанию")))
				{
					AfxMessageBox(err_string);
						return false;
				}
				else if(control_type==APL_NO_T("Определять по входящим"))
				{
					actual_date_end=m_max_actual_date_end;
				}
				else
				{
					err_string+=APL_T("\nПродолжить?");
					if(AfxMessageBox(err_string,MB_YESNO|MB_ICONQUESTION)==IDNO) 
						return false;
				}
			}
		}
	}*/

	if(!cur_project) 
	{
		//Создание нового проекта
		m_project=m_project_mgr->m_data->CreateInstance(m_project_mgr->e_project);
		if(!m_project) return false;
		if(m_parent) m_project_mgr->m_data->PutAttr(m_project,m_project_mgr->a_project_parent,m_parent);
		CaplInstance *cur_person=m_project_mgr->GetCurrentPerson();
		if(cur_person) m_project_mgr->m_data->PutAttr(m_project,m_project_mgr->a_project_owner,cur_person);
		cur_project=m_project;
	}
	if(old_id!=id) 
	{
		if(ver)	m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_id,id);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_id,id);
	}
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_name,buf);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_name,buf);
	m_name_ctrl.GetWindowText(buf1);
	if(buf!=buf1) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_name,buf1);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_name,buf1);
	}

	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_number,buf);
	m_number_ctrl.GetWindowText(buf1);
	if(buf!=buf1) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_number,buf1);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_number,buf1);
	}
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_descr,buf);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_descr,buf);
	m_descr_ctrl.GetWindowText(buf1);
	if(buf!=buf1) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_descr,buf1);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_descr,buf1);
	}
	//заказчик
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_customer,inst);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_customer,inst);
	if(inst!=m_customer) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_customer,m_customer);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_customer,m_customer);
	}
	
	//отв.исполнитель
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_kurator,inst);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_kurator,inst);
	if(inst!=m_kurator) 
	{
		if(ver)m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_kurator,m_kurator);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_kurator,m_kurator);
	}
	//исполнители
	CaplAggr aggr;
	aplExtent ext;
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_executors,ext);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_executors,ext);
	if(isExtentChanged(m_executors,ext))
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_executors,m_executors);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_executors,m_executors);
	}

	//созаказчики
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_co_customers,ext);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_co_customers,ext);
	if(isExtentChanged(m_co_customers,ext))
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_co_customers,m_co_customers);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_co_customers,m_co_customers);
	}

	//соисполнители
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_co_executors,ext);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_co_executors,ext);
	if(isExtentChanged(m_co_executors,ext))
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_co_executors,m_co_executors);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_co_executors,m_co_executors);
	}



	//даты
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_begin,buf);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_planned_begin,buf);
	if(planned_date_begin!=buf)
	{
		if(ver)m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_begin,planned_date_begin);	
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_date_planned_begin,planned_date_begin);	
	}

	if(ver)m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_end,buf);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_planned_end,buf);
	if(planned_date_end!=buf) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_end,planned_date_end);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_date_planned_end,planned_date_end);
	}

	double planned_dlit_db;
	if(ver)m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_duration,planned_dlit_db);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_planned_duration,planned_dlit_db);
	if(planned_dlit!=planned_dlit_db) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_date_planned_duration,planned_dlit);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_date_planned_duration,planned_dlit);
	}

	int date_set_mask_db;
	if(ver)m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_date_set_mask,date_set_mask_db);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_set_mask,date_set_mask_db);
	if(date_set_mask!=date_set_mask_db) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_date_set_mask,date_set_mask);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_date_set_mask,date_set_mask);
	}

	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_actual_begin,buf);
	if(actual_date_begin!=buf) m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_date_actual_begin,actual_date_begin);

	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_actual_end,buf);
	if(actual_date_end!=buf) m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_date_actual_end,actual_date_end);

	//трудоемкость
	CaplInstance *labor=0;
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_labor_useness,labor);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_labor_useness,labor);
	if(!labor)
	{
		labor=m_project_mgr->m_data->CreateInstance(m_project_mgr->e_labor_useness_value);
		if(labor) 
		{
			if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_labor_useness,labor);
			else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_labor_useness,labor);
		}
	}
	if(labor)
	{
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_value,num);
		if(num!=labor_value) m_project_mgr->m_data->PutAttr(labor,m_project_mgr->a_labor_value,labor_value);
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_unit,inst);
		if(inst!=m_labor_unit) m_project_mgr->m_data->PutAttr(labor,m_project_mgr->a_labor_unit,m_labor_unit);
	}
	//фактическая трудоемкость
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_labor_useness_actual,labor);
	if(!labor)
	{
		labor=m_project_mgr->m_data->CreateInstance(m_project_mgr->e_labor_useness_value);
		if(labor) m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_labor_useness_actual,labor);
	}
	bool b_labor_changed=false;//необходимость пересчета трудоемкости родителей проекта
	if(labor)
	{
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_value,num);
		if(num!=actual_labor_value) 
		{
			m_project_mgr->m_data->PutAttr(labor,m_project_mgr->a_labor_value,actual_labor_value);
			b_labor_changed=true;
		}
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_unit,inst);
		//if(inst!=m_labor_unit_actual) m_project_mgr->m_data->PutAttr(labor,m_project_mgr->a_labor_unit,m_labor_unit_actual);
	}
	//трудоемкость единицы
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_labor_of_item,labor);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_labor_of_item,labor);
	if(!labor)
	{
		labor=m_project_mgr->m_data->CreateInstance(m_project_mgr->e_labor_useness_value);
		if(labor) 
		{
			if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_labor_of_item,labor);
			else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_labor_of_item,labor);
		}
	}
	if(labor)
	{
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_value,num);
		if(num!=labor_of_item) 	m_project_mgr->m_data->PutAttr(labor,m_project_mgr->a_labor_value,labor_of_item);
		m_project_mgr->m_data->GetAttr(labor,m_project_mgr->a_labor_unit,inst);
		if(inst!=m_labor_of_item_unit) m_project_mgr->m_data->PutAttr(labor,m_project_mgr->a_labor_unit,m_labor_of_item_unit);
	}
	//объем продукции плановый
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_prd_amount_planned,num);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_prd_amount_planned,num);
	if(num!=prd_amount_planned)
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_prd_amount_planned,prd_amount_planned);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_prd_amount_planned,prd_amount_planned);
		b_labor_changed=true;
	}
	//объем продукции фактический 
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_prd_amount_actual,num);
	if(num!=prd_amount_actual)
	{
		m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_prd_amount_actual,prd_amount_actual);
	}
	CString labor_useness_actual_date_s0;
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_labor_useness_actual_date,labor_useness_actual_date_s0);
	if(labor_useness_actual_date_s0 != labor_useness_actual_date_s)
	{
		m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_labor_useness_actual_date,labor_useness_actual_date_s);
	}

	// ед. изм. объема

	CaplInstance *unit=0, *old_unit;
	int amount_unit_pos=m_prd_amount_unit_ctrl.GetCurSel();
	if(amount_unit_pos>=0) unit=(CaplInstance*)m_prd_amount_unit_ctrl.GetItemData(amount_unit_pos);
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_prd_amount_unit,old_unit);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_prd_amount_unit,old_unit);
	if(unit!=old_unit)
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_prd_amount_unit,unit);
		else  m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_prd_amount_unit,unit);
	}

	//флаг расчета по колич.параметрам
	bool calc_by_amount=false,calc_by_amount_old;
	if(m_calc_by_amount_ctrl.GetCheck()==1) calc_by_amount=true;
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_calc_by_amount,calc_by_amount_old);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_calc_by_amount,calc_by_amount_old);
	if(calc_by_amount!=calc_by_amount_old)
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_calc_by_amount,calc_by_amount);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_calc_by_amount,calc_by_amount);
	}
	//процент выполнения

	// 20.03.2023  Убрано использование a_project_adm_ver_persentage  чтобы не было путаницы
	//if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_persentage,num);
	//else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_persentage,num);
	//if(num!=persentage) 
	//{
	//	if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_persentage,persentage);
	//	else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_persentage,persentage);
	//}

	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_persentage,num);
	if(num!=persentage) m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_persentage,persentage);
	
	//состояние 
	if(persentage>=100 && m_auto_complete)
	{
		m_state_ctrl.SelectString(1,APL_T("завершен"));
		m_cur_state=APL_T("завершен");
	}
	m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_state,buf);
	if(buf!=m_cur_state) 
	{
		m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_state,m_cur_state);
		if(m_cur_state==APL_T("завершен") && m_auto_complete_parent)
		{
			//установка статусов родителей
			if(parent) m_project_mgr->UpdateProjectState(parent);
		}
	}



	//тип
	CaplInstance *old_type=0,*new_type=0;
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_type,old_type);
	else m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_type,old_type);
	i=m_project_type_ctrl.GetCurSel();
	if(i>=0)new_type=(CaplInstance*)m_project_type_ctrl.GetItemData(i);
	if(new_type!=old_type) 
	{
		if(ver) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_type,new_type);
		else m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_type,new_type);
	}
	//пересчет при необходимости трудоемкости и % выполнения родителей проекта
	if(b_labor_changed)
	{
		if(parent) m_project_mgr->RecalcProjectLabor(parent);
	}
	//if(b_need_recalc_parent_dates) 
	m_project_mgr->RecalcParentDates(cur_project);
	if(ver)
	{
		m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_control_type,buf);
		if(buf!=control_type) m_project_mgr->m_data->PutAttr(ver,m_project_mgr->a_project_adm_ver_control_type,control_type);
	}
	else
	{
		m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_control_type,buf);
		if(buf!=control_type) m_project_mgr->m_data->PutAttr(cur_project,m_project_mgr->a_project_control_type,control_type);
	}

	m_api->SaveChanges();

	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Проекты\\Типы проектов для автоматического перевода 'в работу'"),buf,0);
	if(buf!=_T(""))
	{
		CString sState;
		m_project_mgr->m_data->GetAttr(cur_project, m_project_mgr->a_project_state, sState);
		if(sState==_T("") || sState==_T("планирование"))
		{
			CString sType;
			CaplInstance *type;
			m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_type,type);
			if(0!=type) m_project_mgr->m_data->GetAttr(type,m_project_mgr->a_project_type_name, sType);
			if(sType!=_T(""))
			{
				buf.MakeLower(); buf.Insert(0,_T('|')); buf+=_T('|');
				sType.MakeLower(); sType.Insert(0,_T('|')); sType+=_T('|');
				if(buf.Find(sType)>=0)
				{
					// Проверяеместь ли фактические данные
					bool isFact=false; // Есть ли фактические данные
					m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_actual_begin,buf);
					if(buf!=_T("")) isFact=true;
					m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_date_actual_end,buf);
					if(buf!=_T("")) isFact=true;
					double persentage;
					m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_persentage,persentage);
					if(persentage!=0) isFact=true;

					CaplInstance *actual_labor;
					m_project_mgr->m_data->GetAttr(cur_project, m_project_mgr->a_project_labor_useness_actual, actual_labor);
					if(0!=actual_labor)
					{
						double value;
						m_project_mgr->m_data->GetAttr(actual_labor, m_project_mgr->a_labor_value, value);
						if(value!=0) isFact=true;
					}

					if(isFact)
					{
						// Устанавливаем "в работе"  рекурсивно вверх
						CString sState;
						CaplInstance *prj=cur_project;
						while(0!=prj)
						{
							m_project_mgr->m_data->GetAttr(prj, m_project_mgr->a_project_state, sState);
							if(sState==_T("") || sState==_T("планирование"))
							{
								m_project_mgr->m_data->PutAttr(prj, m_project_mgr->a_project_state, APL_T("в работе"));
							}
							m_project_mgr->m_data->GetAttr(prj,m_project_mgr->a_project_parent,prj);
						}
						m_api->SaveChanges();
					}
				}
			}
		}
	}
	return true;
}

void CProjectDlg::OnOK() 
{
	bool bNeedSave=true;
	if(m_auto_end_edit_ctrl.IsWindowVisible())
	{
		if(1==m_auto_end_edit_ctrl.GetCheck())
		{
			OnCheckIn();
			if(m_auto_end_edit_ctrl.IsWindowVisible()) return; // Что-то пошло не так
			bNeedSave=false;
		}
	}

	if(bNeedSave)
	{
		if(!SaveChanges()) return;
	}

	CaplResizableDialog::OnOK();
}

void CProjectDlg::OnSelectLaborUnit() 
{
	CaplInstance *new_unit=m_project_mgr->m_api->m_charact_mgr.SelectUnit(m_labor_unit);
	if(new_unit) 
	{
		if(!m_project_mgr->m_api->m_data.IsKindOf(new_unit,m_project_mgr->m_api->m_charact_mgr.e_apl_step_unit))
		{
			AfxMessageBox(APL_T("Единица измерения должна быть количественная!"));
			return;
		}
		m_labor_unit=new_unit;
		UpdateLaborUnitCtrl();
	}
	
}

void CProjectDlg::OnBnClickedSelectCocustomers()
{
	if(m_project_mgr->m_api->m_appr_mgr.SelectPersonsOrganizations
		(APL_MODE_SELECT_ORG|APL_MODE_SELECT_PERSON, m_co_customers, true, false, APL_T("Выбор исполнителей проекта"), APL_T("Выбор рабочих групп или сотрудников")))
	{
		UpdateCoCutomersCtrl();
	}
}


void CProjectDlg::OnSelectExecutors() 
{
	if(m_project_mgr->m_api->m_appr_mgr.SelectPersonsOrganizations
		(APL_MODE_SELECT_ORG|APL_MODE_SELECT_PERSON, m_executors, true, false, APL_T("Выбор исполнителей проекта"), APL_T("Выбор рабочих групп или сотрудников")))
	{
		UpdateExecutorsCtrl();
	}
}


void CProjectDlg::OnBnClickedSelectCoexecutors()
{
	if(m_project_mgr->m_api->m_appr_mgr.SelectPersonsOrganizations
		(APL_MODE_SELECT_ORG|APL_MODE_SELECT_PERSON, m_co_executors, true, false, APL_T("Выбор соисполнителей проекта"), APL_T("Выбор рабочих групп или сотрудников")))
	{
		UpdateCoExecutorsCtrl();
	}
}

void CProjectDlg::UpdateExecutorsCtrl()
{
	CString buf=_T(""),executors=_T("");
	for(int i=0;i<m_executors.GetSize();i++)
	{
		//if(m_project_mgr->m_api->m_data.IsKindOf(m_executors[i], m_project_mgr->m_api->m_appr_mgr.e_person)) m_project_mgr->m_api->m_appr_mgr.GetPersonName(m_executors[i],buf);
		//else if(m_project_mgr->m_api->m_data.IsKindOf(m_executors[i], m_project_mgr->m_api->m_appr_mgr.e_org)) m_project_mgr->m_api->m_data.GetAttr(m_executors[i],m_project_mgr->m_api->m_appr_mgr.a_org_name,buf); 
		m_project_mgr->GetIdPersOrOrg(m_executors[i],buf);
		if(buf!=_T(""))
		{
			executors+=buf; 
			if(i!=(m_executors.Size-1)) executors+=_T(", "); 
		}
	}
	m_executors_ctrl.SetWindowText(executors);
}


void CProjectDlg::UpdateCoCutomersCtrl()
{
	CString buf=_T(""),cocustomers=_T("");
	for(int i=0;i<m_co_customers.GetSize();i++)
	{
		//if(m_project_mgr->m_api->m_data.IsKindOf(m_executors[i], m_project_mgr->m_api->m_appr_mgr.e_person)) m_project_mgr->m_api->m_appr_mgr.GetPersonName(m_executors[i],buf);
		//else if(m_project_mgr->m_api->m_data.IsKindOf(m_executors[i], m_project_mgr->m_api->m_appr_mgr.e_org)) m_project_mgr->m_api->m_data.GetAttr(m_executors[i],m_project_mgr->m_api->m_appr_mgr.a_org_name,buf); 
		m_project_mgr->GetIdPersOrOrg(m_co_customers[i],buf);
		if(buf!=_T(""))
		{
			cocustomers+=buf; 
			if(i!=(m_co_customers.Size-1)) cocustomers+=_T(", "); 
		}
	}
	m_cosustomers_ctrl.SetWindowText(cocustomers);
}

void CProjectDlg::UpdateCoExecutorsCtrl()
{
	CString buf=_T(""),executors=_T("");
	for(int i=0;i<m_co_executors.GetSize();i++)
	{
		//if(m_project_mgr->m_api->m_data.IsKindOf(m_co_executors[i], m_project_mgr->m_api->m_appr_mgr.e_person)) m_project_mgr->m_api->m_appr_mgr.GetPersonName(m_co_executors[i],buf);
		//else if(m_project_mgr->m_api->m_data.IsKindOf(m_co_executors[i], m_project_mgr->m_api->m_appr_mgr.e_org)) m_project_mgr->m_api->m_data.GetAttr(m_co_executors[i],m_project_mgr->m_api->m_appr_mgr.a_org_name,buf); 
		m_project_mgr->GetIdPersOrOrg(m_co_executors[i],buf);
		if(buf!=_T(""))
		{
			executors+=buf; 
			if(i!=(m_co_executors.Size-1)) executors+=_T(", "); 
		}
	}
	m_coexecutors_ctrl.SetWindowText(executors);
}

void CProjectDlg::UpdateKuratorCtrl()
{
	CString buf=_T("");
	/*if(m_kurator)
	{
		if(m_project_mgr->m_api->m_data.IsKindOf(m_kurator, m_project_mgr->m_api->m_appr_mgr.e_person)) m_project_mgr->m_api->m_appr_mgr.GetPersonName(m_kurator,buf);
		else if(m_project_mgr->m_api->m_data.IsKindOf(m_kurator, m_project_mgr->m_api->m_appr_mgr.e_org)) m_project_mgr->m_api->m_data.GetAttr(m_kurator,m_project_mgr->m_api->m_appr_mgr.a_org_name,buf); 
	}*/
	m_project_mgr->GetIdPersOrOrg(m_kurator,buf);
	m_kurator_ctrl.SetWindowText(buf);
}

void CProjectDlg::UpdateCustomerCtrl()
{
	CString buf=_T("");
	/*if(m_customer) 
	{
		if(m_project_mgr->m_api->m_data.IsKindOf(m_customer, m_project_mgr->m_api->m_appr_mgr.e_person)) m_project_mgr->m_api->m_appr_mgr.GetPersonName(m_customer,buf);
		else if(m_project_mgr->m_api->m_data.IsKindOf(m_customer, m_project_mgr->m_api->m_appr_mgr.e_org)) m_project_mgr->m_api->m_data.GetAttr(m_customer,m_project_mgr->m_api->m_appr_mgr.a_org_name,buf); 
	}*/
	m_project_mgr->GetIdPersOrOrg(m_customer,buf);
	m_customer_ctrl.SetWindowText(buf);
}

void CProjectDlg::UpdateLaborUnitCtrl()
{
	CString buf=_T("");
	if(m_labor_unit) m_project_mgr->m_api->m_charact_mgr.GetUnitName(m_labor_unit,buf);
	m_labor_unit_ctrl.SetWindowText(buf);
}

void CProjectDlg::OnCheckFactBegin() 
{
	// TODO: Add your control notification handler code here
	int check=m_check_fact_begin_ctrl.GetCheck();
	if(check==1)
	{
		m_date_begin_fact_ctrl.EnableWindow(TRUE);
		m_time_begin_fact_ctrl.EnableWindow(TRUE);
	}
	else 
	{
		m_date_begin_fact_ctrl.EnableWindow(FALSE);
		m_time_begin_fact_ctrl.EnableWindow(FALSE);
	}
	RecalcActualDlit();
}

void CProjectDlg::OnCheckFactEnd() 
{
	// TODO: Add your control notification handler code here
	int check=m_check_fact_end_ctrl.GetCheck();
	if(check==1)
	{
		m_date_end_fact_ctrl.EnableWindow(TRUE);
		m_time_end_fact_ctrl.EnableWindow(TRUE);
	}
	else
	{
		m_date_end_fact_ctrl.EnableWindow(FALSE);
		m_time_end_fact_ctrl.EnableWindow(FALSE);
	}
	RecalcActualDlit();
}

void CProjectDlg::OnSelectKurator() 
{
	aplExtent ext;
	//if(m_kurator) ext.Add(m_kurator);
	CaplInstance *inst=m_project_mgr->m_api->m_appr_mgr.SelectPersonOrOrganization(APL_MODE_SELECT_ORG|APL_MODE_SELECT_PERSON, ext, APL_T("Выбор куратора проекта"), APL_T("Выбор рабочей группы или сотрудника"));
	if(inst)
	{
		m_kurator=inst;
		UpdateKuratorCtrl();
	}
}

void CProjectDlg::OnBnClickedDeleteKurator()
{
	if(!m_kurator) return;

	if(IDNO==AfxMessageBox(APL_T("Вы действительно хотите удалить ответственного исполнителя?"), MB_YESNO)) return;
	m_kurator= NULL;
	UpdateKuratorCtrl();	
}

void CProjectDlg::OnSelchangeState() 
{
	m_state_ctrl.GetWindowText(m_cur_state);
}



void CProjectDlg::OnCheckOut() 
{
	// TODO: Add your control notification handler code here
	bool recursive=false;
	if(m_project_mgr->CheckOutWithRequest(m_project,recursive))
	{
		m_project_mgr->m_api->m_data.GetAttr(m_project,m_project_mgr->a_project_locker_adm_version,m_project);
		if(m_project)
		{
			m_check_out_ctrl.ShowWindow(SW_HIDE);
			m_check_in_ctrl.ShowWindow(SW_SHOW);
			m_undo_check_out_ctrl.ShowWindow(SW_SHOW);
			m_auto_end_edit_ctrl.ShowWindow(SW_SHOW);
			m_read_only_ver=false;
			SetWindowText(APL_T("Версия проекта"));
			SetReadOnlyItems();

			m_bNeedUndoCheckout=true;
		}
	}
}

void CProjectDlg::OnCheckIn() 
{
	// TODO: Add your control notification handler code here
	CaplInstance *project_ver_project=0;
	m_project_mgr->m_api->m_data.GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,project_ver_project);
	if(project_ver_project)
	{
		if(!SaveChanges()) return;
		bool recursive=false;
		if(m_project_mgr->CheckInWithRequest(project_ver_project,recursive))
		{
			m_check_out_ctrl.ShowWindow(SW_SHOW);
			m_check_in_ctrl.ShowWindow(SW_HIDE);
			m_undo_check_out_ctrl.ShowWindow(SW_HIDE);
			m_auto_end_edit_ctrl.ShowWindow(SW_HIDE);
			m_read_only_ver=true;
			SetWindowText(APL_T("Проект"));
			SetReadOnlyItems();
			m_project=project_ver_project;
		}
	}	
}

void CProjectDlg::OnUndoCheckOut() 
{
	// TODO: Add your control notification handler code here
	CaplInstance *project_ver_project=0;
	m_project_mgr->m_api->m_data.GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,project_ver_project);
	if(project_ver_project)
	{
		//if(!SaveChanges()) return;
		bool recursive=false;
		if(m_project_mgr->UndoCheckOutWithRequest(project_ver_project,recursive))
		{
			m_check_out_ctrl.ShowWindow(SW_SHOW);
			m_check_in_ctrl.ShowWindow(SW_HIDE);
			m_undo_check_out_ctrl.ShowWindow(SW_HIDE);
			m_auto_end_edit_ctrl.ShowWindow(SW_HIDE);
			m_read_only_ver=true;
			SetWindowText(APL_T("Проект"));
			m_project=project_ver_project;
			SetFromInst();
			SetReadOnlyItems();
		}
	}
	
}

void CProjectDlg::OnSelectCustomer() 
{
	// TODO: Add your control notification handler code here
	aplExtent ext;
	CaplInstance *inst=m_project_mgr->m_api->m_appr_mgr.SelectPersonOrOrganization(APL_MODE_SELECT_ORG|APL_MODE_SELECT_PERSON, ext, APL_T("Выбор заказчика проекта"), APL_T("Выбор рабочей группы или сотрудника"));
	if(inst)
	{
		m_customer=inst;
		UpdateCustomerCtrl();
	}
}


void CProjectDlg::OnBnClickedDeleteCustomer()
{
	if(!m_customer) return;

	if(IDNO==AfxMessageBox(APL_T("Вы действительно хотите удалить заказчика?"), MB_YESNO)) return;
	m_customer= NULL;
	UpdateCustomerCtrl();
}

void CProjectDlg::OnCalcByAmount() 
{
	int check=m_calc_by_amount_ctrl.GetCheck();
	if(check==1)
	{
		/*
		m_select_labor_of_item_unit_btn.EnableWindow(TRUE);
		m_prd_amount_planned_ctrl.SetReadOnly(false);
		m_prd_amount_actual_ctrl.SetReadOnly(false);
		m_labor_of_item_ctrl.EnableWindow(TRUE);
		*/
		m_labor_value_ctrl.SetReadOnly(TRUE);
		m_select_labunit_btn.EnableWindow(FALSE);
		GetDlgItem(IDC_DEL_LABOR_UNIT)->EnableWindow(FALSE);

		m_actual_labor_ctrl.SetReadOnly(TRUE);
		//m_select_actual_labor_unit_btn.EnableWindow(FALSE);
		//m_actual_labor_date_ctrl.EnableWindow(FALSE);

		//m_persentage_ctrl.EnableWindow(FALSE);
		if(RecalcLaborPlanned())
			if(RecalcLaborActual())
			{
				m_labor_unit=m_labor_of_item_unit;
				//m_labor_unit_actual=m_labor_of_item_unit;
				UpdateLaborUnitCtrl();
				//UpdateActualLaborUnitCtrl();
			}
	}
	else if(check==0)
	{
		/*
		m_select_labor_of_item_unit_btn.EnableWindow(FALSE);
		m_prd_amount_planned_ctrl.SetReadOnly(TRUE);
		m_prd_amount_actual_ctrl.SetReadOnly(TRUE);
		m_labor_of_item_ctrl.EnableWindow(FALSE);
		*/
		m_labor_value_ctrl.SetReadOnly(false);
		m_select_labunit_btn.EnableWindow(TRUE);
		GetDlgItem(IDC_DEL_LABOR_UNIT)->EnableWindow(true);

		m_actual_labor_ctrl.SetReadOnly(false);
		//m_select_actual_labor_unit_btn.EnableWindow(TRUE);
		m_actual_labor_date_ctrl.EnableWindow(TRUE);

		//m_persentage_ctrl.EnableWindow(TRUE);
	}
	
}

void CProjectDlg::OnSelectLaborOfItemUnit() 
{
	CaplInstance *new_unit=m_project_mgr->m_api->m_charact_mgr.SelectUnit(m_labor_of_item_unit);
	if(new_unit) 
	{
		if(!m_project_mgr->m_api->m_data.IsKindOf(new_unit,m_project_mgr->m_api->m_charact_mgr.e_apl_step_unit))
		{
			AfxMessageBox(APL_T("Единица измерения должна быть количественная!"));
			return;
		}
		m_labor_of_item_unit=new_unit;
		UpdateLaborOfItemUnitCtrl();
		if(m_calc_by_amount_ctrl.GetCheck()==1)
		{
			m_labor_unit=new_unit;
			//m_labor_unit_actual=new_unit;
			UpdateLaborUnitCtrl();
			//UpdateActualLaborUnitCtrl();
		}
	}
	
}

/*void CProjectDlg::OnSelectActualLaborUnit() 
{
	CaplInstance *new_unit=m_project_mgr->m_api->m_charact_mgr.SelectUnit(m_labor_unit_actual);
	if(new_unit) 
	{
		if(!m_project_mgr->m_api->m_data.IsKindOf(new_unit,m_project_mgr->m_api->m_charact_mgr.e_apl_step_unit))
		{
			AfxMessageBox(APL_T("Единица измерения должна быть количественная!"));
			return;
		}

		//m_labor_unit_actual=new_unit;
		//UpdateActualLaborUnitCtrl();
	}
	
}*/

void CProjectDlg::UpdateLaborOfItemUnitCtrl()
{
	CString buf=_T("");
	m_project_mgr->m_api->m_charact_mgr.GetUnitName(m_labor_of_item_unit,buf);
	m_labor_of_item_unit_ctrl.SetWindowText(buf);
}

/*void CProjectDlg::UpdateActualLaborUnitCtrl()
{
	CString buf=_T("");
	if(m_project_mgr->m_api->m_charact_mgr.GetUnitName(m_labor_unit_actual,buf))
	{
		m_actual_labor_unit_ctrl.SetWindowText(buf);
	}
}*/

void CProjectDlg::OnChangePrdAmoutPlanned() 
{
	int check=m_calc_by_amount_ctrl.GetCheck();
	if(check==1)
	{
		if(RecalcLaborPlanned()) RecalcPercentage();	
	}

}

bool CProjectDlg::RecalcLaborPlanned()
{
	//пересчет трудоемкости при изменении трудоемкости на единицу или планового количества 
	CString buf;
	m_prd_amount_planned_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	double prd_amount_planned=__atof(buf);
	m_labor_of_item_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	double labor_of_item=__atof(buf);
	double labor_amount_planned=labor_of_item*prd_amount_planned;
	buf.Format(_T("%g"),labor_amount_planned);
	m_labor_value_ctrl.SetWindowText(buf);
	return true;
}

void CProjectDlg::OnChangeLaborOfItem() 
{
	CString buf;
	double num;
	m_labor_of_item_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	if(buf==_T("") || !IsRealOrEmpty(buf))
	{
		AfxMessageBox(APL_T("Значение трудоемкости на единицу должно быть числом!"));
		m_labor_of_item_ctrl.GetWindowText(buf);
		num=__atof(buf);
		buf.Format(_T("%g"),num);
		m_labor_of_item_ctrl.SetWindowText(buf);
		m_labor_of_item_ctrl.SetFocus();
		return;
	}
	int check=m_calc_by_amount_ctrl.GetCheck();
	if(check==1)
	{
		if(RecalcLaborPlanned())	
			RecalcLaborActual(); 
	}
}

bool CProjectDlg::RecalcLaborActual()
{
	//пересчет трудоемкости при изменении трудоемкости на единицу или фактического количества 
	CString buf;
	m_prd_amount_actual_ctrl.GetWindowText(buf);
	buf.TrimLeft(); buf.TrimRight();
	double prd_amount_actual=__atof(buf);
	m_labor_of_item_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	double labor_of_item=__atof(buf);
	double labor_amount_actual=labor_of_item*prd_amount_actual;
	buf.Format(_T("%g"),labor_amount_actual);
	m_actual_labor_ctrl.SetWindowText(buf);
	return true;
}



bool CProjectDlg::RecalcPercentage()
{
	CString buf;
	double persentage=0;
	int check=m_calc_by_amount_ctrl.GetCheck();
	if(check==1 && !m_bHaveChildren)//проект не имеет входящих, а трудоемкость расчитывается по колич. продукции
	{
		m_prd_amount_planned_ctrl.GetWindowText(buf);
		buf.TrimLeft(); buf.TrimRight();
		double amount_planned=__atof(buf);
		m_prd_amount_actual_ctrl.GetWindowText(buf);
		buf.TrimLeft();buf.TrimRight();
		double amount_actual=__atof(buf);
		if(amount_planned) persentage=(amount_actual/amount_planned)*100;
	}
	else	//в остальных случаях расчитваем по плановой и "погашенной" трудоемкости
	{
		m_labor_value_ctrl.GetWindowText(buf);
		buf.TrimLeft(); buf.TrimRight();
		//if(m_labor_unit!=m_labor_unit_actual) return false;
		double labor_planned=__atof(buf);
		m_actual_labor_ctrl.GetWindowText(buf);
		buf.TrimLeft();buf.TrimRight();
		double labor_actual=__atof(buf);
		if(labor_planned) persentage=(labor_actual/labor_planned)*100;
	}
	buf.Format(_T("%g"),persentage);
	m_persentage_ctrl.SetWindowText(buf);

	/*  Здесь этому не место.  Есть обработка в SaveChanges
	if(persentage>=100 && m_auto_complete)
	{
		int sel_num=m_state_ctrl.SelectString(1,APL_T("завершен"));
		if(sel_num!=LB_ERR) m_cur_state=APL_T("завершен");
	}
	*/
	return true;
}

void CProjectDlg::OnChangePrdAmoutActual() 
{
	double num;
	CString buf;
	m_prd_amount_actual_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	if(buf==_T("") || !IsRealOrEmpty(buf))
	{
		AfxMessageBox(APL_T("Значение фактического объема выпуска должно быть числом!"));
		m_prd_amount_actual_ctrl.GetWindowText(buf);
		num=__atof(buf);
		buf.Format(_T("%g"),num);
		m_prd_amount_actual_ctrl.SetWindowText(buf);
		m_prd_amount_actual_ctrl.SetFocus();
		return;
	}
	int check=m_calc_by_amount_ctrl.GetCheck();
	if(check==1)
	{
		if(RecalcLaborActual()) RecalcPercentage();	
	}
}

void CProjectDlg::OnChangeLabor() 
{
	CString buf;
	double num;
	m_labor_value_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	if(buf==_T("") || !IsRealOrEmpty(buf))
	{
		AfxMessageBox(APL_T("Значение трудоемкости должно быть числом!"));
		m_labor_value_ctrl.GetWindowText(buf);
		num=__atof(buf);
		buf.Format(_T("%g"),num);
		m_labor_value_ctrl.SetWindowText(buf);
		m_labor_value_ctrl.SetFocus();
		return;
	}
	RecalcPercentage();	
}

void CProjectDlg::OnChangeActualLabor() 
{
	CString buf;
	double num;
	m_actual_labor_ctrl.GetWindowText(buf);
	buf.TrimLeft();buf.TrimRight();
	if(buf==_T("") || !IsRealOrEmpty(buf))
	{
		AfxMessageBox(APL_T("Значение фактической трудоемкости должно быть числом!"));
		m_actual_labor_ctrl.GetWindowText(buf);
		num=__atof(buf);
		buf.Format(_T("%g"),num);
		m_actual_labor_ctrl.SetWindowText(buf);
		m_actual_labor_ctrl.SetFocus();
		return;
	}

	COleDateTime odt1;
	m_actual_labor_date_ctrl.GetTime(odt1);
	odt1.SetDateTime(odt1.GetYear(),odt1.GetMonth(),odt1.GetDay(),23,59,59);

	if(odt1.GetYear()<2000)
	{
		odt1=COleDateTime::GetCurrentTime();
		odt1.SetDateTime(odt1.GetYear(),odt1.GetMonth(),odt1.GetDay(),23,59,59);
		m_actual_labor_date_ctrl.SetTime(odt1);
	}
	RecalcPercentage();	
}

void CProjectDlg::CalcMaxMinSubDates()
{
	if(!m_project) return;
	aplExtent sub_projects;
	CaplInstance *cur_project=m_project,*ver=0;
	if(m_project)
	{
		if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
		{
			m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);
			ver=m_project;
		}
		else 
		{
			ver=m_project_mgr->CheckMyLock(m_project,false);
		}
	}
	CString buf,buf1;
	if(ver) m_project_mgr->m_data->GetAttr(ver,m_project_mgr->a_project_adm_ver_content,sub_projects);
	else if(cur_project) m_project_mgr->m_data->GetAttr(cur_project,m_project_mgr->a_project_content,sub_projects);
	for(int i=0;i<sub_projects.GetSize();i++)
	{
		if(!sub_projects[i]) continue;
		if(sub_projects[i]->GetAccessmode()>aplRO) continue;
		if(sub_projects[i]->GetType()==0) continue;
		m_bHaveChildren=true;
		CaplInstance *sub_lock=m_project_mgr->CheckMyLock(sub_projects[i],false);
		if(sub_lock)
		{
			m_project_mgr->m_data->GetAttr(sub_lock,m_project_mgr->a_project_adm_ver_date_planned_begin,buf);
			m_project_mgr->m_data->GetAttr(sub_lock,m_project_mgr->a_project_adm_ver_date_planned_end,buf1);
		}
		else
		{
			m_project_mgr->m_data->GetAttr(sub_projects[i],m_project_mgr->a_project_date_planned_begin,buf);
			m_project_mgr->m_data->GetAttr(sub_projects[i],m_project_mgr->a_project_date_planned_end,buf1);
		}
		if((buf!=_T("") && buf<m_min_planned_date_begin) || m_min_planned_date_begin==_T("")) m_min_planned_date_begin=buf;
		if(buf1>m_max_planned_date_end) m_max_planned_date_end=buf1;
		m_project_mgr->m_data->GetAttr(sub_projects[i],m_project_mgr->a_project_date_actual_begin,buf1);
		if((buf1!=_T("") && buf1<m_min_actual_date_begin) || m_min_actual_date_begin==_T("")) m_min_actual_date_begin=buf1;
		m_project_mgr->m_data->GetAttr(sub_projects[i],m_project_mgr->a_project_date_actual_end,buf1);
		if(buf1>m_max_actual_date_end) m_max_actual_date_end=buf1;
	}
}

void CProjectDlg::OnSelchangeDateControl() // изменение тиа контроля сроков
{
	CString control_type;
	m_date_control_ctrl.GetWindowText(control_type);
	if(m_bHaveChildren && control_type==APL_NO_T("Определять по входящим"))
	{
		COleDateTime dt,cur_dt;
		cur_dt=COleDateTime::GetCurrentTime();
		int check=0;
		if(m_min_actual_date_begin!=_T(""))
		{
			aplString2Date(m_min_actual_date_begin,dt);
			check=1;
		}
		else
		{
			check=0;
			dt=cur_dt;
		}
		m_check_fact_begin_ctrl.SetCheck(check);
		m_date_begin_fact_ctrl.SetTime(dt);
		m_time_begin_fact_ctrl.SetTime(dt);
		if(m_max_actual_date_end!=_T(""))
		{
			aplString2Date(m_max_actual_date_end,dt);
			check=1;
		}
		else
		{
			check=0;
			dt=cur_dt;
		}
		m_check_fact_end_ctrl.SetCheck(check);
		m_date_end_fact_ctrl.SetTime(dt);
		m_time_end_fact_ctrl.SetTime(dt);
		if(m_min_planned_date_begin!=_T(""))
		{
			aplString2Date(m_min_planned_date_begin,dt);
			check=1;
		}
		else
		{
			check=0;
			dt=cur_dt;
		}
		m_check_planned_begin_ctrl.SetCheck(check);
		m_date_begin_planned_ctrl.SetTime(dt);
		m_time_begin_planned_ctrl.SetTime(dt);
		if(m_max_planned_date_end!=_T(""))
		{
			aplString2Date(m_max_planned_date_end,dt);
			check=1;
		}
		else
		{
			check=0;
			dt=cur_dt;
		}
		m_check_planned_end_ctrl.SetCheck(check);
		m_date_end_planned_ctrl.SetTime(dt);
		m_time_end_planned_ctrl.SetTime(dt);
		RecalcPlanDate();
		RecalcActualDlit();
	}
	SetReadOnlyItems();
}

void CProjectDlg::RecalcActualDlit()
{
	COleDateTime dt_begin,dt_end;

	int check1=m_check_fact_begin_ctrl.GetCheck();
	int check2=m_check_fact_end_ctrl.GetCheck();

	if(check1==1) m_date_begin_fact_ctrl.GetTime(dt_begin);	
	if(check2==1) m_date_end_fact_ctrl.GetTime(dt_end);	

	if(check1==1 && check2==1)
	{
		/* 16.09.2024  Переделано чтобы было одинаково с плановой длительностью

		dt_begin.SetDateTime(dt_begin.GetYear(),dt_begin.GetMonth(),dt_begin.GetDay(),0,0,0);
		dt_end.SetDateTime(dt_end.GetYear(),dt_end.GetMonth(),dt_end.GetDay(),0,0,0);
		COleDateTimeSpan dt_span=dt_end-dt_begin;
		CString buf;
		long days=dt_span.GetDays()+1;
		if(days<0) days=0;
		buf.Format(_T("%d"),days);
		*/

		COleDateTime dt_s, dt_e, t_time;

		m_time_begin_fact_ctrl.GetTime(t_time);
		dt_s.SetDateTime(dt_begin.GetYear(),dt_begin.GetMonth(),dt_begin.GetDay(),t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());

		m_time_end_fact_ctrl.GetTime(t_time);
		dt_e.SetDateTime(dt_end.GetYear(),dt_end.GetMonth(),dt_end.GetDay(),t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());

		COleDateTimeSpan sec(0,0,0,1);
		COleDateTimeSpan dtspan=sec+dt_e-dt_s;
		double duration=dtspan.GetTotalHours()/24;

		CString buf;
		buf.Format(_T("%.4g"),duration);
		m_dlit_actual_ctrl.SetWindowText(buf);
	}
	else m_dlit_actual_ctrl.SetWindowText(_T("0"));
}

void CProjectDlg::OnChangeDlitPlan() 
{
	if(1!=m_check_planed_duration_set_btn.GetCheck()) return;
	RecalcPlanDate();
}

void CProjectDlg::OnChangeDlitActual() 
{
	/* 16.09.2023  Возможность редактирования вроде как была убрана давно, а эта обработка оставалась
	
	CString buf;
	m_dlit_actual_ctrl.GetWindowText(buf);
	long dlit=_atoi(buf);
	if(0!=dlit)
	{
		COleDateTimeSpan dt_span;
		dt_span.SetDateTimeSpan(dlit-1,0,0,0);
		COleDateTime dt;
		int check=m_check_fact_begin_ctrl.GetCheck();
		if(check==1) 
		{
			m_date_begin_fact_ctrl.GetTime(dt);	
			dt+=dt_span;
			m_date_end_fact_ctrl.SetTime(dt);	
		}
		else
		{
			m_date_end_fact_ctrl.GetTime(dt);	
			dt-=dt_span;
			m_date_begin_fact_ctrl.SetTime(dt);	
		}
	}*/

	
}

void CProjectDlg::OnDatetimechangeDateBeginFact(NMHDR* pNMHDR, LRESULT* pResult) 
{
	*pResult = 0;
	//CMonthCalCtrl* pMonthCalCtrl=m_date_begin_fact_ctrl.GetMonthCalCtrl();
	//if(0!=pMonthCalCtrl) pMonthCalCtrl->CloseWindow();

	if(0!=m_forbinen_future_fact_dates)
	{
		COleDateTime dt;
		m_date_begin_fact_ctrl.GetTime(dt);
		if(dt>COleDateTime::GetCurrentTime())
		{
			m_date_begin_fact_ctrl.SetTime(COleDateTime::GetCurrentTime());

			// При выборе из выпадающего календаря контрол посылает 2 идентичных сообщения
			// Вот так избавляемся от дублирования сообщения
			static DWORD dwPrewTick=0;
			if( (GetTickCount()-dwPrewTick) >100)
			{
				AfxMessageBox(APL_T("Ввод фактической даты будущей датой запрещен настройками!"),MB_OK|MB_ICONSTOP);
			}
			dwPrewTick=GetTickCount();
		}
	}
	RecalcActualDlit();	
}

//**************************************************************************************

void CProjectDlg::OnDatetimechangeDateEndFact(NMHDR* pNMHDR, LRESULT* pResult) 
{
	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	*pResult = 0;
	//CMonthCalCtrl* pMonthCalCtrl=m_date_end_fact_ctrl.GetMonthCalCtrl();
	//if(0!=pMonthCalCtrl) pMonthCalCtrl->CloseWindow();

	//MSG msg;
	//while (::PeekMessage(&msg, m_hWnd, WM_NOTIFY, WM_NOTIFY, PM_REMOVE|PM_NOYIELD));
	//while (::PeekMessage(&msg, m_date_end_fact_ctrl.m_hWnd, 0, -1, PM_REMOVE|PM_NOYIELD));

	if(0!=m_forbinen_future_fact_dates)
	{
		COleDateTime dt;
		m_date_end_fact_ctrl.GetTime(dt);
		if(dt>COleDateTime::GetCurrentTime())
		{
			m_date_end_fact_ctrl.SetTime(COleDateTime::GetCurrentTime());

			// При выборе из выпадающего календаря контрол посылает 2 идентичных сообщения
			// Вот так избавляемся от дублирования сообщения
			static DWORD dwPrewTick=0;
			if( (GetTickCount()-dwPrewTick) >100)
			{
				AfxMessageBox(APL_T("Ввод фактической даты будущей датой запрещен настройками!"),MB_OK|MB_ICONSTOP);
			}
			dwPrewTick=GetTickCount();
		}
	}
	RecalcActualDlit();	
}

void CProjectDlg::OnDtnDatetimechangeTimeEndFact(NMHDR *pNMHDR, LRESULT *pResult)
{
	//LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	RecalcActualDlit();	
	*pResult = 0;
}

void CProjectDlg::OnDtnDatetimechangeTimeBeginFact(NMHDR *pNMHDR, LRESULT *pResult)
{
	//LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	RecalcActualDlit();	
	*pResult = 0;
}



//**************************************************************************************

void CProjectDlg::OnDatetimechangeDateBeginPlanned(NMHDR* pNMHDR, LRESULT* pResult) 
{
	COleDateTime dt_s,d_time,t_time;
	m_date_begin_planned_ctrl.GetTime(d_time);	
	m_time_begin_planned_ctrl.GetTime(t_time);
	dt_s.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());

	if(	m_odt_min_planed.GetStatus()!=COleDateTime::null && dt_s<m_odt_min_planed)
	{
		CMonthCalCtrl *monthCtrl=m_date_begin_planned_ctrl.GetMonthCalCtrl();
		if(0!=monthCtrl) ::SendMessage(monthCtrl->m_hWnd, WM_CLOSE, 0, 0);
		m_date_begin_planned_ctrl.SetTime(m_odt_min_planed);
		m_time_begin_planned_ctrl.SetTime(m_odt_min_planed);
		AfxMessageBox(APL_T("Указанная дата выходит за ограничения родительского проекта!\n\n Установлена минимально возможная дата!"));
	}
	RecalcPlanDate();	
	*pResult = 0;
}

void CProjectDlg::OnDatetimechangeDateEndPlanned(NMHDR* pNMHDR, LRESULT* pResult) 
{
	COleDateTime dt_e,d_time,t_time;
	m_date_end_planned_ctrl.GetTime(d_time);	
	m_time_end_planned_ctrl.GetTime(t_time);
	dt_e.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());

	if(	m_odt_max_planed.GetStatus()!=COleDateTime::null && dt_e>m_odt_max_planed)
	{
		CMonthCalCtrl *monthCtrl=m_date_end_planned_ctrl.GetMonthCalCtrl();
		if(0!=monthCtrl) ::SendMessage(monthCtrl->m_hWnd, WM_CLOSE, 0, 0);
		m_date_end_planned_ctrl.SetTime(m_odt_max_planed);
		m_time_end_planned_ctrl.SetTime(m_odt_max_planed);
		AfxMessageBox(APL_T("Указанная дата выходит за ограничения родительского проекта!\n\n Установлена максимально возможная дата!"));
	}
	RecalcPlanDate();	
	*pResult = 0;
}

void CProjectDlg::OnDtnDatetimechangeTimeBeginPlanned(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	// TODO: Add your control notification handler code here
	RecalcPlanDate();
	*pResult = 0;
}

void CProjectDlg::OnDtnDatetimechangeTimeEndPlanned(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	// TODO: Add your control notification handler code here
	RecalcPlanDate();
	*pResult = 0;
}

void CProjectDlg::OnTransactions() 
{
	if(m_project==NULL)
	{
		if(AfxMessageBox(APL_T("Перед вводом информации о транзакциях необходимо сохранить информацию о проекте. Сделать это сейчас?"), MB_YESNO|MB_ICONQUESTION)==IDYES)
		{
			if(!SaveChanges()) return;

			m_cancel_btn.EnableWindow(FALSE);
		}
	}

	CTransactionListDlg dlg(m_project_mgr, this);
	dlg.m_inst = m_project;
	dlg.DoModal();
}

void CProjectDlg::OnBnClickedDelLaborUnit()
{
	m_labor_unit=0;
	UpdateLaborUnitCtrl();
}
//************************************************************************************************
//************************************************************************************************
//************************************************************************************************
// проверяем что установлены только 2 галочки из 3х
bool CProjectDlg::bIsSet3Check()
{
	int i1=m_check_planned_begin_ctrl.GetCheck();
	int i2=m_check_planned_end_ctrl.GetCheck();
	int i3=m_check_planed_duration_set_btn.GetCheck();

	if((1==i1) && (1==i2) && (1==i3))
	{
		AfxMessageBox(APL_T("Из трех параметров: 'дата начала', 'дата окончания' и 'длительность',\nОдновременно могут быть заданы только два!"),
			MB_OK|MB_ICONSTOP);
		return true;
	}
	return false;
}
bool CProjectDlg::RecalcPlanDate()
{
	CString buf;
	COleDateTime dt_s,dt_e,d_time,t_time;
	int i1=m_check_planned_begin_ctrl.GetCheck();
	int i2=m_check_planned_end_ctrl.GetCheck();
	int i3=m_check_planed_duration_set_btn.GetCheck();

	COleDateTimeSpan sec(0,0,0,1);


	m_date_begin_planned_ctrl.GetTime(d_time);	
	m_time_begin_planned_ctrl.GetTime(t_time);
	dt_s.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());


	m_date_end_planned_ctrl.GetTime(d_time);	
	m_time_end_planned_ctrl.GetTime(t_time);
	dt_e.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());

	m_dlit_plan_ctrl.GetWindowText(buf);
	double dlit=__atof(LPCTSTR(buf));


	if((1==i1) && (1==i2) && (1==i3))
	{
		AfxMessageBox(APL_T("Из трех параметров: 'дата начала', 'дата окончания' и 'длительность',\nОдновременно могут быть заданы только два!\n\n Длительность пересчитана из дат!"),
			MB_OK|MB_ICONSTOP);

		m_check_planed_duration_set_btn.SetCheck(0);
		i3=0;

	}

	if( ((1==i1) && (1==i2))  || ((0==i1) && (0==i2) && (0==i3)) ||  ((1==i1) && (0==i2) && (0==i3)) || ((0==i1) && (1==i2) && (0==i3)))
	{
		//вычисляем длительность
		if(dt_e==dt_s) buf=_T("");
		else
		{
			COleDateTimeSpan dtspan=sec+dt_e-dt_s;
			double duration=dtspan.GetTotalHours()/24;
			//double duration=(int)(0.5+((double)((int)((100*dtspan.GetTotalHours())/24)))/100);
			buf.Format(_T("%.4g"),duration);
		}
		m_dlit_plan_ctrl.SetWindowText(buf);

		return true;
	}
	else if(0==i2) //if((1==i1) && (1==i3)) 
	{
		//вычисляем дату окончания
		if(0==dlit) dt_e=dt_s;
		else
		{
			COleDateTimeSpan span(dlit);
			dt_e=dt_s+span-sec;
		}
		if(	m_odt_max_planed.GetStatus()!=COleDateTime::null && dt_e>m_odt_max_planed)
		{
			// вышли за пределы
			COleDateTimeSpan dt_s(dlit);
			COleDateTime testStart=m_odt_max_planed-dt_s;
			if(	m_odt_min_planed.GetStatus()!=COleDateTime::null && testStart<m_odt_min_planed)
			{
				AfxMessageBox(APL_T("Вычисленная дата окончания выходит за ограничения родительского проекта!\n\n Установлены максимально возможные даты и уменьшена длительность!"));
				testStart=m_odt_min_planed;
				COleDateTimeSpan dtspan=m_odt_max_planed-m_odt_min_planed;
				double duration=  dtspan.GetTotalHours()/24;
				//double duration=(int)(0.5+((double)((int)((100*dtspan.GetTotalHours())/24)))/100);
				buf.Format(_T("%.4g"),duration);
				m_dlit_plan_ctrl.SetWindowText(buf);
			}
			else
			{
				AfxMessageBox(APL_T("Вычисленная дата окончания выходит за ограничения родительского проекта!\n\n Установлена максимально возможная дата и уменьшена дата начала!"));
			}
			dt_e=m_odt_max_planed;
			m_date_begin_planned_ctrl.SetTime(testStart);
			m_time_begin_planned_ctrl.SetTime(testStart);
		}
		m_date_end_planned_ctrl.SetTime(dt_e);	
		m_time_end_planned_ctrl.SetTime(dt_e);
		return true;
	}
	else  /* && (i3 ==1)*/
	{
		//вычисляем дату начала
		if(0==dlit) dt_s=dt_e;
		else
		{
			COleDateTimeSpan span(dlit);
			dt_s=(dt_e-span)+sec;
		}

		if(	m_odt_min_planed.GetStatus()!=COleDateTime::null && dt_s<m_odt_min_planed)
		{
			// вышли за пределы
			COleDateTimeSpan span(dlit);
			COleDateTime testEnd=m_odt_min_planed+span-sec;
			if(	m_odt_max_planed.GetStatus()!=COleDateTime::null && testEnd>m_odt_max_planed)
			{
				AfxMessageBox(APL_T("Вычисленная дата начала выходит за ограничения родительского проекта!\n\n Установлены максимально возможные даты и уменьшена длительность!"));
				testEnd=m_odt_max_planed;
				COleDateTimeSpan dtspan=m_odt_max_planed-m_odt_min_planed;
				double duration=dtspan.GetTotalHours()/24;
				//double duration=(int)(0.5+((double)((int)((100*dtspan.GetTotalHours())/24)))/100);
				buf.Format(_T("%.4g"),duration);
				m_dlit_plan_ctrl.SetWindowText(buf);
			}
			else
			{
				AfxMessageBox(APL_T("Вычисленная дата окончания выходит за ограничения родительского проекта!\n\n Установлена минимально возможная дата и увелитчена дата завершения!"));
			}
			dt_s=m_odt_min_planed;
			m_date_end_planned_ctrl.SetTime(testEnd);
			m_time_end_planned_ctrl.SetTime(testEnd);
		}
		m_date_begin_planned_ctrl.SetTime(dt_s);	
		m_time_begin_planned_ctrl.SetTime(dt_s);
		return true;
	}
	return false;
}

void CProjectDlg::OnBnClickedCheckPlannedDuration()
{
	int check=m_check_planed_duration_set_btn.GetCheck();
	if(1==check)
	{
		//поставили галочку
		if(bIsSet3Check()) {m_check_planed_duration_set_btn.SetCheck(FALSE); return;}
		m_dlit_plan_ctrl.SetReadOnly(FALSE);
		RecalcPlanDate();
	}
	else
	{
		//убрали галочку
		m_dlit_plan_ctrl.SetReadOnly(TRUE);
		RecalcPlanDate();

		if((m_check_planned_begin_ctrl.GetCheck()==0) || (m_check_planned_end_ctrl.GetCheck()==0))
			m_dlit_plan_ctrl.SetWindowText(_T(""));
	}
}
void CProjectDlg::OnCheckPlannedBegin() 
{
	int check=m_check_planned_begin_ctrl.GetCheck();
	if(check==1)
	{
		//поставили галочку
		if(bIsSet3Check()) {m_check_planned_begin_ctrl.SetCheck(FALSE); return;}

		m_date_begin_planned_ctrl.EnableWindow(TRUE);
		m_time_begin_planned_ctrl.EnableWindow(TRUE);

		COleDateTime d_time;
		m_date_begin_planned_ctrl.GetTime(d_time);	
		if(d_time.GetYear()==1900 && d_time.GetMonth()==1 && d_time.GetDay()==1)
			m_date_begin_planned_ctrl.SetTime(COleDateTime::GetCurrentTime());

		RecalcPlanDate();
	}
	else if(check==0)
	{
		m_date_begin_planned_ctrl.EnableWindow(FALSE);
		m_time_begin_planned_ctrl.EnableWindow(FALSE);
		RecalcPlanDate();
	}
}

void CProjectDlg::OnCheckPlannedEnd() 
{
	int check=m_check_planned_end_ctrl.GetCheck();
	if(check==1)
	{
		if(bIsSet3Check()) {m_check_planned_end_ctrl.SetCheck(FALSE); return;}
		m_date_end_planned_ctrl.EnableWindow(TRUE);
		m_time_end_planned_ctrl.EnableWindow(TRUE);

		COleDateTime d_time;
		m_date_end_planned_ctrl.GetTime(d_time);	
		if(d_time.GetYear()==1900 && d_time.GetMonth()==1 && d_time.GetDay()==1)
			m_date_end_planned_ctrl.SetTime(COleDateTime::GetCurrentTime());

		RecalcPlanDate();
	}
	else if(check==0)
	{
		m_date_end_planned_ctrl.EnableWindow(FALSE);
		m_time_end_planned_ctrl.EnableWindow(FALSE);

		RecalcPlanDate();
	}
}



//*************************************************************
// Двойной клик на связи
void CProjectDlg::OnNMDblclkPrjRelList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;

	if(0==pNMItemActivate) return;

	int item=pNMItemActivate->iItem;
	CaplInstance *rel=(CaplInstance*)m_prj_rel_list.GetItemData(item);
	if(0==rel) return;

	CaplInstance *cur_project=m_project;
	if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);

	CaplInstance *prj;
	m_api->m_data.GetAttr(rel,m_project_mgr->a_project_seq_prev,prj);
	if(prj==cur_project) m_api->m_data.GetAttr(rel,m_project_mgr->a_project_seq_next,prj);

	m_project_mgr->ShowProjectProperties(prj);
	UpdateRelation(item);
}


void CProjectDlg::PrjRbuttonDown(MSG* pMsg)
{
	if(0==pMsg) return;

	POINT point; point.x=GET_X_LPARAM(pMsg->lParam); point.y=GET_Y_LPARAM(pMsg->lParam); 
	int item=m_prj_rel_list.HitTest(point,0);
	if(item>=0) m_prj_rel_list.SetSelectionMark(item);

	CaplInstance *cur_project=m_project;
	if(m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
		m_project_mgr->m_data->GetAttr(m_project,m_project_mgr->a_project_adm_ver_project,cur_project);


	CMenu menu;CMenu* pPopup;
	VERIFY(menu.LoadMenu(IDR_CONTEXT_MENU));
	pPopup = menu.GetSubMenu(1);
	//LoadContextMenuIcon();
	CaplMenu::Install(this);
	if(item<0)
	{
		pPopup->EnableMenuItem(ID_PROPERTIES, MF_GRAYED|MF_BYCOMMAND );
		pPopup->EnableMenuItem(ID_DEL_REL, MF_GRAYED|MF_BYCOMMAND );
	}
	if(m_read_only || m_read_only_ver)
	{
		pPopup->EnableMenuItem(ID_ADD_PREV, MF_GRAYED|MF_BYCOMMAND );
		pPopup->EnableMenuItem(ID_DEL_REL, MF_GRAYED|MF_BYCOMMAND );
	}

	m_prj_rel_list.ClientToScreen(&point);

	BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON |TPM_RETURNCMD,	point.x, point.y,this); // use main window for cmds

	switch(res)
	{	
	case ID_ADD_PREV:
		{
			if(0==m_project) {AfxMessageBox(APL_T("Сначала надо сохранить проект!"),MB_OK); return;}
			CaplInstance *new_prev_prj=m_api->m_appr_mgr.SelectInstance(APL_MODE_SELECT_PROJECT);
			if(new_prev_prj!=0)
			{
				
				CaplInstance *inst=m_project_mgr->CreateProjectSequence(new_prev_prj,cur_project);
				if(0!=inst)
				
				/*if(cur_project==new_prev_prj) {AfxMessageBox(APL_T("Проект не может быть предыдущим для самого себя!"),MB_OK); return;}

				int i;
				CaplInstance *inst;
				aplExtent ext;
				m_project_mgr->GetProjectSequenceRelation(cur_project,ext,true);
				for(i=0;i<ext.GetSize();i++)
				{
					m_api->m_data.GetAttr(ext[i],m_project_mgr->a_project_seq_prev,inst);
					if(inst==new_prev_prj){AfxMessageBox(APL_T("Такая связь уже есть!"),MB_OK); return;}
				}

				inst=m_api->m_data.CreateInstance(m_project_mgr->e_project_seg);
				m_api->m_data.PutAttr(inst,m_project_mgr->a_project_seq_prev,new_prev_prj);
				m_api->m_data.PutAttr(inst,m_project_mgr->a_project_seq_next,cur_project);
				//m_api->m_data.PutAttr(inst,m_project_mgr->a_project_seq_type,);
				m_api->SaveChanges();*/

				int item=m_prj_rel_list.InsertItem(-1,APL_T("Предыдущий"));
				m_prj_rel_list.SetItemData(item,(int)inst);
				UpdateRelation(item);
			}
		}
		break;
	case ID_PROPERTIES:
		{
			CaplInstance *rel=(CaplInstance*)m_prj_rel_list.GetItemData(item);
			if(0==rel) return;

			CaplInstance *prj;
			m_api->m_data.GetAttr(rel,m_project_mgr->a_project_seq_prev,prj);
			if(prj==cur_project) m_api->m_data.GetAttr(rel,m_project_mgr->a_project_seq_next,prj);

			m_project_mgr->ShowProjectProperties(prj);
			UpdateRelation(item);
		}
		break;
	case ID_DEL_REL:
		CaplInstance *rel=(CaplInstance*)m_prj_rel_list.GetItemData(item);
		if(0==rel) return;

		CaplInstance *prj;
		m_api->m_data.GetAttr(rel,m_project_mgr->a_project_seq_next,prj);
		if(prj!=cur_project) {AfxMessageBox(APL_T("Удалять можно только связи с предыдущими проектами!"),MB_OK|MB_ICONSTOP); return;}

		if(IDYES!=AfxMessageBox(APL_T("Вы действительно хотите удалить связь между проектами?"),MB_YESNO|MB_ICONSTOP)) return;
		
		if(!m_project_mgr->m_data->IsKindOf(m_project,m_project_mgr->e_project_adm_ver))
			{AfxMessageBox(APL_T("Проект не взят на редактирование!"),MB_OK|MB_ICONSTOP); return;}

		int i;
		aplExtent ext;
		m_api->m_data.GetAttr(m_project,m_project_mgr->a_project_adm_ver_prev_sequences,ext);
		for(i=0;i<ext.GetSize();i++)
		{
			if(ext[i]!=rel) continue;
			ext.Remove(i);
			break;
		}
		m_api->m_data.PutAttr(m_project,m_project_mgr->a_project_adm_ver_prev_sequences,ext);
		m_api->m_data.DeleteInstance(rel);
		m_api->SaveChanges();
		m_prj_rel_list.DeleteItem(item);
		break;
	}
}




void CProjectDlg::OnBnClickedNotes()
{
	if(m_project!=0) m_api->m_appr_mgr.ShowNotes(m_project,0,false);
	else AfxMessageBox(APL_T("Сначала сохраните проект"));
}


void CProjectDlg::OnCancel()
{
	if(m_bNeedUndoCheckout && m_auto_end_edit_ctrl.IsWindowVisible())
	{
		if(1==m_auto_end_edit_ctrl.GetCheck())
		{
			OnUndoCheckOut();
			if(m_auto_end_edit_ctrl.IsWindowVisible()) return; // Что-то пошло не так
		}
	}

	CaplResizableDialog::OnCancel();
}

void CProjectDlg::OnDtnDatetimechangeIdcActualLaborDate(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	*pResult = 0;

	if(0!=m_forbinen_future_fact_dates)
	{
		COleDateTime dt;
		m_actual_labor_date_ctrl.GetTime(dt);

		if(dt>COleDateTime::GetCurrentTime())
		{
			m_actual_labor_date_ctrl.SetTime(COleDateTime::GetCurrentTime());

			// При выборе из выпадающего календаря контрол посылает 2 идентичных сообщения
			// Вот так избавляемся от дублирования сообщения
			static DWORD dwPrewTick=0;
			if( (GetTickCount()-dwPrewTick) >100)
			{
				AfxMessageBox(APL_T("Ввод фактической даты будущей датой запрещен настройками!"),MB_OK|MB_ICONSTOP);
			}
			dwPrewTick=GetTickCount();
		}
	}	
}
