#include "stdafx.h"
#include "dictionary.h"

#include "PSMDoc.h"

//#include "aplTopLevelItem.h"
#include "aplTreeApprovalItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplCharacteristicGroupTreeItem.h"
#include "aplDocTreeItem.h"
#include "TreeProductItem.h"
#include "aplFolderTreeItem.h"
#include "aplChangeTreeItem.h"
#include "TabView.h"

#include "resource.h"

//CaplWfFolderTreeItem
CaplChangeTreeItem::CaplChangeTreeItem(CTreeCtrl *tree, CPSMDoc *doc,
									   CaplInstance* chng, CaplInstance* chngItem)
{
	m_type= APL_TREE_ITEM_CHANGE;
	m_doc= doc;
	m_tree= tree;
	m_chng= chng;
	m_chng_item= chngItem;
	m_classifier=0;
	m_folder= NULL;
	if(doc!=0) 
		doc->m_items.Add(this);	
}

bool CaplChangeTreeItem::GetName(CString &name)
{
	name=_T("???");
	_APL_TREE_ITEM_CHEK_PARAM_BOOL

	CString buf;
	
	if(m_chng_item==NULL)
	{
		m_doc->m_api.GetItemName(m_chng,name);
//		m_doc->m_api.m_change_mgr.LoadChangeInfo(m_chng);
//		m_doc_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_id, name);
//		if(!name.IsEmpty())
//		{
//			name+=_T(":");
//		}
//		m_doc_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_name, buf);
//		name+=buf;
	}
	else
	{
//		m_doc->m_api.m_change_mgr.LoadItemInfo(m_chng_item);		
	}

	return true;
}

bool CaplChangeTreeItem::RefreshItem()
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	UINT ico= ICON_CHANGE;
	CString buf;
	aplExtent ext;
	int ico_rel=-1;

	GetMainInstances(ext);
	if(ext.GetSize())
		ico = m_doc->m_api.GetInstIco(ext[0]);

	if(m_doc_data.IsKindOf(ext[0], m_doc->m_api.m_change_mgr.e_chng))	
	{
		ico_rel=ICO_STATE_WORKING;

		m_doc_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_state, buf);

		if(buf==_T("approval")) ico_rel= ICO_STATE_APPROVING;
		else if(buf==_T("approving")) ico_rel= ICO_STATE_APPROVING;
		else if(buf==_T("applied")){ ico+= 2;ico_rel= ICO_STATE_APPROVED;}
		else if(buf==_T("approved"))ico_rel= ICO_STATE_APPROVED;
		else if(buf==_T("canceled"))ico_rel= ICO_STATE_CANCELED;

		SetItemImage(ico_rel, IDX_IL_TREE_STATE, false);

		CString sUrgency;
		m_doc->m_api.m_data.GetAttr(ext[0], m_doc->m_api.m_change_mgr.a_chng_urgency, sUrgency);
		sUrgency.MakeLower();
		if(sUrgency.Find(APL_T("срочно"))>=0)  font_style|=APL_FONT_BOLD;
	}
	
	GetName(buf);

	SetItemImage(ico, IDX_IL_TREE_ITEM);
	m_tree->SetItemText(m_item, buf);

	if(m_doc_data.IsKindOf(ext[0], m_doc->m_api.m_change_mgr.e_chng))
	{
		CString sGroupCode1;
		m_doc->m_api.m_data.GetAttr(ext[0], m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);	
		int ico_eff=0;
		if(sGroupCode1!=_T("")) ico_eff=ICO_EFF_LINK;
		SetItemImage(ico_eff,IDX_IL_TREE_EFF,false);
		 
	}
	else
	{
		// Тип связи
		ico_rel=ICO_EFF_NO;
		
		CaplInstance* pdr_or_pdf;
		CaplInstance* new_pdf;
		
//		m_doc->m_api.LoadItemInfo(ext[0]);

		m_doc->m_api.m_data.GetAttr(ext[0], m_doc->m_api.m_change_mgr.a_psc_changed_product, pdr_or_pdf);
		m_doc->m_api.m_data.GetAttr(ext[0], m_doc->m_api.m_change_mgr.a_psc_changing_product, new_pdf);
	
		if(pdr_or_pdf && m_doc->m_api.m_data.IsKindOf(pdr_or_pdf, m_doc->m_api.m_prd_mgr.e_pdf) && new_pdf)// Добавление
		{
			ico_rel= ICO_EFF_LOW+1;
		}
		else if(pdr_or_pdf && m_doc->m_api.m_data.IsKindOf(pdr_or_pdf, m_doc->m_api.m_prd_mgr.e_pdr))
		{
			if(new_pdf)// Замена
				ico_rel= ICO_EFF_LOW+3;
			else // Удаление
				ico_rel= ICO_EFF_LOW+2;
		}
		
		SetItemImage(ico_rel,IDX_IL_TREE_EFF,false);		
	}
	if(m_bWOForNote)
		SetItemImage(ICO_REL_WO_4NOTE, IDX_IL_TREE_REL_TYPE);
	
	Sort();
	m_tree->RedrawWindow();
	
	if(m_doc->m_tab_view->m_item_old==this) m_doc->ChangeItem(this);
	return true;
}

bool CaplChangeTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	CString buf;
	aplExtent ext;
	UINT ico=NULL;
	int ico_rel=-1;
	
	InsetItem(_T("1"),ico,parent_item);
	m_fictive_item= m_tree->InsertItem(_T("fictive"), 0, 0, m_item);
	RefreshItem();
	m_expanded=false;
	return true;
}

bool CaplChangeTreeItem::Expand(UINT action)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	if(action==2)
	{
		if(m_expanded) return true;
		if(m_hasSubItem) Expand(1);
		if(m_fictive_item!=0)
		{
			m_tree->DeleteItem(m_fictive_item);
			m_fictive_item=0;
		}
		m_hasSubItem= true;


		// показываем дочерние изменения
		aplExtent ext_linked_change;
		m_doc->m_api.m_change_mgr.GetLinkedChange(m_chng,ext_linked_change);

		aplExtent ext_sub_changes;
		m_doc->m_api.m_change_mgr.GetSubChanges(m_chng,ext_sub_changes);

		if(ext_linked_change.GetSize()>0) ext_sub_changes.Append(ext_linked_change);

		CaplInstance *src_pi;
		m_doc->m_api.m_data.GetAttr(m_chng,m_doc->m_api.m_change_mgr.a_chng_src_pi,src_pi);
		if(0!=src_pi)ext_sub_changes.Add(src_pi);
		
		if(ext_sub_changes.GetSize()>0)
		{
			m_doc->m_api.m_change_mgr.LoadChangeInfo(ext_sub_changes);
			int i;
			for(i=0;i<ext_sub_changes.GetSize();i++)
			{
				CaplInstance *change=ext_sub_changes[i];
				CaplTreeItem* aplItem= NULL;
				InsertInstInTree(ext_sub_changes[i],m_item,m_doc,m_tree,m_contents,0, &aplItem);

			}
		}

			bool old = m_bShowNoFoundMessage;
			m_bShowNoFoundMessage = old;
			m_ExecMyExpand = true;
			if(m_doc->m_auto_expand_items.m_showintree_change&APL_SHOW_DOC)
				ShowAllDocs(false,false);
			if(m_doc->m_auto_expand_items.m_showintree_change&APL_SHOW_APPROVAL)
				ShowAllApproval(false);
			
			// раскрываем пакет изменений на элементы изменений
			ShowChangeContent();
			
			m_bShowNoFoundMessage = old;
			m_ExecMyExpand = true;
		Sort();
		m_tree->SetRedraw(TRUE);
		m_expanded= true;
	}
	else if(action==1)
	{
		CollapseItem();
		m_all_items.Clear();
		m_sub_folders.Clear();
	}
	return true;
}

void CaplChangeTreeItem::ShowChangeContent()
{
	aplExtent aeExt, aeItems;
	GetMainInstances(aeExt);
	if(aeExt.Size<=0) return;
	
	CaplInstance *cit = aeExt[0];
	if(cit==0) return ;
	if(cit->GetType()==0) return ;
	if(cit->GetAccessmode()>aplRO)
	{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),cit);return;};
	if(-1!=m_all_items.Find(aeExt[0])) return;

	StartBusy();
	m_tree->SetRedraw(FALSE);
	
	if(m_doc_data.IsKindOf(cit, m_doc->m_api.m_change_mgr.e_chng))
	{
		// берем элементы пакета изменений (пока только документы)
		m_doc_data.GetAttr(cit, m_doc->m_api.m_change_mgr.a_chng_items, aeItems);
		for(int i=0; i<aeItems.GetSize(); i++)
		{
			if(!aeItems[i]) continue;			
			if(-1!=m_all_items.Find(aeItems[i])) continue;

			if(m_doc_data.IsKindOf(aeItems[i], m_doc->m_api.m_change_mgr.e_avc))
			{
				CaplChangeTreeItem *pItem=new CaplChangeTreeItem(m_tree,m_doc,aeItems[i]);
				pItem->CreateTreeItem(m_item);				
			}
			else if(m_doc_data.IsKindOf(aeItems[i], m_doc->m_api.m_change_mgr.e_psc))
			{
				CaplChangeTreeItem *pItem=new CaplChangeTreeItem(m_tree,m_doc,aeItems[i]);
				pItem->CreateTreeItem(m_item);			
			}

			m_all_items.Add(aeItems[i]);
		}				
	}
	else if(m_doc_data.IsKindOf(cit, m_doc->m_api.m_change_mgr.e_avc))
	{
		CaplInstance *cit = NULL;
		CaplInstance* doc_inst= NULL;
		m_doc_data.GetAttr(aeExt[0], m_doc->m_api.m_change_mgr.a_avc_new_rev, cit);
		if(cit)
			m_doc_data.GetAttr(cit, m_doc->m_api.m_doc_mgr.a_apl_doc_rev_doc, doc_inst);
		
		if(doc_inst)
		{
			CaplDocTreeItem *pItem=new CaplDocTreeItem(m_tree,m_doc, doc_inst, 0, cit);
			pItem->CreateTreeItem(m_item);
		}
	}
	else if(m_doc_data.IsKindOf(cit, m_doc->m_api.m_change_mgr.e_psc))
	{
		CaplInstance* inst= NULL;
		CaplInstance* pChange= NULL;
		m_doc->m_api.m_data.GetAttr(cit, m_doc->m_api.m_change_mgr.a_chng_item_of_chng, pChange);
		m_doc->m_api.m_data.GetAttr(cit, m_doc->m_api.m_change_mgr.a_psc_changed_product, inst);
		if(m_doc->m_api.m_data.IsKindOf(inst, m_doc->m_api.m_prd_mgr.e_pdf))
			cit= inst;
		else
			m_doc->m_api.m_data.GetAttr(inst, m_doc->m_api.m_prd_mgr.a_pdr_r_ting, cit);
		if(cit)
		{
			m_doc->m_api.m_data.GetAttr(cit, m_doc->m_api.m_prd_mgr.a_pdf_prd, inst);
			CaplProductTreeItem* pItem= new CaplProductTreeItem(m_tree, m_doc, inst, cit);
			pItem->m_change= pChange;
			pItem->CreateTreeItem(m_item);
		}
	}

	m_tree->SetRedraw(TRUE);
	StopBusy();
}

void CaplChangeTreeItem::ShowProperties()
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID

	if(m_chng==0) return;
	if(m_chng->GetId()==0) return;
	if(m_chng->GetType()==0) return;

	if(m_doc->m_api.m_data.IsKindOf(m_chng, m_doc->m_api.m_change_mgr.e_chng))
	{
		m_doc->m_api.m_change_mgr.LoadChangeInfo(m_chng);
		m_doc->m_api.m_change_mgr.ShowChangeProperties(m_chng);
	}
	else
	{
		m_doc->m_api.m_change_mgr.ShowPSCItemProperty(m_chng);		
	}
	RefreshItem();
}

bool CaplChangeTreeItem::ShowInListCtrl(CListCtrl *list)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	CHECK_SHOW_LIST_CTRL(m_chng);
	
	CaplInstance* pChange= NULL;
	CaplInstance* pChangeItem= NULL;

	if(m_doc->m_api.m_data.IsKindOf(m_chng, m_doc->m_api.m_change_mgr.e_chng))
	{
		pChange= m_chng;
	}
	else
	{
		m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_item_of_chng, pChange);
		pChangeItem= m_chng;
	}

	if(!pChange) return false;

	CString buf, name;
	m_doc->m_api.m_change_mgr.LoadChangeInfo(pChange);
	int i= -1;
	m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_id, buf);
	i=list->InsertItem(i+1,  APL_T("Обозначение:"));
	list->SetItemText(i, 1, buf);
	m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_name, buf);
	i= list->InsertItem(i+1,  APL_T("Наименование:"));
	list->SetItemText(i, 1, buf);
	m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_dscr, buf);
	i= list->InsertItem(i+1,  APL_T("Описание:"));	
	list->SetItemText(i, 1, buf);
	
	i= list->InsertItem(i+1, _T(""));
	
	CString str=  APL_T("Разрабатывается");
	CString sState;
	m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_state, sState);
	
	if(sState==_T("approval") || sState== _T("approving")) str=  APL_T("Согласовывается");
	else if(sState==_T("approved")) str=  APL_T("Согласовано");
	else if(sState==_T("applied")) str=  APL_T("Проведено");
	else if(sState==_T("canceled")) str=  APL_T("Аннулировано");
	
	i= list->InsertItem(i+1,  APL_T("Статус:"));
	list->SetItemText(i, 1, str);
	i= list->InsertItem(i+1, _T(""));

	// Кто и когда создал изменение
	COleDateTime odt;
	CaplInstance* inst= NULL;
	
	m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_create_date, buf);
	if(!buf.IsEmpty()) // Информация о пользователе, создавшем изменение есть
	{
		m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_create_autor, inst);
		buf=_T("");
		m_doc->m_api.m_appr_mgr.GetPersonName(inst, buf);
		m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_create_user, name);
		buf+=_T("[");
		buf+=name;
		buf+=_T("]");
		
		i= list->InsertItem(i+1,  APL_T("Изменение создал:"));
		list->SetItemText(i, 1, buf);
		
		m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_create_date, buf);
		aplString2Date(buf, odt);
		buf= odt.Format();
		i= list->InsertItem(i+1,  APL_T("Дата создания:"));
		list->SetItemText(i, 1, buf);
		
		i= list->InsertItem(i+1, _T(""));		
	}

	if(sState==_T("applied"))
	{
		m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_autor, inst);
		buf=_T("");
		m_doc->m_api.m_appr_mgr.GetPersonName(inst, buf);
		m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_user, name);
		
		buf+=_T("[");
		buf+=name;
		buf+=_T("]");
		
		i= list->InsertItem(i+1,  APL_T("Изменение провел:"));
		list->SetItemText(i, 1, buf);

		m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_apply_date, buf);
		aplString2Date(buf, odt);
		buf= odt.Format();
		
		i= list->InsertItem(i+1,  APL_T("Дата проведения:"));
		list->SetItemText(i, 1, buf);
		
		i= list->InsertItem(i+1, _T(""));		
	}

	GetAccessName(pChange, buf);
	i=list->InsertItem(i+1,  APL_T("Доступ:"));
	list->SetItemText(i, 1, buf);

	aplExtent ext;
	CStringArray comment;
	if(m_chng!=0){ comment.Add(_T("m_chng")); ext.Add(m_chng);}
	if(m_chng_item!=0){ comment.Add(_T("m_chng_item")); ext.Add(m_chng_item);}
	if(m_classifier!=0){
		CaplInstance* classif_ref;
		m_doc->m_api.m_classifier_mgr.TestClassifierAssociation(pChange,m_classifier,&classif_ref);
		if(classif_ref!=0){
			comment.Add(_T("classifier association"));
			ext.Add(classif_ref);
		}
		comment.Add(_T("m_classifier"));
		ext.Add(m_classifier);
	}

	
	ShowInstanceInfoInListCtrl(ext,list,&comment);

	return true;
}

void CaplChangeTreeItem::ShowCmd(long cmd)
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID
	
	if(m_chng==0) return;
	if(m_chng->GetId()==0) return;
	if(m_chng->GetType()==0) return;
	switch (cmd)
	{
		case ID_ITEM_CHECK_OUT: CheckOut(); break;
		case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(m_chng);
		default: PrepareContextMenu(cmd);
	}
	RefreshItem();
}

BOOL CaplChangeTreeItem::ShowToolBarButton(CCmdUI* pCmdUI)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	if(m_chng==0) return false;
	if(m_chng->GetId()==0) return false;
	if(m_chng->GetType()==0) return false;

	if(pCmdUI->m_nID==ID_SET_INST_ACCSESS)
	{
		aplExtent instances;
		GetAccessedInstances(instances);
		if(instances.GetSize()>0)
		{
			if(instances[0]->GetAccessmode()==aplOWN) return TRUE;
		}
		return FALSE;
	}
	
	CString buf;
	m_doc_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_state, buf);
	if(0 == buf.CompareNoCase(_T("canceled")))
		return FALSE;

	switch(pCmdUI->m_nID)
	{
		case ID_ITEM_CHECK_OUT: if(buf!=_T("approval") || m_chng->GetAccessmode()>aplRW) break;
		case ID_CREATE_APPROVAL: if(buf==_T("applied") || m_chng->GetAccessmode()>aplRW) break;
		case ID_CREATE_DOC: if(buf==_T("applied") || m_chng->GetAccessmode()>aplRW) break;
		case ID_CREATE_CHARACTERISTIC: if(buf==_T("applied") || m_chng->GetAccessmode()>aplRW) break;
		case ID_SHOW_ALL_DOCS:
		case ID_SHOW_ALL_APPROVAL:
		case ID_SHOW_ALL_CHARACTERISTIC:
		case ID_SHOW_NOTES:
		case ID_CREATE_NOTE:
			pCmdUI->Enable(TRUE); return TRUE; break;
	}
	return FALSE;
}

bool CaplChangeTreeItem::TrackPopupMenu(CWnd* wnd, CPoint &point, UINT view_mode)
{
	CMenu menu;  gSetPsmResourceHandle();
	CMenu* pPopup= NULL;

	if(m_doc->m_api.m_data.IsKindOf(m_chng, m_doc->m_api.m_change_mgr.e_chng))
	{
		VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
		// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
		CaplMenu::Install(wnd); // 	VERIFY(CaplMenu::Install(wnd, ePopupMenu ));
		pPopup = menu.GetSubMenu(INDEX_CHANGE_MENU);
		
		AppendAddIn((CMenu*)pPopup);
	}
	else
	{
		VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU1));
		CaplMenu::Install(wnd);
		pPopup = menu.GetSubMenu(INDEX_CHANGE_ITEM_MENU);		
	}    

	ASSERT(pPopup != NULL);
	if(pPopup==0) return false;

	UpdateMenu((CMenu**)&pPopup, view_mode);

	CString buf;
	CaplInstance* pChange= NULL;
	CaplInstance* pChangeItem= NULL;

	if(m_doc->m_api.m_data.IsKindOf(m_chng, m_doc->m_api.m_change_mgr.e_chng))
	{
		pChange= m_chng;
		CString sGroupCode1;
		m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);	
		if(sGroupCode1!=_T("")) pPopup->EnableMenuItem(ID_DELETE_CHANGE_LINK, MF_BYCOMMAND | MF_ENABLED);
	}
	else
	{
		m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_item_of_chng, pChange);
		pChangeItem= m_chng;
	}

	m_doc->m_api.m_change_mgr.LoadChangeInfo(pChange);
	m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_state, buf);
	if(buf==_T("applied") || buf==_T("canceled"))
	{
		pPopup->EnableMenuItem(ID_CHANGE_APPLY, MF_BYCOMMAND | MF_GRAYED);
		//pPopup->EnableMenuItem(ID_CREATE_APPROVAL, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_GRAYED);		
	}
	else 
	{
		pPopup->EnableMenuItem(ID_CHANGE_UNDO, MF_BYCOMMAND | MF_GRAYED);		
	}
	if(buf==_T("applied") || buf==_T("not_applied") || buf==_T("canceled"))
	{
		pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);		
	}
	else
	{
		int iValue= 0;
		m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Состояния\\Запретить вручную менять состояние изменения"), iValue, 0);
		if(0!=iValue)
		{
			if(!m_doc_data.IsAdmin())
			{
				pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);		
			}
		}
	}
	if(m_chng->GetAccessmode()>aplOWN)
	{
		pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_GRAYED);		
	}
	else if(m_chng->GetAccessmode()>aplRW)
	{
		pPopup->EnableMenuItem(ID_CHANGE_APPLY, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_APPROVAL, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_CREATE_DOC, MF_BYCOMMAND | MF_GRAYED);		
		pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT, MF_BYCOMMAND | MF_GRAYED);
	}
		
	if(m_folder==0){pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);}
	if(m_classifier==0){pPopup->EnableMenuItem(ID_REMOVE_FROM_CLASSIFIER, MF_BYCOMMAND | MF_GRAYED);}

	if(0==pChange) pPopup->RemoveMenu(ID_CHANGE_CHECK_GROUP_ID, MF_BYCOMMAND);
	else
	{
		bool bRemove=true;
		if(m_doc->m_api.m_options_mgr.CheckInstallCode(_T("grpz")))
		{
			m_doc_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_group_id, buf);
			if(buf!=_T("")) bRemove=false;
		}
		if(bRemove)pPopup->RemoveMenu(ID_CHANGE_CHECK_GROUP_ID, MF_BYCOMMAND);
	}

	if(!m_doc->m_api.m_options_mgr.CheckInstallCode(_T("Созвездие")))
	{
		pPopup->RemoveMenu(ID_SHOW_DEPENDENT_ITEMS, MF_BYCOMMAND);
	}



	BOOL res = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
						point.x, point.y, wnd);
	
	switch (res)
	{
	case ID_SHOW_CONTAINED_FOLDER:
		ShowContainedFolder(pChange);
		break;
	case ID_SHOW_CONTAINED_MESSAGE: ShowContainedMessage(pChange); break;
	case ID_SHOW_CONTAINED_TASKS: ShowContainedTasks(pChange); break;
	case ID_SHOW_CONTAINED_ALERT: ShowContainedAlert(pChange); break;
	case ID_SHOW_CONTAINED_CLASSIFIER:
		ShowContainedClassifier(pChange);
		break;
	case ID_SHOW_CONTAINED_PROCCESS:
		ShowContainedProccess(pChange);
		break;
	case ID_DELETE_CHANGE_LINK:
		{
			CString sGroupCode1;
			m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);	
			if(sGroupCode1==_T("")) {AfxMessageBox(APL_T("Пакет не связан с другими пакетами!"));return false;}
			if(m_chng->GetAccessmode()>aplRW) {AfxMessageBox(APL_T("Нет прав доступа!"),MB_OK|MB_ICONSTOP); return false; }
			CString sState;
			m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_state, sState);
			if(sState==_T("applied")) {AfxMessageBox(APL_T("Проведенные изменения нельзя исключать из группы!"),MB_OK|MB_ICONSTOP); return false; }

			if(IDYES!=AfxMessageBox(APL_T("Вы действительно хотите удалить связь?"),MB_YESNO|MB_ICONSTOP)) return false; 
			m_doc->m_api.m_data.PutAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_group_id, _T(""));
			m_doc->m_api.SaveChanges();
			RefreshItem();
			return true;
		}
		break;
	case ID_REMOVE_FROM_FOLDER:
		if(m_folder!=0)
		{
			if(m_doc->m_api.m_folder_mgr.RemoveFromFolder(m_folder,pChange))
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
		}
		break;
	case ID_REMOVE_FROM_CLASSIFIER:
		if(m_classifier!=0)
		{
			if(m_classifier->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return true;}
			if(m_doc->m_api.m_classifier_mgr.DeleteClassifierAssociation(pChange,m_classifier))
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
		}
		break;
	case ID_CHANGE_CHECK_GROUP_ID:
		{
			CString sErr,sGroupId ;
			m_doc->m_api.m_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupId);
			if(sGroupId==_T("")){AfxMessageBox (APL_T("Изменение не входит в группу!"),MB_OK|MB_ICONSTOP); return false;}

			aplExtent ext_ch;			
			m_doc->m_api.m_change_mgr.GetLinkedChange(pChange,ext_ch);
			ext_ch.Add(pChange);
			m_doc->m_api.m_change_mgr.LoadChangeInfo(ext_ch);

			// Проверяем полноту в изменений в группе
			if(m_doc->m_api.m_change_mgr.CheckGrpzChangeGroupById(ext_ch,sErr)) AfxMessageBox(APL_T("Ошибок не найдено"), MB_OK|MB_ICONINFORMATION);
			else 
			{
				CString buf=APL_T("Найдены ошибки:\n");
				buf+=sErr;
				aplShowBigMsg(buf,APL_T("Найдены ошибки"));
			}
		}
		break;
	case ID_CHANGE_APPLY:
		// добавил: Акуленко А.А. 03.04.2007
		// изменения с описанием - "изменение Р" можно проводить только с
		// рабочего места. (АРМЫ - Р.М. Извещения)
		//НАМ 12.01.2008: функциональность перенести в менеджер. Проводить можно и из PSM
// 		m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_dscr, buf);
// 		if(!buf.CompareNoCase(APL_T("изменение Р")))
// 		{
// 			AfxMessageBox(APL_T("Данное изменение можно провести только из модуля \"Р.М. Извещения\""), MB_ICONINFORMATION);
// 			return true;
// 		}
		
		{						
			m_doc->m_api.m_change_mgr.ApplyChange(pChange);
			RefreshItem();	
		}
		break;
	case ID_CHANGE_UNDO:
		// добавил: Акуленко А.А. 03.04.2007
		// изменения с описанием - "изменение Р" можно откатить только с
		// рабочего места. (АРМЫ - Р.М. Извещения)
		//НАМ 12.01.2008: функциональность перенести в менеджер. Проводить можно и из PSM
// 		m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_dscr, buf);
// 		if(!buf.CompareNoCase(APL_T("изменение Р")))
// 		{
// 			AfxMessageBox(APL_T("Данное изменение можно откатить только из модуля \"Р.М. Извещения\""), MB_ICONINFORMATION);
// 			return true;
// 		}

		{
			m_doc->m_api.m_change_mgr.UndoChange(pChange);
			RefreshItem();
		}
		break;
	case ID_CHECK_CHANGES :
	{
		// 2009.07.23
		if (!m_doc->m_api.m_data.IsKindOf(pChange, m_doc->m_api.m_change_mgr.e_chng))
			return false;

		HINSTANCE hLibraryKTS = AfxLoadLibrary(_T("KTS_EditAddIn3.dll"));
		bool (*pValidateRasc)(aplExtent&, CaplInstance*, CaplAPI*) = NULL;
		bool (*pValidateMat)(aplExtent&, CaplInstance*, CaplAPI*) = NULL;

		if (hLibraryKTS != NULL)
		{
			(FARPROC&)pValidateRasc = ::GetProcAddress(hLibraryKTS, "ValidateShopChains");
			(FARPROC&)pValidateMat = ::GetProcAddress(hLibraryKTS, "ValidateMat");
		}

		aplExtent pdf_lockers;
		m_doc->m_api.m_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_changed_assemlies, pdf_lockers);

		if ((pValidateRasc != NULL) && !pValidateRasc(pdf_lockers, pChange, &m_doc->m_api))
		{
			AfxMessageBox( APL_T("В составе сборок найдены изделия без расцеховки!"));
			return false;
		}

		if ((pValidateMat != NULL) && !pValidateMat(pdf_lockers, pChange, &m_doc->m_api))
		{
			AfxMessageBox( APL_T("В составе сборок найдены изделия без нормы!"));
			return false;
		}

		HINSTANCE hLibrary = AfxLoadLibrary(_T("aplchangemodule.dll"));
		bool (*pIsChangeCorrect)(CaplAPI*, CaplInstance*, aplExtent&) = NULL;

		if(hLibrary)
		{
			(FARPROC&)pIsChangeCorrect = ::GetProcAddress(hLibrary, "IsChangeCorrect");

			if (pIsChangeCorrect != NULL)
			{
				aplExtent extWrongRels;

				if (!pIsChangeCorrect(&m_doc->m_api, pChange, extWrongRels))
					return false;
			}

			AfxMessageBox( APL_T("Проверка успешно завершена."), MB_OK | MB_ICONINFORMATION);
		}		

		break;
	}
	case ID_CHANGE_SHOW_HISTORY:
		if(m_doc->m_api.m_change_mgr.ShowChangesTree(pChange))
			RefreshItem();	
		break;
	case ID_SHOW_PROPERTIES:
		ShowProperties();
		break;
	case ID_SHOW_II:
		{
			CString sId;
			m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_id, sId);
			CaplInstance *doc=m_doc->m_api.m_doc_mgr.FindDocById(sId);
			if(0==doc)AfxMessageBox(APL_T("Извещение не найдено!"),MB_OK|MB_ICONSTOP);
			else m_doc->m_api.m_doc_mgr.ViewWithMarkView(doc);
		}
		break;
	case ID_CREATE_DOC:
		CreateDoc();
		break;
	case ID_ITEM_CHECK_OUT:
		CheckOut();
		break;
	case ID_SHOW_CHANGED_ASSEMBLIES:
		{
			aplExtent chngAssms;
			CaplInstance* prd;
			m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_changed_assemlies, chngAssms);
			if(chngAssms.GetSize())
			{
				for(int i= 0; i<chngAssms.GetSize(); i++)
				{
					if(-1!=m_all_items.Find(chngAssms[i])) continue;

					m_doc->m_api.m_data.GetAttr(chngAssms[i], m_doc->m_api.m_prd_mgr.a_pdf_prd, prd);
					CaplProductTreeItem* pItem= new CaplProductTreeItem(m_tree, m_doc, prd, chngAssms[i]);
					pItem->m_change= m_chng;
					pItem->CreateTreeItem(m_item);	

					m_all_items.Add(chngAssms[i]);
				}
				MyExpand();
			}
			else
			{
				AfxMessageBox( APL_T("Изменяемые версии изделия не найдены."), MB_OK|MB_ICONINFORMATION);
			}
		}
		break;
	case ID_SHOW_DEPENDENT_ITEMS:
		{
			aplExtent dependent_items;
			CaplInstance* prd;
			m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_dependent_items, dependent_items);
			if(dependent_items.GetSize())
			{
				for(int i= 0; i<dependent_items.GetSize(); i++)
				{
					CaplInstance *dep_item=dependent_items[i];
					if(0==dep_item) continue;
					if(dep_item->IsDeleted())continue;
					if(-1!=m_all_items.Find(dep_item)) continue;

					if(m_doc->m_api.m_data.IsKindOf(dep_item, m_doc->m_api.m_prd_mgr.e_pdf))
					{
						m_doc->m_api.m_data.GetAttr(dep_item, m_doc->m_api.m_prd_mgr.a_pdf_prd, prd);
						CaplProductTreeItem* pItem= new CaplProductTreeItem(m_tree, m_doc, prd, dep_item);
						pItem->m_prd_item_type=_T("dependent");
						pItem->CreateTreeItem(m_item);	
						m_all_items.Add(dep_item);
					}
				}
				MyExpand();
			}
			else
			{
				AfxMessageBox( APL_T("Изменяемые версии изделия не найдены."), MB_OK|MB_ICONINFORMATION);
			}
		}
		break;


	case ID_DELETE:
		if(m_chng!=0)
		{
			bool bDeleted= false;
			if(pChangeItem)
			{
				aplExtent items;
				m_doc->m_api.m_data.GetAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_items, items);
				items.Remove(items.Find(pChangeItem));
				m_doc->m_api.m_data.PutAttr(pChange, m_doc->m_api.m_change_mgr.a_chng_items, items);
				bDeleted= m_doc->m_api.m_data.DeleteInstance(pChangeItem, false);
				m_doc->m_api.SaveChanges();
			}
			else
				bDeleted= m_doc->m_api.m_change_mgr.DeleteChange(pChange);
			if(bDeleted)
			{
				for(int i=0;i<m_doc->m_items.Size;i++)
				{
					if(m_doc->m_items[i]!=this)
					{
						if(m_doc->m_items[i]->m_type==m_type)
						{
							CaplChangeTreeItem *item2=
								(CaplChangeTreeItem*)m_doc->m_items[i];
							{
								if(item2->m_chng==m_chng)
								{m_doc->m_items.Remove(i); i--;}
							}
						}
					}
				}
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
			}
		}
		break;
	case ID_FOLDER_CREATE:
		{
			CaplInstance* folderInst=m_doc->m_api.m_folder_mgr.CreateFolder(m_chng,0,0);
			if(folderInst!=0)
			{
				CaplFolderTreeItem *fi=new CaplFolderTreeItem(m_tree,m_doc,this,folderInst);
				fi->CreateTreeItem(m_item);
				m_sub_folders.Add(folderInst);
				MyExpand();
			}
		}break;
	case ID_SHOW_CH_FOLDERS:
		{
			aplExtent sub_folders;
			int l(0);
			m_doc->m_api.m_folder_mgr.GetAllSubFolder(m_chng, sub_folders);
			for(int i=0; i<sub_folders.GetSize(); i++)
			{
				if(-1!=m_sub_folders.Find(sub_folders[i]))
					continue;

				m_sub_folders.Add(sub_folders[i]);
				CaplFolderTreeItem *fi=new CaplFolderTreeItem(m_tree,m_doc,this,sub_folders[i]);
				fi->CreateTreeItem(m_item);
				l++;
			}
			if(l)MyExpand();
			else AfxMessageBox(APL_T("Новые папки не найдены"));
		}break;

	case ID_CREATE_ADD_CHANGE:
		{
			aplExtent ext;
			CaplInstance *subchange=m_doc->m_api.m_change_mgr.CreateChange(0,0,0,0,0,ext,m_chng);
			if(0!=subchange)
			{
				MyExpand();

			}
		}break;

	case ID_CREATE_REPAYMENT_CHANGE:
		{
			aplExtent ext;
			CaplInstance *rep_change=m_doc->m_api.m_change_mgr.CreateRepaymentChange(m_chng);
			if(0!=rep_change)
			{
				MyExpand();	
				CaplTreeItem* aplItem= NULL;
				InsertInstInTree(rep_change,m_item,m_doc,m_tree,m_contents,0, &aplItem);

			}
		}break;
	case ID_CREATE_LINKED_CHANGE:
		{
			aplExtent ext;
			CaplInstance *lnk_change=m_doc->m_api.m_change_mgr.CreateLinkedChange(m_chng);
			if(0!=lnk_change)
			{
				RefreshItem();
				MyExpand();	
				CaplTreeItem* aplItem= NULL;
				InsertInstInTree(lnk_change,m_item,m_doc,m_tree,m_contents,0, &aplItem);
			}
		}break;
	case ID_SHOW_REPAYMENT_CHANGE:
		{
			CaplInstance *rep_change=m_doc->m_api.m_change_mgr.FindRepaymentChange(m_chng);
			if(0==rep_change) AfxMessageBox(APL_T("Погашающее изменение отсутствует."),MB_OK);
			else
			{
				MyExpand();
				m_doc->m_api.m_change_mgr.LoadChangeInfo(rep_change);
				CaplTreeItem* aplItem= NULL;
				InsertInstInTree(rep_change,m_item,m_doc,m_tree,m_contents,0, &aplItem);
			}
		}break;
	default: PrepareContextMenu(res); 	break;
	}	return true;
}

void CaplChangeTreeItem::GetAccessedInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_chng_item) {if(m_chng_item->GetType()!=0)ext.Add(m_chng_item);}
	else if(m_chng) {if(m_chng->GetType()!=0)ext.Add(m_chng);}
}

bool CaplChangeTreeItem::PasteFile(LPCTSTR file, CPoint *point)
{
	if(file==0) return false;
	if(m_chng==0) return false;
	CreateDoc(0,file);
	return true;
}

bool CaplChangeTreeItem::PasteItem(CaplTreeItem *item, CPoint *point)
{
	if(item==0) return false;
	if(m_tree==0) return false;
	if(m_doc==0) return false;
	if(m_chng==0) return false;
	if(!m_doc->m_api.m_data.IsKindOf(m_chng, m_doc->m_api.m_change_mgr.e_chng)) return false;
	
	
	CString sState;
	m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_state, sState);
	if(sState==_T("applied")) {	AfxMessageBox(APL_T("Изменение уже не редактируется!"),MB_OK|MB_ICONSTOP); return false; }
	
	
	aplExtent ext, ext1;
	CaplInstance* doc= NULL;
	CaplInstance* rev= NULL;
	CaplAPI* m_api= &m_doc->m_api;
	int i;

	// Document
	if(item->m_type==APL_TREE_ITEM_DOCUMENT)
	{
		rev= ((CaplDocTreeItem*)item)->m_rev;
		doc= ((CaplDocTreeItem*)item)->m_inst;
	}
	
	if(rev)
	{
		if(sState==_T("applied") || sState==_T("canceled"))
			return false;
		
		CaplInstance* actVer;
		CaplInstance* inst;
		aplExtent revs;
		bool bChecked= true;
		m_api->m_data.GetAttr(doc, m_api->m_doc_mgr.a_apl_doc_active, actVer);
		if(actVer==rev)
		{
			m_api->m_doc_mgr.LoadAllDocumentRevision(doc, revs);
			if(revs.GetSize()>1)
				bChecked= false;		
		}

		m_api->m_data.GetAttr(m_chng, m_api->m_change_mgr.a_chng_items, revs);
		for(i= 0; i<revs.GetSize() && bChecked; i++)
		{
			if(m_api->m_data.IsKindOf(revs[i], m_api->m_change_mgr.e_avc))
			{
				m_api->m_data.GetAttr(revs[i], m_api->m_change_mgr.a_avc_doc, inst);
				if(inst==doc)
				{
					m_api->m_data.GetAttr(revs[i], m_api->m_change_mgr.a_avc_new_rev, inst);
					if(rev!=inst)
					{
						m_api->m_data.PutAttr(revs[i], m_api->m_change_mgr.a_avc_new_rev, rev);
						m_api->SaveChanges();
					}
				}
				bChecked= false;
			}
		}

		if(bChecked)
		{
			CaplInstance* changeItem= m_api->m_data.CreateInstance(m_api->m_change_mgr.e_avc);
			if(changeItem)
			{
				m_api->m_data.PutAttr(changeItem, m_api->m_change_mgr.a_chng_item_of_chng, m_chng);
				m_api->m_data.PutAttr(changeItem, m_api->m_change_mgr.a_chng_item_id, m_api->m_change_mgr.GetAVCId(doc));
				m_api->m_data.PutAttr(changeItem, m_api->m_change_mgr.a_avc_new_rev, rev);
				m_api->m_data.PutAttr(changeItem, m_api->m_change_mgr.a_avc_doc, doc);

				m_api->m_data.GetAttr(m_chng, m_api->m_change_mgr.a_chng_items, revs);
				revs.Add(changeItem);
				m_api->m_data.PutAttr(m_chng, m_api->m_change_mgr.a_chng_items, revs);
				m_api->SaveChanges();
			}
		}
		RefreshAllChildItem();
		ShowChangeContent();
		Sort();
		return true;	
	}

	if(doc)
	{
		m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(m_chng, ext, ext1);
		if(-1==ext.Find(doc))m_doc->m_api.m_doc_mgr.CreateAssociation(m_chng, doc);
		if(-1==m_all_documents.Find(doc))ShowAllDocs(false);
	}
	
	CaplInstance* change_item= NULL;
	CaplInstance* change= NULL;
	CaplInstance* change_of_item= NULL;
	CString sMessage, sFrState;

	if(item->m_type==APL_TREE_ITEM_CHANGE)
	{
		if(m_doc->m_api.m_data.IsKindOf(((CaplChangeTreeItem*)item)->m_chng, m_doc->m_api.m_change_mgr.e_chng_item))
			change_item= ((CaplChangeTreeItem*)item)->m_chng;
		else if(m_doc->m_api.m_data.IsKindOf(((CaplChangeTreeItem*)item)->m_chng, m_doc->m_api.m_change_mgr.e_chng))
			change= ((CaplChangeTreeItem*)item)->m_chng;
				m_api->SaveChanges();
	}

	if(change && m_doc->m_api.m_data.IsKindOf(m_chng, m_doc->m_api.m_change_mgr.e_chng))
	{
		// Связывание пакетов изменений
		CMenu menu;  gSetPsmResourceHandle();
		CMenu* pPopup= NULL;
		VERIFY(menu.LoadMenu(IDR_PASTE_ITEM_MENU));
		pPopup = menu.GetSubMenu(INDEX_PASTE_CHANGE_MENU_1);
		if(0==pPopup) return false;

		BOOL res = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,	point->x, point->y, AfxGetMainWnd());

		if(res==ID_LINK_CHANGE)
		{
			CString sGroupCode1, sGroupCode2;
			m_doc->m_api.m_data.GetAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);
			m_doc->m_api.m_data.GetAttr(change, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode2);
			if(sGroupCode1==sGroupCode2 && sGroupCode1!=_T("")) {AfxMessageBox(APL_T("Изменения уже связаны!"),MB_OK|MB_ICONWARNING); return false; }

			if(sGroupCode2!=_T("") && sGroupCode1!=_T("")) {AfxMessageBox(APL_T("Связываемое изменение уже связанно с другим! Сначала для него надо удалить связь"),MB_OK|MB_ICONSTOP); return false; }

			CString sState1;
			m_doc->m_api.m_data.GetAttr(change, m_doc->m_api.m_change_mgr.a_chng_state, sState1);
			if(sState1==_T("applied")) {AfxMessageBox(APL_T("Изменение уже проведено, его нельзя связывать!"),MB_OK|MB_ICONSTOP); return false; }

			if(change->GetAccessmode()>aplRW || m_chng->GetAccessmode()>aplRW) {AfxMessageBox(APL_T("Нет доступа к связываемым изменениям!"),MB_OK|MB_ICONSTOP); return false; }


			if(sGroupCode1==_T("") && sGroupCode2==_T(""))
			{
				CaplAPI::CreateGuid(sGroupCode1);
				if(sGroupCode1==_T("")) {AfxMessageBox(APL_T("Ошибка создания GUID!"),MB_OK|MB_ICONSTOP); return false; }
				m_doc->m_api.m_data.PutAttr(change, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);
				m_doc->m_api.m_data.PutAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);
			}
			else if(sGroupCode1==_T(""))
			{
				m_doc->m_api.m_data.PutAttr(m_chng, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode2);
			}
			else m_doc->m_api.m_data.PutAttr(change, m_doc->m_api.m_change_mgr.a_chng_group_id, sGroupCode1);

			m_api->SaveChanges();

			CaplTreeItem* aplItem= NULL;
			InsertInstInTree(change,m_item,m_doc,m_tree,m_contents,0, &aplItem);
			return false;
		}
		if(res!=ID_CHANGE_CONTENT_COPY)return false;

	}

	
	if(change_item)
	{
		sMessage=  APL_T("Перенести изменение в выбранный пакет?");
		m_api->m_data.GetAttr(change_item, m_api->m_change_mgr.a_chng_item_of_chng, change_of_item);
	}
	else if(change)
	{
		change_of_item= change;
		sMessage=  APL_T("Перенести содержание изменения в выбранный пакет?");
	}

	if(!sMessage.IsEmpty())
	{
		if(sState==_T("applied")) return false;
		if(sState==_T("canceled")) return false;
		if(change_of_item==m_chng) return false;

		if(change_of_item->GetAccessmode()>aplRW || m_chng->GetAccessmode()>aplRW) 
		{
			AfxMessageBox( APL_T("Нет прав!"), MB_OK|MB_ICONSTOP);
			return false;
		}
		m_doc->m_api.m_data.GetAttr(change_of_item, m_doc->m_api.m_change_mgr.a_chng_state, sFrState);
		if(!m_doc->m_api.m_data.IsAdmin() && (sState!=_T("not_applied")||sFrState!=_T("not_applied")))
		{
			AfxMessageBox( APL_T("Изменение не находится в состоянии \"Разрабатывается\"!"), MB_OK|MB_ICONSTOP);
			return false;
		}
		
		if(IDYES==AfxMessageBox(sMessage, MB_YESNO|MB_ICONQUESTION))
		{
			aplExtent chng_items;
			aplExtent cur_chng_items;
			
			if(change_item)
				chng_items.Add(change_item);
			else if(change)
				m_api->m_data.GetAttr(change, m_api->m_change_mgr.a_chng_items, chng_items);

			for(i= 0; i<chng_items.GetSize(); i++)
				m_api->m_data.PutAttr(chng_items[i], m_api->m_change_mgr.a_chng_item_of_chng, m_chng);
			
			m_api->m_data.GetAttr(m_chng, m_api->m_change_mgr.a_chng_items, cur_chng_items);
			cur_chng_items.Append(chng_items);
			m_api->m_data.PutAttr(m_chng, m_api->m_change_mgr.a_chng_items, cur_chng_items);
			
			m_api->m_data.GetAttr(change_of_item, m_api->m_change_mgr.a_chng_items, cur_chng_items);
			for(i= 0; i<chng_items.GetSize(); i++)
				cur_chng_items.Remove(cur_chng_items.Find(chng_items[i]));
			m_api->m_data.PutAttr(change_of_item, m_api->m_change_mgr.a_chng_items, cur_chng_items);

			m_api->SaveChanges();
			
			RefreshAllChildItem();
			ShowChangeContent();
			Sort();

			if(change_item)
				m_doc->m_items.Remove(m_doc->m_items.Find(item));
			else
				item->CollapseItem();

			return true;	
		}
	}

	CaplInstance* pdf= NULL;
	CaplInstance* pdfChange= NULL;

	if(item->m_type==APL_TREE_ITEM_PRODUCT)
	{
		pdf= ((CaplProductTreeItem*)item)->m_pdf;
		pdfChange= ((CaplProductTreeItem*)item)->m_pdf;
	}

	if(pdf)
	{
		CMenu menu;  gSetPsmResourceHandle();
		CMenu* pPopup= NULL;

		VERIFY(menu.LoadMenu(IDR_PASTE_ITEM_MENU));
		CaplMenu::Install(m_tree);
		pPopup = menu.GetSubMenu(INDEX_REG_CHANGE_MENU);		
		
		POINT pnt;
		if(point==0)
		{
			RECT rect;
			m_tree->GetItemRect(m_item,&rect,TRUE);
			m_tree->ClientToScreen(&rect);
			pnt.x=rect.right;
			pnt.y=rect.bottom;
		}
		else
		{
			pnt.x=point->x;
			pnt.y=point->y;
		}

		aplExtent chngAssms;
		m_api->m_data.GetAttr(m_chng, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);
		CaplInstance* locker= NULL;
		m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_apl_pdf_locker, locker);
		CString sId;
	
		if(pdf->GetAccessmode()>aplRW)
		{
			pPopup->EnableMenuItem(ID_REG_CHANGE, MF_BYCOMMAND | MF_GRAYED);
		}
		if(sState==_T("applied") || sState==_T("canceled"))
		{
			pPopup->EnableMenuItem(ID_REG_CHANGE, MF_BYCOMMAND | MF_GRAYED);
			pPopup->RemoveMenu(ID_REPLACE_CHANGE, MF_BYCOMMAND);			
			pPopup->ModifyMenu(ID_EDIT_CHANGE, MF_BYCOMMAND, ID_EDIT_CHANGE,  APL_T("Просмотреть..."));
		}
		else if(sState==_T("approving"))
		{
			pPopup->ModifyMenu(ID_EDIT_CHANGE, MF_BYCOMMAND, ID_EDIT_CHANGE,  APL_T("Просмотреть..."));
			pPopup->EnableMenuItem(ID_REG_CHANGE, MF_BYCOMMAND | MF_GRAYED);
		}

		if(locker)
		{
			m_doc->m_api.m_data.GetAttr(locker, m_doc->m_api.m_change_mgr.a_chng_state, sFrState);
//			pPopup->EnableMenuItem(ID_REG_CHANGE, MF_BYCOMMAND | MF_GRAYED);
			if(locker==m_chng)
			{
				pPopup->ModifyMenu(ID_EDIT_CHANGE, MF_BYCOMMAND, ID_EDIT_CHANGE,  APL_T("Редактировать..."));
				pPopup->RemoveMenu(ID_REPLACE_CHANGE, MF_BYCOMMAND);			
			}
			else
			{
				m_api->m_data.GetAttr(locker, m_api->m_change_mgr.a_chng_id, sId);
				pPopup->ModifyMenu(ID_REPLACE_CHANGE, MF_BYCOMMAND, ID_REPLACE_CHANGE,  APL_T("Перенести из \"")+sId+_T("\""));
			}
		}
		else
		{
			pPopup->RemoveMenu(ID_REPLACE_CHANGE, MF_BYCOMMAND);			
		}

		BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON|TPM_RETURNCMD, pnt.x, pnt.y, m_tree);

		switch(res)
		{
			case ID_REG_CHANGE:
				{
					m_api->m_data.PutAttr(pdf, m_api->m_prd_mgr.a_apl_pdf_locker, m_chng);
					chngAssms.Add(pdf);
					m_api->m_data.PutAttr(m_chng, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);
					m_api->SaveChanges();
				}
				break;
			case ID_EDIT_CHANGE:
				{
					aplExtent items;
					if(m_api->m_change_mgr.ShowAssemblyChanges(pdf, m_chng, items))
					{
						RefreshAllChildItem();
						ShowChangeContent();
						MyExpand();
					}
				}
				break;
			case ID_REPLACE_CHANGE:
				{
					aplExtent items;
					aplExtent itemsCurChange;
					CaplInstance* basis_item= NULL;
					aplExtent itemsBasis;
					CString sDate;
					COleDateTime odt= COleDateTime::GetCurrentTime();

					if(IDYES==AfxMessageBox( APL_T("Вы действительно хотите перенести данные об изменении версии изделия в другой пакет изменений?"), MB_ICONQUESTION|MB_YESNO))
					{
						m_api->m_change_mgr.GetPdfChangeItems(pdf, locker, items);
						m_api->m_data.GetAttr(m_chng, m_api->m_change_mgr.a_chng_items, itemsCurChange);

						for(i= 0; i<itemsCurChange.GetSize(); i++)
						{
							if(!m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_psc) && 
								!m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_avc) &&
								!m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_char_change) &&
								!m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_abpc))
							{
								basis_item= items[i];
								break;
							}							
						}
												
						for(i= 0; i<items.GetSize(); i++)
						{
							if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_psc) || 
								m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_avc) ||
								m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_char_change))
							{
								m_api->m_data.PutAttr(items[i], m_api->m_change_mgr.a_chng_item_of_chng, m_chng);
								itemsCurChange.Add(items[i]);
							}
							else if(m_api->m_data.IsKindOf(items[i], m_api->m_change_mgr.e_basis_item))
							{
								if(!basis_item)
								{
									aplDate2String(odt, sDate);
									basis_item= m_api->m_data.CreateInstance(m_api->m_change_mgr.e_chng_item);
									if(basis_item)
									{
										m_api->m_data.PutAttr(basis_item, m_api->m_change_mgr.a_chng_item_dscr,  APL_T("Изменение расцеховки и норм расхода материалов"));
										m_api->m_data.PutAttr(basis_item, m_api->m_change_mgr.a_chng_item_user, m_api->m_data.GetNameCurrUser());
										m_api->m_data.PutAttr(basis_item, m_api->m_change_mgr.a_chng_item_autor, m_api->m_appr_mgr.GetCurrentPerson());
										m_api->m_data.PutAttr(basis_item, m_api->m_change_mgr.a_chng_item_accept_date, sDate);
										m_api->m_data.PutAttr(basis_item, m_api->m_change_mgr.a_chng_item_of_chng, m_chng);
									}
								}

								m_api->m_data.PutAttr(items[i], m_api->m_change_mgr.a_basis_item_parent, basis_item);
								m_api->m_data.GetAttr(basis_item, m_api->m_change_mgr.a_chng_item_item, itemsBasis);
								itemsBasis.Add(items[i]);
								m_api->m_data.PutAttr(basis_item, m_api->m_change_mgr.a_chng_item_item, itemsBasis);
							}
						}
						
						m_api->m_data.PutAttr(m_chng, m_api->m_change_mgr.a_chng_items, itemsCurChange);
						
						if(locker)
						{
							m_api->m_data.GetAttr(locker, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);
							chngAssms.Remove(chngAssms.Find(pdf));
							m_api->m_data.PutAttr(locker, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);

							m_api->m_data.PutAttr(pdf, m_api->m_prd_mgr.a_apl_pdf_locker, m_chng);
							
							m_api->m_data.GetAttr(m_chng, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);
							chngAssms.Add(pdf);
							m_api->m_data.PutAttr(m_chng, m_api->m_change_mgr.a_chng_changed_assemlies, chngAssms);

							m_api->m_data.GetAttr(locker, m_api->m_change_mgr.a_chng_items, itemsCurChange);
							for(i= 0; i<items.GetSize(); i++)
								itemsCurChange.Remove(itemsCurChange.Find(items[i]));
							m_api->m_data.PutAttr(locker, m_api->m_change_mgr.a_chng_items, itemsCurChange);
						}
						
						m_api->SaveChanges();
						ShowChangeContent();
						MyExpand();
					}
				}
				break;
			default: return true; break;
		}
	}
	return true;	
}

bool CaplChangeTreeItem::CheckOut()
{
	if(!m_doc->m_api.m_change_mgr.ReturnChangeToEdit(m_chng)) return false;

	m_doc->m_api.m_data.NET_SaveChanges();
	
	ShowProperties();
	return true;
}
