// PSMDoc.cpp : implementation of the CPSMDoc class
//

#include "stdafx.h"

#include "resource.h"
#include "PSM.h"
#include "defence.h"
//#include <aplMPC.h>
#include <finder.h>

#include "CommonClasses.h"
#include "ChildFrame.h"

#include "OptionsShowDlg.h"
#include "OptionsWorkDlg.h"

#include "PSMDoc.h"
#include "MainFrm.h"
#include "NavigatorView.h"

#include "TreeProductItem.h"
#include "aplTopLevelItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplTreeApprovalItem.h"
#include "aplDocTreeItem.h"
#include "aplFolderTreeItem.h"
#include "aplMessageTreeItem.h"
#include "aplMessageFolderTreeItem.h"
#include "aplBPTreeItem.h"
#include "aplChangeTreeItem.h"
#include "aplTreeTaskItem.h"
#include "apl_lot_item.h"
#include "apl_prd_inst_item.h"
#include "aplOrganizationTreeItem.h"
#include "aplClassifierTreeItem.h"
#include "aplQueryItem.h"
#include "aplRecAlertTreeItem.h"
#include "aplTreeProcessItem.h"
#include "aplPublicationTreeItem.h"

#include "TabView.h"
#include "ImportEfDlg.h"
#include "SubscriptionDlg.h"
#include "AddinSetupdlg.h"
#include "DocsListView.h"
#include "SetupShowonExpand.h"
#include "aplSocketTransport.h"

#include <AutoUpdate.h>

#ifdef ENABLE_ASH_MO
	#include "AshMoImportDialog.h"
#endif


//#include "ChooseCharacteristicsDlg.h"
//#include "ShowContentsDialog.h"
#include "gls_impDlg.h"

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


#define DEFAILT_ID_ADMIN_GROUP 3901

#define APL_ALP_LANG_CODE_RUSSIAN 0x419
#define APL_ALP_LANG_CODE_ENGLISH 0x409

CPSMDoc *GetActiveDocument()
{
	CMDIFrameWnd *mdiwnd =(CMDIFrameWnd*)AfxGetMainWnd();
	if(mdiwnd==0) return 0;
	CMDIChildWnd* wnd=mdiwnd->MDIGetActive();
	if(wnd==0)return 0;
	return (CPSMDoc*)wnd->GetActiveDocument();
}

//********************************************************************************
void GetAccessName(CaplInstance *inst,CString &buf)
{
	buf=_T("?");
	if(inst==0) return;
	if(inst->GetType()==0) return;
	if(inst->GetAccessmode()==aplOWN) buf= APL_T("Полный");
	else if(inst->GetAccessmode()==aplRW) buf= APL_T("Чтение и запись");
	else if(inst->GetAccessmode()==aplRO) buf= APL_T("Только чтение");
	else  buf= APL_T("Нет доступа");
}

static CString m_ExePath=_T("");

//********************************************************************************
void GetExePath(CString &path)
{
	path.Empty();
	if(m_ExePath==_T("")){
		HMODULE hModule;
		TCHAR szModuleName[2048];
		
		hModule = GetModuleHandle(NULL);
		if(hModule!=NULL)
		{
			if(GetModuleFileName(hModule, szModuleName, 2048)>0)
			{
				CString buf;
				buf= szModuleName;
				m_ExePath = buf.Left(buf.ReverseFind(_T('\\'))+1);
			}
		}
	}
	path=m_ExePath;
}


//********************************************************************************
void SetStatusString(LPCTSTR str,long wait_dlg)
{
	if(0!=wait_dlg) aplSetTextWaitDlg(wait_dlg,str);
	CMainFrame *frm=(CMainFrame*)AfxGetMainWnd();
	if(frm!=0) frm->SetStatusString(str);
}

//********************************************************************************
void getParam(LPCTSTR buf, LPCTSTR prefix, CString &param)
{
	param.Empty();
	if(prefix==0) return;
	if(buf==0) return;
	int k=_strlen(prefix);
	if(k<=0) return;
	TCHAR *buf1 = const_cast<TCHAR*>(_strstr(buf, prefix));
	if(buf1==0) return;
	buf1+=k;
	int i=0;
	while(buf1[i]!=_T('\0'))
	{
		if(buf1[i]==_T('/')) break;;
		param+=buf1[i];
		i++;
	}
	param.TrimRight(_T(' '));
}

//********************************************************************************
BOOL	CPSMDoc::m_dbl_click_prd_struct_expand_tree=FALSE;
BOOL	CPSMDoc::m_dbl_click_whereused_expand_tree=FALSE;
BOOL	CPSMDoc::m_show_inst_info=FALSE;
BOOL	CPSMDoc::m_bSortPrjByNumzak=FALSE;
BOOL	CPSMDoc::m_show_subst_in_nauo=FALSE;
BOOL	CPSMDoc::m_show_zagotov_in_nauo=FALSE;
BOOL	CPSMDoc::m_auto_show_sign_in_doc_ver=TRUE;
BOOL	CPSMDoc::m_show_revocated_approval=FALSE;
BOOL	CPSMDoc::m_show_saved_query_in_tree=TRUE;
DWORD	CPSMDoc::m_show_old_query_dlg=0;

/////////////////////////////////////////////////////////////////////////////
// CPSMDoc

IMPLEMENT_DYNCREATE(CPSMDoc, CDocument)

BEGIN_MESSAGE_MAP(CPSMDoc, CDocument)
	//{{AFX_MSG_MAP(CPSMDoc)
	ON_COMMAND(ID_REFRESH_ALL_TREE_ITEM, OnRefreshAllTreeItem)
	ON_COMMAND(ID_FILE_SAVE, OnFileSave)
	ON_COMMAND(ID_FILE_APPLOAD_FROM_FILE, OnFileApploadFromFile)
	ON_COMMAND(ID_DB_CONNECT, OnDbConnect)
	ON_COMMAND(ID_DB_FIND, OnDbFind)
	ON_COMMAND(ID_TEST, OnTest)
	ON_COMMAND(ID_CONFIGURE, OnConfigure)
	ON_COMMAND(ID_SHOW_VARIANT_RULE, OnShowVariantRule)
	ON_COMMAND(ID_SHOW_ALL_APPROVAL, OnShowAllApproval)
	ON_COMMAND(ID_SHOW_ALL_CHARACTERISTIC, OnShowAllCharacteristic)
	ON_COMMAND(ID_SHOW_ALL_DOCS, OnShowAllDocs)
	ON_COMMAND(ID_SHOW_PROPERTIES, OnShowProperties)
	ON_COMMAND(ID_SHOW_ALL_LOT, OnShowAllLot)
	ON_COMMAND(ID_SHOW_ALL_PRD_INST, OnShowAllPrdInst)
	ON_COMMAND(ID_RUN_IMPORTEF, OnRunImportef)
	ON_COMMAND(ID_PRODUCT_SHOW_EXPLOSION, OnProductShowExplosion)
	ON_COMMAND(ID_PRODUCT_SHOW_ALL_ZAGOTOV, OnProductShowAllZagotov)
	ON_COMMAND(ID_CREATE_PRODUCT, OnCreateProduct)
	ON_COMMAND(ID_CREATE_CHARACTERISTIC, OnProductCreateCharacteristic)
	ON_COMMAND(ID_CREATE_APPROVAL, OnCreateApproval)
	ON_COMMAND(ID_CREATE_DOC, OnCreateDoc)
	ON_COMMAND(ID_DIG_SUGN_SYS_SETUP, OnDigSugnSysSetup)
	ON_COMMAND(ID_OPTION_SELECT_DEF_CHARACTERYSTIC, OnOptionSelectDefCharacterystic)
	ON_UPDATE_COMMAND_UI(ID_OPTION_SELECT_DEF_CHARACTERYSTIC, OnUpdateOptionSelectDefCharacterystic)
	ON_COMMAND(ID_OPTION_SELECT_DEF_DOC_TYPE, OnOptionSelectDefDocType)
	ON_COMMAND(ID_DB_QUERY, OnDbQuery)
	ON_COMMAND(ID_DB_QUERY_OLD, OnDbQueryOld)
	ON_COMMAND(ID_DB_QUERY_PDF_PI_BP, OnDbQueryPdfPiBp)
	ON_COMMAND(ID_PDF_PI_BP_ANALIZE, OnPdfPiBpAnalize)
	ON_COMMAND(ID_PRODUCT_COMPARE, OnProductCompare)
	ON_COMMAND(ID_MESSAGE_DELIVER, OnMessageDeliver)
	ON_COMMAND(ID_NEW_MESSAGE_CREATE, OnNewMessageCreate)
	ON_COMMAND(ID_SHOW_ALL_VERSION, OnShowAllVersion)
	ON_COMMAND(ID_EXPAND_ALL, OnExpandAll)
	ON_COMMAND(ID_FILE_APPLOAD_FROM_PSS_FILE, OnFileApploadFromPssFile)
	ON_COMMAND(ID_EXPORT_ITEM, OnExportItem)
	ON_COMMAND(ID_CHANGE_PASSWORD, OnChangePassword)
	ON_COMMAND(ID_SHOW_SUBSCRIPTION, OnShowSubscription)
	ON_COMMAND(ID_SHOW_PERSON_ALERTS, OnShowPersonAlerts)
	ON_COMMAND(ID_IMP_GLOSS, OnImpGloss)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_DOCS, OnUpdateShowAllDocs)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_APPROVAL, OnUpdateShowAllApproval)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_CHARACTERISTIC, OnUpdateShowAllCharacteristic)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_LOT, OnUpdateShowAllLot)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_PRD_INST, OnUpdateShowAllPrdInst)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_VERSION, OnUpdateShowAllVersion)
	ON_UPDATE_COMMAND_UI(ID_PRODUCT_SHOW_ALL_ZAGOTOV, OnUpdateProductShowAllZagotov)
	ON_UPDATE_COMMAND_UI(ID_CREATE_DOC, OnUpdateCreateDoc)
	ON_UPDATE_COMMAND_UI(ID_CREATE_APPROVAL, OnUpdateCreateApproval)
	ON_UPDATE_COMMAND_UI(ID_CREATE_PRODUCT, OnUpdateProductCreateSubpart)
	ON_UPDATE_COMMAND_UI(ID_CREATE_CHARACTERISTIC, OnUpdateCreateCharacteristic)
	ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
	ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
	ON_COMMAND(ID_EDIT_CUT, OnEditCut)
	ON_COMMAND(ID_CREATE_BP, OnCreateBP)
	ON_UPDATE_COMMAND_UI(ID_CREATE_BP, OnUpdateCreateBP)
	ON_COMMAND(ID_SHOW_ALL_BP, OnShowAllBP)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_BP, OnUpdateShowAllBP)
	ON_COMMAND(ID_SHOW_ALL_BP_RESOURCE, OnShowAllBPResource)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_BP_RESOURCE, OnUpdateShowAllBPResource)
	ON_COMMAND(ID_DB_DISCONNECT, OnDbDisconnect)
	ON_COMMAND(ID_CREATE_WINDOW, OnCreateWindow)
	ON_COMMAND(ID_REFRESH_ALL, OnRefreshAll)
	ON_COMMAND(ID_ACTIVATE_MAIN_VIEW, OnActivateMainView)
	ON_COMMAND(ID_ITEM_CHECK_IN, OnItemCheckIn)
	ON_UPDATE_COMMAND_UI(ID_ITEM_CHECK_IN, OnUpdateItemCheckIn)
	ON_COMMAND(ID_ITEM_CHECK_OUT, OnItemCheckOut)
	ON_UPDATE_COMMAND_UI(ID_ITEM_CHECK_OUT, OnUpdateItemCheckOut)
	ON_COMMAND(ID_ITEM_UNDO_CHECK_OUT, OnItemUndoCheckOut)
	ON_UPDATE_COMMAND_UI(ID_ITEM_UNDO_CHECK_OUT, OnUpdateItemUndoCheckOut)
	ON_COMMAND(ID_ITEM_VIEW, OnItemView)
	ON_UPDATE_COMMAND_UI(ID_ITEM_VIEW, OnUpdateItemView)
	ON_COMMAND(ID_GET_DOCUMENT_LAST_VERSION, OnGetDocumentLastVersion)
	ON_UPDATE_COMMAND_UI(ID_GET_DOCUMENT_LAST_VERSION, OnUpdateGetDocumentLastVersion)
	ON_COMMAND(ID_SHOW_DOCUMENT_CHANGES, OnShowDocumentChanges)
	ON_UPDATE_COMMAND_UI(ID_SHOW_DOCUMENT_CHANGES, OnUpdateShowDocumentChanges)
	ON_COMMAND(ID_OPEN_ITEM_IN_NEW_WINDOW, OnOpenItemInNewWindow)
	ON_UPDATE_COMMAND_UI(ID_EXPAND_ALL, OnUpdateExpandAll)
	ON_UPDATE_COMMAND_UI(ID_DB_FIND, OnUpdateDbFind)
	ON_UPDATE_COMMAND_UI(ID_DB_QUERY, OnUpdateDbQuery)
	ON_UPDATE_COMMAND_UI(ID_DB_QUERY_OLD, OnUpdateDbQuery)
	ON_UPDATE_COMMAND_UI(ID_DB_QUERY_PDF_PI_BP, OnUpdateDbQueryPdfPiBp)
	ON_UPDATE_COMMAND_UI(ID_NEW_MESSAGE_CREATE, OnUpdateNewMessageCreate)
	ON_UPDATE_COMMAND_UI(ID_PRODUCT_COMPARE, OnUpdateProductCompare)
	ON_UPDATE_COMMAND_UI(ID_CONFIGURE, OnUpdateConfigure)
	ON_UPDATE_COMMAND_UI(ID_SHOW_VARIANT_RULE, OnUpdateShowVariantRule)
	ON_UPDATE_COMMAND_UI(ID_CREATE_WINDOW, OnUpdateCreateWindow)
	ON_UPDATE_COMMAND_UI(ID_OPEN_ITEM_IN_NEW_WINDOW, OnUpdateOpenItemInNewWindow)
	ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy)
	ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateEditPaste)
	ON_UPDATE_COMMAND_UI(ID_ACTIVATE_MAIN_VIEW, OnUpdateActivateMainView)
	ON_UPDATE_COMMAND_UI(ID_WINDOW_TILE_VERT, OnUpdateActivateMainView)
	ON_UPDATE_COMMAND_UI(ID_WINDOW_TILE_HORZ, OnUpdateActivateMainView)
	ON_UPDATE_COMMAND_UI(ID_SPLIT_HOR, OnUpdateActivateMainView)
	ON_UPDATE_COMMAND_UI(ID_SPLIT_VERT, OnUpdateActivateMainView)
	ON_UPDATE_COMMAND_UI(ID_SHOW_PROPERTIES, OnUpdateShowProperties)
	ON_UPDATE_COMMAND_UI(ID_REFRESH_ALL, OnUpdateRefreshAll)
	ON_UPDATE_COMMAND_UI(ID_REFRESH_ALL_TREE_ITEM, OnUpdateRefreshAllTreeItem)
	ON_UPDATE_COMMAND_UI(ID_CHANGE_PASSWORD, OnUpdateChangePassword)
	ON_UPDATE_COMMAND_UI(ID_SHOW_SUBSCRIPTION, OnUpdateShowSubscription)
	ON_UPDATE_COMMAND_UI(ID_SHOW_PERSON_ALERTS, OnUpdateShowPersonAlerts)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_DELIVER, OnUpdateMessageDeliver)
	ON_COMMAND(ID_TASK_DELIVER, OnTaskDeliver)
	ON_UPDATE_COMMAND_UI(ID_TASK_DELIVER, OnUpdateTaskDeliver)
	ON_COMMAND(ID_MY_OFFICIAL, OnMyOfficial)
	ON_COMMAND(ID_CREATE_BP_INST, OnCreateBpInst)
	ON_UPDATE_COMMAND_UI(ID_CREATE_BP_INST, OnUpdateCreateBpInst)
	ON_UPDATE_COMMAND_UI(ID_OPTION_SELECT_DEF_DOC_TYPE, OnUpdateOptionSelectDefDocType)
	ON_COMMAND(ID_SHOW_ALL_BP_INST, OnShowAllBpInst)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_BP_INST, OnUpdateShowAllBpInst)
	ON_COMMAND(ID_SETUP_ADDIN, OnSetupAddin)
	ON_COMMAND(ID_APLREP_TABLE_SETUP, OnReportTableSetup)
	ON_COMMAND(ID_SETUP_CHARACTIRISTIC, OnSetupCharactiristic)
	ON_COMMAND(ID_SHOW_NAME_OPTION, OnShowNameOption)
	ON_COMMAND(ID_OPTIONS_SHOW, OnOptionsShow)
	ON_COMMAND(ID_OPTIONS_WORK, OnOptionsWork)
	ON_COMMAND(ID_SHOW_NOTES, OnShowNotes)
	ON_UPDATE_COMMAND_UI(ID_SHOW_NOTES, OnUpdateShowNotes)
	ON_COMMAND(ID_CREATE_NOTE, OnCreateNote)
	ON_UPDATE_COMMAND_UI(ID_CREATE_NOTE, OnUpdateCreateNote)
	ON_COMMAND(ID_OPTIONS_SHOWINTREE, OnOptionsShowintree)
	ON_COMMAND(ID_SHOW_ALL_DOC_COPYES, OnShowAllDocCopyes)
	ON_UPDATE_COMMAND_UI(ID_SHOW_ALL_DOC_COPYES, OnUpdateShowAllDocCopyes)
	ON_COMMAND(ID_SHOW_MY_HARD_COPYES, OnShowMyDocCopyes)
	ON_UPDATE_COMMAND_UI(ID_SHOW_MY_HARD_COPYES, OnUpdateShowMyDocCopyes)
	ON_COMMAND(ID_SHOW_MY_OUT_OF_ORDER_COPYES, OnShowMyOutOfOrderDocCopyes)
	ON_UPDATE_COMMAND_UI(ID_SHOW_MY_OUT_OF_ORDER_COPYES, OnUpdateShowMyOutOfOrderDocCopyes)
	ON_COMMAND(ID_SHOW_OUT_OF_ORDER_DOC_COPYES, OnShowOutOfOrderCopyes)
	ON_UPDATE_COMMAND_UI(ID_SHOW_OUT_OF_ORDER_DOC_COPYES, OnUpdateShowOutOfOrderCopyes)
	ON_COMMAND(ID_CREATE_HARD_COPY, OnCreateHardCopy)
	ON_UPDATE_COMMAND_UI(ID_CREATE_HARD_COPY, OnUpdateCreateHardCopy)
	ON_COMMAND(ID_PERSONAL_MONITOR, OnPersonalMonitor)
	ON_UPDATE_COMMAND_UI(ID_PERSONAL_MONITOR, OnUpdatePersonalMonitor)
	ON_UPDATE_COMMAND_UI(ID_SETUP_CHARACTIRISTIC, OnUpdateSetupCharactiristic)
	ON_UPDATE_COMMAND_UI(ID_OPTIONS_WORK, OnUpdateOptionsWork)
	ON_UPDATE_COMMAND_UI(ID_PDF_PI_BP_ANALIZE, OnUpdateDbQueryPdfPiBp)
	ON_COMMAND(ID_SET_INST_ACCSESS, OnSetAccess)
	ON_UPDATE_COMMAND_UI(ID_SET_INST_ACCSESS, OnUpdateSetAccess)
	//}}AFX_MSG_MAP
	ON_COMMAND(ID_PERSONAL_OPTIONS, &CPSMDoc::OnPersonalOptions)
	ON_COMMAND(ID_ASH_MO_IMP, &CPSMDoc::OnAshMoImp)
	ON_COMMAND(ID_ASH_MO_VERIFY, &CPSMDoc::OnAshMoVerify)
	END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPSMDoc construction/destruction
//********************************************************************************
CPSMDoc::CPSMDoc()
{ 
	// TODO: add one-time construction code here
	//xm_list=0;

	m_tab_view=0;
	m_tick_connect=0;
	m_BShowInListCtrl=true;
	m_dbl_click_prd_struct_expand_tree=FALSE;
	m_dbl_click_whereused_expand_tree=FALSE;
	m_show_inst_info=FALSE;
	m_bSortPrjByNumzak=FALSE;
	m_bIsAdmin=true;
	m_bMainMenuInit= false;
	m_pCurrentConfiguration = NULL;

	m_user_incoming_folder= NULL;
	m_user_drafted_folder= NULL;
	m_user_sended_folder= NULL;

	m_AllCategLoaded=false;

	m_bUseProject=true;
	
	m_bCheckingAlerts= false;
	m_iTimerTick= 600000;
	
	m_pMainChildFrame = NULL;

	m_bShowMonitor= false;
	m_sMonitorText= _T("");
	m_hMonitorFlag= 0;

	m_b_show_categ=FALSE;

	TCHAR *csLibName;
#ifdef DEBUG
#ifdef UNICODE
	csLibName = _T("PersonalMonitor_ud.dll");
#else
	csLibName=_T("PersonalMonitorD.dll");
#endif
#else
#ifdef UNICODE
	csLibName = _T("PersonalMonitor_u.dll");
#else
	csLibName=_T("PersonalMonitor.dll");
#endif
#endif

	m_hMonitorDll	=NULL;
	m_fShowMonitor=NULL;

	m_hMonitorDll=AfxLoadLibrary(csLibName);
	if(NULL!=m_hMonitorDll)
	{
		(FARPROC&)m_fShowMonitor=::GetProcAddress(m_hMonitorDll,"ShowMonitor");
	}

	//////////////////////////////////////////////////////////////////////////
	
#ifdef _DEBUG
#ifdef UNICODE
	CString strLibFileName = CString("aplConfiguratorMgr_ud.dll");
#else
	CString strLibFileName = CString("aplConfiguratorMgrD.dll");
#endif
#else
#ifdef UNICODE
	CString strLibFileName = CString("aplConfiguratorMgr_u.dll");
#else
	CString strLibFileName = CString("aplConfiguratorMgr.dll");
#endif
#endif

	m_hConfigMgrLib = AfxLoadLibrary(strLibFileName);

	//////////////////////////////////////////////////////////////////////////


#ifdef _DEBUG
	m_api.m_data.SetErrorMessageMode(true);
//	m_api.m_data.SetWarningMessageMode(true);
#else
	m_api.m_data.SetErrorMessageMode(false);
	m_api.m_data.SetWarningMessageMode(false);
#endif

	LoadLocalOptonss();
	m_navigator=0;

	CString buf=AfxGetApp()->m_pszHelpFilePath;
	buf.MakeLower();
	CString old_hp=buf;
// 	buf.Replace(_T("psm.hlp"),_T("default_characteristic.txt"));
// 
// 	CStdioFile f;
// 	if(f.Open(LPCSTR(buf),CFile::modeCreate|CFile::modeNoTruncate|CFile::modeRead|CFile::typeText))
// 	{
// 		f.ReadString(buf);
// 		f.ReadString(buf);
// 		while(1)
// 		{
// 			if(!f.ReadString(buf)) break;
// 			buf.TrimLeft(_T(' '));
// 			buf.TrimRight(_T(' '));
// 			m_api.m_charact_mgr.m_sel_charact_names.Add(buf);
// 		}
// 		f.Close();
// 	}
// 	buf=old_hp;
// 	buf.Replace(_T("psm.hlp"),_T("default_doc_types.txt"));
// 
// 	if(f.Open(LPCSTR(buf),CFile::modeCreate|CFile::modeNoTruncate|CFile::modeRead|CFile::typeText))
// 	{
// 		f.ReadString(buf);
// 		f.ReadString(buf);
// 		while(1)
// 		{
// 			if(!f.ReadString(buf)) break;
// 			buf.TrimLeft(_T(' '));
// 			buf.TrimRight(_T(' '));
// 			m_sel_doc_types_names.Add(buf);
// 		}
// 		f.Close();
// 		m_api.m_doc_mgr.m_sel_doc_types_names.RemoveAll();
// 		m_api.m_doc_mgr.m_sel_doc_types_names.Append(m_sel_doc_types_names);
// 	}

	m_cur_context=0;
	m_next_alert= 0;
	
	m_RecAlert=0;
	m_DisAlert=0;

	m_nIndex= ID_PLUGIN_000;	
//	LoadPSMAddIns();
	LoadCharacteristicShow();
	m_api.m_folder_mgr.m_folders_map = &m_folders_map;
	m_api.m_wf_mgr= &m_wf_mgr;
	m_api.m_expl_mgr= &m_expl_mgr;
	
	//////////////////////////////////////////////////////////////////////////

	m_project_mgr= new CaplProjectManager;
	if(m_api.m_project_mgr)
	{
		delete m_api.m_project_mgr;
		m_api.m_project_mgr= NULL;
	}
	m_api.m_project_mgr= m_project_mgr;		

}
//********************************************************************************
CPSMDoc::~CPSMDoc()
{
	CMainFrame *wnd=(CMainFrame*)AfxGetMainWnd();
	if(wnd!=0) wnd->m_last_open_doc=0;

#ifdef ENABLE_ASH_MO
	if(m_api.m_data.IsConnected())
	{
		CString buf, sUserName=_T("Неизвестный");
		CaplInstance *curuser=m_api.m_appr_mgr.GetCurrentPerson();
		if(0!=curuser) m_api.m_appr_mgr.GetPersonName(curuser,sUserName,false);
		buf.Format(_T("\nПользователь %s Отключился от БД."),sUserName);
		WriteAshMoDBLog(&m_api,buf);
	}
#endif

	for(int i= 0; i<m_additional_ctrlbars.GetSize(); i++)
		delete m_additional_ctrlbars[i];
	m_additional_ctrlbars.RemoveAll();

	AfxGetApp()->WriteProfileInt(_T("options"),_T("m_b_show_categ"),m_b_show_categ);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("m_num_doc_4_group"),CaplTreeItem::m_num_doc_4_group);

//---------------
	AfxGetApp()->WriteProfileInt(_T("options"),_T("CatDescrShow"),CTabView::show_excel_view);
//---------

	AfxGetApp()->WriteProfileInt(_T("options"),_T("def_context_menu"),CaplTreeItem::m_def_context_menu);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("AutoCloseItem"),CNavigatorView::AutoCloseItem);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("DblclickViewDoc"),CNavigatorView::DblclickViewDoc);

	AfxGetApp()->WriteProfileInt(_T("options"),_T("dbl_click_prd_struct_expand_tree"),m_dbl_click_prd_struct_expand_tree);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("dbl_click_whereused_expand_tree"),m_dbl_click_whereused_expand_tree);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("show_inst_info"),m_show_inst_info);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("bSortPrjByNumzak"),m_bSortPrjByNumzak);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("show_subst_in_nauo"),m_show_subst_in_nauo);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("show_zagotov_in_nauo"),m_show_zagotov_in_nauo);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("m_auto_show_sign_in_doc_ver"),m_auto_show_sign_in_doc_ver);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("m_show_revocated_approval"),m_show_revocated_approval);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("show_saved_query_in_tree"),m_show_saved_query_in_tree);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("show_old_query_dlg"),m_show_old_query_dlg);
	
/*	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowId"),CaplProductTreeItem::m_ShowId);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowName"),CaplProductTreeItem::m_ShowName);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowPosition"),CaplProductTreeItem::m_ShowPosition);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowCount"),CaplProductTreeItem::m_ShowCount);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("PrdNoShowPlusToPart"),CaplProductTreeItem::m_PrdNoShowPlusToPart);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("m_PrdUnikByIdAndName"),CaplProductTreeItem::m_PrdUnikByIdAndName);

	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowDocId"),CaplDocTreeItem::m_bShowID);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowDocName"),CaplDocTreeItem::m_bShowName);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowDocVersion"),CaplDocTreeItem::m_bShowActiveVersion);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowDocType"),CaplDocTreeItem::m_bShowType);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowSelectAppDlg"),CaplDocTreeItem::m_bShowSelectAppDlg);*/
	AfxGetApp()->WriteProfileString(_T("options"),_T("WorkFolder"),CaplDocTreeItem::m_EditPath);

/*	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowCharacteristicValue"),CaplCharacteristicTreeItem::m_ShowValue);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowCharacteristicUnit"),CaplCharacteristicTreeItem::m_ShowUnit);

	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowApprovalStatus"),CaplApprovalTreeItem::m_ShowStatus);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowApprovalPesonRole"),CaplApprovalTreeItem::m_ShowPesonRole);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowApprovalPeson"),CaplApprovalTreeItem::m_ShowPerson);

	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowOrgId"),CaplApprovalTreeItem::m_ShowOrgId);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowOrgName"),CaplApprovalTreeItem::m_ShowOrgName);*/

	AfxGetApp()->WriteProfileInt(_T("options"),_T("AutoFrezeApproval"),CaplApprovalTreeItem::m_AutoFrezeApproval);

/*	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowCategId"),CaplCategoryTreeItem::m_bShowID);
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowCategName"),CaplCategoryTreeItem::m_bShowName);
	
	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowCharacterysticID_or_Name"),CaplCharacteristicTreeItem::m_ShowID_or_Name);*/
	AfxGetApp()->WriteProfileInt(_T("options"),_T("LbtnDblClick_Open"),(UINT)CaplTreeItem::m_LbDblClick_Open);

//	AfxGetApp()->WriteProfileString(_T("options"),_T("DocIdMask"),CaplDocManager::m_doc_id_mask);

	AfxGetApp()->WriteProfileInt(_T("options"),_T("CreateAssocFolderDoc"),CaplFolderManager::m_create_assoc_folder_doc);

/*	AfxGetApp()->WriteProfileInt(_T("options"), _T("ShowTaskComplete"), CaplTaskTreeItem::m_ShowCompleted);
	AfxGetApp()->WriteProfileInt(_T("options"), _T("ShowTaskSuspend"), CaplTaskTreeItem::m_ShowSuspended);
	AfxGetApp()->WriteProfileInt(_T("options"), _T("ShowTaskCancel"), CaplTaskTreeItem::m_ShowCanceled);*/

/*	if(m_api.m_bp_mgr.m_bShowId)
		AfxGetApp()->WriteProfileInt(_T("options"), _T("bBPShowId"), 1);
	else AfxGetApp()->WriteProfileInt(_T("options"),_T("bBPShowId"), 0);*/

/*	if(m_api.m_bp_mgr.m_bShowName)
		AfxGetApp()->WriteProfileInt(_T("options"), _T("bBPShowName"), 1);
	else AfxGetApp()->WriteProfileInt(_T("options"),_T("bBPShowName"), 0);

	if(m_api.m_bp_mgr.m_bShowType)
		AfxGetApp()->WriteProfileInt(_T("options"), _T("bBPShowType"), 1);
	else AfxGetApp()->WriteProfileInt(_T("options"),_T("bBPShowType"), 0);*/

	CString buf=AfxGetApp()->m_pszHelpFilePath;
	buf.MakeLower();
	CString old_hp=buf;
// 	buf.Replace(_T("psm.hlp"),_T("default_characteristic.txt"));
// 	CStdioFile f;
// 	if(f.Open(LPCSTR(buf),CFile::modeCreate|CFile::modeWrite|CFile::typeText))
// 	{
// 		f.WriteString( APL_T("Список характеристик для отображения:\n\n"));
// 		for(int i=0;i<m_api.m_charact_mgr.m_sel_charact_names.GetSize();i++)
// 		{
// 			f.WriteString(m_api.m_charact_mgr.m_sel_charact_names[i]);
// 			f.WriteString(_T("\n"));
// 		}
// 		f.Flush();
// 		f.Close();
// 	}
// 
// 	buf=old_hp;
// 	buf.Replace(_T("psm.hlp"),_T("default_doc_types.txt"));
// 	if(f.Open(LPCSTR(buf),CFile::modeCreate|CFile::modeWrite|CFile::typeText))
// 	{
// 		f.WriteString( APL_T("Список типов документов для отображения:\n\n"));
// 		for(int i=0;i<m_sel_doc_types_names.GetSize();i++)
// 		{
// 			f.WriteString(m_sel_doc_types_names[i]);
// 			f.WriteString(_T("\n"));
// 		}
// 		f.Flush();
// 		f.Close();
// 	}
	SaveFolders();

	if(m_hMonitorDll!=0) AfxFreeLibrary(m_hMonitorDll);
}

CNavigatorView *CPSMDoc::GetMyActiveView()
{
	if(m_navigator==0) return 0; // Ничено ни инициализировано
	if(m_navigator->m_hWnd==0) return 0;

	CMDIFrameWnd *mdifrm=(CMDIFrameWnd*)AfxGetMainWnd();
	if(mdifrm!=0)
	{
		CFrameWnd *frm=mdifrm->MDIGetActive();
		if(frm!=0)
		{
			CView *pView = 	frm->GetActiveView();
			if(pView && pView->IsKindOf(RUNTIME_CLASS(CNavigatorView))) return (CNavigatorView*)pView;
			if(pView) return (CNavigatorView*)pView;
			return NULL;
		}
	}
	return 0;
}

CaplTreeItem *CPSMDoc::GetSelItem()
{
	CNavigatorView *view=GetMyActiveView();
	if(view==0) return 0;
	return (CaplTreeItem*) view->GetSelectedItemData();
}
 
void CPSMDoc::LoadLocalOptonss()
{
	((CPSMApp*)AfxGetApp())->m_data=&m_api.m_data;
	int i;

#ifdef _UNICODE
	m_b_show_categ=false;
#else
	m_b_show_categ=AfxGetApp()->GetProfileInt(_T("options"),_T("m_b_show_categ"),FALSE);
#endif


	CaplTreeItem::m_num_doc_4_group=AfxGetApp()->GetProfileInt(_T("options"),_T("m_num_doc_4_group"),10);

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowId"),1);
	if(i==1)CaplProductTreeItem::m_ShowId=TRUE; else CaplProductTreeItem::m_ShowId=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowName"),1);
	if(i==1)CaplProductTreeItem::m_ShowName=TRUE; else CaplProductTreeItem::m_ShowName=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowPosition"),0);
	if(i==1)CaplProductTreeItem::m_ShowPosition=TRUE; else CaplProductTreeItem::m_ShowPosition=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowCount"),1);
	if(i==1)CaplProductTreeItem::m_ShowCount=TRUE; else CaplProductTreeItem::m_ShowCount=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("PrdNoShowPlusToPart"),1);
	if(i==1)CaplProductTreeItem::m_PrdNoShowPlusToPart=TRUE; else CaplProductTreeItem::m_PrdNoShowPlusToPart=FALSE;
	
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("CreateAssocFolderDoc"),0);
	if(i==1)CaplFolderManager::m_create_assoc_folder_doc=TRUE; else CaplFolderManager::m_create_assoc_folder_doc=FALSE;
	int opt=0;
	m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Настройка документов\\Запретить ассоциацию с папкой"),opt,0);
	if(1==opt) CaplFolderManager::m_create_assoc_folder_doc=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowDocId"),1);
	if(i==1)CaplDocTreeItem::m_bShowID=TRUE; else CaplDocTreeItem::m_bShowID=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowDocName"),1);
	if(i==1)CaplDocTreeItem::m_bShowName=TRUE; else CaplDocTreeItem::m_bShowName=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowDocVersion"),1);
	if(i==1)CaplDocTreeItem::m_bShowActiveVersion=TRUE; else CaplDocTreeItem::m_bShowActiveVersion=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowDocType"),1);
	if(i==1)CaplDocTreeItem::m_bShowType=TRUE; else CaplDocTreeItem::m_bShowType=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowSelectAppDlg"),0);
	if(i==1)CaplDocTreeItem::m_bShowSelectAppDlg=TRUE; else CaplDocTreeItem::m_bShowSelectAppDlg=FALSE;
	CaplDocTreeItem::m_EditPath=AfxGetApp()->GetProfileString(_T("options"),_T("WorkFolder"));

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowCharacteristicValue"),1);
	if(i==1)CaplCharacteristicTreeItem::m_ShowValue=TRUE; else CaplCharacteristicTreeItem::m_ShowValue=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowCharacteristicUnit"),1);
	if(i==1)CaplCharacteristicTreeItem::m_ShowUnit=TRUE; else CaplCharacteristicTreeItem::m_ShowUnit=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowApprovalStatus"),1);
	if(i==1)CaplApprovalTreeItem::m_ShowStatus=TRUE; else CaplApprovalTreeItem::m_ShowStatus=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowApprovalPesonRole"),1);
	if(i==1)CaplApprovalTreeItem::m_ShowPesonRole=TRUE; else CaplApprovalTreeItem::m_ShowPesonRole=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowApprovalPeson"),1);
	if(i==1)CaplApprovalTreeItem::m_ShowPerson=TRUE; else CaplApprovalTreeItem::m_ShowPerson=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("def_context_menu"),0);
	if(i==1)CaplTreeItem::m_def_context_menu=TRUE; else CaplTreeItem::m_def_context_menu=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("AutoCloseItem"),0);
	if(i==1)CNavigatorView::AutoCloseItem=TRUE; else CNavigatorView::AutoCloseItem=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("DblclickViewDoc"),0);
	CNavigatorView::DblclickViewDoc=(i==1);
	m_api.m_show.m_doc__view_on_dblclick = CNavigatorView::DblclickViewDoc;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowOrgId"),0);
	if(i==1)CaplApprovalTreeItem::m_ShowOrgId=TRUE; else CaplApprovalTreeItem::m_ShowOrgId=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowOrgName"),1);
	if(i==1)CaplApprovalTreeItem::m_ShowOrgName=TRUE; else CaplApprovalTreeItem::m_ShowOrgName=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("AutoFrezeApproval"),0);
	if(i==1)CaplApprovalTreeItem::m_AutoFrezeApproval=TRUE; else CaplApprovalTreeItem::m_AutoFrezeApproval=FALSE;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowCategId"),0);
	if(i==1)CaplCategoryTreeItem::m_bShowID=TRUE; else CaplCategoryTreeItem::m_bShowID=FALSE;
	i=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowCategName"),1);
	if(i==1)CaplCategoryTreeItem::m_bShowName=TRUE; else CaplCategoryTreeItem::m_bShowName=FALSE;

	CaplCharacteristicTreeItem::m_ShowID_or_Name=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowCharacterysticID_or_Name"),0);

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("LbtnDblClick_Open"),1);
	if(i==1)CaplTreeItem::m_LbDblClick_Open=true;
	else CaplTreeItem::m_LbDblClick_Open=false;

	m_dbl_click_prd_struct_expand_tree=AfxGetApp()->GetProfileInt(_T("options"),_T("dbl_click_prd_struct_expand_tree"),FALSE);
	m_dbl_click_whereused_expand_tree=AfxGetApp()->GetProfileInt(_T("options"),_T("dbl_click_whereused_expand_tree"),FALSE);
	m_show_inst_info=AfxGetApp()->GetProfileInt(_T("options"),_T("show_inst_info"),FALSE);
	m_bSortPrjByNumzak=AfxGetApp()->GetProfileInt(_T("options"),_T("bSortPrjByNumzak"),FALSE);
	m_show_subst_in_nauo=AfxGetApp()->GetProfileInt(_T("options"),_T("show_subst_in_nauo"),FALSE);
	m_show_zagotov_in_nauo=AfxGetApp()->GetProfileInt(_T("options"),_T("show_zagotov_in_nauo"),FALSE);
	m_auto_show_sign_in_doc_ver=AfxGetApp()->GetProfileInt(_T("options"),_T("m_auto_show_sign_in_doc_ver"),TRUE);
	m_show_revocated_approval=AfxGetApp()->GetProfileInt(_T("options"),_T("m_show_revocated_approval"),FALSE);
	m_show_saved_query_in_tree=AfxGetApp()->GetProfileInt(_T("options"),_T("show_saved_query_in_tree"),TRUE);
	m_show_old_query_dlg=AfxGetApp()->GetProfileInt(_T("options"),_T("show_old_query_dlg"),0);

//	CProductDlg::m_mask=AfxGetApp()->GetProfileString(_T("options"),_T("PrdIdMask"));
//	CaplDocManager::m_doc_id_mask=AfxGetApp()->GetProfileString(_T("options"),_T("DocIdMask"));
	
	i= AfxGetApp()->GetProfileInt(_T("options"), _T("ShowTaskComplete"), 0);
	if(i) CaplTaskTreeItem::m_ShowCompleted= true;
	else CaplTaskTreeItem::m_ShowCompleted= false;
	i= AfxGetApp()->GetProfileInt(_T("options"), _T("ShowTaskSuspend"), 0);
	if(i) CaplTaskTreeItem::m_ShowSuspended= true;
	else CaplTaskTreeItem::m_ShowSuspended= false;
	i= AfxGetApp()->GetProfileInt(_T("options"), _T("ShowTaskCancel"), 0);
	if(i) CaplTaskTreeItem::m_ShowCanceled= true;
	else CaplTaskTreeItem::m_ShowCanceled= false;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("bBPShowId"),1);
	if(i==1)CaplBPManager::m_bShowId=true;
	else CaplBPManager::m_bShowId=false;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("bBPShowName"),1);
	if(i==1)CaplBPManager::m_bShowName=true;
	else CaplBPManager::m_bShowName=false;

	i=AfxGetApp()->GetProfileInt(_T("options"),_T("bBPShowType"),0);
	if(i==1)CaplBPManager::m_bShowType=true;
	else CaplBPManager::m_bShowType=false;
	
	i = AfxGetApp()->GetProfileInt(_T("options"),_T("CatDescrShow"),0);
	if(i==0) CTabView::show_excel_view = false;
	else CTabView::show_excel_view = true;

	CaplWorkFlowManager::LoadOptions();
}
//***************************************************************************

void CPSMDoc::LoadGlobalOptonss()
{

	int PrdUnikByIdAndName=FALSE;
	if(m_api.m_data.IsConnected()) m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Уникальность изделия проверять по комбинации обозначения и наименования"),PrdUnikByIdAndName);
}

//********************************************************************************
void CPSMDoc::OnDbDisconnect() 
{

#ifdef ENABLE_ASH_MO
	if(m_api.m_data.IsConnected())
	{
		CString buf,  sUserName=_T("Неизвестный");
		CaplInstance *curuser=m_api.m_appr_mgr.GetCurrentPerson();
		if(0!=curuser) m_api.m_appr_mgr.GetPersonName(curuser,sUserName,false);
		buf.Format(_T("\nПользователь %s отключился от БД."),sUserName);
		WriteAshMoDBLog(&m_api,buf);
	}
#endif

	if(FALSE==SaveModified()) return;
	SaveFolders();
	OnActivateMainView();
	if(m_tab_view!=0) m_tab_view->Update(0);
	if(m_api.m_data.IsConnected()) m_api.Disconnect();
	if(m_tab_view!=0) m_tab_view->m_UpdateMode=false;
    if(m_navigator!=0)
	{
		m_navigator->SetRedraw(FALSE);
		((CChildFrame*)m_navigator->GetParentFrame())->DeleteSplitters();
	}
	m_BShowInListCtrl=false;
	m_items.Clear();
	
	m_BShowInListCtrl=true;
	m_AllCategLoaded=false;
	
	// Убрать дополнительные виды
	int i = 0;
removing_additional_framers:
 	try
 	{
		for(;i<m_additional_frames.GetSize();i++)
		{
			if(m_additional_frames[i]==NULL) continue;
			if(!::IsWindow(m_additional_frames[i]->m_hWnd)) continue;
			if(m_additional_frames[i]->IsKindOf(RUNTIME_CLASS(CChildFrame)))
				delete m_additional_frames[i];
			else
				m_additional_frames[i]->DestroyWindow();
		}
 	}
 	catch(...)
 	{
 		if(i<m_additional_frames.GetSize())
 			m_additional_frames.RemoveAt(i);
		if(i<m_additional_frames.GetSize())
			goto removing_additional_framers;
 	}
	m_additional_frames.RemoveAll();
	m_additional_views.RemoveAll();
	
	m_incoming_messages.Clear();
	m_send_or_dr_messages.Clear();

	if(m_navigator!=0)m_navigator->SetRedraw(TRUE);
	if(m_navigator!=0)m_navigator->m_queries_item=0;
	m_cur_context=0;

	if(m_tab_view!=0) m_tab_view->m_UpdateMode=true;
	CMainFrame *wnd=(CMainFrame*)AfxGetMainWnd();
	if(wnd!=0) wnd->m_last_open_doc=this;
	if(m_navigator!=0)m_navigator->RedrawWindow();
	
	UINT msg = ((CPSMApp*)AfxGetApp())->m_view_disconnect;
	for(i= 0; i<m_addin_tab_views.GetSize(); i++)
	{
		if(aplTab==m_addin_tab_views.GetAt(i)->viewtype)
			::SendMessage(m_addin_tab_views.GetAt(i)->view->m_hWnd, msg, 3, 0);	
	}

	SetTitle( APL_T("Соединение не установлено"));
}
//********************************************************************************
BOOL CPSMDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument()) return FALSE;
	
	CMainFrame *wnd=(CMainFrame*)AfxGetMainWnd();
	if(wnd && !m_bMainMenuInit){
		m_bMainMenuInit= true;
//		wnd->AppendMainMenu(this);
	}
	
	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CPSMDoc diagnostics

#ifdef _DEBUG
void CPSMDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CPSMDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CPSMDoc commands
//********************************************************************************
BOOL CPSMDoc::OnOpenDocument(LPCTSTR lpszPathName) 
{
//	CView *pview=0;
//	POSITION pos=GetFirstViewPosition();
//	if(pos!=0){
//		do{
//			pview=GetNextView(pos);
//			if(pview!=0){
//				if(pview->GetParentFrame()->IsKindOf(RUNTIME_CLASS(CChildFrame))){
//					CMenu* pSysMenu = pview->GetParentFrame()->GetSystemMenu(FALSE);
//					if (pSysMenu != NULL)
//					{
//						pSysMenu->EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
//					}
//					
//				}
//			}
//		}while(pos!=0);
//		
//	}
//
	OnDbDisconnect();
	CString buf=lpszPathName;

	if(buf==_T("")) return FALSE;

	if(buf[buf.GetLength()-1]==_T('*'))
	{
		if(!DbConnect())
			return FALSE;
	}
	else
	{
		if (!CDocument::OnOpenDocument(lpszPathName))
			return FALSE;

		if(!m_api.m_data.LoadFromFile(lpszPathName))return FALSE;
		m_api.Init();
		m_wf_mgr.Attach(&m_api);
		m_exchng_mgr.Attach(&m_api);
		m_fault_mgr.Attach(&m_api);

		CMainFrame *wnd=(CMainFrame*)AfxGetMainWnd();
		if(wnd!=0) wnd->m_last_open_doc=this;
	}
	
	CMainFrame *wnd=(CMainFrame*)AfxGetMainWnd();
	if(wnd && !m_bMainMenuInit){
		m_bMainMenuInit= true;
//		wnd->AppendMainMenu(this);
	}
	
	return TRUE;
}
//********************************************************************************
void CPSMDoc::SetTitle( LPCTSTR lpszPathName)
{
	CString title, buf;

	buf=((CMainFrame*)AfxGetMainWnd())->m_sModuleName;
	if(buf==_T("")) buf.LoadString(AFX_IDS_APP_TITLE);
	if(m_api.m_data.GetNameCurrBase()==_T(""))
	{
//		CDocument::SetTitle(lpszPathName);
		buf +=  APL_T(" - [Соединение не установлено]");
	}
	else
	{
//		title.Format(APL_T("База \'%s\' Пользователь \'%s\'"),
//			m_api.m_data.GetNameCurrBase(),m_api.m_data.GetNameCurrUser());
		title=m_api.m_data.GetTitulCurrBD(true,true,true,true,false);
//		CDocument::SetTitle(title);
		buf +=_T(" - [")+title+_T("]");
	}
	AfxGetMainWnd()->SetWindowText(buf);
}
//********************************************************************************
BOOL CPSMDoc::OnSaveDocument(LPCTSTR lpszPathName) 
{
	// TODO: Add your specialized code here and/or call the base class
    m_api.m_data.SaveToTextFile(lpszPathName);
	SetModifiedFlag(FALSE);
    return TRUE;
	//return CDocument::OnSaveDocument(lpszPathName);
}
//********************************************************************************
void CPSMDoc::OnRefreshAllTreeItem() 
{
	m_navigator->SetRedraw(FALSE);

	CTreeCtrl &tree = m_navigator->aplGetTreeCtrl();
	HTREEITEM ht = tree.GetRootItem();
	HTREEITEM categht=0;
	HTREEITEM orght=0;
	CaplTreeItem *item=0,*item_org=0,*item_classif=0;
	if(ht) item = (CaplTreeItem*)tree.GetItemData(ht);
	while(ht)
	{
		ht = tree.GetNextItem(ht,TVGN_NEXT);
		item = 0;
		if(ht) item = (CaplTreeItem*)tree.GetItemData(ht);
		if(item)
		{
			if(item->m_type==APL_TREE_ITEM_ORGANIZATION){item_org=item;orght= ht;}
			if(item->m_type==APL_TREE_ITEM_CLASSIFIERSYSTEM){item_classif=item;}
			if(item->m_type==APL_TREE_ITEM_CATEGORIES) categht = ht;
		}
	}
	
	// для начала велим серверу перечитать список шаблонов
	m_api.m_data.NET_RefreshAccessPatterns();

	if(!m_api.m_show.m_show_org_struct && item_org!=0)
	{
		item_org->CollapseItem();
		m_items.Remove(m_items.Find(item_org));
	}
	else if(item_org==0 && m_api.m_show.m_show_org_struct)
	{
		CaplOrganizationTreeItem *item =  new CaplOrganizationTreeItem(&tree,this);
		item->CreateTreeItem(TVI_ROOT);
		if(categht)
		{
			CaplTreeItem *data = (CaplTreeItem*)tree.GetItemData(item->m_item);
			HTREEITEM old = item->m_item;
			int ic1, ic2;
			CString txt;
			tree.GetItemImage(item->m_item,ic1,ic2);
			txt = tree.GetItemText(item->m_item);
			tree.DeleteItem(old);
			old = tree.InsertItem(txt,ic1,ic2,TVI_ROOT,categht);
			item->m_fictive_item = tree.InsertItem(_T("fictive"),old);
			item->m_item = old;
			tree.SetItemData(old,(DWORD)data);
			orght=old;
		}
	}
	
	if(!m_api.m_show.m_show_classificators && item_classif!=0)
	{
		item_classif->CollapseItem();
		m_items.Remove(m_items.Find(item_classif));
	}
	else if(item_classif==0 && m_api.m_show.m_show_classificators)
	{
		CaplClassifierTreeItem *item =  new CaplClassifierTreeItem(&tree,this);
		item->CreateTreeItem(TVI_ROOT);
		if(orght!=0){ht=orght;}else{ht=categht;}
		if(ht!=0)
		{
			CaplTreeItem *data = (CaplTreeItem*)tree.GetItemData(item->m_item);
			HTREEITEM old = item->m_item;
			int ic1, ic2;
			CString txt;
			tree.GetItemImage(item->m_item,ic1,ic2);
			txt = tree.GetItemText(item->m_item);
			tree.DeleteItem(old);
			old = tree.InsertItem(txt,ic1,ic2,TVI_ROOT,ht);
			item->m_fictive_item = tree.InsertItem(_T("fictive"),old);
			item->m_item = old;
			tree.SetItemData(old,(DWORD)data);
		}
	}
	int i;
	TRACE(_T("m_additional_views\n"));
	for(i=0; i<m_additional_views.GetSize();i++)
	{
		if(m_additional_views[i]->m_hWnd!=0)
				m_additional_views[i]->SetRedraw(FALSE);
	}
	TRACE(_T("m_items\n"));
	for(i=0; i<m_items.Size;i++)
	{
		// из-за ShowContents в RefreshItem этих Item'ов PSM не может проморгаться
		// несколько минут при обновлении наименований...
		// наверное, надо убрать ShowContents из RefreshItem и как-нибудь по-другому
		// обновлять содержимое этих Items (отдельно наименования и иконки, отдельно содержимое)
		// Я трогать это не стал.
		if(!m_items[i]->m_type.CompareNoCase(_T("ClassifierLevel"))) continue;
		if(!m_items[i]->m_type.CompareNoCase(_T("ClassifierSystem"))) continue;

		//TRACE(_T("m_items %s\n"), m_items[i]->m_type);
		m_items[i]->RefreshItem();
	}	
	//TRACE(_T("m_additional_views\n"));
	for(i=0; i<m_additional_views.GetSize();i++)
	{
		if(m_additional_views[i]->m_hWnd!=0)
				m_additional_views[i]->SetRedraw(TRUE);
	}
	m_navigator->SetRedraw(TRUE);
	UpdateAllViews(m_navigator);
}
void CPSMDoc::OnRefreshAll() 
{
	InitialLoad();
	OnRefreshAllTreeItem();
	ShowUserAlerts((CMainFrame*)AfxGetMainWnd());
}
//********************************************************************************
void CPSMDoc::OnFileSave() 
{
	if(m_api.m_data.IsConnected()){ if(m_api.m_data.NET_SaveChanges()) SetModifiedFlag(FALSE);}
	else DoSave(NULL,TRUE);
}
//********************************************************************************
BOOL CPSMDoc::DoSave(LPCTSTR lpszPathName, BOOL bReplace)
{
	CString FileName;
	TCHAR*  lpszDefExt=_T("");
	TCHAR* szStepFilter = _T("STEP Data Files (*.std)|*.std|")
						_T("JSON Files (*.json)|*.json|") 
						_T("STEP Text Files (*.txt)|*.txt|") 
						_T("STEP Files (*.stp)|*.stp|")
		_T("All Files (*.*)|*.*||");

	CFileDialog dlgFile(FALSE, _T("std"),lpszPathName,
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT|OFN_EXTENSIONDIFFERENT,szStepFilter);

	if(dlgFile.DoModal() == IDOK)
	{
		CString ext=dlgFile.GetFileExt();
		FileName=dlgFile.GetPathName( );
		
		aplP21Header header;
		if(ext==_T("stp")) m_api.m_data.SaveP21(FileName,header);
		else if(ext==_T("json"))
		{
			m_api.m_data.m_Default_TextFormat=false;
			m_api.m_data.SaveToJsonFile(FileName);
		}
		else if(ext==_T("txt"))
		{
			m_api.m_data.m_Default_TextFormat=true;
			m_api.m_data.SaveToTextFile(FileName);
		}
		else if(ext==_T("std"))
		{
			m_api.m_data.m_Default_TextFormat=false;
			m_api.m_data.SaveToFile(FileName);
		}
		else m_api.m_data.SaveToTextFile(FileName);
    
		SetModifiedFlag(FALSE);
		if(!m_api.m_data.IsConnected())SetPathName(FileName);
	}
	return TRUE;        // success
}
//********************************************************************************
bool CPSMDoc::InitialLoad()
{
	CaplEntity *ent=0, *ent1=0;
	CaplAttr *attr;

	if(!m_api.m_data.IsConnected()) return true;

	long trd=aplStartWaitDlg(_T(""), APL_T("Загрузка словарей"));

	try
	{
		SetStatusString( APL_T("Чтение оргструктуры"),trd);	m_api.m_appr_mgr.LoadOrgStruct();

		SetStatusString( APL_T("Чтение характеристик"),trd);m_api.m_charact_mgr.LoadDictionary();
		m_api.m_unit_exch_mgr.InitUnitsBases();
		
		SetStatusString( APL_T("Чтение контекстов"),trd);m_api.m_charact_mgr.LoadContextInfo();
		SetStatusString( APL_T("Чтение сортамента"),trd);m_api.m_prd_mgr.LoadAssortment();
		SetStatusString( APL_T("Чтение иностранных языков"),trd);m_api.m_prd_mgr.LoadDictionary();
		// Чтение типов ресурсов
		SetStatusString( APL_T("Чтение типов бизнес-процессов"),trd);
		m_api.m_bp_mgr.LoadDictionary();

		CaplLoadData ld(&m_api.m_data,DEF_SOURCE);
		int i;
		// Чтение типов документов
		SetStatusString( APL_T("Чтение типов документов"),trd);
		m_api.m_doc_mgr.LoadDictionary();

		SetStatusString( APL_T("Чтение маршрутов"),trd);
		i=ld.AddQuery(_T('e'), 0, m_wf_mgr.e_proc_tmpl,0, true,true);
		if (!ld.LoadEx(true,0, APL_T("Чтение маршрутов")))AfxMessageBox(IDS_ERROR_LOAD_DATA_APL,MB_OK|MB_ICONSTOP);
		ld.ClearQuery();

		// Чтение текущего User-a
		CaplInstance *inst=m_api.m_data.GetCurrUser();
		if(inst!=0)
		{
			SetStatusString( APL_T("Чтение текущего пользователя"),trd);
			attr=m_api.m_appr_mgr.a_apl_user_po;
			ld.AddQuery(_T('i'), inst->GetId(), 0,attr, true);
			if (!ld.LoadEx())AfxMessageBox(IDS_ERROR_LOAD_DATA_APL,MB_OK|MB_ICONSTOP);
			ld.ClearQuery();
		}
		// Чтение типов проектов
		SetStatusString( APL_T("Чтение типов проектов"),trd);
		m_api.m_options_mgr.LoadDictionary();
		m_api.m_project_mgr->LoadDictionary();

		//SetStatusString( APL_T("Чтение пользовательских форм"),trd);
		//LoadFormsData(); Убрана поддержка форм им. Орлова

		int iVal=0;

		if(1==m_api.m_options_mgr.GetIntOptionValueBN( APL_NO_T("Изделия\\Запретить создание и изменение атрибутов изделий"),0))
		{
			//if(!m_api.m_prd_mgr.IsAdmin()) //ЯАИ:  01.12.2014 Админиу тоже нельзя (Если включать то не для ГРПЗ) 
				m_api.m_prd_mgr.bNoCreateAndChangePDF=true;
		}
		else 
		{
			m_api.m_prd_mgr.bNoCreateAndChangePDF=false;
			CString sRole;
			m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Изделия\\Роль для создания и изменения атрибутов изделий"),sRole);
			if(sRole!=_T(""))
			{
				if(!m_api.m_appr_mgr.CheckPersonRole(0,sRole))m_api.m_prd_mgr.bNoCreateAndChangePDF=true;
			}
		}

		// Режим работы с неисправностями
		{
			m_fault_mgr.m_bReadOnly=false;
			CString opt;
			m_api.m_options_mgr.GetOptionValueBN(APL_NO_T("Надежность\\Роль для ввода неисправностей"), opt, _T(""));
			if(opt!=_T(""))
			{
				if(!m_api.m_appr_mgr.CheckPersonRole(0,opt)) m_fault_mgr.m_bReadOnly=true;
			}

			/*m_api.m_options_mgr.GetOptionValueBN(APL_NO_T("Надежность\\Роль для просмотра неисправностей"), opt, _T(""));
			if(opt!=_T(""))
			{
				if(m_api.m_appr_mgr.CheckPersonRole(0,opt)) return true;
				return false;
			}*/
			m_fault_mgr.LoadClassifiers();
		}

		// Чтение публикаций
		//SetStatusString(APL_T("Чтение публикаций")); m_tg_mgr.LoadModulesStruct();

		//Построение карты групп видов документов
		m_map_dt_dg.Clear();
		aplExtent ext_dg, ext_dt;
		int j;
		m_api.m_data.GetEntityExtent(m_api.m_doc_mgr.e_dt_group,ext_dg);
		for(i=0;i<ext_dg.GetSize();i++)
		{
			CaplInstance *dg=ext_dg[i];
			if(dg->IsDeleted()) continue;
			m_api.m_data.GetAttr(dg,m_api.m_doc_mgr.a_dt_group_content,ext_dt);

			for(j=0;j<ext_dt.GetSize();j++)
			{
				CaplInstance *dt=ext_dt[j];
				if(dg->IsDeleted()) continue;

				int k=m_map_dt_dg.QFindByIn((long)dt);
				if(k<0) m_map_dt_dg.Add((long)dt,(long)dg);
				else
				{
					// Документ относится к нескольким группам
					m_map_dt_dg.Data[k].out=-1;
				}
			}
		}
	}
	catch(...)
	{

	}
	aplEndWaitDlg(trd);
	SetStatusString(_T(""));
	return true;
}
//********************************************************************************
BOOL CPSMDoc::SaveModified() 
{
	bool modified=m_api.m_data.CheckModified();
	if(modified)
	{
		OnFileSave();
		//int k=AfxMessageBox(APL_T("Сохранить изменения ?"),MB_YESNOCANCEL);
		//if(k==IDYES) OnFileSave();
		//else if(k==IDCANCEL) return FALSE;
	}
	return TRUE;
	//return CDocument::SaveModified();
}
//********************************************************************************
void CPSMDoc::OnFileApploadFromFile() 
{
	// Проверка доступа
	CString buf,sRole;
	m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для импорта данных"), sRole, _T(""));
	if(sRole!=_T(""))
	{
		if(!m_api.m_appr_mgr.CheckPersonRole(0,sRole))
		{
			buf.Format( APL_T("Вы не обладаете ролью \"%s\", необходимой для выполнения функции."),LPCTSTR(sRole));
			AfxMessageBox(buf,MB_OK|MB_ICONSTOP);
			return;
			
		}
	}

	if(IDYES!=AfxMessageBox(APL_T("Данная функция является системной !!!\n\nЕе неправильное использование может привести к уничтожению данных !!!\n\nВы действительно хотите ее использовать ?"),
		MB_YESNO|MB_ICONSTOP|MB_DEFBUTTON2)) return;
	
	buf=_T("StepData Files (*.std)|*.std|Text Files (*.txt)|*.txt|JSON Files (*.json)|*.json|All Files (*.*)|*.*||");

	CFileDialog FileDlg(TRUE, _T(""), NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, buf);
	if (FileDlg.DoModal() != IDOK) return;

	int i,j;
	CaplStepData data;
	data.LoadDictionary(LPCTSTR(m_api.m_data.m_CurSchema));
	CaplDataBuf dbuf;
	if(!data.LoadFromFile(LPCTSTR(FileDlg.GetPathName()))) 
	{
		AfxMessageBox(APL_T("Ошибка открытия файла!"),MB_OK|MB_ICONSTOP);
		return;
	}
	for(i=0;i<data.instances.Size;i++)
	{
		data.instances[i]->SetId(0);
		data.instances[i]->SetAccessmode(aplOWN);
	}
	data.SaveToDataBuf(dbuf);
	data.ClearData();
	m_api.m_data.ApploadFromDataBuf(dbuf);
	for(i=0;i<m_api.m_data.instances.Size;i++)
	{
		if(m_api.m_data.instances[i]->attrs==0)continue;
		if(m_api.m_data.instances[i]->GetType()==0)continue;
		for(j=0;j<m_api.m_data.instances[i]->GetType()->all_attrs.Size;j++)
		{
			m_api.m_data.instances[i]->attrs[j].changed=true;
		}
	}
	m_api.SaveChanges();
	AfxMessageBox(APL_T("Готово!"));
}
//********************************************************************************
void CPSMDoc::ChangeItem(CaplTreeItem *item)
{
	m_app.m_api= &m_api;
	m_app.m_cur_tree_item= item;
	
	if(m_tab_view!=0)m_tab_view->Update(item,true);
	if(!item) return;

	CMainFrame* mFrm= (CMainFrame*)AfxGetMainWnd();
	if(!mFrm) return;
	DWORD type= item->GetAddInType();
	
	UINT msg = ((CPSMApp*)AfxGetApp())->m_view_update;
	
	CaplUpdateItem updateItem;
	updateItem.app = &m_app;

	if(!m_api.m_data.IsConnected()){
		return;
	}
	aplExtent ext; item->GetAccessedInstances(ext);
	updateItem.inst = ext[0];
	
	for(int i= 0; i<m_additional_ctrlbars.GetSize(); i++)
	{
		if(m_additional_ctrlbars[i]->m_type&type && m_additional_ctrlbars[i]->m_iIsVisible)
		{
			mFrm->ShowControlBar(m_additional_ctrlbars[i], TRUE, FALSE);
			m_additional_ctrlbars[i]->UpdateWnd(msg, APL_UPDATE_INST_ITEM, LPARAM(&updateItem));
		}
		else
			mFrm->ShowControlBar(m_additional_ctrlbars[i], FALSE, FALSE);
	}
}

void CPSMDoc::RefreshAllItemsByType(LPCTSTR type)
{
	m_navigator->aplGetTreeCtrl().SetRedraw(FALSE);
	for(int i=0;i<m_items.Size;i++)
	{
		if(m_items[i]->m_type==type)
		{
			m_items[i]->RefreshItem();
		}
	}
	m_navigator->aplGetTreeCtrl().SetRedraw(TRUE);
}


void CPSMDoc::UpdateAddinPanels()
{	
	CaplTreeItem *item= (CaplTreeItem*)m_app.m_cur_tree_item;
	DWORD type= item->GetAddInType();
	
	CMainFrame* mFrm= (CMainFrame*)AfxGetMainWnd();
	if(!mFrm) return;
	UINT msg = ((CPSMApp*)AfxGetApp())->m_view_update;

	CaplUpdateItem updateItem;
	updateItem.app = &m_app;
	aplExtent ext; item->GetAccessedInstances(ext);
	updateItem.inst = ext[0];
	
	for(int i= 0; i<m_additional_ctrlbars.GetSize(); i++)
	{
		if(m_additional_ctrlbars[i]->m_type&type && m_additional_ctrlbars[i]->m_iIsVisible)
		{
			mFrm->ShowControlBar(m_additional_ctrlbars[i], TRUE, FALSE);
			m_additional_ctrlbars[i]->UpdateWnd(msg, APL_UPDATE_INST_ITEM, LPARAM(&updateItem));
		}
		else
			mFrm->ShowControlBar(m_additional_ctrlbars[i], FALSE, FALSE);
	}
}
//********************************************************************************
void CPSMDoc::OnDbConnect() 
{
	if(!DbConnect())
	{
		OnCloseDocument();
	}
}


long _application_close_funct(LPVOID param)
{
	if(AfxMessageBox( APL_T("Все несохраненные данные будут утеряны. Вы вправду хотите завершить приложение?"),MB_YESNO)==IDYES)
	{
		AfxGetApp()->CloseAllDocuments(TRUE);
		return 0;
	}
	return -1;
}

bool CPSMDoc::DbConnect() 
{
	// TODO: Add your command handler code here
	if(m_api.m_data.TestNeedRestore())return true;
	if(m_api.m_data.IsConnected())
	{
		if(IDYES!=AfxMessageBox( APL_T("Разорвать  соединение ?"),MB_YESNO))
			return true;
	}
	OnDbDisconnect();

	CString user,psw,db;//,cmd_line=AfxGetApp()->m_lpCmdLine;
	getParam(AfxGetApp()->m_lpCmdLine,_T("/user="),user);
	getParam(AfxGetApp()->m_lpCmdLine,_T("/password="),psw);
	getParam(AfxGetApp()->m_lpCmdLine,_T("/db="),db);
	getParam(AfxGetApp()->m_lpCmdLine,_T("/showproduct="),m_show_prd);
	getParam(AfxGetApp()->m_lpCmdLine,_T("/showdocument="),m_show_doc);

	/* Если захочется переделать на новый механихм
	CaplMPC::GetParam(cmd_line,_T("/user="),user);
	CaplMPC::GetParam(cmd_line,_T("/password="),psw);
	CaplMPC::GetParam(cmd_line,_T("/db="),db);
	CaplMPC::GetParam(cmd_line,_T("/showproduct="),m_show_prd);
	CaplMPC::GetParam(cmd_line,_T("/showdocument="),m_show_doc);*/

	CWinApp *app=AfxGetApp();
	if(app==0) return true;
	bool b_connect=m_api.Connect(LPCTSTR(user), LPCTSTR(psw), LPCTSTR(db));
	CMainFrame* frm= (CMainFrame*)AfxGetMainWnd(); 

	if (!b_connect)
	{
//	 	AfxMessageBox(APL_T("Соединение не установлено !!!"),MB_OK|MB_ICONSTOP|MB_SYSTEMMODAL);
		SetTitle( APL_T("Соединение не установлено"));
	}
	else
	{
		long a=0;
		CString buf;
		m_api.m_data.SetApplicationCloseFunction(_application_close_funct);
		m_api.m_data.NET_GetLicenseStatus(buf,a);

		#ifndef _DEMO
			if(a==-1)
			{
				AfxMessageBox( APL_T("Демонстрационный сервер, работа невозможна !"));
				if(m_api.m_data.IsConnected()) m_api.Disconnect();
				return true;
			}
		#endif	

		CaplAutoUpdate au(_T("PSS"));
		au.LoadOptions();
		// вызываем проверку только если 1) источник обновления - сервер приложений 2) если стоит флаг автообновляться
		if(au.m_source==1 && au.m_AutoUpdate)
		{
			au.m_data=&(m_api.m_data);

			if(au.Update(true,false))
			{
				OnDbDisconnect();
				return false;
			}
		}
		
		SetTitle(_T("*"));
		// Проверка на администратора
		m_bIsAdmin=m_api.m_data.IsAdmin();

		if(!m_api.m_data.IsVersionOk())
		{
			AfxMessageBox( APL_T("Слишком старый словарь !!!\n\n Работа невозможна"),MB_OK|MB_ICONSTOP|MB_SYSTEMMODAL);
			m_api.Disconnect();
		}
		if(!m_bIsAdmin)
		{
			CString roles;
			m_api.m_options_mgr.GetOptionValueBN(APL_NO_T("Роли для использования модуля PDM"),roles,_T(""));
			if(roles!=_T(""))
			{
				if(!m_api.m_appr_mgr.CheckPersonRole(0,roles))
				{
					AfxMessageBox( APL_T("У Вас нет прав для использования модуля!"),MB_OK|MB_ICONSTOP|MB_SYSTEMMODAL);
					m_api.Disconnect();
				}
			}
		}

		m_wf_mgr.Attach(&m_api);
//		m_project_mgr.Attach(&m_api);
		m_exchng_mgr.Attach(&m_api);
		//m_tg_mgr.Attach(&m_api);
		m_fault_mgr.Attach(&m_api);

		
		CArray<HMODULE, HMODULE> modules;
		bool bFine;
		bool (*lpInitConnect)(CaplAPI*);

		for(int i= 0; i<m_addin_menu_items.GetSize(); i++)
		{
			bFine= false;
			for(int j= 0; j<modules.GetSize() && !bFine; j++)
				if(modules[j]==m_addin_menu_items[i].m_hModule) bFine= true;
			
			if(!bFine)
			{
				modules.Add(m_addin_menu_items[i].m_hModule);
				(FARPROC&)lpInitConnect = GetProcAddress(m_addin_menu_items[i].m_hModule,"InitConnect");
				if(lpInitConnect)lpInitConnect(&m_api);
			}
		}

		InitialLoad();

		long trd=aplStartWaitDlg( APL_T("Загрузка локальных параметров"));
		LoadGlobalOptonss();
		LoadFoldersMap();
		LoadCompositionRequirements();
		LoadCharacteristicShow();
		m_iTimerTick= 600000; //лезем в базу
		m_alerts.Clear();
		aplEndWaitDlg(trd);

		m_api.m_query_mgr.SetStyleDlg(m_show_old_query_dlg);
		
		m_tick_connect = GetTickCount();
		/*CheckNewMessages();
		CheckNewTask();*/

#ifdef ENABLE_ASH_MO
		{
			CString sUserName=_T("Неизвестный");
			CaplInstance *curuser=m_api.m_appr_mgr.GetCurrentPerson();
			if(0!=curuser) m_api.m_appr_mgr.GetPersonName(curuser,sUserName,false);
			buf.Format(_T("\nПользователь %s подключился к БД."),sUserName);
			WriteAshMoDBLog(&m_api,buf);
		}
#endif

	}
	

	//m_AutoDeliveMesTimer=SetTimer((long)this, 1000*2*1, &AutoDeliveMes);
	if(m_navigator)
	{
		//m_navigator->OnInitialUpdate();
		CFrameWnd *pFrame=m_navigator->GetParentFrame();
		m_pDocTemplate->InitialUpdateFrame(pFrame, this);
	}

	if(m_api.m_data.IsConnected())
	{
		int iRes;
		CString str;
		iRes = 0;
		ShowUserAlerts(frm);
		CheckAllNewMessages(iRes);
		CheckAllNewTask(iRes);
		CheckAllNewProcessController(iRes);
		
		int iVal;
		m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Настройка Workflow\\Показывать персональный монитор при входе"), iVal, 0);
		
		if((0!=iRes) || (0!=iVal)) // монитор показывается всегда при входе
		{
			if(iRes&1)
			{
				if(str.IsEmpty()) str=  APL_T("Получены новые:\n \n");
				str +=  APL_T("\n  - сообщения");
			}
			if(iRes&2)
			{
				if(str.IsEmpty()) str=  APL_T("Получены новые:\n \n");
				str +=  APL_T("\n  - задания");
			}
			if(iRes&4)
			{
				if(str.IsEmpty()) str=  APL_T("Получены новые:\n \n");
				str +=  APL_T("\n  - процессы, в которых Вы являетесь ответственным за контроль");

			}

			
			if((!str.IsEmpty()) || (0!=iVal))
			{
				CheckNewMonitorEvents(iRes, str);
			}
		}
	}

//	frm->m_AutoDeliveMes= m_api.m_data.IsConnected();
	frm->SetAutoDeliveMes();
	return true;
}
//********************************************************************************
void CPSMDoc::ShowItem(LPCTSTR type, LPCTSTR show_id)
{
	if(m_navigator==0) return;

	//if(m_navigator->m_queries_item==0)m_navigator->m_queries_item=m_navigator->GetTreeCtrl().InsertItem(APL_T("Запросы"),ICON_QUERYES,ICON_QUERYES);

	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	if(doc==0)return;
	CNavigatorView *view=doc->m_navigator;
	if(view==0) return;
	if(view->m_queries_item==0)return;
	
	CaplQueryTreeItem *item=new CaplQueryTreeItem(&(view->aplGetTreeCtrl()),this,0,0,APL_TREE_ITEM_FIND);
	
	item->CreateTreeItem(view->m_queries_item->m_item);
	item->Run(false,type,show_id);
	OnActivateMainView();
	
/*
	if(m_navigator->m_queries_item==0){
		m_navigator->m_queries_item= new CaplQueryTreeItem(&m_navigator->GetTreeCtrl(),this);
		m_navigator->m_queries_item->CreateTreeItem(TVI_ROOT);
	}

	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	
	CString id=show_id;

	CaplAttrValue tst_values[2];
	aplExtent ext;
	CaplEntity *ent=0;
	if(type==_T("product")) ent=m_api.m_data.GetEntityBN(S::product);
	else if(type==_T("document")) ent=m_api.m_data.GetEntityBN(S::apl_document);
	tst_values[0].value.Set((LPCSTR)id);
	tst_values[0].attr=m_api.m_data.GetAttrDefinition(ent,S::id);
	//int	trd=aplStartWaitDlg(APL_T("Поиск данных ..."));
	//StartBusy();
	m_api.m_data.NET_FindInstancesWithAttrValues(ent,1,&tst_values[0],ext,false);
	//StopBusy();
	//aplEndWaitDlg(trd);
	if(ext.Size==0)
	{
		int i=id.ReverseFind(_T('-'));
		if(i>0)
		{
			CString buf;
			buf=id;
			id=buf.Left(i);
		}
	}
/*
	CaplFindTreeItem *item=new CaplFindTreeItem(&(m_navigator->GetTreeCtrl()),this);
	item->m_mode=type;
	item->CreateTreeItem(m_navigator->m_queries_item->m_queries_item);
	item->m_id_str=id;
	item->m_id=true;
	item->m_id_equ=false;
	item->Run(false);
*/
}
//********************************************************************************
void CPSMDoc::OnDbFind() 
{
	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	if(doc==0)return;
	bool need_activate_main = true;
	
	short state=GetKeyState(VK_LCONTROL);
	if((state & 0xff00)!=0 )
	{
		CFrameWnd* pFrame=aplCreateQueryFrame((CMainFrame*)AfxGetMainWnd(), &m_api, IDR_PSMTYPE);
		if(pFrame)
		{
			m_additional_frames.Add(pFrame);
			((CMainFrame*)AfxGetMainWnd())->MDITile(MDITILE_HORIZONTAL);
		}
	}
	else
	{
		CNavigatorView *view=doc->m_navigator;
		if(view==0) return;
		if(view->m_queries_item==0)return;

		need_activate_main = view->m_queries_item->Create(APL_TREE_ITEM_FIND);
	}

	if(need_activate_main)OnActivateMainView();
}
//********************************************************************************
void CPSMDoc::OnDbQuery() 
{
	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	if(doc==0) return;
	CNavigatorView *view=doc->m_navigator;
	if(view==0) return;
	if(view->m_queries_item==0)return;
	if(view->m_queries_item->Create(APL_TREE_ITEM_QUERY))
		OnActivateMainView();
}

void CPSMDoc::OnDbQueryOld() 
{
	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	if(doc==0) return;
	CNavigatorView *view=doc->m_navigator;
	if(view==0) return;
	if(view->m_queries_item==0)return;
	if(view->m_queries_item->Create(APL_TREE_ITEM_QUERY,true))
		OnActivateMainView();
}

void CPSMDoc::OnDbQueryPdfPiBp()
{
	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	if(doc==0) return;
	CNavigatorView *view=doc->m_navigator;
	if(view==0) return;
	if(view->m_queries_item==0)return;
	view->m_queries_item->Create(APL_TREE_ITEM_QUERY_NIIAO);
}

void CPSMDoc::OnPdfPiBpAnalize()
{
	CPSMDoc *doc=(CPSMDoc*)((CMainFrame*)AfxGetMainWnd())->m_last_open_doc;
	if(doc==0) return;
	CNavigatorView *view=doc->m_navigator;
	if(view==0) return;
	if(view->m_queries_item==0)return;
	view->m_queries_item->Create(APL_TREE_ITEM_COMBINED_TABLE);
	//doc->m_api.m_query_mgr.ShowCombinedTable(0);
	
	//AnalizeGroupInstances(&(doc->m_api),0);
}


//********************************************************************************
bool CMyOleDataSource::m_exit=false;
CMyOleDataSource::CMyOleDataSource(){m_doc=0; m_inst=0; m_item=0; m_bNoEdit=false;}
//********************************************************************************
BOOL CMyOleDataSource::OnRenderData( LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium )
{
	if(m_exit) return true;
	if(m_doc==0) return FALSE;
	if(m_inst==0) return FALSE;
	if(m_FileName==_T("")) return FALSE;
	
	//AfxMessageBox(_T("OnRenderData"));
	//UINT cf_fn=RegisterClipboardFormat(CFSTR_FILENAME);	
	UINT cf_fc=RegisterClipboardFormat(CFSTR_FILECONTENTS);
	//Beep(1000,100);
	if((lpFormatEtc==0)||(lpStgMedium==0)) return FALSE;
	if(lpFormatEtc->cfFormat!=cf_fc) return FALSE;
	if((lpFormatEtc->tymed&TYMED_HGLOBAL)==0) return FALSE;

	CWnd *pWndPopupOwner=AfxGetMainWnd();
	if(pWndPopupOwner==0) return TRUE;
	pWndPopupOwner->SetForegroundWindow();

	POINT point;
	GetCursorPos(&point);

	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
//	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(pWndPopupOwner);//	VERIFY(CaplMenu::Install(pWndPopupOwner, ePopupMenu ));
    CMenu* pPopup = menu.GetSubMenu(INDEX_DROPPED_FILE);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return false;
	if(m_bNoEdit)
		pPopup->EnableMenuItem(ID_ITEM_CHECK_OUT,MF_BYCOMMAND|MF_GRAYED);
	int res=pPopup->TrackPopupMenu(TPM_NONOTIFY|TPM_LEFTALIGN|TPM_RIGHTBUTTON|TPM_RETURNCMD, point.x, point.y,
			pWndPopupOwner);
	if((res!=ID_ITEM_VIEW)&&(res!=ID_ITEM_CHECK_OUT))return TRUE;
	

	//++Колесников - это безобразие необходимо для корректной работы PSM с интеграцией
	CString tmp,sBuf,sDef,sWF;
	CaplInstance* ciWFInst = NULL;
	CFileFind ff;
	//принадлежит ли файл интеграции с SolidWorks, если нет
	m_doc->m_api.m_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_apl_doc_system,sBuf);
	if (!sBuf.IsEmpty()&&!sBuf.CompareNoCase(_T("SolidWorks")))
	{
		CString msg=APL_T("Данный документ был создан при помощи интеграции с SolidWorks.\n");
		msg+=APL_T("Дальнейшая работа с ним может быть некорректной.\nПродолжить?");
		
		if(IDNO == AfxMessageBox(msg,MB_YESNO))	return TRUE;
		

		sDef =  APL_NO_T("SW_REFS\\Рабочая папка");
		sWF = _T("c:\\sw\\");
		ciWFInst = m_doc->m_api.m_options_mgr.FindOptionBN(sDef);

		if ((!ciWFInst)||(ciWFInst == (CaplInstance*)-1))
			ciWFInst = m_doc->m_api.m_options_mgr.CreateOption(sDef,sWF);
		else
		if (m_doc->m_api.m_data.IsKindOf(ciWFInst,m_doc->m_api.m_options_mgr.e_str))
			m_doc->m_api.m_data.GetAttr(ciWFInst,m_doc->m_api.m_options_mgr.a_str_value,sWF);

		if(TRUE == ff.FindFile(sWF))
			ff.Close();
		else
			CreateDirectory(sWF,NULL);
	}
	else //++конец безобразия - старая версия, в скобка внутри else
	{
		aplGetTempPath(tmp);
	}
	

	tmp+=m_FileName;

	if(res==ID_ITEM_VIEW)
	{
		if(!m_doc->m_api.m_doc_mgr.LoadRevision(m_inst,tmp)) return FALSE;
	}
	else if(res==ID_ITEM_CHECK_OUT)
	{
		CString msg=APL_T("При выполнении данной операции путь к файлу будет запомнен некорректно.\n\n");
		msg+=APL_T("Вы хотите выполнить операцию ?");
		if(IDYES!=AfxMessageBox(msg,MB_YESNO|MB_ICONSTOP)) return TRUE;
		if(!m_doc->m_api.m_doc_mgr.CheckOut(m_inst,tmp)) return FALSE;
	}
	CFile file;
	if(!file.Open(LPCTSTR(tmp),CFile::modeRead|CFile::typeBinary)) return FALSE;
	DWORD flen=(DWORD)file.GetLength();

	//return TRUE;
	lpStgMedium->tymed = TYMED_HGLOBAL;
	HGLOBAL hGlobal;
	hGlobal = GlobalAlloc(GHND | GMEM_SHARE, flen);
	if(hGlobal)
	{
/*		LPSTR pszFile = (LPSTR)GlobalLock(hGlobal);
		if(pszFile)
		{
			strcpy(pszFile,_T("abra-kadabra"));
			//CreateMyTempFile(_T("aaaa.txt"), pszFile);
			GlobalUnlock(hGlobal);
			lpStgMedium->hGlobal=hGlobal;
		}*/
		void *buf= GlobalLock(hGlobal);
		if(buf)
		{
#if _MSC_VER >= 1400
			file.Read(buf,flen);
#else
			file.ReadHuge(buf,flen);
#endif
			GlobalUnlock(hGlobal);
			lpStgMedium->hGlobal=hGlobal;
		}
    }
	file.Close();
	SetFileAttributes(tmp,FILE_ATTRIBUTE_NORMAL);
	CFile::Remove(tmp);
	if(m_item!=0)m_item->RefreshAllThisDocItem();
	return TRUE;
}

void Test1(CaplAPI &m_api)
{
}

//********************************************************************************
void CPSMDoc::OnConfigure()
{
	bool (*funcSelectConfiguration)(CaplAPI*, CaplInstance*&, bool) = NULL;
	if(m_hConfigMgrLib != NULL)
	{
		(FARPROC&)funcSelectConfiguration = ::GetProcAddress(m_hConfigMgrLib, "add_SelectConfiguration");	
		if(funcSelectConfiguration)
		{
			funcSelectConfiguration(&m_api, m_pCurrentConfiguration, true);			
		}
	}
}

void CPSMDoc::OnShowVariantRule()
{
	bool (*funcShowVariantRule)(CaplAPI*, aplExtent&, bool) = NULL;
	if(m_hConfigMgrLib != NULL)
	{
		(FARPROC&)funcShowVariantRule = ::GetProcAddress(m_hConfigMgrLib, "add_PdfVariantRulesForPdf");	
		if(funcShowVariantRule)
		{
			CNavigatorView *view = GetMyActiveView();
			if(view)
			{
				HTREEITEM selectedItem = view->aplGetTreeCtrl().GetSelectedItem();
				if(selectedItem)
				{
					CaplTreeItem *tree_item= reinterpret_cast<CaplTreeItem*>(view->aplGetTreeCtrl().GetItemData(selectedItem));
					if(tree_item && tree_item->m_type == _T("Product"))
					{
						CaplProductTreeItem *productItem = dynamic_cast<CaplProductTreeItem*>(tree_item);
						if(productItem && productItem->m_nauo)
						{
							aplExtent items; items.Add(productItem->m_nauo);
							if(funcShowVariantRule(&m_api, items, false))
								productItem->RefreshItem();							
						}						
					}
				}				
			}		
		}
	}	
}


#ifndef _DEBUG
void CPSMDoc::OnTest() {} // ЯАИ: Надеюсь всем хватит мозгов, чтобы сюда ничего не писать
#else if

void CPSMDoc::OnTest() 
{
	//CaplInstance *Item=0;
	//m_api->m_classifier_mgr.SelectItem(&Item, 0 ,APL_SELECT_CLASSIFIER_LEVEL/*|APL_CONCEPT*/, _T("AAAAAAAAAAA"));
	//m_api.m_classifier_mgr.SelectItem(&Item, 0 ,APL_SELECT_CLASSIFIER_ITEM, _T("AAAAAAAAAAA"));
	//m_api.m_classifier_mgr.SelectItem(&Item, 0 ,APL_CLASSIFIER_EDITOR, _T("AAAAAAAAAAA"));
	//m_api.m_classifier_mgr.SelectItem(&Item, 0 ,APL_SELECT_CLASSIFIER_LEVEL|APL_SHOW_ESQUISSE, _T("AAAAAAAAAAA"));
	//Item=0;
	//return;

	/*
	CaplFinder ff(DEF_SOURCE);
	int index = ff.CreateExt(m_api.m_doc_mgr.e_doc);
	ff.AddAttr(index, m_api.m_doc_mgr.a_doc_id, _T("Test"), CaplFinder::cmpLike);
	ff.AddToResult(index);
	ff.Find(m_api.m_data, true, false, false, true, true);

	*/
	
/*	// проверка отправки и сохранения почты
	if(false)
	{
		//CaplInstance* message = m_api.m_data.GetInstById(28833);
		CaplInstance* message = m_api.m_data.GetInstById(13750);
		CString errmess = _T("");
 		m_api.m_message_mgr.LoadMessageInfo(message);
		m_api.m_message_mgr.SendMessageToEmlServer(message, &errmess);
	}

	if(false)
	{
		CaplInstance* message = m_api.m_data.GetInstById(13750);
		m_api.m_message_mgr.LoadMessageInfo(message);
		m_api.m_message_mgr.SaveMessageToEml(message, _T("d:\\temp\\1\\111.eml"));

// 		message = m_api.m_data.GetInstById(28825);
// 		m_api.m_message_mgr.LoadMessageInfo(message);
// 		m_api.m_message_mgr.SaveMessageToEml(message, "d:\\temp\\1\\222.eml");
// 
// 		message = m_api.m_data.GetInstById(28838);
// 		m_api.m_message_mgr.LoadMessageInfo(message);
// 		m_api.m_message_mgr.SaveMessageToEml(message, "d:\\temp\\1\\333.eml");
	}

	

	AfxMessageBox(_T("Ok!"));

return;

	// справочник для изучения
	CaplInstance* ciBaseClass= m_api.m_classifier_mgr.GetClassifierSystemBN(_T("222"), true);
	if(!ciBaseClass)
		return;

	aplExtent BaseClassifierSystems;
	BaseClassifierSystems.Add(ciBaseClass);
	CaplInstance* ciSelected;

	// Поля фильтра
	SSelectItemFilter filter;
	// В диалоге справочника будут показаны только папки, поиск тоже только по ним
	filter.search_entity = m_api.m_folder_mgr.e_folder;
	filter.search_entity_name = APL_T("Папку");

	// В поле поиска будут доступны следующие атрибуты
	filter.selection_array.Add( m_api.m_folder_mgr.a_folder_name);
	filter.selection_array_names.Add(APL_T("Наименование"));
	filter.selection_array.Add( m_api.m_folder_mgr.a_folder_descr);
	filter.selection_array_names.Add(APL_T("Описание"));
	filter.selection_array.Add( m_api.m_folder_mgr.a_folder_guid);
	filter.selection_array_names.Add(_T("GUID"));

	// При открытии диалога будет выбран поиск по GUID
	filter.default_selection = m_api.m_folder_mgr.a_folder_guid;
	// При открытии диалога будет выбрано отношение поиска "равно"
	filter.default_relation = CaplQLQuery::aplEQUAL;
	// При открытии диалога будет выбрано значение для поиска - "111"
	filter.default_value = _T("111");

	// В таблице будет показаны столбцы для атрибутов "Наименование" и "Описание"
	// Названия стобцов будут взяты из стандартной таблички инстансов
 	filter.display_array.Add( m_api.m_folder_mgr.a_folder_name);
 	filter.display_array.Add( m_api.m_folder_mgr.a_folder_descr);
	// При открытии диалога будет сортировка по убыванию по атрибуту "описание"
	filter.sorting_field = m_api.m_folder_mgr.a_folder_descr;

	// запускаем диалог
	m_api.m_classifier_mgr.SelectItem(&ciSelected, BaseClassifierSystems,APL_SELECT_CLASSIFIER_ITEM,APL_T("Проверка"),&filter);

	return ;

*/
// 	CaplCSV file(_T(';'));
// 	file.OpenFile(_T("D:\\1.csv"));
// 
// 	CStringArray srLine;
// 	file.ReadString(srLine);
// 
// 	CaplInstance* ciClass= m_api.m_classifier_mgr.GetClassifierSystemBN(APL_T("Справочник профессий"), true);
// 	if(!ciClass)
// 		return;
// 	
// 	aplExtent arLevels;
// 	m_api.m_classifier_mgr.LoadSubClassifierLevels(ciClass, arLevels, true, true);
// 
// 	m_api.SetAutoSave(false);
// 	if(IDYES==AfxMessageBox(APL_T("Очистить справочник?"), MB_YESNO|MB_ICONQUESTION))
// 	{
// 		for(int i=0; i<arLevels.GetSize(); i++)
// 			m_api.m_data.DeleteInstance(arLevels[i]);
// 		m_api.SaveChanges();
// 	}		
// 
// 	CaplInstance* ciClLevel (NULL);
// 
// 	while(file.ReadString(srLine))
// 	{
// 		ciClLevel= m_api.m_classifier_mgr.GetClassifierLevelById(srLine[0], ciClass, false);
// 		if(ciClLevel)
// 			m_api.m_data.PutAttr(ciClLevel, m_api.m_classifier_mgr.a_apl_classifier_level_name, srLine[1]);
// 		else
// 			m_api.m_classifier_mgr.CreateClassifierLevel(ciClass, NULL, srLine[0], srLine[1]);
// 	}
// 	m_api.SaveChanges();
// 	m_api.SetAutoSave(true);
// 	AfxMessageBox(_T("!!!"));

/*
	CaplCryptographicManager cm;

	char *sFile="D:\\___________________\\КЮФУ8.683.226_2d_кюфу8683226.jpg";
	CString sHash0="D5EA4347CF08DDABD7E411755EB84FCAB2CC5796358BDB66C2EDFCEB2055CD1D";
	CString sOpenKey0="04405cdb47225c0c94c830703ad5cf585036cf4ae6ba7dba7db658be2dbf695453cc29c44042dd29b36b2ee9423230be83aea8fdbfbae49b4969b9218689d487902c";
	sOpenKey0.MakeUpper();
	//CString sSign0="B8B7CA3B50DDD4411C5ACE6989685159A509CB5CD26BE0EA0EC9568D004A16FFF105D7BDBCF49082A606260788662C7509001205F63B3A04B84DE597436AFE5B";
	// Моя подпись
	CString sSign_pss="B0D7E71D2F49577CA04BFAFB3C8C1B1953D1198FF9F3AA40D85A59BFC9C2E15E5011A2E4B3F18CD5CE4D676F3081207FA4A201A50016C4495B4CA23BA4E5E540";

	// подпись из файла
	//CString sSign_csp="72FD536DCDF4B6134608C8C89B6B09ADDA942FC7F6D9D26FE36CBB819E9C8A3305FC77D0E55287319247F2D762240EDF7F97D9096AFD5544DBC69979C59026D2";
	CString sSign_csp="EDE85C03663D5150F7DF155B536E943C11051F73EB674984D81B87F9FCBE924C3216F251CFC83204BA9FBB25191C6E298CB7E8672B4FC4332E9F663417E26DA9";
	
	CString sHash1, sOpenKey1,sSign1;
*/
	/*int i;
	for(i=sSign_csp.GetLength()-2; i>=0; i-=2)
	{
		sSign1+=sSign_csp[i];
		sSign1+=sSign_csp[i+1];
	}*/

	//int k00=cm.csp_CheckSign(sFile,0,sHash0,sOpenKey0,sSign_pss,0,0,APL_CSP_2012_256);
	//int k01=cm.csp_CheckSign(sFile,0,sHash0,sOpenKey0,sSign_csp,0,0,APL_CSP_2012_256);
	//int k02=cm.csp_CheckSign(sFile,0,sHash0,sOpenKey0,sSign1,0,0,APL_CSP_2012_256);


	// Проверяем сертификатом
	/*CFile fcert;
	if(fcert.Open("D:\\___________________\\baranov.cer",CFile::modeRead))
	{
		int certlen=(int)fcert.GetLength();
		BYTE *certbuf=new BYTE[certlen];
		int r=fcert.Read(certbuf,certlen);
		fcert.Close();
		int k01_1=cm.csp_CheckSign(sFile,0,sHash0,certbuf,certlen,sSign_csp,0,0,APL_CSP_2012_256);

		delete certbuf;
	}*/

	
	/*CString sUser,sCert;
	int j1=cm.csp_Sign(sFile,0,sUser,sCert,sHash1,sOpenKey1,sSign1,0,0,APL_CSP_2012_256);
	int k1=cm.csp_CheckSign(sFile,0,sHash1,sOpenKey1,sSign1,0,0,APL_CSP_2012);

	int k3=cm.csp_CheckSign(sFile,0,sHash0,sOpenKey0,sSign_csp,0,0,APL_CSP_2012_256);

	if(sOpenKey1!=sOpenKey0 || sHash1!=sHash0)
	{
		AfxMessageBox("!=");
	}*/
	//int kkkk=0;

}
#endif


//********************************************************************************
void CPSMDoc::OnRunImportef() 
{
	// Проверка доступа
	CString buf,sRole;
	m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для импорта данных"), sRole, _T(""));
	if(sRole!=_T(""))
	{
		if(!m_api.m_appr_mgr.CheckPersonRole(0,sRole))
		{
			buf.Format( APL_T("Вы не обладаете ролью \"%s\", необходимой для выполнения функции."),LPCTSTR(sRole));
			AfxMessageBox(buf,MB_OK|MB_ICONSTOP);
			return;
			
		}
	}

	if(!m_api.m_data.IsConnected())
	{
		AfxMessageBox( APL_T("Соединение с БД не установлено"),MB_OK|MB_ICONSTOP);
		return;
	}
	CImportEfDlg dlg;
	dlg.m_api=&m_api;
	dlg.DoModal();
	if(dlg.m_ReloadFolder)
	{
		int i;
		// Закрытие папки
		for(i=0; i<m_items.Size;i++)
		{
			if(m_items[i]->m_type==APL_TREE_ITEM_FOLDER)
			{
				if(((CaplFolderTreeItem*)(m_items[i]))->m_inst==0)
				{
					if(m_items[i]->m_tree->GetItemText(m_items[i]->m_item)== APL_T("Папки"))
					{
						m_items[i]->Expand(1);
						m_items[i]->m_tree->Expand(m_items[i]->m_item,TVE_COLLAPSE);
						m_items[i]->Expand(2);
						m_items[i]->m_tree->Expand(m_items[i]->m_item,TVE_EXPAND);
					}
					break;
				}
			}
		}
		// обновление информации
		m_navigator->SetRedraw(FALSE);
		for(i=0; i<m_items.Size;i++) m_items[i]->RefreshItem();
		m_navigator->SetRedraw(TRUE);
	}
}
//********************************************************************************
void CPSMDoc::OnProductShowExplosion() 
{
	DoShowContentsDialog(&m_api);
}
//********************************************************************************
void CPSMDoc::OnDigSugnSysSetup() 
{
	CaplCryptographicManager::EditCSPSet();
}
//********************************************************************************
void CPSMDoc::OnOptionSelectDefCharacterystic() 
{
	// TODO: Add your command handler code here
	CStringArray Columns;
	CaplTAggr<CStringArray*,CStringArray*,APLAGGR_AUTOKILLREF|APLAGGR_LIST> Items;
	Columns.Add( APL_T("Название"));
	Columns.Add( APL_T("Идентификатор"));
	CStringArray* array;

	CUIntArray mask;
	int i,j;
	CString buf;
	aplExtent ext0;

	m_charact_names.RemoveAll();
	m_api.m_data.GetEntityExtentBN(_T("apl_characteristic"),ext0);
	for(i=0;i<ext0.Size;i++)
	{
		m_api.m_data.GetAttrBN(ext0[i],S::name,buf);
		m_charact_names.Add(buf);
		array=new CStringArray();
		array->Add(buf);
		m_api.m_data.GetAttrBN(ext0[i],S::id,buf);
		array->Add(buf);
		Items.Add(array);
	}
	for(i=0;i<m_api.m_charact_mgr.m_sel_charact_names.GetSize();i++)
	{
		for(j=0;j<m_charact_names.GetSize();j++)
		{
			if(m_api.m_charact_mgr.m_sel_charact_names[i]==m_charact_names[j])
			{
				mask.Add(j);
				break;
			}
		}
	}

	if(DoChooseCharacteristicsDlg(&Columns, &Items,&mask))
	{
		m_api.m_charact_mgr.m_sel_charact_names.RemoveAll();
		for(i=0;i<mask.GetSize();i++)
		{
			if(mask[i]<(unsigned int)m_charact_names.GetSize())
				m_api.m_charact_mgr.m_sel_charact_names.Add(m_charact_names[mask[i]]);
		}
	}
}
//********************************************************************************
void CPSMDoc::OnOptionSelectDefDocType() 
{
	CStringArray Columns;
	CaplTAggr<CStringArray*,CStringArray*,APLAGGR_AUTOKILLREF|APLAGGR_LIST> Items;
	Columns.Add( APL_T("Вид документа"));
	CStringArray* array;

	CUIntArray mask;
	int i,j;
	CString buf;
	aplExtent ext0;

	m_doc_types_names.RemoveAll();
	m_api.m_data.GetEntityExtent(m_api.m_doc_mgr.e_dt,ext0);
	for(i=0;i<ext0.Size;i++)
	{
		if(ext0[i]==0)continue;
		if(ext0[i]->GetAccessmode()==aplNO) continue;

		m_api.m_data.GetAttr(ext0[i],m_api.m_doc_mgr.a_dt_pdt,buf);
		m_doc_types_names.Add(buf);
		array=new CStringArray();
		array->Add(buf);
		Items.Add(array);
	}
	for(i=0;i<m_sel_doc_types_names.GetSize();i++)
	{
		for(j=0;j<m_doc_types_names.GetSize();j++)
		{
			if(m_sel_doc_types_names[i]==m_doc_types_names[j])
			{
				mask.Add(j);
				break;
			}
		}
	}

	if(DoChooseCharacteristicsDlg(&Columns, &Items,&mask,
		 APL_T("Выбор типов документов"), APL_T("Отображаемые типы документов"), APL_T("Неотображаемые типы документов")))
	{
		m_sel_doc_types_names.RemoveAll();
		for(i=0;i<mask.GetSize();i++)
		{
			if(mask[i]<(unsigned int)m_doc_types_names.GetSize())
				m_sel_doc_types_names.Add(m_doc_types_names[mask[i]]);
		}
		m_api.m_doc_mgr.m_sel_doc_types_names.RemoveAll();
		m_api.m_doc_mgr.m_sel_doc_types_names.Append(m_sel_doc_types_names);
	}
}
//********************************************************************************
void CPSMDoc::OnProductCompare() 
{
	aplExtent ext;
	CaplTreeItem* item=GetSelItem();
	if(item!=0)
	{
		if(item->m_type==APL_TREE_ITEM_PRODUCT)
		{
			CaplInstance *inst= ((CaplProductTreeItem*)item)->m_pdf;
			if(inst!=0) ext.Add(inst);
		}
	}
	m_api.m_prd_mgr.StartCompareProduct(ext);
}
//********************************************************************************
void CPSMDoc::OnMessageDeliver() 
{
	/*через попу, но иначе не работает...*/
	CString buf;
	for(int i= 0; i<m_items.GetSize(); i++)
	{
		m_items[i]->GetName(buf);
		if(buf== APL_T("Почта")) 
		{
			m_items[i]->m_tree->Expand(
				m_items[i]->m_tree->GetParentItem(m_items[i]->m_item), 
				TVE_EXPAND);
			
			m_items[i]->MyExpand();
			break;
		}
	}
	
	if(!m_user_incoming_folder->IsExpandet())
		m_user_incoming_folder->MyExpand();
	else 
		((CaplMessageFolderTreeItem*)m_user_incoming_folder)->InsertMessages();

}
//********************************************************************************
void CPSMDoc::OnTaskDeliver() 
{
	int iRes;
	iRes = 0;
	CheckNewTask(iRes);
}
//********************************************************************************
void CPSMDoc::OnNewMessageCreate() 
{
	CaplInstance* inst= NULL;
	CaplTreeItem* item= GetSelItem();
	if(item)
	{
		if(item->m_type==APL_TREE_ITEM_DOCUMENT)
		{
			inst=((CaplDocTreeItem*)item)->m_rev;
			if(inst==0) inst=((CaplDocTreeItem*)item)->m_inst;
		}
		else if(item->m_type==APL_TREE_ITEM_BP)
		{
			inst=((CaplBPTreeItem*)item)->m_rev;
			if(inst==0) inst=((CaplBPTreeItem*)item)->m_inst;
		}
		else
		{
			aplExtent ext;
			item->GetMainInstances(ext);
			if(ext.Size>0)
			{
				if(ext[0]!=0)
				{
					if(ext[0]->GetAccessmode()<=aplRO)
					{
						if(ext[0]->GetType()!=0) inst= ext[0];
					}
				}
			}
		}
	}
	aplExtent ext1;
	if(inst)	ext1.Add(inst);
	CaplMessageTreeItem::CreateMessage(this, NULL, ext1);
}
//********************************************************************************
void CPSMDoc::CheckNewMessages(int& iRes)
{
	if(!m_api.m_data.IsConnected()) return;
	if(CaplMessageTreeItem::CheckMessages(this))
	{
/*		if(IDYES==MessageBox(NULL, APL_T("Получены новые сообщения. \n\nДоставить почту?"), APL_T("Новые сообщения"),
			MB_ICONQUESTION | MB_YESNO))
		{
			CaplMessageTreeItem::ShowAllMessages(this);
			if(!m_user_incoming_folder->IsExpandet())
				m_user_incoming_folder->MyExpand();
		}*/
		/*
		MessageBox(NULL, APL_T("Получены новые сообщения. Проверьте почту."), APL_T("Новые сообщения"),
			MB_ICONQUESTION | MB_OK);
			*/
		/*MessageBox(NULL, APL_T("Получены новые сообщения. Проверьте почту."), 
			APL_T("Новые сообщения"), MB_ICONINFORMATION|MB_OK|MB_SYSTEMMODAL);*/
		
		//CheckNewMonitorEvents();	
		iRes++;

	}
}
//********************************************************************************
void CPSMDoc::CheckNewTask(int &iRes)
{
	if(!m_api.m_data.IsConnected()) return;
	if(CaplTaskTreeItem::CheckNewTasks(this))
	{
		
		/*MessageBox(NULL, APL_T("Получены новые задания. "));
			APL_T("\n\nДля просмотра заданий откройте раздел \"Работы -> Задания\"."), 
			APL_T("Новые задания"),	MB_ICONINFORMATION|MB_OK);*/
		//CheckNewMonitorEvents();	
		iRes|=2;
	}
}
//********************************************************************************
void CPSMDoc::CheckNewProcessController(int& iRes)
{
	CaplInstance*	ciPerson	=NULL;
	aplExtent		aeProcesses;
	CaplInstance*	cit1		=NULL;
	CaplInstance*	cit2		=NULL;
	CString			cst1,cst2, sDate;
	COleDateTime odt= COleDateTime::GetCurrentTime(); 
	CString	buf;
	int i;
	if(!m_api.m_data.IsConnected()) return;
	
	ciPerson=m_api.m_appr_mgr.GetCurrentPerson();
	if(NULL==ciPerson)
	{
//		AfxMessageBox(APL_T("У пользователя не задан сотрудник!"),MB_ICONSTOP|MB_OK);
		return;
	}
	m_wf_mgr.GetUserProcessList(ciPerson, aeProcesses);
	
	bool bFindNew= false;
	aplDate2String(odt, sDate);

	for(i=0;i<aeProcesses.GetSize();i++)
	{
		cit1=aeProcesses.GetAt(i);
		
		m_api.m_data.GetAttr(cit1,	m_wf_mgr.a_proc_manager, cit2);
		if(NULL == cit2) continue;
		if(!aplIsPersonOrgElement(&m_api, cit2,ciPerson))
			continue;
		
		iRes|=16;

		m_api.m_data.GetAttr(cit1, m_wf_mgr.a_act_inst_last_susp_date, buf);
		if(buf.IsEmpty())
		{
			bFindNew= true;
			m_api.m_data.PutAttr(cit1, m_wf_mgr.a_act_inst_last_susp_date, sDate);
		}
	}

	if(bFindNew)
	{
		//AfxMessageBox(APL_T("Получены новые процессы, в которых Вы являетесь Ответсвенным за контроль."));
		/*MessageBox(NULL, APL_T("Получены новые процессы, в которых Вы являетесь Ответсвенным за контроль. "));
			APL_T("\n\nДля просмотра заданий откройте раздел \"Работы -> Задания\"."), 
			APL_T("Новые задания"),	MB_ICONINFORMATION|MB_OK);*/
		//CheckNewMonitorEvents();	
		m_api.SaveChanges();
		iRes|=4;
	}
}

void CPSMDoc::CheckNewMonitorEvents(int& iRes, CString sText)
{
	if(false==m_api.m_data.IsConnected())
		return;

	CaplInstance*	ciPerson								=NULL;	
	CaplInstance*	ciSelItem								=NULL;
	CaplInstance*	cit1									=NULL;
	CaplEntity		ent1,ent2;

	CaplTreeItem*	pitem									=NULL;

	HTREEITEM		hitem									=NULL;

	BOOL			bGo										=FALSE;

	CMap<CaplEntity*,CaplEntity*,CString,CString&>			type_map;
	CMap<CaplEntity*,CaplEntity*,CString,CString&>			name_map;

	CString			csType,csName;
	CString			cst,cst2;

	BOOL			bFound	=FALSE;

	int				i;

	if(NULL==m_navigator)
	{
		m_bShowMonitor= true;
		m_sMonitorText= sText;
		m_hMonitorFlag= iRes;
		return;
	}
	else
	{
		m_bShowMonitor= false;
		m_sMonitorText= _T("");
		m_hMonitorFlag= 0;
	}

	ciPerson = m_api.m_appr_mgr.GetCurrentPerson();
	if(NULL == ciPerson)
		return;

	CMainFrame *frm=(CMainFrame*)AfxGetMainWnd();
	if(frm!=0)
	{
		if(!frm->m_NotifyWithPersonalMonitor)
		{
			AfxMessageBox(sText,MB_OK|MB_ICONWARNING);
			return;
		}
	}

	if(NULL!=m_fShowMonitor)
	{
		if(true==m_fShowMonitor(&m_api, ciSelItem, sText))
			bGo=TRUE;
	}

	// Сбрасываем, чтобы не показывался

	if(FALSE==bGo || NULL==ciSelItem)	return;

	type_map.SetAt(m_wf_mgr.e_task,CString(_T("WfFolder")));
	type_map.SetAt(m_api.m_message_mgr.e_alert,CString(_T("received")));
	type_map.SetAt(m_wf_mgr.e_proc,CString(_T("WfFolder")));
	type_map.SetAt(m_api.m_message_mgr.e_message,CString(APL_TREE_ITEM_MESSAGEFOLDER));
	type_map.SetAt(m_api.m_bp_mgr.e_bp,CString(_T("Super_type")));
	type_map.SetAt(m_api.m_doc_mgr.e_doc,CString(_T("Super_type")));
	type_map.SetAt(m_api.m_doc_mgr.e_apl_doc,CString(_T("Super_type")));
	type_map.SetAt(m_api.m_doc_mgr.e_apl_digital_document,CString(_T("Super_type")));
	type_map.SetAt(m_api.m_doc_mgr.e_apl_stored_document,CString(_T("Super_type")));
	type_map.SetAt(m_api.m_doc_mgr.e_apl_assigned_document,CString(_T("Super_type")));

	name_map.SetAt(m_wf_mgr.e_task,CString( APL_T("Задания")));
	name_map.SetAt(m_api.m_message_mgr.e_alert,CString( APL_T("Полученные")));// сразу полученные
	name_map.SetAt(m_wf_mgr.e_proc,CString( APL_T("Процессы")));
	name_map.SetAt(m_api.m_message_mgr.e_message,CString( APL_T("Почта")));
	name_map.SetAt(m_api.m_bp_mgr.e_bp,CString( APL_T("Редактируемые объекты")));
	name_map.SetAt(m_api.m_doc_mgr.e_doc,CString( APL_T("Редактируемые объекты")));
	name_map.SetAt(m_api.m_doc_mgr.e_apl_doc,CString( APL_T("Редактируемые объекты")));
	name_map.SetAt(m_api.m_doc_mgr.e_apl_digital_document,CString( APL_T("Редактируемые объекты")));
	name_map.SetAt(m_api.m_doc_mgr.e_apl_stored_document,CString( APL_T("Редактируемые объекты")));
	name_map.SetAt(m_api.m_doc_mgr.e_apl_assigned_document,CString( APL_T("Редактируемые объекты")));

	type_map.Lookup(ciSelItem->GetType(),csType);
	name_map.Lookup(ciSelItem->GetType(),csName);

	for(i=0;i<m_items.GetSize();i++)
	{
		pitem=m_items.GetAt(i);
		if(pitem->m_type==csType)
		{
			pitem->GetName(cst);
			if(cst==csName)
			{
				bFound=TRUE;
				break;
			}
		}
	}

	if(FALSE==bFound)
		return;

//	pitem->MyExpand(false);
	pitem->Expand(1);
	
	pitem->m_tree->EnsureVisible(pitem->m_item);
	pitem->m_tree->SelectItem(pitem->m_item);
	pitem->m_tree->SelectDropTarget(pitem->m_item);

	pitem->MyExpand(true);
//	pitem->Expand(2);

	if(FALSE==pitem->m_tree->ItemHasChildren(pitem->m_item))
		return;

	hitem=pitem->m_tree->GetChildItem(pitem->m_item);

	//	задания - должны быть внутри
	if(m_api.m_data.IsKindOf(ciSelItem,m_wf_mgr.e_task))
	{
		CaplTaskTreeItem* pitem2=NULL;

		pitem2=(CaplTaskTreeItem*)pitem->m_tree->GetItemData(hitem);
		cit1=pitem2->m_task;

		while(cit1!=ciSelItem)
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			if(!hitem) break;
			pitem2=(CaplTaskTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem2->m_task;
		}

		if(NULL!=pitem2)
			pitem=pitem2;
	}
	else
	//	напоминания - должны быть внутри
	if(m_api.m_data.IsKindOf(ciSelItem,m_api.m_message_mgr.e_alert))
	{
		CaplAlertTreeItem* pitem2=NULL;

		pitem2=(CaplAlertTreeItem*)pitem->m_tree->GetItemData(hitem);
		cit1=pitem2->m_inst;

		while(cit1!=ciSelItem)
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			pitem2=(CaplAlertTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem2->m_inst;
		}

		if(NULL!=pitem2)
			pitem=pitem2;
	}
	else
	//	процессы - должны быть внутри
	if(m_api.m_data.IsKindOf(ciSelItem,m_wf_mgr.e_proc))
	{
		CaplProcessTreeItem* pitem2=NULL;

		pitem2=(CaplProcessTreeItem*)pitem->m_tree->GetItemData(hitem);
		cit1=pitem2->m_process;

		while(cit1!=ciSelItem)
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			pitem2=(CaplProcessTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem2->m_process;
		}

		if(NULL!=pitem2)
			pitem=pitem2;
	}
	else
	//	почта - входящие или отправленные. внутри
	if(m_api.m_data.IsKindOf(ciSelItem,m_api.m_message_mgr.e_message))
	{
		//	получаем тип сообщения - отправленное или входящее
		m_api.m_data.GetAttr(ciSelItem,m_api.m_message_mgr.a_message_status,cst);
		
		if(_T("draft")==cst)
			cst2= APL_T("Черновики");
		else
			cst2= APL_T("Входящие");

/*
 *	
	CaplProcessTreeItem* pitem2=NULL;

		pitem2=(CaplProcessTreeItem*)pitem->m_tree->GetItemData(hitem);
		cit1=pitem2->m_process;

		while(cit1!=ciSelItem)
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			pitem2=(CaplProcessTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem2->m_process;
		}

		if(NULL!=pitem2)
			pitem=pitem2;

 */
		CaplMessageFolderTreeItem* pitem2=NULL;

		//	получаем CaplMessageFolderTreeItem - ищем входящие или отправленные
//		pitem->MyExpand(false);
//		pitem->Expand(1);
//		pitem->Expand(2);
//		pitem->MyExpand(true);
		pitem2=(CaplMessageFolderTreeItem*)pitem->m_tree->GetItemData(hitem);
		pitem2->GetName(cst);

		while(cst!=cst2)
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			pitem2=(CaplMessageFolderTreeItem*)pitem->m_tree->GetItemData(hitem);
			pitem2->GetName(cst);
		}

		//	раскрываем входящие или отправленные
//		pitem2->MyExpand(false);
		pitem2->Expand(1);
		pitem2->m_tree->EnsureVisible(pitem2->m_item);
		pitem2->m_tree->SelectItem(pitem2->m_item);
		pitem2->m_tree->SelectDropTarget(pitem2->m_item);
		pitem2->MyExpand(true);
//		pitem2->Expand(2);


		CaplMessageTreeItem* pitem3= NULL;
		hitem=pitem->m_tree->GetChildItem(pitem2->m_item);

		if(hitem==NULL)
		{
			((CaplMessageFolderTreeItem*)pitem2)->InsertMessages(false);
			pitem2->MyExpand(true);
			hitem=pitem->m_tree->GetChildItem(pitem2->m_item);
		}
		
		pitem3=(CaplMessageTreeItem*)pitem2->m_tree->GetItemData(hitem);
		cit1=pitem3->m_message;
		
		while(ciSelItem->GetId()!=cit1->GetId())
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			if(!hitem) break;
			pitem3=(CaplMessageTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem3->m_message;
			
		}

		if(NULL!=pitem3)
			pitem=pitem3;	
	}
	else
	//	редактируемые объекты - должны быть внутри
	if(m_api.m_data.IsKindOf(ciSelItem,m_api.m_bp_mgr.e_bp) ||
	   m_api.m_data.IsKindOf(ciSelItem,m_api.m_doc_mgr.e_doc))
	{
		CaplDocTreeItem*	pitem2Doc	=NULL;
		CaplBPTreeItem*		pitem2BP	=NULL;

		BOOL				bDoc		=FALSE;

		if(m_api.m_data.IsKindOf(ciSelItem,m_api.m_doc_mgr.e_doc))
			bDoc=TRUE;

		if(TRUE==bDoc)
		{
			pitem2Doc=(CaplDocTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem2Doc->m_inst;
		}
		else
		{
			pitem2BP=(CaplBPTreeItem*)pitem->m_tree->GetItemData(hitem);
			cit1=pitem2BP->m_inst;
		}


		while(cit1!=ciSelItem)
		{
			hitem=pitem->m_tree->GetNextSiblingItem(hitem);
			if(!hitem) break;
			if(TRUE==bDoc)
			{
				pitem2Doc=(CaplDocTreeItem*)pitem->m_tree->GetItemData(hitem);
				cit1=pitem2Doc->m_inst;
			}
			else
			{
				pitem2BP=(CaplBPTreeItem*)pitem->m_tree->GetItemData(hitem);
				cit1=pitem2BP->m_inst;
			}
		}

		if(TRUE==bDoc)
		{
			if(NULL!=pitem2Doc)
				pitem=pitem2Doc;
		}
		else
		{
			if(NULL!=pitem2BP)
				pitem=pitem2BP;
		}
	}

	pitem->m_tree->EnsureVisible(pitem->m_item);
	pitem->m_tree->SelectItem(pitem->m_item);
	pitem->m_tree->SelectDropTarget(pitem->m_item);

	
	if(AfxGetMainWnd()->IsIconic())
		AfxGetMainWnd()->ShowWindow(SW_RESTORE);
	AfxGetMainWnd()->SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
//	AfxGetMainWnd()->ShowWindow(SW_RESTORE);
//	AfxGetMainWnd()->ShowWindow(AfxGetApp()->m_nCmdShow);
}

bool CPSMDoc::ShowUserAlerts(CMainFrame* mFrm)
{
	if(!m_api.m_data.IsConnected()) return false;
	if(m_bCheckingAlerts) return false;
	
	m_bCheckingAlerts= true;
	
	//на время показа останавливаем проверку
	if(mFrm)mFrm->SetAlertTimer(0);
 	UINT dur= 600000;//10 минут

	CString buf, sDate;
	COleDateTime curOdt, odt;
	if(!m_api.m_data.NET_GetServerDateTime(curOdt))
	{
		if(m_api.m_data.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
			if(m_api.m_ModeInteractive)AfxMessageBox(APL_T("Ошибка чтения данных!"),MB_OK|MB_ICONSTOP);
		}
		return false;
	}
	aplDate2String(curOdt, sDate);
	
	bool bShow= true;	
	
	if(m_iTimerTick>=600000)//лезем в базу
	{
		m_iTimerTick= 0;
		if(!m_api.m_message_mgr.FindAlerts(m_alerts, m_api.m_appr_mgr.GetCurrentPerson(), NULL, NULL))
		{
			return false;
		}
		aplSortByDate(&m_api.m_data, m_alerts, 0, m_alerts.GetSize()-1, m_api.m_message_mgr.a_alert_next_date);
	}

	while(bShow)
	{
		bShow= false;
		for(int i= 0; i<m_alerts.GetSize(); i++)
		{
			if(!m_alerts[i] || !m_alerts[i]->GetType() || !m_alerts[i]->GetId())
				{m_alerts.Remove(i); i--; continue;}

			//проверка состояния
			CString state;
			m_api.m_data.GetAttr(m_alerts[i], m_api.m_message_mgr.a_alert_state, state);
			if(state==CString(m_api.m_message_mgr.m_alert_state_completed))
				{m_alerts.Remove(i); i--; continue;}
			
			//чтобы дата была актуальная  
			m_api.m_data.NET_GetServerDateTime(curOdt);
			aplDate2String(curOdt, sDate);

			m_api.m_data.GetAttr(m_alerts[i], m_api.m_message_mgr.a_alert_next_date, buf);
			if(buf.CompareNoCase(sDate)<0)//дата следующей проверки уже прошла
			{
				bShow= true;
				if(m_api.m_message_mgr.ShowAlert(m_alerts[i]))
				{
					CString sModule, sFunc;
					LPADDINFUNCTION lpFunction= NULL;
					HMODULE hModule= 0;
					
					if(!m_alerts[i] || !m_alerts[i]->GetType() || !m_alerts[i]->GetId())
						{m_alerts.Remove(i); i--; continue;}

					m_api.m_data.GetAttr(m_alerts[i], m_api.m_message_mgr.a_alert_module, sModule);
					m_api.m_data.GetAttr(m_alerts[i], m_api.m_message_mgr.a_alert_function, sFunc);
					if(sModule.IsEmpty() || sFunc.IsEmpty()) continue;
					
					//запускаем обработчик
					for(int j= 0; j<m_addin_menu_items.GetSize(); j++)
					{
						int iIndex= m_addin_menu_items[j].m_AddInFile.Find(sModule, -1);
						if(-1!=iIndex)
						{
							hModule= m_addin_menu_items[j].m_hModule;
							if(m_addin_menu_items[j].m_sFuncName.Compare(sFunc))
							{
								lpFunction= m_addin_menu_items[j].m_pFunc;
								break;
							}
						}
					}
					
					if(!lpFunction)
					{
						try
						{
							if(!hModule)
							{
								hModule= AfxLoadLibrary(sModule);
								if(!hModule) continue;
							}
#ifdef UNICODE
							CaplStringAdapter sFuncAdapter(sFunc);
							(FARPROC&)lpFunction= GetProcAddress(hModule, (LPCSTR)sFuncAdapter);
#else
							(FARPROC&)lpFunction= GetProcAddress(hModule, sFunc);
#endif
							if(!lpFunction) continue;
						}
						catch(...)
						{
							continue;
						}
					}

					CaplInstance* inst= NULL;
					aplExtent items;
					m_api.m_data.GetAttr(m_alerts[i], m_api.m_message_mgr.a_alert_item, inst);
					if(inst) items.Add(inst);				
					if(lpFunction)lpFunction(&m_api, items, false);
				}
			}
			else if(!bShow)//если ничего не показывали ставится таймер и все
			{
				COleDateTime odt, next_odt;
				m_api.m_data.NET_GetServerDateTime(odt);
				m_api.m_data.NET_GetServerDateTime(next_odt);
				
				CString sNextDate;
				m_api.m_data.GetAttr(m_alerts[0], m_api.m_message_mgr.a_alert_next_date, sNextDate);
				aplString2Date(sNextDate, next_odt);	
				
				COleDateTimeSpan odts;
				odts= next_odt-odt;				
				dur= (UINT)odts.GetTotalSeconds()*1000;
								
				break;
			}
		}
		
		//пересортировка
		if(bShow)
		{
			aplExtent ext_old;
			int i;
			ext_old.Append(m_alerts);
			m_alerts.Clear();
			for(i= 0; i<ext_old.GetSize(); i++)
			{
				if(!ext_old[i]) continue;
				if(!ext_old[i]->GetType()) continue;
				m_alerts.Add(ext_old[i]);
			}

			aplSortByDate(&m_api.m_data, m_alerts, 0, m_alerts.GetSize()-1, m_api.m_message_mgr.a_alert_next_date);
		}
	}
	
	m_iTimerTick+=dur;				
	//раз в 10 минут лезем в базу (уменьшаем dur до 10 минут)
	if(m_iTimerTick>600000){dur+=600000-m_iTimerTick;/*Для отладки, а так не важно*/ m_iTimerTick= 600000;} 
	//на всякий случай, если крутанулось после "-"... 
	if(dur>600000) dur= 600000;
	
	if(mFrm)mFrm->SetAlertTimer(dur);
	
	m_bCheckingAlerts= false;
	return true;
}

bool CPSMDoc::SortUserAlerts()
{
	if(!m_api.m_data.IsConnected()) return true;
	bool bRes= true;

	if(m_api.m_message_mgr.FindAlerts(m_alerts, m_api.m_appr_mgr.GetCurrentPerson(), 
		NULL, NULL))
	{
		aplSortByDate(&m_api.m_data, m_alerts, 0, m_alerts.GetSize()-1, m_api.m_message_mgr.a_alert_next_date);
	}
	return bRes;
}

//********************************************************************************
void CPSMDoc::OnFileApploadFromPssFile() 
{
	// Проверка доступа
	CString buf,sRole;
	m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для импорта данных"), sRole, _T(""));
	if(sRole!=_T(""))
	{
		if(!m_api.m_appr_mgr.CheckPersonRole(0,sRole))
		{
			buf.Format( APL_T("Вы не обладаете ролью \"%s\", необходимой для выполнения функции."),LPCTSTR(sRole));
			AfxMessageBox(buf,MB_OK|MB_ICONSTOP);
			return;
			
		}
	}
	
	m_exchng_mgr.ImportDataFromFile(_T(""));
	OnRefreshAllTreeItem();
}

//********************************************************************************
void CPSMDoc::OnExportItem() {ExportItem(0);}
//********************************************************************************
bool CPSMDoc::ExportItem(CaplInstance *item)
{
	// Проверка доступа
	CString buf,sRole;
	m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Роли\\Роль для экспорта данных"), sRole, _T(""));
	if(sRole!=_T(""))
	{
		if(!m_api.m_appr_mgr.CheckPersonRole(0,sRole))
		{
			buf.Format( APL_T("Вы не обладаете ролью \"%s\", необходимой для выполнения функции."),LPCTSTR(sRole));
			AfxMessageBox(buf,MB_OK|MB_ICONSTOP);
			return false;
			
		}
	}
	else
	{
		if(!m_api.m_data.IsAdmin()) {AfxMessageBox(_T("Функция доступна только администратору!"),MB_ICONWARNING); return false;}
	}


	if(!m_AllCategLoaded)
	{
//		m_api.m_categ_mgr.Load(true);
		m_AllCategLoaded=true;
	}

	if(0==item)
	{
		item=m_api.m_doc_mgr.SelectInstance(
			/*APL_MODE_SELECT_CATEGORY|*/
			APL_MODE_SELECT_FOLDER|
			APL_MODE_SELECT_PRD|
			APL_MODE_SELECT_PDF|
			APL_MODE_SELECT_DOC|
			APL_MODE_SELECT_BP|
			APL_MODE_SELECT_LOT|
			APL_MODE_SELECT_PRDINST|
			APL_MODE_SELECT_CLASSIF_SYSTEM|
			APL_MODE_SELECT_CHANGE|
			APL_MODE_SELECT_PROJECT|
			APL_MODE_SELECT_REQUIREMENT
			,
			 APL_T("Выберите экспортируемый объект"));
	}

	if(0==item) return false;

	if(item->GetAccessmode()>aplRO) {AfxMessageBox(_T("Недостаточно прав доступа!"),MB_ICONSTOP); return false;}



	CString err_mess;
	bool b=m_exchng_mgr.ExportInstance(item,_T(""),false,0,&err_mess);
	if(!b && err_mess==_T("")) return true; // была отмена

	if(err_mess==_T("")) AfxMessageBox( APL_T("Экспорт завершен!"));
	else {AfxMessageBox( APL_T("При экспорте возникли ошибки: ")+err_mess);return false;}

	return true;
}

//********************************************************************************
void CPSMDoc::OnShowSubscription() 
{
	aplExtent subscr_items;
	if(!m_api.m_message_mgr.GetPersonSubscribeList(NULL, subscr_items)) return;

	CSubscriptionDlg dlg;
	dlg.m_subscr_items.Append(subscr_items);
	dlg.m_api = &m_api;
	dlg.DoModal();
}
//********************************************************************************
void CPSMDoc::OnShowPersonAlerts() 
{
	CaplInstance *cur_person=m_api.m_message_mgr.GetCurrentPerson();
	if(cur_person) 
	{
		m_api.m_message_mgr.ShowPersonAlerts(cur_person);
	}
	else
	{
		AfxMessageBox( APL_T("Для текущего пользователя не указан сотрудник!"));
	}
}
void CPSMDoc::OnShowAllDocCopyes() 
{
	m_api.m_doc_mgr.ShowAllDocCopyes();
}
void CPSMDoc::OnShowMyDocCopyes() 
{
	CDocCopyFilter filter;
	filter.m_owner=m_api.m_appr_mgr.GetCurrentPerson();
	filter.m_b_only_out_of_order=false;
	filter.m_state=_T("");
	m_api.m_doc_mgr.ShowAllDocCopyes(&filter);
}
void CPSMDoc::OnShowMyOutOfOrderDocCopyes() 
{
	CDocCopyFilter filter;
	filter.m_owner=m_api.m_appr_mgr.GetCurrentPerson();
	filter.m_b_only_out_of_order=true;
	filter.m_state=_T("");
	m_api.m_doc_mgr.ShowAllDocCopyes(&filter);
}

void CPSMDoc::OnShowOutOfOrderCopyes() 
{
	CDocCopyFilter filter;
	filter.m_b_only_out_of_order=true;
	filter.m_state=_T("");
	m_api.m_doc_mgr.ShowAllDocCopyes(&filter);
}
void CPSMDoc::OnCreateHardCopy() 
{
	if(m_api.m_doc_mgr.CreateDocumentHardCopy())
	{
		AfxMessageBox( APL_T("Информация о копии документа успешно внесена в БД"));
	}
}
//********************************************************************************

#define SHOW_CMD_IF_DB_CONNECTED {if(!m_api.m_data.IsConnected())pCmdUI->Enable(FALSE);}

void CPSMDoc::OnUpdateExpandAll(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateDbFind(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateDbQuery(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateDbQueryPdfPiBp(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateNewMessageCreate(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateProductCompare(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateCreateWindow(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateEditCopy(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateEditPaste(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateActivateMainView(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateShowProperties(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateRefreshAll(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
void CPSMDoc::OnUpdateRefreshAllTreeItem(CCmdUI* pCmdUI) SHOW_CMD_IF_DB_CONNECTED
//********************************************************************************
void CPSMDoc::OnUpdateOpenItemInNewWindow(CCmdUI* pCmdUI)
{
	if(!m_api.m_data.IsConnected()) {pCmdUI->Enable(FALSE); return;}
}
//********************************************************************************
void CPSMDoc::OnChangePassword() {m_api.ChangeCurrentUserPassword();}
void CPSMDoc::OnImpGloss() { CGls_impDlg dlg; dlg.m_doc=this;dlg.DoModal();}
//********************************************************************************
void CPSMDoc::OnEditCopy() 
{
	//CNavigatorView *view=GetMyActiveView(); if(view!=0)view->OnCopy();
	CWnd* top_wnd = AfxGetMainWnd()->GetFocus();
	if(top_wnd->IsKindOf(RUNTIME_CLASS(CNavigatorView)))
	{
		((CNavigatorView*)top_wnd)->OnCopy();
	}
	else
	{
		top_wnd->SendMessage(WM_COPY,0,0);
	}
}

void CPSMDoc::OnEditPaste()
{
	//CNavigatorView *view=GetMyActiveView(); if(view!=0)view->OnPaste();
	CWnd* top_wnd = AfxGetMainWnd()->GetFocus();
	if(top_wnd->IsKindOf(RUNTIME_CLASS(CNavigatorView)))
	{
		((CNavigatorView*)top_wnd)->OnPaste();
	}
	else
	{
		top_wnd->SendMessage(WM_PASTE,0,0);
	}
}

void CPSMDoc::OnEditCut()
{
	CWnd* top_wnd = AfxGetMainWnd()->GetFocus();
	top_wnd->SendMessage(WM_CUT,0,0);
}
//********************************************************************************

#define PSM_CHEK_UPDATE {CNavigatorView *view=GetMyActiveView(); if(view==0)pCmdUI->Enable(FALSE); \
	else {if(!view->ShowToolBarButton(pCmdUI)) pCmdUI->Enable(FALSE);}}

#define PSM_CHEK_CONNECT {if(!m_api.m_data.IsConnected())pCmdUI->Enable(FALSE);}

void CPSMDoc::OnUpdateShowAllDocs(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllApproval(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllCharacteristic(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllLot(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllPrdInst(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllBpInst(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllVersion(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateProductShowAllZagotov(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateCreateDoc(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateCreateApproval(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateProductCreateSubpart(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateCreateCharacteristic(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateCreateBP(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllBP(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllBPResource(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateItemCheckIn(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateItemCheckOut(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateItemUndoCheckOut(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateGetDocumentLastVersion(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowDocumentChanges(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateItemView(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateCreateBpInst(CCmdUI* pCmdUI)  PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateOptionSelectDefDocType(CCmdUI* pCmdUI)  PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateOptionSelectDefCharacterystic(CCmdUI* pCmdUI)  PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateSetAccess(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
//********************************************************************************
void CPSMDoc::OnUpdateChangePassword(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateShowSubscription(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateShowPersonAlerts(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateMessageDeliver(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateTaskDeliver(CCmdUI* pCmdUI) PSM_CHEK_CONNECT

void CPSMDoc::OnUpdateShowNotes(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateCreateNote(CCmdUI* pCmdUI) PSM_CHEK_UPDATE
void CPSMDoc::OnUpdateShowAllDocCopyes(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateShowMyDocCopyes(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateShowMyOutOfOrderDocCopyes(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateShowOutOfOrderCopyes(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
void CPSMDoc::OnUpdateCreateHardCopy(CCmdUI* pCmdUI) PSM_CHEK_CONNECT


void CPSMDoc::OnUpdateSetupCharactiristic(CCmdUI* pCmdUI)
{
//	PSM_CHEK_CONNECT
}
void CPSMDoc::OnUpdateOptionsWork(CCmdUI* pCmdUI) PSM_CHEK_CONNECT
//********************************************************************************
#define PSM_RUN_CMD(cmd) {CNavigatorView *view=GetMyActiveView(); \
	if(view!=0) view->RunToolCmd(cmd);}

void CPSMDoc::OnShowAllApproval() PSM_RUN_CMD(ID_SHOW_ALL_APPROVAL)
void CPSMDoc::OnShowAllCharacteristic() PSM_RUN_CMD(ID_SHOW_ALL_CHARACTERISTIC)
void CPSMDoc::OnShowAllDocs() PSM_RUN_CMD(ID_SHOW_ALL_DOCS)
void CPSMDoc::OnShowAllLot() PSM_RUN_CMD(ID_SHOW_ALL_LOT)
void CPSMDoc::OnShowAllPrdInst() PSM_RUN_CMD(ID_SHOW_ALL_PRD_INST)
void CPSMDoc::OnShowAllBpInst() PSM_RUN_CMD(ID_SHOW_ALL_BP_INST)
void CPSMDoc::OnProductShowAllZagotov() PSM_RUN_CMD(ID_PRODUCT_SHOW_ALL_ZAGOTOV)
void CPSMDoc::OnCreateProduct() PSM_RUN_CMD(ID_CREATE_PRODUCT)
void CPSMDoc::OnCreateBpInst()  PSM_RUN_CMD(ID_CREATE_BP_INST)
void CPSMDoc::OnProductCreateCharacteristic() PSM_RUN_CMD(ID_CREATE_CHARACTERISTIC)
void CPSMDoc::OnShowAllVersion() PSM_RUN_CMD(ID_SHOW_ALL_VERSION)
void CPSMDoc::OnCreateApproval()PSM_RUN_CMD(ID_CREATE_APPROVAL)
void CPSMDoc::OnCreateDoc() PSM_RUN_CMD(ID_CREATE_DOC)
void CPSMDoc::OnExpandAll() PSM_RUN_CMD(ID_EXPAND_ALL)
void CPSMDoc::OnCreateBP() PSM_RUN_CMD(ID_CREATE_BP)
void CPSMDoc::OnShowAllBP() PSM_RUN_CMD(ID_SHOW_ALL_BP)
void CPSMDoc::OnShowAllBPResource() PSM_RUN_CMD(ID_SHOW_ALL_BP_RESOURCE)
void CPSMDoc::OnItemCheckIn() PSM_RUN_CMD(ID_ITEM_CHECK_IN)
void CPSMDoc::OnItemCheckOut() PSM_RUN_CMD(ID_ITEM_CHECK_OUT)
void CPSMDoc::OnGetDocumentLastVersion() PSM_RUN_CMD(ID_GET_DOCUMENT_LAST_VERSION)
void CPSMDoc::OnShowDocumentChanges() PSM_RUN_CMD(ID_SHOW_DOCUMENT_CHANGES)
void CPSMDoc::OnItemUndoCheckOut() PSM_RUN_CMD(ID_ITEM_UNDO_CHECK_OUT)
void CPSMDoc::OnItemView() PSM_RUN_CMD(ID_ITEM_VIEW)
void CPSMDoc::OnShowNotes() PSM_RUN_CMD(ID_SHOW_NOTES)
void CPSMDoc::OnCreateNote() PSM_RUN_CMD(ID_CREATE_NOTE)
void CPSMDoc::OnSetAccess() PSM_RUN_CMD(ID_SET_INST_ACCSESS)

void CPSMDoc::OnShowProperties() {CNavigatorView *view=GetMyActiveView(); if(view!=0) view->ShowProperties();}



void CPSMDoc::OnOpenItemInNewWindow() 
{
	CNavigatorView *view=GetMyActiveView(); 
	if(view==0) return;
	CaplTreeItem *item=(CaplTreeItem*)view->GetSelectedItemData();
	if(item==0) return;
	aplExtent ext;
	item->GetMainInstances(ext);
	if(ext.Size<1) return;
	OpenInstanceInNewWindow(ext[0]);
	return;
}
//********************************************************************************
void CPSMDoc::OnCreateWindow() 
{
	CFrameWnd * pFrame=m_pDocTemplate->CreateNewFrame(this,(CFrameWnd*)AfxGetMainWnd());
	m_pDocTemplate->InitialUpdateFrame(pFrame, this);
	m_additional_frames.Add(pFrame);
}
//********************************************************************************
void CPSMDoc::OpenExtentInNewWindow(aplExtent &ext, LPCTSTR sWndHeader)
{
	if(0==ext.GetSize()) return;

	int i;
	m_inserted_instances_in_new_window.Clear();
	for(i=0;i<ext.GetSize();i++)
	{
		CaplInstance *inst=ext[i];
		if(inst==0) continue;
		if(inst->GetAccessmode()>aplRO) continue;
		//if(inst->GetId()==0) return;
		if(m_api.m_data.IsKindOfBN(inst,_T("apl_user"))) continue;
		if(m_api.m_data.IsKindOf(inst,m_api.m_charact_mgr.e_apl_charact_value)) continue;
		if(m_api.m_data.IsKindOf(inst,m_api.m_charact_mgr.e_charact_val_group)) continue;
		if(m_api.m_data.IsKindOf(inst,m_api.m_appr_mgr.e_apl_appr_pers_org)) continue;

		m_inserted_instances_in_new_window.Add(inst);
	}
	if(0==m_inserted_instances_in_new_window.GetSize())
	{
		AfxMessageBox(APL_T("Нет объектов для показа в новом окне"),MB_ICONWARNING|MB_OK); 
		return;
	}

	CFrameWnd * pFrame=m_pDocTemplate->CreateNewFrame(this,(CFrameWnd*)AfxGetMainWnd());
	m_pDocTemplate->InitialUpdateFrame(pFrame, this);
	m_additional_frames.Add(pFrame);
 	m_inserted_instances_in_new_window.Clear();

	if(0!=sWndHeader) 	pFrame->SetWindowText(sWndHeader);
	else
	{
		CString buf;
		buf.Format(APL_T("%i объектов"),ext.GetSize());
		pFrame->SetWindowText(buf);
	}
}

//********************************************************************************
void CPSMDoc::OpenInstanceInNewWindow(CaplInstance *inst)
{
	//aplExtent ext; ext.Add(inst); return OpenExtentInNewWindow(ext); // для отладки

	if(inst==0) return;
	//if(inst->GetId()==0) return;
	if(m_api.m_data.IsKindOfBN(inst,_T("apl_user"))) return;
	if(m_api.m_data.IsKindOf(inst,m_api.m_charact_mgr.e_apl_charact_value)) return;
	if(m_api.m_data.IsKindOf(inst,m_api.m_charact_mgr.e_charact_val_group)) return;
	if(m_api.m_data.IsKindOf(inst,m_api.m_appr_mgr.e_apl_appr_pers_org)) return;
	

	if(m_api.m_data.IsKindOf(inst,m_api.m_classifier_mgr.e_apl_classifier_system))
	{
		CFrameWnd* pFrame=aplCreateClassifiersFrame((CMainFrame*)AfxGetMainWnd(), &m_api, inst, IDR_PSMTYPE);
		if(pFrame)
		{
			m_additional_frames.Add(pFrame);
			((CMainFrame*)AfxGetMainWnd())->MDITile(MDITILE_HORIZONTAL);
		}
		return;
	}
	
	if(m_api.m_data.IsKindOf(inst,m_api.m_folder_mgr.e_folder))
	{
		CString sName;
		m_api.m_data.GetAttr(inst, m_api.m_folder_mgr.a_folder_name, sName);

		if (m_api.m_options_mgr.CheckInstallCode(_T("KVZ")))
		{
			CString sRootFolder;
			m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("КВЗ\\АРМ Редактор ТС\\Корневая папка"), sRootFolder, APL_NO_T("__Технологические сборки"));			
			if(sName== APL_NO_T("__Технологические сборки") || sRootFolder==sName)
			{
				if(InitTechToolsPanel(inst))
					return;
			}
		}
		
		// модуль LifeCycleManagment
		{
			CString sRootFolder;
			m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Корневая папка для проектов"), sRootFolder, APL_NO_T("Все проекты"));
			
			if(sName==APL_NO_T("Все проекты") || sRootFolder==sName)
			{
				if(InitLifeCycleManagmentPanel(inst))
					return;
			}
		}
	}

	if (m_api.m_data.IsKindOf(inst, m_api.m_prd_mgr.e_apl_pdf))
	{
		CString strProductType;
		CString strDistrCode;

		m_api.m_data.GetAttr(inst, m_api.m_prd_mgr.a_apl_pdf_type, strProductType);

		if (strProductType == _T("module"))
		{
// 			m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Код установки"), strDistrCode, _T(""));

			if (strDistrCode.IsEmpty() || strDistrCode.CompareNoCase(_T("KVZ")) == 0)
			{
				if (InitModuleContentEditorFrame(inst))
					return;
			}
		}
	}

	m_inserted_instances_in_new_window.Clear();
	m_inserted_instances_in_new_window.Add(inst);
	CFrameWnd * pFrame=m_pDocTemplate->CreateNewFrame(this,(CFrameWnd*)AfxGetMainWnd());
	m_pDocTemplate->InitialUpdateFrame(pFrame, this);
	m_additional_frames.Add(pFrame);
	m_inserted_instances_in_new_window.Clear();

	CString buf, sFrameHeader;
	sFrameHeader=m_api.GetItemTypeName(inst);
	sFrameHeader+=_T(":  ");
	m_api.GetItemName(inst,buf);
	sFrameHeader+=buf;
	pFrame->SetWindowText(sFrameHeader);
}

CFrameWnd* CPSMDoc::InitLifeCycleManagmentPanel(CaplInstance *pFolder)
{
	CFrameWnd * (*funcInitLifeCycleManagment)(CMainFrame*, CaplAPI*, CaplInstance*, UINT) = NULL;
	HINSTANCE hLifeCycleManagmentDLL = NULL;	
	CString strLibModuleName;

#ifdef DEBUG
	strLibModuleName = _T("LifeCycleManagmentDLL_d.dll");
#else
	strLibModuleName = _T("LifeCycleManagmentDLL.dll");
#endif

	hLifeCycleManagmentDLL = AfxLoadLibrary(strLibModuleName);;
	if (hLifeCycleManagmentDLL == NULL)
		return 0;

	(FARPROC&)funcInitLifeCycleManagment = ::GetProcAddress(hLifeCycleManagmentDLL, "InitFrame");
	if (funcInitLifeCycleManagment == NULL)
		return 0;	

	CFrameWnd *pFrame = funcInitLifeCycleManagment((CMainFrame*)AfxGetMainWnd(), &m_api, pFolder, IDD_TSE_ID);	
	if(pFrame)
	{
		m_additional_frames.Add(pFrame);
		((CMainFrame*)AfxGetMainWnd())->MDITile(MDITILE_HORIZONTAL);
	}

	return pFrame;
}

CFrameWnd* CPSMDoc::InitTechToolsPanel(CaplInstance *pFolder)
{
	CFrameWnd * (*funcInitTechTools)(CMainFrame*, CaplAPI*, CaplInstance*, UINT) = NULL;
	HINSTANCE hTechToolsLibDLL = NULL;	
	CString strLibModuleName;

#ifdef DEBUG
	strLibModuleName = _T("TechToolsLibD.dll");
#else
	strLibModuleName = _T("TechToolsLib.dll");
#endif

	hTechToolsLibDLL = AfxLoadLibrary(strLibModuleName);;
	if (hTechToolsLibDLL == NULL)
		return 0;

	(FARPROC&)funcInitTechTools = ::GetProcAddress(hTechToolsLibDLL, "InitFrame");
	if (funcInitTechTools == NULL)
		return 0;

	//////////////////////////////////////////////////////////////////////////		

// 	CFrameWnd *pMainWnd = (CFrameWnd*)AfxGetMainWnd();
// 	CRuntimeClass *pTechToolsFrameClass;
// 	CCreateContext ccTechToolsFrameContext;
// 	CMultiDocTemplate *pDocTemplate;

	CFrameWnd *pFrame =funcInitTechTools((CMainFrame*)AfxGetMainWnd(), &m_api, pFolder, IDD_TSE_ID);

// 	ccTechToolsFrameContext.m_pNewViewClass = pTechToolsFrameClass;
// 	ccTechToolsFrameContext.m_pCurrentDoc   = this;	
// 
// 	pDocTemplate = new CMultiDocTemplate(
// 		IDR_MAINFRAME,
// 		RUNTIME_CLASS(CPSMDoc),
// 		pTechToolsFrameClass, // custom MDI child frame
// 		RUNTIME_CLASS(CNavigatorView));
// 
// 	AfxGetApp()->AddDocTemplate(pDocTemplate);	
// 
// 	CFrameWnd* pFrame= pDocTemplate->CreateNewFrame(this, pMainWnd);		
// 	pDocTemplate->InitialUpdateFrame(pFrame, this);
	if(pFrame)
	{
		m_additional_frames.Add(pFrame);
		((CMainFrame*)AfxGetMainWnd())->MDITile(MDITILE_HORIZONTAL);
	}

	return pFrame;
}

CFrameWnd* CPSMDoc::InitModuleContentEditorFrame(CaplInstance *pModuleProduct)
{
	CFrameWnd *(*funcModuleContentEditor)(CMainFrame*, CaplAPI*, CaplInstance*, UINT) = NULL;
	HINSTANCE hCatalogEditorLibDLL = NULL;	
	CString strLibModuleName;

#ifdef DEBUG
	strLibModuleName = _T("aplCatalogEditorD.dll");
#else
	strLibModuleName = _T("aplCatalogEditor.dll");
#endif

	hCatalogEditorLibDLL = AfxLoadLibrary(strLibModuleName);;

	if (hCatalogEditorLibDLL == NULL)
		return 0;

	(FARPROC&)funcModuleContentEditor = ::GetProcAddress(hCatalogEditorLibDLL, "InitModuleContentEditorFrame");

	if (funcModuleContentEditor == NULL)
		return 0;

	CFrameWnd *pModuleContentEditorFrame = funcModuleContentEditor((CMainFrame*)AfxGetMainWnd(), &m_api, pModuleProduct, IDD_MCE_ID);

	if (pModuleContentEditorFrame != NULL)
	{
		m_additional_frames.Add(pModuleContentEditorFrame);
		((CMainFrame*)AfxGetMainWnd())->MDITile(MDITILE_HORIZONTAL);
	}

	return pModuleContentEditorFrame;
}

//********************************************************************************
BOOL CPSMDoc::CanCloseFrame(CFrameWnd* pFrame) 
{
	if(!m_navigator) return TRUE;
	CFrameWnd *fr=m_navigator->GetParentFrame();
	if(fr==pFrame) return FALSE;
	return TRUE;
}
//********************************************************************************
void CPSMDoc::OnActivateMainView() 
{
	if(m_navigator==0) return;
	CWnd *my_frm=m_navigator->GetParentFrame();
	if(my_frm!=0)((CMDIFrameWnd*)AfxGetMainWnd())->MDIActivate(my_frm);	
}
//********************************************************************************
void CPSMDoc::LoadPSMAddIns()
{
	m_addin_menu_items.RemoveAll();
	CaplPluginItem::InitForcedPlagins();
	
	CaplStringFile pl_file;
// 	CStdioFile pl_file;
	CString exe_path;
	CString sPath(_T(""));
	GetExePath(exe_path);
	m_addin_tab_views.DeleteAllViews();
	
	m_nIndex = ID_PLUGIN_000;

	CMainFrame* wnd= (CMainFrame*)AfxGetMainWnd();

	if(!pl_file.Open(exe_path+_T("psm.add"),CFile::modeRead|CFile::shareDenyNone)) return;

//		int ind = ID_PLUGIN_000;
	HINSTANCE hInst = AfxGetResourceHandle();
	CString err_mess;
	
	CaplPluginItem::m_parent = (CWnd*)m_tab_view;
	CaplPluginItem::m_doc= this;
	CaplPluginItem::m_frame= wnd;
	CaplPluginItem::m_msg = ((CPSMApp*)AfxGetApp())->m_view_update;
	CaplPluginItem::m_allMess[0] = ((CPSMApp*)AfxGetApp())->m_view_update;
	CaplPluginItem::m_allMess[1] = ((CPSMApp*)AfxGetApp())->m_view_disconnect;

	for(int fi=0; fi<1;)
	{
		CaplPluginItem *pItem = new CaplPluginItem;
		ASSERT(pItem);
		pItem->m_global_views = &m_addin_tab_views;

		int res = pItem->ReadDataFromFile(pl_file, sPath, APL_LOAD_DATA, &err_mess);
//			ind= m_nIndex;
		
		if(res==0)
			pItem->InitMenuItems(m_nIndex, m_addin_menu_items);

		delete pItem;
		if(res==-2) break;
	}
	if(err_mess!=_T("")){
		AfxMessageBox( APL_T("При загрузке дополнений возникли следующие ошибки:")+err_mess,MB_SYSTEMMODAL|MB_OK);
	}

	if(CaplPluginItem::m_arForcedPlagins.GetSize())
	{
		int iIndex (-1);

		CaplTAggr<CaplPluginItem*, CaplPluginItem*, APLAGGR_AUTOKILLREF|APLAGGR_LIST> arPLItems;

		CaplPluginItem* pItem= new CaplPluginItem;		
		ASSERT(pItem);

		if(pItem)
		{
			pItem->ReadItem(CaplPluginItem::m_arForcedPlagins, iIndex, arPLItems, &err_mess);
			pItem->m_global_views = &m_addin_tab_views;
		}

		for(int i= 0; i<arPLItems.GetSize(); i++)
		{
			arPLItems[i]->InitMenuItems(m_nIndex, m_addin_menu_items);
			arPLItems[i]->CreateTabViews();
			arPLItems[i]->CreateDocbars();
		}
	}

	for(int vc=0;vc<m_addin_tab_views.GetSize();vc++)
	{
		CaplViewInfo *vi = m_addin_tab_views.GetAt(vc);
		AddView(vi->view);

		if(aplDocbar==vi->viewtype && wnd)
		{
			
		}
	}

	AfxSetResourceHandle(hInst);
	pl_file.Close();
	CMainFrame *frm=(CMainFrame *)AfxGetMainWnd();
	if(frm)
	{
		frm->AppendMainMenu(this);
	}
	return;
	
}
/* Убрана поддержка форм им. Орлова
void CPSMDoc::LoadFormsData(void)
{
	aplExtent		aeForms;
	aplExtent		aeFormsNF;
	aplExtent		aeInsts;

	CaplInstance*	cit			=NULL;
	CaplInstance*	cit2		=NULL;
	CaplInstance*	cit3		=NULL;
	CaplInstance*	cit4		=NULL;

	CString			cst;

	int				i,j;
	
	if(false==m_api.m_data.IsConnected())
		return;


	m_caFormMenuItems.RemoveAll();
	
	m_api.m_form_mgr.LoadData();

	m_api.m_data.GetEntityExtent(m_api.m_form_mgr.e_form,aeFormsNF);

	cst=_T("");
	m_form_mgr_dlg.FilterForms(&m_api,aeFormsNF,aeForms,cst);

	for(i=0;i<aeForms.GetSize();i++)
	{
		FormMenuItem item;

		item.m_iID=ID_FORM_000+i;

		cit=aeForms.GetAt(i);
		m_api.m_data.GetAttr(cit,m_api.m_form_mgr.a_form_active,cit4);
		if(NULL==cit4)
			continue;
		item.m_ciForm=cit4;
		m_api.m_data.GetAttr(cit,m_api.m_form_mgr.a_form_name,cst);
		item.m_csFormName=cst;
		m_api.m_data.GetAttr(cit,m_api.m_form_mgr.a_form_instances,aeInsts);
		for(j=0;j<aeInsts.GetSize();j++)
		{
			cit2=aeInsts.GetAt(j);
			m_api.m_data.GetAttr(cit2,m_api.m_form_mgr.a_form_instance_base_instance,cit3);
			if(NULL==cit3)
			{
				m_api.m_data.GetAttr(cit2,m_api.m_form_mgr.a_form_instance_entity_name,cst);
				item.m_csBaseInstEntName=cst;
				break;
			}
		}
		aeInsts.Clear();
		m_caFormMenuItems.Add(item);
	}

	m_nIndex+=i;
}
*/

void CPSMDoc::OnMyOfficial() 
{
//	m_api.m_appr_mgr.GetPersonOfficials();
	CaplInstance *person=m_api.m_appr_mgr.GetCurrentPerson();
	if(person==NULL)
	{
		AfxMessageBox( APL_T("Анонимный пользователь !!!"));
		return;
	}
	m_api.m_appr_mgr.ShowPersonOfficials(person);
}

void CPSMDoc::OnSetupAddin() 
{
	for(int i= 0; i<m_additional_ctrlbars.GetSize(); i++)
	{
		m_additional_ctrlbars[i]->SaveState(_T(""));
		m_additional_ctrlbars[i]->m_MyWnd->DestroyWindow();
		m_additional_ctrlbars[i]->DestroyWindow();
		delete m_additional_ctrlbars[i];
	}
	m_additional_ctrlbars.RemoveAll();
	CMainFrame* frm= (CMainFrame*)AfxGetMainWnd();
	if(frm)frm->RecalcLayout();

	CAddInSetupDlg dlg;
	dlg.DoModal();
	LoadPSMAddIns();
	if(m_api.m_data.IsConnected())
	{
		OnRefreshAllTreeItem();
	}
}


bool CPSMDoc::LoadCompositionRequirements()
{
	bool (*funcLoadComposotionReq)(CaplAPI*) = NULL;

	if(m_hConfigMgrLib != NULL)
	{
		(FARPROC&)funcLoadComposotionReq = ::GetProcAddress(m_hConfigMgrLib, "add_LoadCompositionRequirements");	
		if(funcLoadComposotionReq)
		{
			funcLoadComposotionReq(&m_api);			
		}
	}

	return true;
}

bool CPSMDoc::LoadFoldersMap()
{
	CStdioFile f;
	CString fname = m_api.m_data.GetNameCurrBase();
	fname+=m_api.m_data.GetNameCurrUser();
	fname+=_T(".folder");
	TCHAR buf[1024]=_T("");
	DWORD len = 1024;
	GetPrivateProfileString(_T("Paths"), _T("Dictionary"), _T(""), buf, len,
								   _T("AplTransport.ini"));
	CString dir = buf;
	if(f.Open(dir+_T("\\")+fname,CFile::modeRead))
	{
		CString str;
		while(f.ReadString(str))
		{
			DWORD dw;
			CString path;
			dw = _atoi(str.Left(str.Find(_T(" "))));
			path = str.Right(str.GetLength()-str.Find(_T(" "))-1);
			m_folders_map[dw]=path;
		}
		f.Close();
	}
	return true;
}

bool CPSMDoc::SaveFolders()
{
	CStdioFile f;
	CString fname = m_api.m_data.GetNameCurrBase();
	fname+=m_api.m_data.GetNameCurrUser();
	if(fname.IsEmpty()) return false;
	fname+=_T(".folder");
	TCHAR buf[1024]=_T("");
	DWORD len = 1024;
	GetPrivateProfileString(_T("Paths"), _T("Dictionary"), _T(""), buf, len,
								   _T("AplTransport.ini"));

	CString str, sOut;

	int cnt = m_folders_map.GetCount();
	POSITION pos = m_folders_map.GetStartPosition();
	DWORD dw;
	CString path;
	for(int i=0; i<cnt;i++)
	{
		m_folders_map.GetNextAssoc(pos,dw,path);
		str.Format(_T("%d %s"),dw,path);
		sOut+=str;
		sOut+=_T("\n");
	}

	CString dir = buf;
	CString sFileName=dir+_T("\\")+fname;

	if(sOut.IsEmpty())
	{
		CaplFile::Remove(sFileName);
	}
	else
	{
		if(f.Open(sFileName,CFile::modeCreate|CFile::modeWrite))
		{
			f.WriteString(sOut);
			f.Close();
		}
	}
	return true;
}

void CPSMDoc::OnReportTableSetup()
{
	m_api.m_doc_mgr.SetupApprovalFieldsInReports();
}

void CPSMDoc::OnSetupCharactiristic() 
{
	CStringArray Columns;
	CaplTAggr<CStringArray*,CStringArray*,APLAGGR_AUTOKILLREF|APLAGGR_LIST> Items;
	Columns.Add( APL_T("Название"));
	Columns.Add( APL_T("Идентификатор"));
	CStringArray* array;

	CUIntArray mask;
	int i;
	CString buf;
	aplExtent ext0;

	m_charact_names.RemoveAll();
	m_api.m_data.GetEntityExtentBN(_T("apl_characteristic"),ext0);
	for(i=0;i<ext0.Size;i++)
	{
		m_api.m_data.GetAttrBN(ext0[i],S::name,buf);
		m_charact_names.Add(buf);
		array=new CStringArray();
		array->Add(buf);
		m_api.m_data.GetAttrBN(ext0[i],S::id,buf);
		array->Add(buf);
		Items.Add(array);
		if(m_characteristics_show.Find(ext0[i])>-1)
			mask.Add(i);
	}
	if(DoChooseCharacteristicsDlg(&Columns, &Items,&mask))
	{
		m_characteristics_show.Clear();
		for(i=0; i<mask.GetSize();i++)
			m_characteristics_show.Add(ext0[mask[i]]);
		if(!m_api.m_data.IsConnected()) return;
		CRegKey key;
		if(!key.Open(HKEY_CURRENT_USER,_T("Software\\CALS Centre \"Applied Logistic\"\\PSM\\options\\Characteristics"))==ERROR_SUCCESS)
			key.Create(HKEY_CURRENT_USER,_T("Software\\CALS Centre \"Applied Logistic\"\\PSM\\options\\Characteristics"),
			REG_NONE,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS);
		DWORD cnt = 0;
#if _MSC_VER >= 1400
		if(key.QueryDWORDValue(_T("Count"), cnt)==ERROR_SUCCESS)
#else
		if(key.QueryValue(cnt,_T("Count"))==ERROR_SUCCESS)
#endif
		{
			for(DWORD i=0;i<cnt;i++)
			{
				CString value;
				value.Format(_T("value%d"),i);
				key.DeleteValue(value);
			}
		}
		cnt = m_characteristics_show.Size;
#if _MSC_VER >= 1400
		key.SetDWORDValue(_T("Count"), cnt);
#else
		key.SetValue(cnt,_T("Count"));
#endif
		for(i=0; i<(int)cnt;i++)
		{
			CString id, value;
			CaplInstance *inst  =m_characteristics_show[i];
			m_api.m_data.GetAttr(inst,m_api.m_charact_mgr.a_apl_charact_id,id);
			value.Format(_T("value%d"),i);
#if _MSC_VER >= 1400
			key.SetStringValue(value, id.GetBuffer(0));
#else
			key.SetValue(id.GetBuffer(0),value);
#endif
		}
		key.Close();
		((CDocsListView*)(this->m_tab_view->m_DocsView))->UpdateHeaders();
	}
}

void CPSMDoc::LoadCharacteristicShow()
{
	if(!m_api.m_data.IsConnected()) return;
	m_characteristics_show.Clear();
	CRegKey key;
	if(key.Open(HKEY_CURRENT_USER,_T("Software\\CALS Centre \"Applied Logistic\"\\PSM\\options\\Characteristics"))==ERROR_SUCCESS)
	{
		DWORD cnt = 0;
#if _MSC_VER >= 1400
		long res = key.QueryDWORDValue(_T("Count"), cnt);
#else
		long res = key.QueryValue(cnt,_T("Count"));
#endif
		if(res==ERROR_SUCCESS)
		for(DWORD i=0; i<cnt;i++)
		{
			CString value;
			DWORD dw=64;
			TCHAR *id = new TCHAR [64];
			value.Format(_T("value%d"),i);
#if _MSC_VER >= 1400
			if(key.QueryStringValue(value, id, &dw) == ERROR_SUCCESS)
#else
			if(key.QueryValue(id,value,&dw)==ERROR_SUCCESS)
#endif
			{
				CaplInstance *inst = m_api.m_charact_mgr.GetCharacteristicById(id);
				m_characteristics_show.Add(inst);
			}
			delete [] id;
		}
		key.Close();
	}
}

void CPSMDoc::OnShowNameOption() 
{
	if(m_api.m_show.ShowOption())
	{
		OnRefreshAllTreeItem();	
	}
}

void CPSMDoc::OnOptionsShow() 
{
	COptionsShowDlg  dlg;
	dlg.m_show_classificators = m_api.m_show.m_show_classificators;
	dlg.m_show_org_struct = m_api.m_show.m_show_org_struct;
	dlg.m_PrdNoShowPlusToPart = m_api.m_show.m_PrdNoShowPlusToPart;
	dlg.m_b_show_categ = m_b_show_categ;
	
	int opt_val = m_api.m_options_mgr.GetIntOptionValueBN(APL_NO_T("PSS\\Настройки\\show_old_query_dlg"),0);
	if(opt_val == 1 && CPSMDoc::m_show_old_query_dlg == 0)
	{
		dlg.m_show_old_query_dlg=TRUE;
	}
	dlg.m_doc = this;
	if(dlg.DoModal()==IDOK)
	{
		m_api.m_show.m_show_org_struct = dlg.m_show_org_struct;
		m_api.m_show.m_show_classificators = dlg.m_show_classificators;
		m_api.m_show.m_PrdNoShowPlusToPart = dlg.m_PrdNoShowPlusToPart;
		m_b_show_categ = dlg.m_b_show_categ;
		m_api.m_show.SaveData();
		m_api.m_query_mgr.SetStyleDlg(CPSMDoc::m_show_old_query_dlg);

		if(dlg.m_bNeewResetFont)
		{
			if(m_navigator) 
			{
				m_navigator->ResetFont();
				m_navigator->Invalidate();
			}
			int i;
			for(i=0; i<m_additional_frames.GetSize();i++) 
			{
				CView *pView = (m_additional_frames[i])->GetActiveView();
				if(0!=pView)
				{
					if(pView->IsKindOf(RUNTIME_CLASS(CNavigatorView)))
					{
						((CNavigatorView*)pView)->ResetFont();
						((CNavigatorView*)pView)->Invalidate();
					}
				}
			}
			for(i=0; i<m_additional_views.GetSize();i++) 
			{
				m_additional_views[i]->ResetFont();
				m_additional_views[i]->Invalidate();
			}
		}
		OnRefreshAllTreeItem();
	}	
}

void CPSMDoc::OnOptionsWork() 
{
	// TODO: Add your command handler code here
	CMainFrame *frm=(CMainFrame*) AfxGetMainWnd();
	if(frm==0) return;

	COptionsWorkDlg  dlg;
	dlg.m_doc=this;
	
	dlg.m_mesTime= frm->m_AutoDeliveMesTime;
	dlg.m_taskTime= frm->m_AutoDeliveTaskTime;
	dlg.m_mesDelive= frm->m_AutoDeliveMes;
	dlg.m_taskDelive= frm->m_AutoDeliveTask;
	dlg.m_NotifyWithPersonalMonitor= frm->m_NotifyWithPersonalMonitor;

	dlg.m_auto_change_wf_state = m_api.m_show.m_auto_wfstate;
	
	if(dlg.DoModal()==IDOK) 
	{
		m_api.m_show.m_auto_wfstate = dlg.m_auto_change_wf_state;

		frm->m_AutoDeliveMesTime= dlg.m_mesTime;
		frm->m_AutoDeliveTaskTime= dlg.m_taskTime;
		frm->m_AutoDeliveMes= dlg.m_mesDelive;
		frm->m_AutoDeliveTask= dlg.m_taskDelive;
		frm->m_NotifyWithPersonalMonitor= dlg.m_NotifyWithPersonalMonitor;
		
		frm->SetAutoDeliveMes();
		AfxGetApp()->WriteProfileString(_T("options"),_T("WorkFolder"),CaplDocTreeItem::m_EditPath);
		//m_last_open_doc->OnRefreshAllTreeItem();
	}	
}


void CPSMDoc::OnOptionsShowintree() 
{
	m_auto_expand_items.Setup();
}

void CPSMDoc::OnUpdatePersonalMonitor(CCmdUI* pCmdUI) 
{
	if(m_api.m_data.IsConnected()) pCmdUI->Enable(TRUE);
	else pCmdUI->Enable(FALSE);
	
}
void CPSMDoc::OnPersonalMonitor() 
{
	CaplInstance* ciPerson=m_api.m_appr_mgr.GetCurrentPerson();
	
	if(NULL==ciPerson)
	{
		// о-бос-саться...
//		AfxMessageBox(APL_T("У пользователя не задан сотрудник!"),MB_ICONSTOP|MB_OK);
		return;
	}
	int i=0;
	
	CMainFrame *frm=(CMainFrame*) AfxGetMainWnd();
	BOOL bOld1= frm->m_AutoDeliveMes;
	BOOL bOld2= frm->m_AutoDeliveTask;
	frm->m_AutoDeliveMes=FALSE;
	frm->m_AutoDeliveTask= FALSE;
	frm->SetAutoDeliveMes();
	CheckNewMonitorEvents(i, _T(""));	
	frm->m_AutoDeliveMes=bOld1;
	frm->m_AutoDeliveTask=bOld2;
	frm->SetAutoDeliveMes();
}




void CPSMDoc::CheckAllNewMessages(int &iRes)
{
	CaplInstance* ciPerson;
	aplExtent aeMail;
	int i;
	CaplInstance* cit1;
	CString cst1;
	ciPerson = m_api.m_appr_mgr.GetCurrentPerson();
	if(m_api.m_message_mgr.GetPersonIncomingMessages(aeMail,ciPerson,false,false,false))
		iRes|=1;
	for(i=0;i<aeMail.GetSize();i++)
	{
		cit1=aeMail.GetAt(i);
		m_api.m_data.GetAttr(cit1,m_api.m_message_mgr.a_message_status,cst1);
		
		if(_T("readed")!=cst1&&_T("replyed")!=cst1)
		{
			iRes|=8;
			return;
		}	
	}
}

void CPSMDoc::CheckAllNewProcessController(int &iRes)
{
	CaplInstance*	ciPerson	=NULL;
	aplExtent		aeProcesses;
	CaplInstance*	cit1		=NULL;
	CaplInstance*	cit2		=NULL;
	CString			cst1,cst2, sDate;
	COleDateTime odt= COleDateTime::GetCurrentTime(); 
	CString	buf;
	int i;
	if(!m_api.m_data.IsConnected()) return;
	
	ciPerson=m_api.m_appr_mgr.GetCurrentPerson();
	if(NULL==ciPerson)
	{
//		AfxMessageBox(APL_T("У пользователя не задан сотрудник!"),MB_ICONSTOP|MB_OK);
		return;
	}
	m_wf_mgr.GetUserProcessList(ciPerson, aeProcesses, false, true);
	
	bool bFindNew= false;
	aplDate2String(odt, sDate);

	for(i=0;i<aeProcesses.GetSize();i++)
	{
		cit1=aeProcesses.GetAt(i);
		
		m_api.m_data.GetAttr(cit1,	m_wf_mgr.a_proc_manager, cit2);
		if(NULL == cit2) continue;
		if(!aplIsPersonOrgElement(&m_api, cit2,ciPerson))
			continue;
		
		iRes|=32;

		m_api.m_data.GetAttr(cit1, m_wf_mgr.a_act_inst_last_susp_date, buf);
		if(buf.IsEmpty())
		{
			bFindNew= true;
			m_api.m_data.PutAttr(cit1, m_wf_mgr.a_act_inst_last_susp_date, sDate);
		}
	}

	if(bFindNew)
	{
		//AfxMessageBox(APL_T("Получены новые процессы, в которых Вы являетесь Ответсвенным за контроль."));
		/*MessageBox(NULL, APL_T("Получены новые процессы, в которых Вы являетесь Ответсвенным за контроль. "));
			APL_T("\n\nДля просмотра заданий откройте раздел \"Работы -> Задания\"."), 
			APL_T("Новые задания"),	MB_ICONINFORMATION|MB_OK);*/
		//CheckNewMonitorEvents();	
		m_api.SaveChanges();
		iRes|=4;
	}
}

void CPSMDoc::CheckAllNewTask(int &iRes)
{
	CaplInstance* ciPerson;
	CaplInstance* cit1;
	CaplInstance* cit2;
	aplExtent aeTasks;
	int i;
	CString cst1;	
	ciPerson=m_api.m_appr_mgr.GetCurrentPerson();
	
	if(m_wf_mgr.GetUserTaskList(ciPerson,aeTasks,false,false,false))
		iRes|=2;

	for(i=0;i<aeTasks.GetSize();i++)
	{
		cit1=aeTasks.GetAt(i);
		m_api.m_data.GetAttr(cit1,m_wf_mgr.a_task_performer,cit2);
//		if(ciPerson!=cit2)
//			continue;

		m_api.m_data.GetAttr(cit1,m_wf_mgr.a_task_state,cst1);
		if(cst1==_T("suspend") || cst1==_T("complete") || cst1==_T("cancel"))
			continue;
		iRes|=16;
		return;
	}	
}

void CPSMDoc::CheckAllNewAlerts(int &iRes)
{
	CaplInstance*		ciPerson;
	CaplInstance*		cit1;
	CaplLoadData		cld(&m_api.m_data,DEF_SOURCE);
	aplExtent			aeReminders;
	CString				cst1,cst2;
	COleDateTime		codt1,codt2;
	int i;
			ciPerson = m_api.m_appr_mgr.GetCurrentPerson();
			if(NULL == ciPerson)	return;

			m_api.m_message_mgr.LoadPersonAlerts(ciPerson,false,true, aeReminders);

			for(i=0;i<aeReminders.GetSize();i++)
			{
				cit1=aeReminders.GetAt(i);
				m_api.m_data.GetAttr(cit1,m_api.m_message_mgr.a_alert_state,cst1);
				if(cst1==m_api.m_message_mgr.m_alert_state_active)
				{
					m_api.m_data.GetAttr(cit1,m_api.m_message_mgr.a_alert_date,cst2);
					if(_T("")!=cst2)
					{
						m_api.m_data.NET_GetServerDateTime(codt1);
						aplString2Date(cst2,codt2);
						if(codt1>codt2)
						{
							iRes|=64;
							return;
						}
						
					}
				}
			
			}
}



void CPSMDoc::OnUpdateConfigure(CCmdUI* pCmdUI) 
{
	if(!m_api.m_data.IsConnected() || NULL == m_hConfigMgrLib) 
		pCmdUI->Enable(FALSE);
}

void CPSMDoc::OnUpdateShowVariantRule(CCmdUI* pCmdUI) 
{
	if(!m_api.m_data.IsConnected() || NULL == m_hConfigMgrLib) 
		pCmdUI->Enable(FALSE);
}



void CPSMDoc::OnPersonalOptions()
{
	if(!m_api.m_data.IsConnected()){AfxMessageBox(APL_T("Соединение с БД не установлено!"),MB_ICONSTOP); return;}

	m_api.m_options_mgr.EditPersonalOptions();
}

void CPSMDoc::OnAshMoImp()
{
#ifdef ENABLE_ASH_MO
	CAshMoImportDialog impDlg;
	impDlg.m_api=&m_api;
	if(!impDlg.Init()) return;

	impDlg.DoModal();

	return;
#endif
}

void CPSMDoc::OnAshMoVerify()
{
#ifdef ENABLE_ASH_MO
	CAshMoImportDialog impDlg;
	impDlg.m_api=&m_api;
	
	// Пока основной код будет с шифтом.  А без него - заглушка
	if(GetKeyState(VK_SHIFT)< 0)  
	{
		impDlg.AshMoVerifyPackage();
		return;
	}	

	impDlg.m_bOnlyVerify=true;

	if(!impDlg.Init()) return;

	impDlg.DoModal();

#endif
}
