//this file is part of eMule
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


// emuleDlg.cpp : Implementierungsdatei
//

#include "stdafx.h"
#include "emule.h"
#include "emuleDlg.h"
#include "sockets.h"
#include "knownfilelist.h"
#include "knownfile.h"
#include "serverlist.h"
#include "opcodes.h"
#include "sharedfilelist.h"
#include "creditsdlg.h"
#include "ED2KLink.h"
#include "math.h"
#include "Splashscreen.h"
#pragma comment(lib, "winmm.lib")
#include "Mmsystem.h"
#include "enbitmap.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//extern volatile BYTE		g_byHashThreadRunning; // declared in SharedFileList.cpp

extern void URLDecode(CString& result, const char* buff);

const static UINT UWM_ARE_YOU_EMULE=RegisterWindowMessage(_T(EMULE_GUID));
// CemuleDlg Dialog

CemuleDlg::CemuleDlg(CWnd* pParent /*=NULL*/)
	: CTrayDialog(CemuleDlg::IDD, pParent){
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_app_state	=	APP_STATE_RUNNING;
	ready = false; startUpMinimized=false;
	lastuprate = 0;
	lastdownrate = 0;
	status = 0;
	connicons[0] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_NOTCONNECTED),IMAGE_ICON,16,16,0);
	connicons[1] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_CONNECTED),IMAGE_ICON,16,16,0);
	connicons[2] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_CONNECTEDHIGH),IMAGE_ICON,16,16,0);
	transicons[0] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_UPDOWN),IMAGE_ICON,16,16,0);
	transicons[1] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_UP0DOWN1),IMAGE_ICON,16,16,0);
	transicons[2] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_UP1DOWN0),IMAGE_ICON,16,16,0);
	transicons[3] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_UP1DOWN1),IMAGE_ICON,16,16,0);
	imicons[0] = 0;
	imicons[1] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_MESSAGE),IMAGE_ICON,16,16,0);
	imicons[2] = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_MPENDING),IMAGE_ICON,16,16,0);
	sourceTrayIcon= (HICON)LoadImage(AfxGetInstanceHandle() ,MAKEINTRESOURCE(IDR_TRAYICON),IMAGE_ICON,16,16,LR_DEFAULTCOLOR);
	sourceTrayIconGrey= (HICON)LoadImage(AfxGetInstanceHandle() ,MAKEINTRESOURCE(IDR_TRAYICON_GREY),IMAGE_ICON,16,16,LR_DEFAULTCOLOR);
	usericon = (HICON)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_USER),IMAGE_ICON,16,16,0);
}

CemuleDlg::~CemuleDlg()
{
	::DestroyIcon(m_hIcon);
	::DestroyIcon(connicons[0]);
	::DestroyIcon(connicons[1]);
	::DestroyIcon(connicons[2]);
	::DestroyIcon(transicons[0]);
	::DestroyIcon(transicons[1]);
	::DestroyIcon(transicons[2]);
	::DestroyIcon(transicons[3]);
	::DestroyIcon(imicons[1]);
	::DestroyIcon(imicons[2]);
	::DestroyIcon(sourceTrayIcon);
	::DestroyIcon(sourceTrayIconGrey);
	::DestroyIcon(usericon);
}
void CemuleDlg::DoDataExchange(CDataExchange* pDX){
	CTrayDialog::DoDataExchange(pDX);
	

}

BEGIN_MESSAGE_MAP(CemuleDlg, CTrayDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_SIZE()
	ON_WM_CLOSE()
	
	ON_COMMAND(MP_CONNECT, StartConnection)
	ON_COMMAND(MP_DISCONNECT, CloseConnection)
	ON_COMMAND(MP_EXIT, OnClose )

	ON_MESSAGE(WM_TASKBARNOTIFIERCLICKED, OnTaskbarNotifierClicked)
	ON_MESSAGE(WM_COPYDATA, OnWMData)
	ON_MESSAGE(TM_FINISHEDHASHING,OnFileHashed)
	ON_COMMAND(MP_RESTORE, RestoreWindow)

// quick-speed changer -- 
	ON_COMMAND_RANGE(MP_QS_U10, MP_QS_UP10, QuickSpeedUpload)
	ON_COMMAND_RANGE(MP_QS_D10, MP_QS_DC, QuickSpeedDownload)
	//--- quickspeed - paralize all ---
	ON_COMMAND_RANGE(MP_QS_PA, MP_QS_UA, QuickSpeedOther)
// quick-speed changer -- based on xrmb	
	ON_REGISTERED_MESSAGE(UWM_ARE_YOU_EMULE, OnAreYouEmule)

	ON_WM_QUERYENDSESSION()
END_MESSAGE_MAP()

// CemuleDlg eventhandler

LRESULT CemuleDlg::OnAreYouEmule(WPARAM, LPARAM)
{
  return UWM_ARE_YOU_EMULE;
} 

BOOL CemuleDlg::OnInitDialog(){	
	CTrayDialog::OnInitDialog();

	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL){
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, GetResString(IDS_ABOUTBOX));

			switch (theApp.glob_prefs->GetWindowsVersion()){
				case _WINVER_98_:
				case _WINVER_95_:	
				case _WINVER_ME_:
					break;
				default: {

					CMenu optionsM;
					optionsM.CreateMenu();
					AddSpeedSelectorSys(&optionsM);
			
					// set connect/disconnect to enabled and disabled
					optionsM.AppendMenu(MF_STRING ,MP_CONNECT, GetResString(IDS_CONNECTTOANYSERVER));
					optionsM.AppendMenu(MF_STRING ,MP_DISCONNECT,   GetResString(IDS_MAIN_BTN_DISCONNECT)); 
			
					pSysMenu->AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)optionsM.m_hMenu, GetResString(IDS_EM_PREFS));
				}
			}
	}

	SetIcon(m_hIcon, TRUE);			
	SetIcon(m_hIcon, FALSE);

	toolbar.Create(WS_CHILD | WS_VISIBLE , CRect(0,0,0,0), this, IDC_TOOLBAR);
	toolbar.Init();


	//set title
	char buffer[50];
	sprintf(buffer,"eMule V%s",CURRENT_VERSION_LONG);
	SetWindowText(buffer);

	//START - enkeyDEV(kei-kun) -TaskbarNotifier-
	m_wndTaskbarNotifier.Create(this);
	CEnBitmap m_imgTaskbar;
	VERIFY (m_imgTaskbar.LoadImage(IDR_TASKBAR,"GIF"));
	m_wndTaskbarNotifier.SetBitmap(&m_imgTaskbar, 255, 0, 255);
	m_wndTaskbarNotifier.SetTextFont("Arial",70,TN_TEXT_NORMAL,TN_TEXT_UNDERLINE);
	m_wndTaskbarNotifier.SetTextColor(RGB(255,255,255),RGB(255,255,255));		
	m_wndTaskbarNotifier.SetTextRect(CRect(5,45,m_wndTaskbarNotifier.m_nBitmapWidth-80, m_wndTaskbarNotifier.m_nBitmapHeight-35));
	//END - enkeyDEV(kei-kun) -TaskbarNotifier-

	// set statusbar
	statusbar.Create(WS_CHILD|WS_VISIBLE|CCS_BOTTOM|SBARS_SIZEGRIP,CRect(0,0,0,0), this, IDC_STATUSBAR) ;
	statusbar.EnableToolTips(true);
	CRect rect;
	statusbar.GetClientRect(&rect);
	int widths[5] = { rect.right-650, rect.right-410, rect.right-220,rect.right-25, -1 };
	statusbar.SetParts(5, widths);
	statusbar.SetIcon(1,usericon);
	statusbar.SetText(GetResString(IDS_UUSERS)+": 0",1,0);
	

	// create dialog pages
	preferenceswnd.SetPrefs(theApp.glob_prefs);
	serverwnd.Create(IDD_SERVER);
	sharedfileswnd.Create(IDD_FILES);
	searchwnd.Create(IDD_SEARCH);
	chatwnd.Create(IDD_CHAT);
	transferwnd.Create(IDD_TRANSFER);
	statisticswnd.Create(IDD_STATISTICS);
	ircwnd.Create(IDD_IRC);
	serverwnd.ShowWindow(SW_SHOW);
	activewnd = &serverwnd;

	// Added by Tarod [Hardware]
	// start ping thread
	theApp.Dynup = (CPingThread*)AfxBeginThread(RUNTIME_CLASS(CPingThread), THREAD_PRIORITY_BELOW_NORMAL, 0, CREATE_SUSPENDED);
	theApp.Dynup->Init();
	if (theApp.glob_prefs->IsDynupEnabled()) {
		theApp.Dynup->SetIP(1, theApp.glob_prefs->GetMaxGraphUploadRate(), theApp.glob_prefs->GetURLPing());
		theApp.emuledlg->AddLogLine(false, "Dynamic Upload System: min.:%.1f, max.:%.1f pinging %s", 1, theApp.glob_prefs->GetMaxGraphUploadRate(), theApp.glob_prefs->GetURLPing());
		theApp.Dynup->SetInitialPing();
		theApp.Dynup->StartDynup();
	}

	// set updateintervall of graphic rate display (in seconds)
	ShowConnectionState(false);

	// anchors
	AddAnchor(serverwnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(transferwnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(sharedfileswnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(searchwnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(chatwnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(ircwnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(statusbar,BOTTOM_LEFT,BOTTOM_RIGHT);
	AddAnchor(statisticswnd,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(toolbar,TOP_LEFT, TOP_RIGHT);
	ShowTransferRate();
	statisticswnd.ShowInterval();
	// tray icon
	TraySetMinimizeToTray(theApp.glob_prefs->GetMinTrayPTR());
	TrayMinimizeToTrayChange();

	if (theApp.pendinglink){
		OnWMData(NULL,(LPARAM) &theApp.sendstruct);//changed by Cax2 28/10/02
		delete theApp.pendinglink;
	}

	// Restore saved window placement
	WINDOWPLACEMENT wp;wp.length=sizeof(wp);
	wp=theApp.glob_prefs->GetEmuleWindowPlacement();
	SetWindowPlacement(&wp);

	Localize();

	// splashscreen
	if (theApp.glob_prefs->UseSplashScreen() && !theApp.glob_prefs->GetStartMinimized()){
		CSplashScreen splash(this);
		splash.DoModal();
	}

	m_hTimer = ::SetTimer(NULL,				// Window to associate with
						NULL,				// ID of timer (ignored if window = null)
						300,				// Time out duration
						(TIMERPROC)CemuleDlg::Timer);	// Proc to run
	if (!m_hTimer)
		theApp.emuledlg->AddLogLine(false, GetResString(IDS_ERR_TIMERCREATEFAILED));

	return TRUE;
}

void CALLBACK CemuleDlg::Timer(HWND hwnd, UINT uiMsg, UINT idEvent, DWORD dwTime)
{
	switch(theApp.emuledlg->status){
		case 0:
			theApp.emuledlg->status++;
			theApp.emuledlg->ready = true;
			theApp.sharedfiles->SetOutputCtrl(&theApp.emuledlg->sharedfileswnd.sharedfilesctrl);
			break;
		case 1:
			theApp.emuledlg->status++;
			theApp.serverlist->Init();
			theApp.emuledlg->status++;
			break;
		case 2:
			break;
		case 3:
			theApp.emuledlg->status++;
			theApp.downloadqueue->Init();
			if(!theApp.listensocket->StartListening())
				theApp.emuledlg->AddLogLine(false, GetResString(IDS_MAIN_SOCKETERROR),theApp.glob_prefs->GetPort());
			if(!theApp.clientudp->Create())
				theApp.emuledlg->AddLogLine(false, GetResString(IDS_MAIN_SOCKETERROR),theApp.glob_prefs->GetPort());
			theApp.emuledlg->AddLogLine(true, GetResString(IDS_MAIN_READY),CURRENT_VERSION_LONG);
			if(theApp.glob_prefs->DoAutoConnect())
				theApp.emuledlg->OnBnClickedButton2();
			break;
		default:
			theApp.emuledlg->StopTimer();
	}
}

void CemuleDlg::StopTimer(){
	try	{
		if (m_hTimer)
			::KillTimer(NULL, m_hTimer);
	} catch (...) {}
}

void CemuleDlg::OnSysCommand(UINT nID, LPARAM lParam){
	// Systemmenu-Speedselector
	if (nID>=MP_QS_U10 && nID<=10512) {
		QuickSpeedUpload(nID);
		return;
	}
	if (nID>=MP_QS_D10 && nID<=10531) {
		QuickSpeedDownload(nID);
		return;
	}
	if (nID==MP_QS_PA || nID==MP_QS_UA) {
		QuickSpeedOther(nID);
		return;
	}
	
switch (nID /*& 0xFFF0*/){

		case  IDM_ABOUTBOX : {
			CCreditsDlg dlgAbout;
			dlgAbout.DoModal();
			break;
		}
		case MP_CONNECT : {
			theApp.serverconnect->ConnectToAnyServer();
			break;
		}
		case MP_DISCONNECT : {
			theApp.serverconnect->Disconnect();
			break;
		}

		default:{
			CTrayDialog::OnSysCommand(nID, lParam);
		}
	}
}

void CemuleDlg::OnPaint() {

	if (!startUpMinimized) {
		startUpMinimized=true;
		if (theApp.glob_prefs->GetStartMinimized()) OnCancel();
	}

	if (IsIconic()){
		CPaintDC dc(this);

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		dc.DrawIcon(x, y, m_hIcon);
	}
	else{
		CTrayDialog::OnPaint();
	}
}


HCURSOR CemuleDlg::OnQueryDragIcon(){
	return static_cast<HCURSOR>(m_hIcon);
}

void CemuleDlg::OnBnClickedButton2(){
  if (!theApp.serverconnect->IsConnected()) 
    //connect if not currently connected
	if (!theApp.serverconnect->IsConnecting()  ) StartConnection(); else {
		theApp.serverconnect->StopConnectionTry();
		ShowConnectionState(false);
	}
  else
    //disconnect if currently connected
    CloseConnection();
}

void CemuleDlg::ResetLog(){
	logtext="";
	serverwnd.logbox.SetWindowText(logtext);
}

void CemuleDlg::ResetDebugLog(){
	debuglog="";
	serverwnd.debuglog.SetWindowText(debuglog);
}

void CemuleDlg::AddLogLine(bool addtostatusbar,CString line,...){
	char osDate[30],osTime[30]; //<<--9/21/02
	char temp[1060]; //<<--9/21/02
	char bufferline[1000];

	va_list argptr;
	va_start(argptr, line);
	_vsnprintf(bufferline, 1000, line, argptr);
	va_end(argptr);
	if (addtostatusbar)
		statusbar.SetText(bufferline,0,0);
	
	_strtime( osTime ); //<<--9/21/02
	_strdate( osDate ); //<<--9/21/02
	sprintf(temp,"%s %s: %s",osDate,osTime,bufferline);//<<--9/21/02 
	logtext += temp; //<<--9/21/02
	logtext += "\r\n";
	if (ready){
		if (serverwnd.logbox.GetLineCount() > 100) {
			CString strToken;
			int pos = 0;
			strToken = logtext.Tokenize("\n", pos);
			logtext = logtext.Right(logtext.GetLength() - strToken.GetLength());
		}

		serverwnd.logbox.SetWindowText(logtext);
		serverwnd.logbox.LineScroll(serverwnd.logbox.GetLineCount());
		ShowNotifier(bufferline, TBN_LOG, false);
	}
}
void CemuleDlg::AddDebugLogLine(bool addtostatusbar,CString line,...){
	if( !theApp.glob_prefs->GetVerbose() )
		return;
	char osDate[30],osTime[30]; //<<--9/21/02
	char temp[1060]; //<<--9/21/02
	char bufferline[1000];

	va_list argptr;
	va_start(argptr, line);
	_vsnprintf(bufferline, 1000, line, argptr);
	va_end(argptr);
	if (addtostatusbar)
		statusbar.SetText(bufferline,0,0);
	
	_strtime( osTime ); //<<--9/21/02
	_strdate( osDate ); //<<--9/21/02
	sprintf(temp,"%s %s: %s",osDate,osTime,bufferline);//<<--9/21/02 
	debuglog += temp; //<<--9/21/02
	debuglog += "\r\n";
	if (ready){
		if (serverwnd.debuglog.GetLineCount() > 100) {
			CString strToken;
			int pos = 0;
			strToken = debuglog.Tokenize("\n", pos);
			logtext = debuglog.Right(debuglog.GetLength() - strToken.GetLength());
		}

		serverwnd.debuglog.SetWindowText(debuglog);
		serverwnd.debuglog.LineScroll(serverwnd.debuglog.GetLineCount());
	}
}

void CemuleDlg::AddServerMessageLine(char* line,...){
	CString content;
	va_list argptr;
	char bufferline[500];
	va_start(argptr, line);
	_vsnprintf(bufferline, 500, line, argptr);
	va_end(argptr);
	serverwnd.servermsgbox.AppendText(CString(bufferline)+CString("\n"));
}

void CemuleDlg::ShowConnectionState(){ShowConnectionState( theApp.serverconnect->IsConnected() ,"");}

void CemuleDlg::ShowConnectionState(bool connected){ShowConnectionState(connected,"");}

void CemuleDlg::ShowConnectionState(bool connected, CString server,bool iconOnly){
	if (connected)
	{
		char szBuf[200];
		sprintf(szBuf, "%s", GetResString(IDS_MAIN_BTN_DISCONNECT));
		LPSTR pszBuf;
		TBBUTTONINFO tbi;
		LPTBBUTTONINFO lptbbi;
		pszBuf = szBuf;
		lptbbi = &tbi;
		tbi.dwMask = TBIF_IMAGE | TBIF_TEXT;
		tbi.cbSize = sizeof (TBBUTTONINFO);
		tbi.iImage = 9;
		tbi.pszText = pszBuf;
		tbi.cchText = sizeof (szBuf);
		toolbar.SetButtonInfo(IDC_TOOLBARBUTTON+0, lptbbi);
		//TOOLTIP: GetResString(IDS_MAIN_BTN_DISCONNECT_TOOLTIP)
				
		if (theApp.serverconnect->IsLowID()) 
			statusbar.SetIcon(3,connicons[1]);
		 else 
			statusbar.SetIcon(3,connicons[2]);
		
		if (!iconOnly) {
			statusbar.SetText(GetResString(IDS_MAIN_CONNECTEDTO) +CString(server),0,0);
			statusbar.SetTipText(3,server);
			statusbar.SetText(server,3,0);
		}
	}
	else
	{
		if (theApp.serverconnect->IsConnecting()) 
		{
			char szBuf[200];
			sprintf(szBuf, "%s", GetResString(IDS_MAIN_BTN_CANCEL));
			LPSTR pszBuf;
			TBBUTTONINFO tbi;
			LPTBBUTTONINFO lptbbi;
			pszBuf = szBuf;
			lptbbi = &tbi;
			tbi.dwMask = TBIF_IMAGE | TBIF_TEXT;
			tbi.cbSize = sizeof (TBBUTTONINFO);
			tbi.iImage = 10;
			tbi.pszText = pszBuf;
			tbi.cchText = sizeof (szBuf);
			toolbar.SetButtonInfo(IDC_TOOLBARBUTTON+0, lptbbi);
			//TOOLTIP: GetResString(IDS_MAIN_BTN_CONNECT_TOOLTIP)
			
			statusbar.SetIcon(3,connicons[0]);
			if (!iconOnly) {
				statusbar.SetText(GetResString(IDS_CONNECTING),3,0);
				statusbar.SetTipText(3,"");
			}
			ShowUserCount(0,0);

		} 
		else 
		{
			char szBuf[200];
			sprintf(szBuf, "%s", GetResString(IDS_MAIN_BTN_CONNECT));
			LPSTR pszBuf;
			TBBUTTONINFO tbi;
			LPTBBUTTONINFO lptbbi;
			pszBuf = szBuf;
			lptbbi = &tbi;
			tbi.dwMask = TBIF_IMAGE | TBIF_TEXT;
			tbi.cbSize = sizeof (TBBUTTONINFO);
			tbi.iImage = 0;
			tbi.pszText = pszBuf;
			tbi.cchText = sizeof (szBuf);
			toolbar.SetButtonInfo(IDC_TOOLBARBUTTON+0, lptbbi);
			//TOOLTIP: GetResString(IDS_CONNECTTOANYSERVER)
			//toolbar.AutoSize();

			statusbar.SetIcon(3,connicons[0]);
			if (!iconOnly) {
				statusbar.SetText(GetResString(IDS_NOTCONNECTED),3,0);
				theApp.emuledlg->AddLogLine(true,GetResString(IDS_DISCONNECTED));
				statusbar.SetTipText(3,"");
			}
			ShowUserCount(0,0);
		}

	}
}

void CemuleDlg::ShowUserCount(uint32 user_toshow, uint32 file_toshow){
	uint32 totaluser, totalfile;
	totaluser = totalfile = 0;
	if( user_toshow || file_toshow )
	 	theApp.serverlist->GetUserFileStatus( totaluser, totalfile );
	char buffer[100];
	sprintf(buffer, "%s: %s(%s) | %s: %s(%s)", GetResString(IDS_UUSERS), CastItoIShort(user_toshow), CastItoIShort(totaluser), GetResString(IDS_FILES), CastItoIShort(file_toshow), CastItoIShort(totalfile));
	statusbar.SetText(buffer,1,0);
}

void CemuleDlg::ShowMessageState(uint8 iconnr){
	statusbar.SetIcon(4,imicons[iconnr]);
}

void CemuleDlg::ShowTransferRate(){
	char buffer[50];
	char buffer2[100];

	lastuprate = theApp.uploadqueue->GetDatarate();
	lastdownrate= theApp.downloadqueue->GetDatarate();
	int lastuprateoverhead = theApp.uploadqueue->GetDatarateOverhead();
	int lastdownrateoverhead = theApp.downloadqueue->GetDatarateOverhead();

	if( theApp.glob_prefs->ShowOverhead() )
		sprintf(buffer,GetResString(IDS_UPDOWN),(float)lastuprate/1024, (float)lastuprateoverhead/1024, (float)lastdownrate/1024, (float)lastdownrateoverhead/1024);
	else
		sprintf(buffer,GetResString(IDS_UPDOWNSMALL),(float)lastuprate/1024, (float)lastdownrate/1024);

	statusbar.SetText(buffer,2,0);

	// set trayicon-icon
	int DownRateProcent=(int)ceil ( (lastdownrate/10.24)/ theApp.glob_prefs->GetMaxGraphDownloadRate());
	if (DownRateProcent>100) DownRateProcent=100;
	UpdateTrayIcon(DownRateProcent);

	if (theApp.serverconnect->IsConnected()) 
		sprintf(buffer2,"eMule v%s (%s | "+GetResString(IDS_CONNECTED)+")",CURRENT_VERSION_LONG,buffer);
	else
		sprintf(buffer2,"eMule v%s (%s | "+GetResString(IDS_DISCONNECTED)+")",CURRENT_VERSION_LONG,buffer);

	TraySetToolTip(buffer2);

	if (lastuprate && lastdownrate)
		statusbar.SetIcon(2,transicons[3]);
	else if (lastuprate)
		statusbar.SetIcon(2,transicons[2]);
	else if (lastdownrate)
		statusbar.SetIcon(2,transicons[1]);
	else
		statusbar.SetIcon(2,transicons[0]);
}

void CemuleDlg::OnCancel(){
	if (*theApp.glob_prefs->GetMinTrayPTR()) {
			TrayShow();
			ShowWindow(SW_HIDE);
		} else {
			ShowWindow(SW_MINIMIZE);
		}
}

void CemuleDlg::SetActiveDialog(CDialog* dlg){

	if (dlg == &statisticswnd ){
		statisticswnd.ShowStatistics();
	}
	if(dlg == activewnd)
		return;
	activewnd->ShowWindow(SW_HIDE);
	dlg->ShowWindow(SW_SHOW);
	activewnd = dlg;
	if (dlg==&transferwnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+2);
	else if (dlg==&serverwnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+1);
	else if (dlg==&chatwnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+5);
	else if (dlg==&ircwnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+6);
	else if (dlg==&sharedfileswnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+4);
	else if (dlg==&searchwnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+3);
	else if (dlg==&statisticswnd) theApp.emuledlg->toolbar.CheckButton(IDC_TOOLBARBUTTON+7);	
}

void CemuleDlg::OnSize(UINT nType,int cx,int cy){
	CTrayDialog::OnSize(nType,cx,cy);
	CRect rect;
	statusbar.GetClientRect(&rect);
	int widths[5] = { rect.right-650, rect.right-410, rect.right-220,rect.right-25, -1 };
	statusbar.SetParts(5, widths);
}

extern void URLDecode(CString& result, const char* buff);

LRESULT CemuleDlg::OnWMData(WPARAM wParam,LPARAM lParam){
	tagCOPYDATASTRUCT* data = (tagCOPYDATASTRUCT*)lParam;

	if (data->dwData == OP_ED2KLINK){
		FlashWindow(true);
		if( theApp.glob_prefs->IsBringToFront() ){
			if (IsIconic())
				ShowWindow(SW_SHOWNORMAL);
			else if (TrayHide()){
				ShowWindow(SW_SHOW);
			}
		else
			SetForegroundWindow();
		}
		try {
			CString link2;
			CString link;
			link2 = (char*)data->lpData;
			link2.Replace("%7c","|");
			URLDecode(link,(const char*)link2.GetBuffer());
			CED2KLink* pLink = CED2KLink::CreateLinkFromUrl(link);
			_ASSERT( pLink !=0 );
			switch (pLink->GetKind()) {
			case CED2KLink::kFile:
				{
					CED2KFileLink* pFileLink = pLink->GetFileLink();
					_ASSERT(pFileLink !=0);
					theApp.downloadqueue->AddFileLinkToDownload(pFileLink);
				}
				break;
			case CED2KLink::kServerList:
				{
					CED2KServerListLink* pListLink = pLink->GetServerListLink(); 
					_ASSERT( pListLink !=0 ); 
					CString strAddress = pListLink->GetAddress(); 
					if(strAddress.GetLength() != 0)
						theApp.emuledlg->serverwnd.UpdateServerMetFromURL(strAddress);
				}
				break;
			case CED2KLink::kServer:
				{
					CString defName;
					CED2KServerLink* pSrvLink = pLink->GetServerLink();
					_ASSERT( pSrvLink !=0 );
					in_addr host;
					host.S_un.S_addr = pSrvLink->GetIP();
					CServer* pSrv = new CServer(pSrvLink->GetPort(),inet_ntoa(host));
					_ASSERT( pSrv !=0 );
					pSrvLink->GetDefaultName(defName);
					pSrv->SetListName(defName.GetBuffer());

					// Barry - Default all new servers to high priority
					pSrv->SetPreference(PR_HIGH);

					if (!theApp.emuledlg->serverwnd.serverlistctrl.AddServer(pSrv,true)) 
						delete pSrv; 
					else theApp.emuledlg->AddLogLine(true,GetResString(IDS_SERVERADDED)+CString(pSrv->GetListName()));
				}
				break;
			default:
				break;
			}
			delete pLink;
		} catch(...) {
			OUTPUT_DEBUG_TRACE();
			AddLogLine(true, GetResString(IDS_LINKNOTADDED));
		}
	} else if (data->dwData==OP_CLCOMMAND){
		// command line command received
		CString clcommand;
		clcommand= (char*)data->lpData;
		clcommand.MakeLower();
		AddLogLine(true,clcommand);

		if (clcommand=="connect") {StartConnection(); return true;}
		if (clcommand=="disconnect") {theApp.serverconnect->Disconnect(); return true;}
		if (clcommand=="resume") {theApp.downloadqueue->StartNextFile(); return true;}
		if (clcommand=="exit") {OnClose(); return true;}
		if (clcommand=="help" || clcommand=="/?") {
			// show usage

			return true;
		}

		if (clcommand=="status") {
			CString pString;

			// todo: output to console
			
			pString.Format("%sstatus.log",theApp.glob_prefs->GetAppDir());
			FILE* file = fopen(pString , "w");

			if (theApp.serverconnect->IsConnected()) pString=GetResString(IDS_CONNECTED); else
				if (theApp.serverconnect->IsConnecting()) pString=GetResString(IDS_CONNECTING); else pString=GetResString(IDS_DISCONNECTED);
			fprintf(file, pString);


			pString.Format("\n"+GetResString(IDS_UPDOWNSMALL),(float)theApp.uploadqueue->GetDatarate()/1024, (float)theApp.downloadqueue->GetDatarate()/1024);
			fprintf(file, pString);

			pString="\n"+transferwnd.downloadlistctrl.getTextList();
			fprintf(file, pString);
			
			fclose(file);
			return true;
		}
		// show "unknown command";
	}
	return true;
}

LRESULT CemuleDlg::OnFileHashed(WPARAM wParam,LPARAM lParam){
	CKnownFile* result = (CKnownFile*)lParam;
	if (wParam){
		CPartFile* requester = (CPartFile*)wParam;
		requester->PartFileHashFinished(result);
	}
	else{
		theApp.sharedfiles->filelist->SafeAddKFile(result);
		theApp.sharedfiles->SafeAddKFile(result);	
	}
	return true;
}

void CemuleDlg::OnClose()
{
	if ( m_app_state == APP_STATE_RUNNING )
		if (theApp.glob_prefs->IsConfirmExitEnabled() )
			if (IDNO==MessageBox(GetResString(IDS_MAIN_EXIT),GetResString(IDS_MAIN_EXITTITLE),MB_YESNO | MB_DEFBUTTON2)) return;

	m_app_state	=	APP_STATE_SHUTINGDOWN;
	theApp.OnlineSig(); // Added By Bouc7 

	// TODO: Add your message handler code here and/or call default
	WINDOWPLACEMENT wp;wp.length=sizeof(wp);GetWindowPlacement(&wp);
	theApp.glob_prefs->SetWindowLayout(wp);

	// saving data & stuff
	theApp.downloadqueue->SaveAllSourcesToFile();  //to save sources of a PartFile to disk mr fry

	theApp.knownfiles->Save();
	transferwnd.downloadlistctrl.SaveSettings(CPreferences::tableDownload);
	transferwnd.uploadlistctrl.SaveSettings(CPreferences::tableUpload);
	transferwnd.queuelistctrl.SaveSettings(CPreferences::tableQueue);
	searchwnd.searchlistctrl.SaveSettings(CPreferences::tableSearch);
	sharedfileswnd.sharedfilesctrl.SaveSettings(CPreferences::tableShared);
	serverwnd.serverlistctrl.SaveSettings(CPreferences::tableServer);

	theApp.glob_prefs->Add2TotalDownloaded(theApp.stat_sessionReceivedBytes);
	theApp.glob_prefs->Add2TotalUploaded(theApp.stat_sessionSentBytes);

	theApp.glob_prefs->Save();

	// delete dynamic upload
	theApp.Dynup->StopDynup();
	theApp.Dynup->EndDynup();

	// Barry - Restore old registry if required
	if (theApp.glob_prefs->AutoTakeED2KLinks())
		RevertReg();

	transferwnd.downloadlistctrl.DeleteAllItems();
	chatwnd.chatselector.DeleteAllItems();
	theApp.clientlist->DeleteAll();
	searchwnd.searchlistctrl.DeleteAllItems();

	delete theApp.listensocket;
	delete theApp.clientudp;
	delete theApp.sharedfiles;
	delete theApp.serverconnect;
	delete theApp.serverlist;
	delete theApp.knownfiles;
	delete theApp.searchlist;
	delete theApp.clientcredits;
	delete theApp.downloadqueue;
	delete theApp.uploadqueue;
	delete theApp.clientlist;
	delete theApp.friendlist;
	delete theApp.glob_prefs;

	m_app_state	=	APP_STATE_DONE;
	CTrayDialog::OnCancel();
}

void CemuleDlg::OnTrayRButtonDown(CPoint pt){
	if (trayPopup) return;

	trayPopup.CreatePopupMenu(); 
	UINT flagsC;
	UINT flagsD;

	// set connect/disconnect to enabled and disabled
	if (!theApp.serverconnect->IsConnected()) {
		flagsD=MF_STRING || MF_DISABLED; flagsC=MF_STRING;
	} else {
		flagsC=MF_STRING || MF_DISABLED; flagsD=MF_STRING;
	}
	trayPopup.AddMenuTitle((CString)"eMule V"+(CString)CURRENT_VERSION_LONG);
	trayPopup.AppendMenu(	MF_STRING ,MP_RESTORE, GetResString(IDS_MAIN_POPUP_RESTORE) ); 
	trayPopup.SetDefaultItem(MP_RESTORE);
	trayPopup.AppendMenu(MF_SEPARATOR);

	/*
	// Show QuickSpeedOthers
	if ((theApp.glob_prefs->GetMaxDownload() == 1) && (theApp.glob_prefs->GetMaxUpload() == 1)) {
		trayPopup.AppendMenu(MF_STRING, MP_QS_UA, GetResString(IDS_PW_UA));
	} else {
		trayPopup.AppendMenu(MF_STRING, MP_QS_PA, GetResString(IDS_PW_PA));
	};
	trayPopup.AppendMenu(MF_SEPARATOR);
	*/

	//AddSpeedSelector(&trayPopup);
	CTitleMenu trayUploadPopup;
	CTitleMenu trayDownloadPopup;
	CString text;

	// creating UploadPopup Menu
	trayUploadPopup.CreateMenu();
	trayUploadPopup.AddMenuTitle(GetResString(IDS_PW_TIT_UP));
	text.Format("20%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.2),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U20,  text);
	text.Format("40%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.4),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U40,  text);
	text.Format("60%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.6),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U60,  text);
	text.Format("80%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.8),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U80,  text);
	text.Format("100%%\t%i %s", (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()),GetResString(IDS_KBYTESEC));		trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U100, text);
	trayUploadPopup.AppendMenu(MF_SEPARATOR);
	
	if (GetRecMaxUpload()>0) {
		text.Format(GetResString(IDS_PW_MINREC)+GetResString(IDS_KBYTESEC),GetRecMaxUpload());
		trayUploadPopup.AppendMenu(MF_STRING, MP_QS_UP10,text );
	}
	
	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_UPC, GetResString(IDS_PW_UNLIMITED));

	// creating DownloadPopup Menu
	trayDownloadPopup.CreateMenu();
	trayDownloadPopup.AddMenuTitle(GetResString(IDS_PW_TIT_DOWN));
	text.Format("20%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.2),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D20,  text);
	text.Format("40%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.4),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D40,  text);
	text.Format("60%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.6),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D60,  text);
	text.Format("80%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.8),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D80,  text);
	text.Format("100%%\t%i %s", (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()),GetResString(IDS_KBYTESEC));		trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D100, text);
	trayDownloadPopup.AppendMenu(MF_SEPARATOR);
	trayDownloadPopup.AppendMenu(MF_STRING, MP_QS_DC, GetResString(IDS_PW_UNLIMITED));

	// Show UploadPopup Menu
	if(theApp.glob_prefs->GetMaxUpload()==UNLIMITED)
		text.Format("%s:\t%s (%i %s)", GetResString(IDS_PW_UPL),GetResString(IDS_PW_UNLIMITED), theApp.glob_prefs->GetMaxGraphUploadRate(),GetResString(IDS_KBYTESEC));
	else
		text.Format("%s:\t%i %s (%i %s)", GetResString(IDS_PW_UPL), theApp.glob_prefs->GetMaxUpload(),GetResString(IDS_KBYTESEC) ,theApp.glob_prefs->GetMaxGraphUploadRate(),GetResString(IDS_KBYTESEC));

	trayPopup.AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)trayUploadPopup.m_hMenu, text);
	

	// Show DownloadPopup Menu
	if(theApp.glob_prefs->GetMaxDownload()==UNLIMITED)
		text.Format("%s:\t%s (%i %s)", GetResString(IDS_PW_DOWNL),GetResString(IDS_PW_UNLIMITED), theApp.glob_prefs->GetMaxGraphDownloadRate(),GetResString(IDS_KBYTESEC));
	else
		text.Format("%s:\t%i %s (%i %s)", GetResString(IDS_PW_DOWNL), theApp.glob_prefs->GetMaxDownload(),GetResString(IDS_KBYTESEC), theApp.glob_prefs->GetMaxGraphDownloadRate(),GetResString(IDS_KBYTESEC));
	trayPopup.AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)trayDownloadPopup.m_hMenu, text);

	trayPopup.AppendMenu(MF_SEPARATOR);

	trayPopup.AppendMenu(flagsC,MP_CONNECT, GetResString(IDS_CONNECTTOANYSERVER));
	trayPopup.AppendMenu(flagsD ,MP_DISCONNECT,   GetResString(IDS_MAIN_BTN_DISCONNECT)); 

	trayPopup.AppendMenu(MF_STRING,MP_EXIT, GetResString(IDS_EXIT)); 
	SetForegroundWindow();
	trayPopup.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); 
	PostMessage(WM_NULL, 0, 0);
	trayPopup.DestroyMenu();
}

void CemuleDlg::AddSpeedSelectorSys(CMenu* addToMenu)
{
	CMenu trayUploadPopup;
	CMenu trayDownloadPopup;
	CString text;

	// creating UploadPopup Menu
	trayUploadPopup.CreateMenu();
	//trayUploadPopup.AddMenuTitle(GetResString(IDS_PW_TIT_UP));
	text.Format("20%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.2),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U20,  text);
	text.Format("40%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.4),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U40,  text);
	text.Format("60%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.6),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U60,  text);
	text.Format("80%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.8),GetResString(IDS_KBYTESEC));	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U80,  text);
	text.Format("100%%\t%i %s", (uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()),GetResString(IDS_KBYTESEC));		trayUploadPopup.AppendMenu(MF_STRING, MP_QS_U100, text);
	trayUploadPopup.AppendMenu(MF_SEPARATOR);
	
	if (GetRecMaxUpload()>0) {
		text.Format(GetResString(IDS_PW_MINREC)+GetResString(IDS_KBYTESEC),GetRecMaxUpload());
		trayUploadPopup.AppendMenu(MF_STRING, MP_QS_UP10, text );
	}

	trayUploadPopup.AppendMenu(MF_STRING, MP_QS_UPC, GetResString(IDS_PW_UNLIMITED));

	// creating DownloadPopup Menu
	trayDownloadPopup.CreateMenu();
	//trayDownloadPopup.AddMenuTitle(GetResString(IDS_PW_TIT_DOWN));
	text.Format("20%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.2),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D20,  text);
	text.Format("40%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.4),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D40,  text);
	text.Format("60%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.6),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D60,  text);
	text.Format("80%%\t%i %s",  (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.8),GetResString(IDS_KBYTESEC));	trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D80,  text);
	text.Format("100%%\t%i %s", (uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()),GetResString(IDS_KBYTESEC));		trayDownloadPopup.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D100, text);
	trayDownloadPopup.AppendMenu(MF_SEPARATOR);
	trayDownloadPopup.AppendMenu(MF_STRING, MP_QS_DC, GetResString(IDS_PW_UNLIMITED));

	// Show UploadPopup Menu
	text.Format("%s:", GetResString(IDS_PW_UPL));
	addToMenu->AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)trayUploadPopup.m_hMenu, text);

	// Show DownloadPopup Menu
		text.Format("%s:", GetResString(IDS_PW_DOWNL));

	addToMenu->AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)trayDownloadPopup.m_hMenu, text);

	addToMenu->AppendMenu(MF_SEPARATOR);
//////////////////////////
}


void CemuleDlg::StartConnection(){
	AddLogLine(true, GetResString(IDS_CONNECTING));
	if ( serverwnd.serverlistctrl.GetSelectedCount()>1 )
	{
		serverwnd.serverlistctrl.PostMessage(WM_COMMAND,MP_CONNECTTO,0L);
	}
	else
	{
		theApp.serverconnect->ConnectToAnyServer();
	}
	ShowConnectionState(false);
}

void CemuleDlg::CloseConnection(){
	theApp.serverconnect->Disconnect();
	theApp.OnlineSig(); // Added By Bouc7 
}

void CemuleDlg::RestoreWindow(){
	if (TrayIsVisible())
		TrayHide();	
	
	ShowWindow(SW_SHOW);
}

void CemuleDlg::ShowStatistics() {
	statisticswnd.ShowStatistics();	
}

void CemuleDlg::UpdateTrayIcon(int procent)
{
	//HICON mytrayIcon;
	//if (mytrayIcon!=NULL) DestroyIcon(mytrayIcon);

	// set the limits of where the bar color changes (low-high)
	int pLimits16[1] = {100};

	// set the corresponding color for each level
	COLORREF pColors16[1] = {RGB(17,121,120)};

	// start it up
	if (theApp.serverconnect->IsConnected())
		trayIcon.Init(sourceTrayIcon,100,1,1,16,16,theApp.glob_prefs->GetStatsColor(11));
	else trayIcon.Init(sourceTrayIconGrey,100,1,1,16,16,theApp.glob_prefs->GetStatsColor(11));

	// load our limit and color info
	trayIcon.SetColorLevels(pLimits16,pColors16,1);

	// generate the icon (destroy these icon using DestroyIcon())
	int pVals16[1] = {procent};

	mytrayIcon = trayIcon.Create(pVals16);
	ASSERT (mytrayIcon != NULL);
	if (mytrayIcon)
		TraySetIcon(mytrayIcon,true);
	TrayUpdate();
}

int CemuleDlg::OnCreate(LPCREATESTRUCT lpCreateStruct){
	CTrayDialog::OnCreate(lpCreateStruct);
	/*if (theApp.glob_prefs->UseSplashScreen()){
		ModifyStyleEx(0,WS_EX_LAYERED);
		SetLayeredWindowAttributes(0, 0, LWA_ALPHA);
	}*/
	
	return 0;

}

//START - enkeyDEV(kei-kun) -TaskbarNotifier-
void CemuleDlg::ShowNotifier(CString Text, int MsgType, bool ForceSoundOFF) {
	bool ShowIt = false;
	switch(MsgType) {
		case TBN_CHAT:
            if (theApp.glob_prefs->GetUseChatNotifier()) {
				m_wndTaskbarNotifier.Show(Text, MsgType);
				ShowIt = true;
			}
			break;
		case TBN_DLOAD:
            if (theApp.glob_prefs->GetUseDownloadNotifier()) {
				m_wndTaskbarNotifier.Show(Text, MsgType);
				ShowIt = true;			
			}
			break;
		case TBN_LOG:
            if (theApp.glob_prefs->GetUseLogNotifier()) {
				m_wndTaskbarNotifier.Show(Text, MsgType);
				ShowIt = true;			
			}
			break;
		case TBN_IMPORTANTEVENT:
			if (theApp.glob_prefs->GetNotifierPopOnImportantError()) {
				m_wndTaskbarNotifier.Show(Text, MsgType);
				ShowIt = true;			
			}
			break;	// added by InterCeptor (bugfix) 27.11.02
		case TBN_NULL:
            m_wndTaskbarNotifier.Show(Text, MsgType);
			ShowIt = true;			
			break;
	}
	
    if (theApp.glob_prefs->GetUseSoundInNotifier() && !ForceSoundOFF && ShowIt == true)
        PlaySound(theApp.glob_prefs->GetNotifierWavSoundPath(), NULL, SND_FILENAME | SND_NOSTOP | SND_NOWAIT | SND_ASYNC);
}

LRESULT CemuleDlg::OnTaskbarNotifierClicked(WPARAM wParam,LPARAM lParam)
{
	int msgType = TBN_NULL;
	msgType = m_wndTaskbarNotifier.GetMessageType();
	
	switch(msgType)
	{
	case TBN_CHAT:
		RestoreWindow();
		SetActiveDialog(&chatwnd);
		break;
	case TBN_DLOAD:
		RestoreWindow();
		SetActiveDialog(&transferwnd);
	//	{TODO: aprire la cartella incoming?}
		break;
	case TBN_IMPORTANTEVENT:
		RestoreWindow();
		SetActiveDialog(&serverwnd);	
		break;
	case TBN_LOG:
		RestoreWindow();
		SetActiveDialog(&serverwnd);	
		break;
	}
    return 0;
}
//END - enkeyDEV(kei-kun) -TaskbarNotifier-

void CemuleDlg::Localize(){
	toolbar.Localize();
	ShowConnectionState();
}


// quick-speed changer -- 

void CemuleDlg::QuickSpeedOther(UINT nID)
{
	switch (nID) {
		case MP_QS_PA: theApp.glob_prefs->SetMaxUpload((uint16)(1));
			theApp.glob_prefs->SetMaxDownload((uint16)(1));
			break ;
		case MP_QS_UA: 
			theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()));
			theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()));
			break ;
	}
}
		   

void CemuleDlg::QuickSpeedUpload(UINT nID)
{
	switch (nID) {
		case MP_QS_U10: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.1)); break ;
		case MP_QS_U20: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.2)); break ;
		case MP_QS_U30: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.3)); break ;
		case MP_QS_U40: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.4)); break ;
		case MP_QS_U50: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.5)); break ;
		case MP_QS_U60: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.6)); break ;
		case MP_QS_U70: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.7)); break ;
		case MP_QS_U80: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.8)); break ;
		case MP_QS_U90: theApp.glob_prefs->SetMaxUpload((uint16)(theApp.glob_prefs->GetMaxGraphUploadRate()*0.9)); break ;
		case MP_QS_U100: theApp.glob_prefs->SetMaxUpload(theApp.glob_prefs->GetMaxGraphUploadRate()); break ;
		case MP_QS_UPC: theApp.glob_prefs->SetMaxUpload(UNLIMITED); break ;
		case MP_QS_UP10: theApp.glob_prefs->SetMaxUpload(GetRecMaxUpload()); break ;
	}
}

void CemuleDlg::QuickSpeedDownload(UINT nID)
{
	switch (nID) {
		case MP_QS_D10: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.1)); break ;
		case MP_QS_D20: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.2)); break ;
		case MP_QS_D30: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.3)); break ;
		case MP_QS_D40: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.4)); break ;
		case MP_QS_D50: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.5)); break ;
		case MP_QS_D60: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.6)); break ;
		case MP_QS_D70: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.7)); break ;
		case MP_QS_D80: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.8)); break ;
		case MP_QS_D90: theApp.glob_prefs->SetMaxDownload((uint16)(theApp.glob_prefs->GetMaxGraphDownloadRate()*0.9)); break ;
		case MP_QS_D100: theApp.glob_prefs->SetMaxDownload(theApp.glob_prefs->GetMaxGraphDownloadRate()); break ;
		case MP_QS_DC: theApp.glob_prefs->SetMaxDownload(UNLIMITED); break ;
	}
}
// quick-speed changer -- based on xrmb

int CemuleDlg::GetRecMaxUpload() {
	
	if (theApp.glob_prefs->GetMaxGraphUploadRate()<7) return 0;
	if (theApp.glob_prefs->GetMaxGraphUploadRate()<15) return theApp.glob_prefs->GetMaxGraphUploadRate()-3;
	return (theApp.glob_prefs->GetMaxGraphUploadRate()-4);
}

BOOL CemuleDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
	switch(wParam)
	{	
		case IDC_TOOLBARBUTTON + 0:
			DisConnect();
			break;
		case IDC_TOOLBARBUTTON + 1:
			SetActiveDialog(&serverwnd);
			break;
		case IDC_TOOLBARBUTTON + 2:
			SetActiveDialog(&transferwnd);
			break;
		case IDC_TOOLBARBUTTON + 3:
			SetActiveDialog(&searchwnd);
			break;
		case IDC_TOOLBARBUTTON + 4:
			SetActiveDialog(&sharedfileswnd);
			break;
		case IDC_TOOLBARBUTTON + 5:
			SetActiveDialog(&chatwnd);
			break;
		case IDC_TOOLBARBUTTON + 6:
			SetActiveDialog(&ircwnd);
			break;
		case IDC_TOOLBARBUTTON + 7:
			SetActiveDialog(&statisticswnd);
			break;
		case IDC_TOOLBARBUTTON + 8:
			toolbar.PressButton(IDC_TOOLBARBUTTON+8,TRUE);
			preferenceswnd.DoModal();
			toolbar.PressButton(IDC_TOOLBARBUTTON+8,FALSE);
			break;
		default: break;
	}	

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

void CemuleDlg::DisConnect()
{
	if(!theApp.serverconnect->IsConnected()) 
	{
		if(!theApp.serverconnect->IsConnecting()) 
			StartConnection(); 
		else 
		{
			theApp.serverconnect->StopConnectionTry();
			ShowConnectionState(false);
		}
	}
  else

    CloseConnection();
}

BOOL CemuleDlg::OnQueryEndSession()
{
	if (!CTrayDialog::OnQueryEndSession())
		return FALSE;

	if ( m_app_state == APP_STATE_DONE )
	{
		return TRUE;
	}
	else if ( m_app_state	==	APP_STATE_RUNNING )
	{
		m_app_state	=	APP_STATE_SHUTINGDOWN;
		OnClose();
	}
	return FALSE;
}

// Barry - To find out if app is running or shutting/shut down
bool CemuleDlg::IsRunning()
{
	return (m_app_state == APP_STATE_RUNNING);
}
