// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include <afxmt.h>
#include "PSM.h"
#include "resource.h"

#include "MainFrm.h"
#include "TabView.h"
#include "NavigatorView.h"

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

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CaplMDIFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CaplMDIFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	ON_WM_SIZE()
	ON_COMMAND(ID_INFO_PANEL, OnNavigatorPanel)
	ON_UPDATE_COMMAND_UI(ID_INFO_PANEL, OnUpdateNavigatorPanel)
	ON_WM_DESTROY()
	ON_WM_SHOWWINDOW()
	ON_COMMAND(ID_SHOW_TOOLBAR_BMP, OnShowToolbarBmp)
	ON_WM_CLOSE()
	ON_WM_SETCURSOR()
	ON_COMMAND(ID_CUST_MAIN_TB, OnCustMainTb)
	ON_COMMAND(ID_TREE_XP_STYLE, OnTreeXpStyle)
	ON_UPDATE_COMMAND_UI(ID_TREE_XP_STYLE, OnUpdateTreeXpStyle)
	ON_UPDATE_COMMAND_UI(ID_SHOW_TOOLBAR_BMP, OnUpdateShowToolbarBmp)
	//}}AFX_MSG_MAP
	ON_WM_DRAWITEM()
	ON_WM_MEASUREITEM()
	ON_COMMAND(ID_VIEW_TOOLBAR, &CMainFrame::OnViewToolbar)
	ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLBAR, &CMainFrame::OnUpdateViewToolbar)
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

int CMainFrame::m_AutoDeliveMesTime= 5;
BOOL CMainFrame::m_AutoDeliveMes= TRUE;
int CMainFrame::m_AutoDeliveTaskTime= 5;
BOOL CMainFrame::m_AutoDeliveTask= TRUE;
BOOL CMainFrame::m_NotifyWithPersonalMonitor= TRUE;
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	// TODO: add member initialization code here
	m_last_open_doc=0;
	m_ShowToolBarBitmap=AfxGetApp()->GetProfileInt(_T("options"),_T("ShowToolBarBitmap"),1);
	m_hCursor=0;
	m_old_cx=0;
	m_AutoDeliveMesTimer=0;

	m_AlertTimer= 0;

#ifdef ENABLE_ASH_MO
	m_bEnableAshMo=false;
#endif

}
//********************************************************************************
CMainFrame::~CMainFrame()
{
/*	for(int i= 0; i<m_sub_menu.GetSize(); i++)
	{
		if(m_sub_menu[i])
		{
			m_sub_menu[i]->DestroyMenu();
			delete m_sub_menu[i];
		}
	}*/

	AfxGetApp()->WriteProfileInt(_T("options"),_T("ShowToolBarBitmap"),m_ShowToolBarBitmap);
}
//********************************************************************************
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CaplMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	CaplTreeView::LoadXpMode();

#ifdef ENABLE_ASH_MO
	CString cmdLine=AfxGetApp()->m_lpCmdLine;
	if(cmdLine.Find(_T("/ash-mo"))>=0) m_bEnableAshMo=true;
#endif

	if (!m_wndToolBar.CreateEx(this,TBSTYLE_FLAT|TBSTYLE_TRANSPARENT|RBBS_CHILDEDGE) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
		{TRACE0("Failed to create toolbar\n");return -1;}

/*	if (!m_wndMainTB0.CreateEx(this,TBSTYLE_FLAT|TBSTYLE_TRANSPARENT) ||
		!m_wndMainTB0.LoadToolBar(IDR_MAIN_TB0))
		{TRACE0("Failed to create toolbar\n");return -1;}
*/
	if (!m_wndMainTB1.CreateEx(this,TBSTYLE_FLAT|TBSTYLE_TRANSPARENT) ||
		!m_wndMainTB1.LoadToolBar(IDR_MAIN_TB2))
		{TRACE0("Failed to create toolbar\n");return -1;}


	if (!m_wndReBar.Create(this,RBS_FIXEDORDER|RBS_BANDBORDERS/*|RBS_AUTOSIZE*/  ) ||
		!m_wndReBar.AddBar(&m_wndToolBar,_T(""),0,RBBS_GRIPPERALWAYS|RBBS_FIXEDBMP ) ||
//		!m_wndReBar.AddBar(&m_wndMainTB0 ,_T(""),0,RBBS_GRIPPERALWAYS|RBBS_FIXEDBMP) ||
		!m_wndReBar.AddBar(&m_wndMainTB1 ,_T(""),0,RBBS_GRIPPERALWAYS|RBBS_FIXEDBMP))
	{
		TRACE0("Failed to create rebar\n");
		return -1;      // fail to create
	}

	if(aplGetBitPerPixel(this)>8)
	{
		CBitmap bmp0;
		bmp0.LoadBitmap(IDB_TB_MAINFRAME_BIG);
		m_il_ToolBar.Create(32,32,ILC_COLOR24|ILC_MASK,0,100);
		m_il_ToolBar.Add(&bmp0,RGB(192,192,192));
		m_wndToolBar.GetToolBarCtrl().SetImageList(&m_il_ToolBar);

		HIMAGELIST tmp_i_l=aplImageListCopyAsSpecificBlend((HIMAGELIST)m_il_ToolBar,25,true);
		m_il_ToolBar_d.Attach(tmp_i_l);
		m_wndToolBar.GetToolBarCtrl().SetDisabledImageList(&m_il_ToolBar_d);


		/*CBitmap bmp1;
		bmp1.LoadBitmap(IDR_TB0);
		m_il_TB0.Create(20,20,ILC_COLOR8|ILC_MASK,0,100);
		m_il_TB0.Add(&bmp1,RGB(192,192,192));
		m_wndMainTB0.GetToolBarCtrl().SetImageList(&m_il_TB0);	*/

		CBitmap bmp1;
		bmp1.LoadBitmap(IDB_TC_MAIN_TB2);
		m_il_TB1.Create(32,32,ILC_COLOR24|ILC_MASK,0,100);
		m_il_TB1.Add(&bmp1,RGB(192,192,192));
		m_wndMainTB1.GetToolBarCtrl().SetImageList(&m_il_TB1);	
		
		HIMAGELIST tmp_il1=aplImageListCopyAsSpecificBlend((HIMAGELIST)(*m_wndMainTB1.GetToolBarCtrl().GetImageList()),25,true);
		m_il_TB1_d.Attach(tmp_il1);
		m_wndMainTB1.GetToolBarCtrl().SetDisabledImageList(&m_il_TB1_d);	
	}

	m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |	CBRS_TOOLTIPS | CBRS_FLYBY);
	m_wndMainTB1.SetBarStyle(m_wndToolBar.GetBarStyle() |	CBRS_TOOLTIPS | CBRS_FLYBY);
	m_wndReBar.GetReBarCtrl().MinimizeBand(0);


	/*CRect rect_mf;
	GetWindowRect(rect_mf);
	SetWindowPos(&wndTopMost,rect_mf.left,rect_mf.top,rect_mf.Width(),rect_mf.Height(),SWP_SHOWWINDOW);	
	SetWindowPos(&wndNoTopMost,rect_mf.left,rect_mf.top,rect_mf.Width(),rect_mf.Height(),SWP_SHOWWINDOW);*/

	
#ifndef _DEBUG
	UINT tect_btn_index=m_wndMainTB1.GetToolBarCtrl().CommandToIndex(ID_TEST);
	if(tect_btn_index>=0)m_wndMainTB1.GetToolBarCtrl().DeleteButton(tect_btn_index);
#endif

	if(m_ShowToolBarBitmap)
	{
		if(aplGetBitPerPixel(this)>8)
		{

			CMenu *mnu=GetMenu();
			mnu->CheckMenuItem(ID_SHOW_TOOLBAR_BMP,MF_BYCOMMAND|MF_CHECKED);
			
//			m_wndReBar.SetBitmap(&m_BkBmp);
//			m_wndToolBar.RedrawWindow();
//			m_wndMainTB0.RedrawWindow();
//			m_wndMainTB1.RedrawWindow();
		}		
	}
	

	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}
	if (!m_InfoBar.Create( APL_T("Панель закладок"), this, CSize(300, 50),
	        TRUE, ID_ORGANIZER_BAR))
    {
		TRACE0("Failed to create mybar\n");return -1;      // fail to create
	}

	m_InfoBar.SetBarStyle(m_InfoBar.GetBarStyle() |
        CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);

	// TODO: Delete these three lines if you don't want the toolbar to
	//  be dockable
// До ReBar	m_wndToolBar.EnableDocking(CBRS_ALIGN_TOP);

	m_InfoBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
//	DockControlBar(&m_wndToolBar);
	DockControlBar(&m_InfoBar, AFX_IDW_DOCKBAR_RIGHT);

	m_InfoBar.LoadState(_T("InfoBar"));
	LoadBarState(_T("ControlBars_2_8_9"));

	/*CMenu!!!
	CaplMenu::LoadXpMode(); //< Чтение из реестра
	CaplMenu::SetXPBitmap3D(0);
	CaplMenu::SetIconSize(20,16);
	*/

	// заполняем меню доступных языков перевода
	//aplFillLanguageMenu(GetMenu(), _T("&Настройки"), _T("Language (Язык интерфейса)"));
	aplFillLanguageMenu(GetMenu(), _T("Language (Язык интерфейса)"));

	CaplMenu::m_icon_size.cx=20;
	CaplMenu::m_icon_size.cy=16;
	CaplMenu::Install(this);

 	// Чтение иконок для всех меню заранее
	CaplMenu::LoadToolBar(IDR_MENU_ICONS, IDB_TC_POPUP_MENU);
	CaplMenu::LoadToolBar(IDR_MENU_ICONS_CONTINUE);
	CaplMenu::LoadToolBar(IDR_MENU_ICONS_4TC_0,IDB_TC_MENU_ICON);

	CBitmap bmp;
	bmp.LoadBitmap(IDB_TB_LOGO);
	m_wndReBar.CreateLogoBar(&bmp,RGB(192,192,192));


#ifdef ENABLE_ASH_MO 
	if(m_bEnableAshMo)
	{
		if (!m_wndAshMoTB.CreateEx(this,TBSTYLE_FLAT|TBSTYLE_TRANSPARENT) ||
			!m_wndAshMoTB.LoadToolBar(IDR_TB_ASH_MO))
		{TRACE0("Failed to create toolbar\n");return -1;}

		m_sModuleName=(_T("АСХ МО"));

		m_wndReBarAshMoTB.Create(this,RBS_FIXEDORDER|RBS_BANDBORDERS/*|RBS_AUTOSIZE*/  ) ;
		m_wndReBarAshMoTB.AddBar(&m_wndAshMoTB ,_T(""),0,RBBS_GRIPPERALWAYS|RBBS_FIXEDBMP);

		CBitmap bmp0;
		bmp0.LoadBitmap(IDB_TC_ASH_MO_TB);
		m_il_ToolBarAshMo.Create(48,48,ILC_COLOR24|ILC_MASK,0,100);
		m_il_ToolBarAshMo.Add(&bmp0,RGB(192,192,192));
		m_wndAshMoTB.GetToolBarCtrl().SetImageList(&m_il_ToolBarAshMo);

		HIMAGELIST tmp_i_l=aplImageListCopyAsSpecificBlend((HIMAGELIST)m_il_ToolBarAshMo,25,true);
		m_il_ToolBarAshMo_d.Attach(tmp_i_l);
		m_wndAshMoTB.GetToolBarCtrl().SetDisabledImageList(&m_il_ToolBarAshMo_d);

		m_wndAshMoTB.SetBarStyle(m_wndToolBar.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY);
		
		m_wndReBarAshMoTB.GetReBarCtrl().MinimizeBand(0);

		CBitmap bmp;
		bmp.LoadBitmap(IDB_ASH_MO_LOGO);
		m_wndReBarAshMoTB.CreateLogoBar(&bmp,RGB(192,192,192));

		m_about_ash_mo.LoadBitmap(IDB_ASH_MO_ABOUT);
		aplSetLogoBmp(&m_about_ash_mo);
	}
#endif

	if(!m_InfoBar.CreateView(0))
		return FALSE;

	{
		CRect rt;
		((CTabView*)m_InfoBar.m_MyWnd)->OnInitialUpdate();
		m_InfoBar.GetClientRect(rt);
		m_InfoBar.m_MyWnd->MoveWindow(rt,TRUE);
	}	

#ifdef ENABLE_ASH_MO 
	if(m_bEnableAshMo)
	{
		ShowControlBar(&m_wndReBar, FALSE, FALSE);
		ShowControlBar(&m_InfoBar, FALSE, FALSE);
	}
#endif

	m_AutoDeliveMesTime=AfxGetApp()->GetProfileInt(_T("options"), _T("AutoDeliveMesTime"), 5);
	m_AutoDeliveTaskTime=AfxGetApp()->GetProfileInt(_T("options"), _T("AutoDeliveTaskTime"), 5);
	int i= AfxGetApp()->GetProfileInt(_T("options"),_T("AutoDeliveMes"), 0);
	if(i)
		m_AutoDeliveMes= TRUE;
	else
		m_AutoDeliveMes= FALSE;
	i= AfxGetApp()->GetProfileInt(_T("options"),_T("AutoDeliveTask"), 0);
	if(i)
		m_AutoDeliveTask= TRUE;
	else
		m_AutoDeliveTask= FALSE;

	i= AfxGetApp()->GetProfileInt(_T("options"),_T("NotifyWithPersonalMonitor"), 1);
	if(i)
		m_NotifyWithPersonalMonitor= TRUE;
	else
		m_NotifyWithPersonalMonitor= FALSE;


//	SetAutoDeliveMes();
	SetAlertTimer(10000);
	return 0;
}
//********************************************************************************
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CaplMDIFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs
	cs.style &=~FWS_ADDTOTITLE;

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CaplMDIFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CaplMDIFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers

//********************************************************************************
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) 
{
	// TODO: Add your specialized code here and/or call the base class
	BOOL k=CaplMDIFrameWnd::OnCreateClient(lpcs, pContext); 
	if(m_last_open_doc==0)
	{
		if(pContext!=0)
			m_last_open_doc=(CPSMDoc*)pContext->m_pCurrentDoc;
	}
	return TRUE;
}
//********************************************************************************
void CMainFrame::SetStatusString(LPCTSTR str)
{
	m_wndStatusBar.SetWindowText(str);
}
//********************************************************************************
void CMainFrame::OnSize(UINT nType, int cx, int cy) 
{
	CaplMDIFrameWnd::OnSize(nType, cx, cy);

#ifdef ENABLE_ASH_MO
	if(0!=m_wndReBarAshMoTB.m_hWnd)  m_wndReBarAshMoTB.GetReBarCtrl().MinimizeBand(0);
#endif

	// TODO: Add your message handler code here
	RecalcLayout();
	if(nType==SIZE_MINIMIZED) return;
	/*if(m_wndReBar.m_hWnd!=0) 
	{
		m_wndReBar.GetReBarCtrl().MinimizeBand(0);
		m_wndReBar.GetReBarCtrl().MaximizeBand(1);
		m_wndReBar.GetReBarCtrl().MaximizeBand(2);
	}*/
	
	// Разворот панели Пропорционально
	if(m_InfoBar.m_hWnd!=0) 
	{
		if(cx>0)
		{
			if(m_old_cx>0)
			{
				double k=(double)cx/(double)m_old_cx;
				int a=(long)((double)(m_InfoBar.m_szHorz.cx)*k);
				if(a<cx-10)
				{
					m_InfoBar.m_szHorz.cx=a;
					m_InfoBar.m_szVert.cx=(long)((double)(m_InfoBar.m_szVert.cx)*k);
					m_InfoBar.m_szFloat.cx=(long)((double)(m_InfoBar.m_szFloat.cx)*k);
					RecalcLayout();
				}
			}
			m_old_cx=cx;
		}
	}
}
//********************************************************************************
void CMainFrame::OnNavigatorPanel() 
{
	BOOL bShow = m_InfoBar.IsVisible();
	ShowControlBar(&m_InfoBar, !bShow, FALSE);
}
//********************************************************************************
void CMainFrame::OnUpdateNavigatorPanel(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable();
	pCmdUI->SetCheck(m_InfoBar.IsVisible());
}
//********************************************************************************
void CMainFrame::OnDestroy() 
{
	CaplMDIFrameWnd::OnDestroy();
}
//********************************************************************************
void CMainFrame::OnShowWindow(BOOL bShow, UINT nStatus) 
{
	CaplMDIFrameWnd::OnShowWindow(bShow, nStatus);
	
	// TODO: Add your message handler code here
	m_wndReBar.UpdateLogoBarVizible();

#ifdef ENABLE_ASH_MO 
	if(m_bEnableAshMo)
	{
		//m_wndReBarAshMoTB.OnRbnChildSize(0, 0);
		m_wndReBarAshMoTB.UpdateLogoBarVizible();
	}
#endif	

	RecalcLayout();
	
}
//********************************************************************************
void CMainFrame::StartBusy(){m_wndReBar.StartAnimation(true);
				m_hCursor=AfxGetApp()->LoadStandardCursor(IDC_WAIT);
};

void CMainFrame::StopBusy(){m_wndReBar.StartAnimation(false);/*EndWaitCursor();*/m_hCursor=0;}

CWaitCursor *wcur=0;
void StartBusy()
{
	CMainFrame *frm=(CMainFrame *)AfxGetMainWnd();
	if(frm!=0) frm->StartBusy();
	AfxGetApp()->BeginWaitCursor();
//	AfxGetApp()->DoWaitCursor(1);
//	if(wcur==0) wcur=new CWaitCursor();
}
void StopBusy()
{
	CMainFrame *frm=(CMainFrame *)AfxGetMainWnd();
	if(frm!=0) frm->StopBusy();
	AfxGetApp()->EndWaitCursor();
//	AfxGetApp()->DoWaitCursor(-1);
	if(wcur!=0) {delete wcur;wcur=0;}

}
//********************************************************************************
void CMainFrame::OnShowToolbarBmp() 
{
	CMenu *mnu=GetMenu();
	if(mnu==0) return;
	if(m_ShowToolBarBitmap)
	{
		m_wndReBar.SetBitmap(0);
		//m_wndToolBar.SetShowBkBmpMode(false);
		m_ShowToolBarBitmap=FALSE;
	}
	else
	{
		m_wndReBar.SetBitmap(&m_BkBmp);
		//m_wndToolBar.SetShowBkBmpMode(true);
		m_ShowToolBarBitmap=TRUE;
	}
	m_wndToolBar.RedrawWindow();
//	m_wndMainTB0.RedrawWindow();
	m_wndMainTB1.RedrawWindow();
	
}
void CMainFrame::OnUpdateShowToolbarBmp(CCmdUI* pCmdUI) 
{
	if(m_ShowToolBarBitmap) pCmdUI->SetCheck(1);
	else pCmdUI->SetCheck(0);
}

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


void CMainFrame::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	CMyOleDataSource::m_exit=true;

	// Сохранение позици
	AfxGetApp()->WriteProfileInt(_T("MainFrame"),_T("Maximized"),IsZoomed());


	m_InfoBar.SaveState(_T("InfoBar"));
    SaveBarState(_T("ControlBars_2_8_9"));
	
	int n= 0;
	if(m_AutoDeliveMes)
		n= 1;
	AfxGetApp()->WriteProfileInt(_T("options"), _T("AutoDeliveMesTime"), m_AutoDeliveMesTime);
	AfxGetApp()->WriteProfileInt(_T("options"), _T("AutoDeliveMes"), n);
	n= 0;
	if(m_AutoDeliveTask)
		n= 1;
	AfxGetApp()->WriteProfileInt(_T("options"), _T("AutoDeliveTaskTime"), m_AutoDeliveTaskTime);
	AfxGetApp()->WriteProfileInt(_T("options"), _T("AutoDeliveTask"), n);

	n= 0;
	if(m_NotifyWithPersonalMonitor) n= 1;
	AfxGetApp()->WriteProfileInt(_T("options"), _T("NotifyWithPersonalMonitor"), n);

	CaplMDIFrameWnd::OnClose();
}


BOOL CMainFrame::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) 
{
	// TODO: Add your message handler code here and/or call default
	if (m_hCursor != NULL)
	{
		::SetCursor(m_hCursor);
		return TRUE;
	}
	return CaplMDIFrameWnd::OnSetCursor(pWnd, nHitTest, message);
}

void CALLBACK EXPORT AutoDeliveMes( HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime)
{	
	CaplInstance*	ciPerson								=NULL;
	
	CPSMDoc *doc=GetActiveDocument();
	int iRes;
	CString str;
	
	static int iMyCountCheck = 0; // Счетчик времени с момента последней проверки в минутах
	static int iMyCountShow = 0;  // Счетчик времени с момента последнего отображения
	
	iMyCountCheck++;	
	iMyCountShow++;	
	
	if(0==doc) return;
	if(!doc->m_api.m_data.IsConnected()) return;

	iRes = 0;
	CMainFrame *frm=(CMainFrame*) AfxGetMainWnd();
	if(0==frm) return;
	bool bShow= false, bChecked= false;
	if(iMyCountCheck>=frm->m_AutoDeliveMesTime)// проверить новые
	{		
		iMyCountCheck= 0;
		if(doc!=0 && frm->m_AutoDeliveMes)
		{
			//TRACE(_T("one %i\n"), iMyCountCheck);
			BOOL bOld1= frm->m_AutoDeliveMes;
			BOOL bOld2= frm->m_AutoDeliveTask;
			frm->m_AutoDeliveMes=FALSE;
			frm->m_AutoDeliveTask= FALSE;
			frm->SetAutoDeliveMes();

//			doc->CheckNewMessages(iRes);
//			doc->CheckNewTask(iRes);
//			doc->CheckNewProcessController(iRes);
			
			doc->CheckAllNewMessages(iRes);
			doc->CheckAllNewTask(iRes);
			doc->CheckAllNewProcessController(iRes);
			
			bChecked= true;

			if(iRes)
			{
				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  - процессы, в которых Вы являетесь\n    ответственным за контроль");
				}
				
				if(!str.IsEmpty())
				{
					doc->CheckNewMonitorEvents(iRes, str);
					bShow= true; // уже показали разок, причем с проверкой новых
				}
			}
			str.Empty();
			
			frm->m_AutoDeliveMes=bOld1;
			frm->m_AutoDeliveTask=bOld2;
			frm->SetAutoDeliveMes();
		}
	}
	
	if(iMyCountShow>=frm->m_AutoDeliveTaskTime)// показать если есть что
	{
		iMyCountShow= 0;
		if(doc!=0 && !bShow && frm->m_AutoDeliveTask) // второй раз не показываем
		{
			//TRACE(_T("sec %i\n"), iMyCountShow);
			BOOL bOld1= frm->m_AutoDeliveMes;
			BOOL bOld2= frm->m_AutoDeliveTask;
			frm->m_AutoDeliveMes=FALSE;
			frm->m_AutoDeliveTask= FALSE;
			frm->SetAutoDeliveMes();
			
			if(!bChecked) // чтобы второй раз не лезть в базу
			{
				doc->CheckAllNewMessages(iRes);
				doc->CheckAllNewTask(iRes);
				doc->CheckAllNewProcessController(iRes);
			
			}
					
			if(iRes)
			{
				if(iRes&8)
				{
					if(str.IsEmpty()) str=  APL_T("У Вас есть:\n \n");
					str +=  APL_T("\n  - непрочитанные сообщения");
				}
				if(iRes&16)
				{
					if(str.IsEmpty()) str=  APL_T("У Вас есть:\n \n");
					str +=  APL_T("\n  - невыполненные задания");
				}
				if(iRes&32)
				{
					if(str.IsEmpty()) str=  APL_T("У Вас есть:\n \n");
					str +=  APL_T("\n  - невыполненные процессы, в которых \n");
					str +=  APL_T("    Вы являетесь ответственным \n"); 
					str +=  APL_T("    за контроль");
				}
				
				if(!str.IsEmpty()) doc->CheckNewMonitorEvents(iRes, str);
			}
			str.Empty();
			
			frm->m_AutoDeliveMes=bOld1;
			frm->m_AutoDeliveTask=bOld2;
			frm->SetAutoDeliveMes();
		}		
	}
}

void CMainFrame::SetAutoDeliveMes()
{
	if(m_AutoDeliveMesTimer!=0) {
		KillTimer(m_AutoDeliveMesTimer);m_AutoDeliveMesTimer=0;}

	if(m_AutoDeliveMes || m_AutoDeliveTask)
	{
		// Таймер должен срабатывать каждую минуту, а период проверки определяется счетчиком внутри функции
#ifdef _DEBUG
	m_AutoDeliveMesTimer=SetTimer((long)this, 1000*15, &AutoDeliveMes);	/*15 секунд*/
#else
	m_AutoDeliveMesTimer=SetTimer((long)this, 1000*60, &AutoDeliveMes); // 1 мин.
#endif
	}
}

void CALLBACK EXPORT CheckUserAlerts( HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime)
{
	CPSMDoc *doc= GetActiveDocument();
	CMainFrame* mFrm= (CMainFrame*)AfxGetMainWnd();
	if(0==doc || 0== mFrm) return;
	if(!doc->m_bCheckingAlerts)doc->ShowUserAlerts(mFrm);
	
}

void CMainFrame::SetAlertTimer(UINT time)
{
	if(m_AlertTimer!=0) 
	{
		KillTimer(m_AlertTimer);m_AlertTimer= 0;
	}
	if(time>0) 
	{
		m_AlertTimer= SetTimer((long)this - 2, time, &CheckUserAlerts);
	}
}

void CMainFrame::OnCustMainTb() 
{
	m_wndToolBar.GetToolBarCtrl().Customize();	
}

void CMainFrame::AppendMainMenu(CPSMDoc *doc)
{
	if(!doc) return;

	CArray <CMenu*,CMenu*> menu_for_delete;

	CMenu* pSubMenu= NULL;
	m_menu.LoadMenu(IDR_MAINFRAME);

	// заполняем меню доступных языков перевода
	//aplFillLanguageMenu(&m_menu, _T("&Настройки"), _T("Language (Язык интерфейса)"));
	aplFillLanguageMenu(&m_menu, _T("Language (Язык интерфейса)"));

	int i;
	for(i= 0; i<doc->m_addin_menu_items.GetSize(); i++)
	{
		//наш или не наш клиент?
		if(doc->m_addin_menu_items[i].m_itemType.IsEmpty() && doc->m_addin_menu_items[i].m_mEnable)
		{			
			CString tmp, name, buf= doc->m_addin_menu_items[i].m_menuName;			
			
			buf.Remove(_T('&'));
			
			pSubMenu = &m_menu;
			while(true)
			{
				int index= buf.Find(_T('\\'));
				if(-1==index)//корневой элемент
				{
					int iPos= buf.Find(_T(']'));
					if(-1!=iPos)
					{
						int n= buf.Find(_T('['));
						if(-1==n){iPos= -1;}
						else 
						{
							tmp= buf.Mid(n+1, iPos-n-1);
							buf= buf.Right(buf.GetLength()-iPos-1);
							iPos= _atoi(tmp);
						}
					}		
					
					if(!buf.IsEmpty()) pSubMenu->InsertMenu(iPos, MF_BYPOSITION|MF_STRING, doc->m_addin_menu_items[i].m_id, buf);
					else pSubMenu->InsertMenu(iPos, MF_BYPOSITION|MF_SEPARATOR, 0, _T(""));
					break;
				}
				else
				{
					CString str;
					name= buf.Left(index);
					tmp= buf.Right(buf.GetLength()-index-1);
					buf= tmp;
					
					int iPos= name.Find(_T(']'));
					if(-1!=iPos)
					{
						int n= name.Find(_T('['));
						if(-1==n){iPos= -1;}
						else 
						{
							tmp= name.Mid(n+1, iPos-n-1);
							name= name.Right(name.GetLength()-iPos-1);
							iPos= _atoi(tmp);
						}
					}

					CMenu *found_menu=0;

					int count= pSubMenu->GetMenuItemCount();
					for (int pos= 0; pos<count; pos++)
					{
						pSubMenu->GetMenuString(pos, str, MF_BYPOSITION);
						str.Remove(_T('&'));
						if(str.CompareNoCase(name)==0)
						{
							found_menu=(CMenu*)pSubMenu->GetSubMenu(pos);
							if(found_menu!=0) break;
						}
					}
					if(found_menu==0)
					{
						
						found_menu= new CMenu;
						menu_for_delete.Add (found_menu);
						found_menu->CreateMenu();
						//pSubMenu->InsertODMenu(iPos, name, MF_BYPOSITION|MF_POPUP,(UINT)found_menu->m_hMenu,-1);
						pSubMenu->InsertMenu(iPos, MF_BYPOSITION|MF_POPUP,(UINT)found_menu->m_hMenu,name);
						int cnt = pSubMenu->GetMenuItemCount();
					}
					pSubMenu=found_menu;
				}
			}
		}
	}


	for(i=0; i<menu_for_delete.GetSize(); i++)
	{
		CMenu *mnu=menu_for_delete[i];
		mnu->Detach();
		delete mnu;
	}
	menu_for_delete.RemoveAll();



	//Это Саня добавлял (выбор пунктов для отображения закладок)
	CString str;
	int count= m_menu.GetMenuItemCount();
	for(int pos=0; pos<count; pos++)
	{
		m_menu.GetMenuString(pos, str, MF_BYPOSITION);
		str.Remove(_T('&'));
		if(str.CompareNoCase( APL_T("Вид"))==0)
		{
			CMenu* view_menu=(CMenu*)m_menu.GetSubMenu(pos);
			if(!view_menu) break;
			int iPos= view_menu->GetMenuItemCount();
			view_menu->InsertMenu(iPos++, MF_BYPOSITION|MF_SEPARATOR, 0, _T(""));
			
			if(doc->m_additional_ctrlbars.GetSize()>0)
			{
				CMenu* addin_menu= new CMenu;
				addin_menu->CreateMenu();
				//view_menu->InsertODMenu(iPos++, APL_T("Дополнения"), MF_BYPOSITION|MF_POPUP,(UINT)addin_menu->m_hMenu,-1);
				view_menu->InsertMenu(iPos++, MF_BYPOSITION|MF_POPUP,(UINT)addin_menu->m_hMenu, APL_T("Дополнения"));

				for(i= 0; i<doc->m_additional_ctrlbars.GetSize(); i++)
				{
					addin_menu->InsertMenu(i, MF_BYPOSITION|MF_STRING, 
						doc->m_additional_ctrlbars[i]->m_iBarID, 
						doc->m_additional_ctrlbars[i]->m_BarName);
				}
				break;
			}
		}			
	}

	OnUpdateFrameMenu(m_menu.m_hMenu);
	m_menu.Detach();//Без этого Detach происходит падение при повторном вызове этой функции
	DrawMenuBar( );

}

BOOL CMainFrame::OnCommand(WPARAM wParam, LPARAM lParam) 
{
	int i;
	int iCommand= wParam;
	if(m_last_open_doc)
	{
		if(iCommand>=ID_PLUGIN_000 && iCommand<=ID_PLUGIN_150)
		{
			for(i= 0; i<m_last_open_doc->m_addin_menu_items.GetSize(); i++)
			{
				if(iCommand==m_last_open_doc->m_addin_menu_items[i].m_id &&
					m_last_open_doc->m_addin_menu_items[i].m_pFunc)
				{
					aplExtent ext;
					CaplTreeItem *item = NULL;
					CNavigatorView* pView = m_last_open_doc->GetMyActiveView();
					if (pView)
						item=(CaplTreeItem *)m_last_open_doc->GetMyActiveView()->GetSelectedItemData();
					
					if(item!=0) item->GetMainInstances(ext);
					
					bool bUI= false;
					m_last_open_doc->m_addin_menu_items[i].m_pFunc(&m_last_open_doc->m_api, ext, bUI);
					return TRUE;
				}
			}
			bool bNeedUpdate= false;
			for(i= 0; i<m_last_open_doc->m_additional_ctrlbars.GetSize(); i++)
			{
				if(m_last_open_doc->m_additional_ctrlbars[i]->m_iBarID==(DWORD)iCommand)
				{
					m_last_open_doc->m_additional_ctrlbars[i]->m_iIsVisible=
						!m_last_open_doc->m_additional_ctrlbars[i]->m_iIsVisible;
					bNeedUpdate= true;
				}
			}
			if(bNeedUpdate) m_last_open_doc->UpdateAddinPanels();
		}
	}

	aplSetLanguageOnCommandHandler(wParam,lParam,this); // обработка переключения языка

	return CaplMDIFrameWnd::OnCommand(wParam, lParam);
}

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

BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) 
{
	for(int i= 0; m_last_open_doc && i<m_last_open_doc->m_additional_ctrlbars.GetSize(); i++)
	{
		if(nID==m_last_open_doc->m_additional_ctrlbars[i]->m_iBarID)
		{
			if(pExtra)((CCmdUI*)pExtra)->SetCheck(m_last_open_doc->m_additional_ctrlbars[i]->m_iIsVisible);
			return TRUE;
		}
	}
	
	// Функция проверяет обработку сообщений. 
	// И если обработчик вызывается для галочки языка в меню, устанавливает значение галочки
	aplSetLaguageOnCmdMsgHandler( nID, nCode, pExtra); // Обработка установки галочки в меню для переключения языка

	return CaplMDIFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}

void CMainFrame::OnMenuXpStyle() 
{
	/*CMenu!!!
	if(0==CaplMenu::GetMenuDrawMode()) CaplMenu::SetMenuDrawMode(1);
	else  CaplMenu::SetMenuDrawMode(0);

	CaplMenu::SaveXpMode(); //< Сохранение в реестре*/
}

void CMainFrame::OnUpdateMenuXpStyle(CCmdUI* pCmdUI) 
{
	/*CMenu!!!if(1==CaplMenu::GetMenuDrawMode()) pCmdUI->SetCheck(1);
	else pCmdUI->SetCheck(0);*/
}

void CMainFrame::OnTreeXpStyle() 
{
	CaplTreeView::m_xp_mode=!CaplTreeView::m_xp_mode;
	CaplTreeView::SaveXpMode(); //< Сохранение в реестре
}

void CMainFrame::OnUpdateTreeXpStyle(CCmdUI* pCmdUI) 
{
	if(CaplTreeView::m_xp_mode) pCmdUI->SetCheck(1);
	else pCmdUI->SetCheck(0);

}

void CMainFrame::SaveBarState(LPCTSTR lpszProfileName) const
{
	CDockState state;
	GetDockState(state);
	state.SaveState(lpszProfileName);	
}

void CMainFrame::GetDockState(CDockState& state) const
{
	state.Clear(); //make sure dockstate is empty
	// get state info for each bar
	POSITION pos = m_listControlBars.GetHeadPosition();
	while (pos != NULL)
	{
		CControlBar* pBar = (CControlBar*)m_listControlBars.GetNext(pos);
		ASSERT(pBar != NULL);
		if(pBar->IsKindOf(RUNTIME_CLASS(CaplAddInBar)))
		{
			CaplAddInBar* navBar= (CaplAddInBar*)pBar;
			navBar->SaveState(_T(""));
			continue;
		}
		CControlBarInfo* pInfo = new CControlBarInfo;
		pBar->GetBarInfo(pInfo);
		state.m_arrBarInfo.Add(pInfo);
	}	
}


void CMainFrame::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	// TODO: Add your message handler code here and/or call default
/*
	CaplMDIFrameWnd::OnDrawItem(nIDCtl, lpDrawItemStruct);
	aplMainMenu.OnDrawItem(this,nIDCtl,lpDrawItemStruct);*/
}

void CMainFrame::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
	// TODO: Add your message handler code here and/or call default
/*
	if(lpMeasureItemStruct->CtlType!=ODT_MENU) CaplMDIFrameWnd::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
	else aplMainMenu.OnMeasureItem(this,nIDCtl,lpMeasureItemStruct);*/
}

void CMainFrame::OnUpdateFrameTitle(BOOL bAddToTitle)
{
	// TODO: Add your specialized code here and/or call the base class
	CaplMDIFrameWnd::OnUpdateFrameTitle(bAddToTitle);

	CaplMenu::UpdateMenu(GetMenu()); 
	CaplMenu::SetMenuBk(this);
}
//********************************************************************************

void CMainFrame::OnViewToolbar()
{
	BOOL bShow = m_wndReBar.IsVisible();
	ShowControlBar(&m_wndReBar, !bShow, FALSE);
}

void CMainFrame::OnUpdateViewToolbar(CCmdUI *pCmdUI)
{
	pCmdUI->Enable();
	pCmdUI->SetCheck(m_wndReBar.IsVisible());
}
