/*
 * $Id: wvcncm.c 1.54 1997/03/28 19:46:27 dumoulin Exp $
 */

/*-- This is the first line of WVCNCM.C -------------------------------*/

#include <windows.h>
#include <windowsx.h>
#include "wvglob.h"
#include "winvn.h"
#include "defaults.h"
#pragma hdrstop
#include <stdlib.h>
#include <limits.h>
#include <io.h>                                 // for _access
#include <ctype.h>                      // for isspace
#include <commctrl.h>
#include <Shellapi.h>
#define MAX_DIR_ENTRIES 8

#include "visualstylesxp.h"

void enableDemandLogonCtl (HWND hDlg, int forceType);
eEncodingType SetupEncodingOptions (HWND hDlg, eEncodingType type, BOOL includeCustom, BOOL showNone);

BOOL ProcessEncodingOptions (HWND hDlg, eEncodingType  *newEncodingType);

#ifdef _INCLSSL
#include "intgensock.h"	
#endif


/*-- function WinVnCommDlg ---------------------------------------------
 *
 *   Dialog function to process the Configure Communications
 *   dialog box.
 */

INT_PTR CALLBACK WinVnCommDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
#define MAXSTR  32
	static int SaveDemand, saveMailForceType;
	static unsigned int saveNewsForceType, saveIPFamily;
	static BOOL bHaveSSL = FALSE;

	int mail_force_radio, news_force_radio, news_ip_family;
	char NNTPPassword[MAXNNTPSIZE];
	BOOL bOK;
	BOOL bWarnChange = FALSE;

	static HFONT hDlgFont = NULL;
	

	switch (iMessage) 
	{

	case WM_INITDIALOG:
		CenterWindow (hDlg, GetParent(hDlg) );
		/* Get dialog font and create non-bold version */ 
		bHaveSSL = FALSE;
		if (g_bIsXP && !hDlgFont)
		{  //fix password font
			LOGFONT lFont;
			lFont.lfHeight = 14;
			lFont.lfWidth = 0;
			lFont.lfEscapement = 0;
			lFont.lfOrientation = 0;
			lFont.lfWeight = 200; // non-bold font weight
			lFont.lfItalic = 0;
			lFont.lfUnderline = 0;
			lFont.lfStrikeOut = 0;
			lFont.lfCharSet = ANSI_CHARSET;
			lFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
			lFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
			lFont.lfQuality = DEFAULT_QUALITY;
			lFont.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
			strcpy(lFont.lfFaceName, "Microsoft Sans Serif");
			hDlgFont = CreateFontIndirect(&lFont);

			SendDlgItemMessage(hDlg, ID_CONFIG_AUTH_PASSWORD, WM_SETFONT,  (WPARAM)hDlgFont, (DWORD)TRUE);
			// Send WM_SETFONT message to desired controls

		}

		SetDlgItemText (hDlg, ID_CONFIG_NNTP_SERVER, NNTPHost);
		CheckDlgButton (hDlg, ID_CONFIG_CONNECT_AT_START, ConnectAtStartup);
#ifdef _INCLSSL
		CheckDlgButton (hDlg, ID_CONFIG_USESSL, UseSSL);
		if (UseSSL)
			SendMessage(hDlg, WM_COMMAND, ID_CONFIG_USESSL, 0);

#else
		CheckDlgButton (hDlg, ID_CONFIG_USESSL, 0);
		//SendDlgItemMessage (hDlg, ID_CONFIG_USESSL,	WM_SHOWWINDOW, SW_HIDE, 0);
		EnableWindow(GetDlgItem(hDlg, ID_CONFIG_USESSL), 0);
		ShowWindow(GetDlgItem(hDlg, ID_CONFIG_USESSL), SW_HIDE);

#endif
		SetDlgItemText (hDlg, ID_CONFIG_SMTP_SERVER, SMTPHost);
		SetDlgItemText (hDlg, ID_CONFIG_NNTP_PORT, NNTPService);
		SetDlgItemText (hDlg, ID_CONFIG_AUTH_USERNAME, NNTPUserName);
		MRRDecrypt (NNTPPasswordEncrypted, (unsigned char *) NNTPPassword, MAXNNTPSIZE);
		SetDlgItemText (hDlg, ID_CONFIG_AUTH_PASSWORD, NNTPPassword);
		SetDlgItemText (hDlg, ID_CONFIG_MAPI_PREFIX, MAPIPrefix);
		SetDlgItemInt  (hDlg, ID_CONFIG_TIMEOUT, StallTimeout, FALSE);
		SetDlgItemInt  (hDlg, ID_CONFIG_KEEPALIVE, CommTimeout, FALSE);
		
		
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_NNTP_SERVER), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_NNTP_PORT), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_SMTP_SERVER), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_AUTH_USERNAME), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_AUTH_PASSWORD), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_MAPI_PREFIX), MAXPREFIXSIZE);

		saveMailForceType = MailForceType;
		if (MailForceType == -1)
			mail_force_radio = IDD_MAIL_SELECT_AUTO;
		else
			mail_force_radio = MailForceType + IDD_MAIL_SELECT_NONE;

		CheckRadioButton (hDlg, IDD_MAIL_SELECT_NONE,
								IDD_MAIL_SELECT_AUTO, mail_force_radio);

		saveNewsForceType = force_xhdr;
		if (force_xhdr == HDR_AUTO)
			news_force_radio = IDD_NEWS_SELECT_AUTO;
		else if (force_xhdr == HDR_XOVER)
			news_force_radio = IDD_NEWS_SELECT_XOVER;   
		else if (force_xhdr == HDR_XHDR)
			news_force_radio = IDD_NEWS_SELECT_XHDR;
		else
			news_force_radio = IDD_NEWS_SELECT_AUTO;

		CheckRadioButton (hDlg, IDD_NEWS_SELECT_BASE,
					  IDD_NEWS_SELECT_AUTO, news_force_radio);

		CheckDlgButton (hDlg, IDC_CB_COMPRESS, use_zhdr ? 1 : 0);
		
		saveIPFamily = ip_family;			  
		switch(ip_family)
		{
			case 4:
				news_ip_family = ID_CONFIG_IP4;
				break;
			case 6:
				news_ip_family = ID_CONFIG_IP6;
				break;
			default:
				news_ip_family = ID_CONFIG_IPAUTO;
				break;
		}
		CheckRadioButton (hDlg, ID_CONFIG_IPAUTO, ID_CONFIG_IP6, news_ip_family);

		// PCT, 10/05/94
		CheckDlgButton (hDlg, IDD_SAVEPASSWORD, NNTPSavePassword);

		SaveDemand = MailDemandLogon;
		CheckDlgButton (hDlg, IDD_DEMANDLOGON, SaveDemand);
		enableDemandLogonCtl (hDlg, saveMailForceType);
		EnableWindow (GetDlgItem (hDlg, ID_CONFIG_SMTP_SERVER), (mail_force_radio == IDD_MAIL_SELECT_SMTP || mail_force_radio == IDD_MAIL_SELECT_AUTO));
		EnableWindow (GetDlgItem (hDlg, ID_CONFIG_MAPI_PREFIX), (mail_force_radio == IDD_MAIL_SELECT_MAPI || mail_force_radio == IDD_MAIL_SELECT_AUTO));
		if (lParam)
		{
			SetFocus( GetDlgItem (hDlg, ID_CONFIG_AUTH_PASSWORD));
			return FALSE;

		}
		return TRUE;
		break;

		case WM_HELP:
			{
				LPHELPINFO lphi = (LPHELPINFO) lParam; 
				
				DoHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, HELP_CONTEXT, (DWORD)401);

				if (lphi->iContextType == HELPINFO_WINDOW && lphi->iCtrlId != 9 )
				{
					DWORD dwHelp[4] = {	lphi->iCtrlId, lphi->iCtrlId + 0x10000, 0,0};
					//dwHelp[0] = 401;
					//dwHelp[1] = 401 + 0x10000;
					//WinHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, mybuf, HELP_WM_HELP, (DWORD)(LPVOID)dwHelp);
				}

			}
			break;

		case WM_COMMAND:
		switch (wParam) 
		{
			case IDHELP:
				DoHelp (hDlg, HELP_CONTEXT, (DWORD)401);
				break;

			case IDOK:
				ConnectAtStartup = (IsDlgButtonChecked (hDlg, ID_CONFIG_CONNECT_AT_START) != 0);

#ifdef _INCLSSL
				if ( (IsDlgButtonChecked (hDlg, ID_CONFIG_USESSL) != 0) ^ (UseSSL))
					bWarnChange = TRUE; 
				UseSSL = (IsDlgButtonChecked (hDlg, ID_CONFIG_USESSL) != 0);
#else
				UseSSL = 0;
#endif				
				{
					char TempHost[MAXNNTPSIZE] = {0};
					
					GetDlgItemText (hDlg, ID_CONFIG_NNTP_SERVER, TempHost, MAXNNTPSIZE);
					if (*TempHost == '\0') 
					{
						WVMessageBox (hDlg, IDS_WVCNCM_ENTER_ADDR, IDS_WVCNCM_INVALID_SERVER, MB_OK | MB_ICONSTOP);
						break;
					}
					for (int i = strlen(TempHost)-1; i >= 0; i--)
					{
						if ( isspace ((unsigned char) TempHost[i]) )
						{
							TempHost[i] = '\0';
							continue;
						}
						break;
					}
					if ( Initializing == 0 && _stricmp(TempHost, NNTPHost))
					{
						bWarnChange = TRUE;
					}
					strcpy(NNTPHost, TempHost);
				}
				{
					char TempService[MAXNNTPSIZE] = {0};
					GetDlgItemText (hDlg, ID_CONFIG_NNTP_PORT, TempService, MAXNNTPSIZE);
					if (*TempService == '\0') 
					{
						WVMessageBox (hDlg, IDS_WVCNCM_ENTER_PORT, IDS_WVCNCM_INVALID_PORT, MB_OK | MB_ICONSTOP);
						break;
					}
					if ( Initializing != INIT_NOT_CONNECTED && _stricmp(TempService, NNTPService))
					{
						//warn when port change will take effect
						bWarnChange = TRUE;
					}
					strcpy(NNTPService, TempService);
				}
				GetDlgItemText (hDlg, ID_CONFIG_SMTP_SERVER, SMTPHost, MAXNNTPSIZE);
				if (*SMTPHost == '\0' && saveMailForceType == MT_SMTP) 
				{
					WVMessageBox (hDlg, IDS_WVCNCM_INVALID_MAIL, IDS_WVCNCM_INVALID_SMTP, MB_OK | MB_ICONSTOP);
					saveMailForceType = MT_NONE;
				}
      
				GetDlgItemText (hDlg, ID_CONFIG_MAPI_PREFIX, MAPIPrefix, MAXPREFIXSIZE);

				// PCT, 10/05/94
				NNTPSavePassword = IsDlgButtonChecked (hDlg, IDD_SAVEPASSWORD);
				GetDlgItemText (hDlg, ID_CONFIG_AUTH_USERNAME, NNTPUserName, MAXNNTPSIZE);
				GetDlgItemText (hDlg, ID_CONFIG_AUTH_PASSWORD, NNTPPassword, MAXNNTPSIZE);
				{
					unsigned int Value = GetDlgItemInt(hDlg, ID_CONFIG_TIMEOUT, &bOK, FALSE);
					if (bOK && Value != StallTimeout)
					{
						if (Value != 0 && Value < 15) Value = 15;
						StallTimeout = Value;
						InternalTimeoutCounter = StallTimeout * 1000 / COMM_TIMER_INTERVAL;
					}

					Value = GetDlgItemInt(hDlg, ID_CONFIG_KEEPALIVE, &bOK, FALSE);
					if (bOK && Value != CommTimeout)
					{
						if (Value != 0 && Value < 15) Value = 15;
						CommTimeout = Value;
						TimeoutCounter = CommTimeout * 1000 / COMM_TIMER_INTERVAL;
					}

				}
				MRREncrypt ((unsigned char *) NNTPPassword, strlen (NNTPPassword) + 1,
								  NNTPPasswordEncrypted);
				MailDemandLogon = SaveDemand;
				ip_family = saveIPFamily;

				if ((saveMailForceType != MailForceType) || (saveNewsForceType != force_xhdr)) 
				{
					   /* change of mail transport medium
						  Not entirely correct as may change from
						  explicit selection to auto detect which
						  in this case will (but in reality may not)
						  affect a relogin to mail)  */
					MailForceType = saveMailForceType;
					force_xhdr = saveNewsForceType;
					
					if (Initializing == INIT_NOT_CONNECTED || force_xhdr == HDR_XHDR)
						xoverp = 0;
					else if (force_xhdr == HDR_AUTO || force_xhdr == HDR_XOVER) 
						xoverp = 1;
					
					MailCrashExit (hDlg);
					MailInit (hDlg);
					UpdateAllMailMenus ();
				}
				if (!IsDlgButtonChecked (hDlg, IDC_CB_COMPRESS))
					use_zhdr = 0;
				else if (use_zhdr == 0)
					use_zhdr = 1;

				if (bWarnChange && CommState != ST_ESTABLISH_COMM)
					WVMessageBox (hDlg, IDS_WVCNCM_WARN_CHANGE, IDS_WINVN_CONFIG1, MB_OK | MB_ICONINFORMATION);

				if (hDlgFont)
				{
					SendDlgItemMessage(hDlg, ID_CONFIG_AUTH_PASSWORD, WM_SETFONT,  (WPARAM)SendMessage(hDlg, WM_GETFONT,0,0), (DWORD)TRUE);
					DeleteObject(hDlgFont);
					hDlgFont = NULL;
				}

				
				EndDialog (hDlg, TRUE);
			break;

			case IDCANCEL:
				if (hDlgFont)
				{
					SendDlgItemMessage(hDlg, ID_CONFIG_AUTH_PASSWORD, WM_SETFONT,  (WPARAM)SendMessage(hDlg, WM_GETFONT,0,0), (DWORD)TRUE);
					DeleteObject(hDlgFont);
					hDlgFont = NULL;
				}

				EndDialog (hDlg, FALSE);
				break;
			case ID_CONFIG_USESSL:

#ifdef _INCLSSL

				if (IsDlgButtonChecked (hDlg, ID_CONFIG_USESSL) == BST_CHECKED)
				{
#ifndef SSLSTATIC
					if (!bHaveSSL)
					{
					
						//see if we can find the req. files
						TCHAR sslpath[_MAX_PATH], libpath[_MAX_PATH], *p;
						TCHAR szMsg[1024];
						BOOL bIs64 = FALSE;
						DWORD dwVer = 0;
						BOOL bWant64 = 	
#ifdef _WIN64
		 TRUE;
#define NAMESSLLIB "libssl-1_1-x64.dll"
#define NAMECRYLIB "libcrypto-1_1-x64.dll"
#else
		FALSE;
#define NAMESSLLIB "libssl-1_1.dll"		
#define NAMECRYLIB "libcrypto-1_1.dll"
#endif							
						
						if (SearchPath(NULL,NAMESSLLIB, NULL, _MAX_PATH, sslpath, &p))
						{
							TCHAR szDesc[255] = {_T("(no description)")};
							if (GetSSLVersion(sslpath, szDesc, 255, bIs64) && bWant64 != bIs64)
							{
								GetSystemDirectory(sslpath, _MAX_PATH);
								_tcscat(sslpath, _T("\\")NAMESSLLIB);
								GetSSLVersion(sslpath, szDesc, 255, bIs64);							
							}
							if (SearchPath(NULL,NAMECRYLIB, NULL, _MAX_PATH, libpath, &p))
							{
								BOOL bOK = TRUE;
								if ( GetFileVersion(libpath,NULL, 0, &bIs64) == (DWORD) -1 || bWant64 != bIs64)
								{
									GetSystemDirectory(libpath, _MAX_PATH);
									_tcscat(libpath, "\\" NAMECRYLIB);	
									if (GetFileVersion(libpath,NULL, 0, &bIs64) != (DWORD) -1 && bWant64 != bIs64)
									{
										bOK = TRUE;
									}
								}
								else
								{
									bOK = TRUE;
								}
								if (bOK)
								{
									wsprintf(szMsg,"Found %s\r\nat %s", szDesc, sslpath);


									if (lParam)
										WVMessageBox(hDlg, (char*)szMsg, (char*) "SSL Libraries found",MB_OK | MB_ICONINFORMATION);
									bHaveSSL = TRUE;
								}
							
							}
							else
								WVMessageBox(hDlg, "Error " NAMECRYLIB " not found", (char*) "SSL Not Available",MB_OK | MB_ICONWARNING);	
						
						}
						else
						{
							WVMessageBox(hDlg,
							"You need to install OpenSLL to use this feature.\r\nSee www.openssl.org under related/binaries",
							(char*) "SSL Not Available",MB_OK);
						}

					}
#else
                    bHaveSSL = TRUE;
#endif //!SSLSTATIC
					
					if (bHaveSSL)
						SetDlgItemText (hDlg, ID_CONFIG_NNTP_PORT, "563");
					else
					{
						CheckDlgButton (hDlg, ID_CONFIG_USESSL, 0);
						if (!lParam && !strcmp(NNTPService, "563"))
							SetDlgItemText (hDlg, ID_CONFIG_NNTP_PORT, "nntp");
					}

					
				}
				else
				{
					SetDlgItemText (hDlg, ID_CONFIG_NNTP_PORT, "nntp");
				}
#endif

				break; 


			case IDD_MAIL_SELECT_NONE:
			case IDD_MAIL_SELECT_MAPI:        
			case IDD_MAIL_SELECT_SMTP:
				saveMailForceType = wParam - IDD_MAIL_SELECT_NONE;
				enableDemandLogonCtl (hDlg, saveMailForceType);
				EnableWindow (GetDlgItem (hDlg, ID_CONFIG_MAPI_PREFIX), (saveMailForceType == MT_MAPI));
				EnableWindow (GetDlgItem (hDlg, ID_CONFIG_SMTP_SERVER), (saveMailForceType == MT_SMTP));
				break;

			case IDD_MAIL_SELECT_AUTO:
				saveMailForceType = -1;
				enableDemandLogonCtl (hDlg, saveMailForceType);
				EnableWindow (GetDlgItem (hDlg, ID_CONFIG_SMTP_SERVER), ENABLE);
				EnableWindow (GetDlgItem (hDlg, ID_CONFIG_MAPI_PREFIX), ENABLE);
				break;

			case IDD_NEWS_SELECT_XOVER:
				saveNewsForceType = HDR_XOVER;
				break;

			case IDD_NEWS_SELECT_AUTO:
				saveNewsForceType = HDR_AUTO;
				break;

			case IDD_NEWS_SELECT_XHDR:
				saveNewsForceType = HDR_XHDR;
				break;
			case ID_CONFIG_IPAUTO:
				saveIPFamily = 0;
				break;
			case ID_CONFIG_IP4:
				saveIPFamily = 4;
				break;
			case ID_CONFIG_IP6:
				saveIPFamily = 6;
				break;

			case IDD_DEMANDLOGON:
				SaveDemand = !SaveDemand;
				CheckDlgButton (hDlg, IDD_DEMANDLOGON, SaveDemand);
				break; 
			case ID_CONFIG_ADVSMTP:
			      if (DialogBox (hInst, MAKEINTRESOURCE(IDD_WINVNSMTP), hDlg, lpfnWinVnSMTPDlg) == IDOK)
				  {
					SetDlgItemText (hDlg, ID_CONFIG_SMTP_SERVER, SMTPHost);
				  }
				  break;


			default:
				return FALSE;
		}
		break;

	default:
			return FALSE;
			break;
	}
	

	return TRUE;
}
/*
 *  enable/disable the check box for the DemandLogon variable
 *  as requested
 *
 *  some mail transports do not require authentification (logon)
 *  so demand (deferred ) logon is not an option 
 *
 */
void enableDemandLogonCtl (HWND hDlg, int forceType)
{
	EnableWindow (GetDlgItem (hDlg, IDD_DEMANDLOGON),
                  (forceType == -1) || (forceType == MT_MAPI));
}

/*-- function WinVnSaveArtDlg ---------------------------------------
 *
 *  Dialog function to handle Save Article dialog box.
 */

INT_PTR CALLBACK WinVnSaveArtDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{

  char fileName[MAXFILENAME];

	switch (iMessage) 
	{

		case WM_INITDIALOG:
		{
			int i;
			char szEntry[20];
			HWND hList = GetDlgItem(hDlg, IDD_FILENAME);

			CheckDlgButton (hDlg, IDD_APPEND, SaveArtAppend);
			for (i = MAX_DIR_ENTRIES; i > 0; i--)
			{
				wsprintf(szEntry, "file%02d", i);
				GetPrivateProfileString (MRUENTRIES, szEntry, "", fileName, MAXFILENAME, szAppProFile);
				if (*fileName)
				SendMessage (hList, CB_INSERTSTRING, 0, (LONG) (LPSTR) fileName);

			}
			if (*SaveArtFileName)
				SetDlgItemText (hDlg, IDD_FILENAME, SaveArtFileName);
			else
				SendMessage(hList, CB_SETCURSEL, 0, 0);
			return TRUE;
		}
		break;
		case WM_HELP:
			DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNSAVEART); //IDD_WINVNSAVEART
			break;


		case WM_COMMAND:
			switch (GET_WM_COMMAND_ID(wParam, lParam)) 
			{

				case IDOK:
				{
					HWND hList = GetDlgItem(hDlg, IDD_FILENAME);
					int i = 1, j = 0;
					GetDlgItemText (hDlg, IDD_FILENAME, SaveArtFileName, MAXFILENAME - 1);
					if (*SaveArtFileName == '\0') 
					{
						WVMessageBox (hDlg, IDS_WVCNCM_ENTER_FILENAME, IDS_WVCNCM_FILENAME_ERROR, MB_OK | MB_ICONSTOP);
						break;
					}

					SaveArtAppend = IsDlgButtonChecked(hDlg, IDD_APPEND);
					WritePrivateProfileString(MRUENTRIES, "file01", SaveArtFileName, szAppProFile);
					while ( j < MAX_DIR_ENTRIES)
					{
						if (SendMessage (hList, CB_GETLBTEXT, j, (LONG) (LPSTR) fileName) != CB_ERR)
						{
							if (_stricmp(fileName, SaveArtFileName))
							{
								char szEntry[20];
								wsprintf(szEntry, "file%02d", ++i);

								WritePrivateProfileString(MRUENTRIES, szEntry, fileName, szAppProFile);
							}
						}
						j++;  
					} 


					if ( MRRWriteDocument (ActiveArticleDoc, sizeof (TypText), SaveArtFileName, SaveArtAppend) != NO_ERROR) 
					{
						WVMessageBox (NetDoc.hDocWnd, IDS_WVCNCM_WRITE_ERROR, IDS_WVCNCM_PROBLEMS_SAVING, MB_OK | MB_ICONEXCLAMATION);
						*SaveArtFileName = '\0';
					}
					EndDialog (hDlg, TRUE);
				}
				break;

				case ID_BROWSE:
					{
						char szDir[MAXFILENAME];
						fileName[0] = '\0';
						GetDlgItemText (hDlg, IDD_FILENAME, szDir, MAXFILENAME - 1);

						if (AskForNewFileName (hDlg, fileName, szDir, IsDlgButtonChecked(hDlg, IDD_APPEND) ) == SUCCESS)
							SetDlgItemText (hDlg, IDD_FILENAME, fileName);
					}
					break;
				case IDD_APPEND:
					break;

				case IDCANCEL:
					EndDialog (hDlg, FALSE);
					break;

				default:
					return FALSE;
			}
			break;

		default:
			return FALSE;
			break;
	}
	return TRUE;
}

/*-- function WinVnSaveArtsDlg ---------------------------------------
 *
 *  Dialog function to handle Save Articles dialog box.
 *  Same as Save Article dialog, except actual save is deferred until
 *  later (When IDM_RETRIEVE_COMPLETE Message gets sent to Group win)
 *  (JSC)
 */

INT_PTR CALLBACK WinVnSaveArtsDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  char fileName[MAXFILENAME];
  OFSTRUCT ofs;
  HFILE hFile;
  UINT mode;
  static BOOL bAskOverwrite = FALSE;

  switch (iMessage) 
  {

  case WM_INITDIALOG:
  {
          int i;
          char szEntry[20];
          HWND hList = GetDlgItem(hDlg, IDD_FILENAME);

          CheckDlgButton (hDlg, IDD_APPEND, SaveArtAppend);
          CheckDlgButton (hDlg, IDD_KEEP_HEADER_VISIBLE, KeepArticleHeaderVisible);
          SetDlgItemText (hDlg, IDD_FILENAME, SaveArtFileName);


          for (i = MAX_DIR_ENTRIES; i > 0; i--)
          {
              wsprintf(szEntry, "file%02d", i);
              GetPrivateProfileString (MRUENTRIES, szEntry, "", fileName, MAXFILENAME, szAppProFile);
              if (*fileName)
                SendMessage (hList, CB_INSERTSTRING, 0, (LONG) (LPSTR) fileName);

          }
          if (*SaveArtFileName)
            SetDlgItemText (hDlg, IDD_FILENAME, SaveArtFileName);
          else
            SendMessage(hList, CB_SETCURSEL, 0, 0);
          
          return TRUE;
		break;
	}
    
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNSAVEARTS); //IDD_WINVNSAVEARTS
		break;


	case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) 
		{

        case IDOK:
          {
            HWND hList = GetDlgItem(hDlg, IDD_FILENAME);
            int i = 1, j = 0;
			BOOL bAppend = IsDlgButtonChecked (hDlg, IDD_APPEND);

            GetDlgItemText (hDlg, IDD_FILENAME, fileName, MAXFILENAME - 1);
            if (*fileName == '\0') 
			{
                  WVMessageBox (hDlg, IDS_WVCNCM_WRITE_ERROR, IDS_WVCNCM_PROBLEMS_SAVING, MB_OK | MB_ICONSTOP);
                  break;
            }
            mode = (OpenFile (fileName, &ofs, OF_EXIST) == HFILE_ERROR) ? OF_CREATE : OF_WRITE;
            if (mode == OF_WRITE && !bAskOverwrite && !bAppend)
			{
				if (WVArgMessageBox( hDlg, IDS_WVCNCM_OVERWRITE, IDS_WVCNCM_OVERWRITE_TITLE, MB_YESNO | MB_ICONWARNING, fileName) == IDNO)
					break;
			}
			
			if ((hFile = OpenFile (fileName, &ofs, mode)) == HFILE_ERROR) 
			{
                  WVArgMessageBox (hDlg, IDS_WVCNCM_WRITE_ERROR_ARG, IDS_WVCNCM_PROBLEMS_SAVING, MB_OK | MB_ICONSTOP, fileName);
                  break;
            }
            _lclose (hFile);
            strcpy (SaveArtFileName, fileName);

            WritePrivateProfileString(MRUENTRIES, "file01", SaveArtFileName, szAppProFile);
            while ( j < MAX_DIR_ENTRIES)
            {
              if (SendMessage (hList, CB_GETLBTEXT, j, (LONG) (LPSTR) fileName) != CB_ERR)
              {
                if (_stricmp(fileName, SaveArtFileName))
                {
                  char szEntry[20];
                  wsprintf(szEntry, "file%02d", ++i);
                  
                  WritePrivateProfileString(MRUENTRIES, szEntry, fileName, szAppProFile);
                }
              }
              j++;  
            } 

            KeepArticleHeaderVisible = IsDlgButtonChecked (hDlg, IDD_KEEP_HEADER_VISIBLE);
            SaveArtAppend = bAppend;

            EndDialog (hDlg, TRUE);

          }
          break;

        case ID_BROWSE:
          {
            TCHAR szDir[MAXFILENAME], *p, *p1;
            fileName[0] = '\0';
            GetDlgItemText (hDlg, IDD_FILENAME, szDir, MAXFILENAME - 1);
            p=p1=szDir;
            while (*p)
            { 
				if (*p++ == '\\')
					p1=p;
			}
			if (*p1)
				*p1 = _T('\0');
					
           
          	bAskOverwrite = FALSE;
            if (AskForNewFileName (hDlg, fileName, szDir, IsDlgButtonChecked(hDlg, IDD_APPEND)) == SUCCESS)
			{
				bAskOverwrite = !IsDlgButtonChecked(hDlg, IDD_APPEND); 
                SetDlgItemText (hDlg, IDD_FILENAME, fileName);
			}
          }
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*-- function WinVnDecodeArtsDlg ---------------------------------------
 *
 *  Dialog function to handle Decode Articles dialog box.
 *  (JSC)
 */

INT_PTR CALLBACK WinVnDecodeArtsDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  int len;

  switch (iMessage) {

  case WM_INITDIALOG:
        SetDlgItemText (hDlg, IDD_DECODE_PATH, DecodePathName);
        CheckDlgButton (hDlg, IDD_EXECUTE_DECODED, ExecuteDecodedFiles);
        CheckDlgButton (hDlg, IDD_KEEP_HEADER_VISIBLE, KeepArticleHeaderVisible);
        CheckDlgButton (hDlg, IDD_VERBOSE_STATUS, CodingStatusVerbose);
        CheckDlgButton (hDlg, IDD_MINIMIZE_CODING_STATUS, MinimizeStatusWindows);
        CheckDlgButton (hDlg, IDD_DUMB_DECODE, DumbDecode);
        CheckDlgButton (hDlg, IDD_INCLUDE_OPEN_ARTS, AlsoDecodeOpenArticles);

        EnableWindow (GetDlgItem (hDlg, IDD_INCLUDE_OPEN_ARTS), (BOOL) (NumArticleWnds > 0));
        EnableWindow (GetDlgItem (hDlg, IDD_KEEP_HEADER_VISIBLE), (BOOL) lParam);
        if (lParam)
          WVSetWindowText (hDlg, IDS_WVCNCM_DECODE1);
        else
          WVSetWindowText (hDlg, IDS_WVCNCM_DECODE2);
        break;

	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNDECODEARTS);
		break;
  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
          AlsoDecodeOpenArticles = (IsDlgButtonChecked (hDlg, IDD_INCLUDE_OPEN_ARTS) != 0);
          GetDlgItemText (hDlg, IDD_DECODE_PATH, DecodePathName, MAXFILENAME - 1);
          RemoveTrailingWhiteSpace (DecodePathName);
          len = strlen (DecodePathName);
          if (len == 0) {
                WVMessageBox (hDlg, IDS_WVCNCM_ENTER_PATH, IDS_WVCNCM_DECODE_PATH, MB_OK | MB_ICONWARNING);
                break;
          }

          /* allow path like c:\ -- but otherwise trim off trailing slashes */
          if ((len != 3 || DecodePathName[1] != ':' || DecodePathName[2] != '\\') &&
                  DecodePathName[len - 1] == '\\') {
                DecodePathName[len - 1] = '\0';
          }

          if (_access (DecodePathName, 0) < 0) {
                WVArgMessageBox (hDlg, IDS_WVCNCM_NO_PATH, IDS_WVCNCM_DECODE_PATH, MB_OK | MB_ICONSTOP, DecodePathName);
                break;
          }

          ExecuteDecodedFiles = (IsDlgButtonChecked (hDlg, IDD_EXECUTE_DECODED) != 0);
          KeepArticleHeaderVisible = IsDlgButtonChecked (hDlg, IDD_KEEP_HEADER_VISIBLE);
          CodingStatusVerbose = IsDlgButtonChecked (hDlg, IDD_VERBOSE_STATUS);
          MinimizeStatusWindows = IsDlgButtonChecked (hDlg, IDD_MINIMIZE_CODING_STATUS);
          DumbDecode = IsDlgButtonChecked (hDlg, IDD_DUMB_DECODE);
          EndDialog (hDlg, TRUE);
          break;

        case ID_BROWSE:
          if (AskForFilePath (hDlg, DecodePathName, "Select Decode Path") == SUCCESS)
                SetDlgItemText (hDlg, IDD_DECODE_PATH, DecodePathName);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case IDD_SMART_FILER:
          DialogBox (hInst, MAKEINTRESOURCE(IDD_WINVNSMARTFILER), hDlg, lpfnWinVnSmartFilerDlg);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}


void SelectTypeByExtension (HWND hListBox, char *fileName)
{
  
  
  SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) WVGetMIMETypeForFile(fileName));

  /*
  char temp[MAXFILENAME];

  
  GetFileExtension (temp, fileName);
  if (!_stricmp (temp, "gif"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "image/gif");
  else if (!_stricmp (temp, "jpg") || !_strnicmp (temp, "jpe", 3))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "image/jpeg");
  else if (!_stricmp (temp, "tif") || !_strnicmp (temp, "tif", 3))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "image/tiff");
  else if (!_stricmp (temp, "png"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "image/png");
  else if (!_stricmp (temp, "bmp"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "image/bmp");

  else if (!_stricmp (temp, "zip"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/zip");
  else if (!_stricmp (temp, "gzip"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/x-gzip");
  else if (!_stricmp (temp, "z") )
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/x-compress");
  else if (!_stricmp (temp, "doc"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/msword");
  else if (!_stricmp (temp, "rtf"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/rtf");
  else if (!_stricmp (temp, "swf"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/x-shockwave-flash");
  else if (!_stricmp (temp, "pdf"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/pdf");
 else if (!_stricmp (temp, "exe") || !_stricmp (temp, "bin") || !_stricmp (temp, "dll")	||
		  !_stricmp (temp, "7z")  || !_stricmp (temp, "rar") || !_stricmp (temp, "par"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/octet-stream");

  else if (!_stricmp (temp, "mpg") || !_strnicmp (temp, "mpe", 3))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "video/mpeg");
  else if (!_stricmp (temp, "avi") || !_stricmp (temp, "wmv"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "video/x-msvideo");
  else if (!_stricmp (temp, "asf") || !_stricmp (temp, "asr") || !_stricmp (temp, "asx"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "video/x-ms-asf");
  else if (!_stricmp (temp, "mov") || !_stricmp (temp, "qt"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "video/quicktime");
  
  else if (!_stricmp (temp, "ps") || !_stricmp (temp, "eps") || !_stricmp (temp, "ai"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/postScript");
  else if (!_stricmp (temp, "txt") || !_stricmp (temp, "bat") || !_stricmp (temp, "c") || !_stricmp (temp, "cpp") || !_stricmp (temp, "h"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "text/plain");
  else if (!_stricmp (temp, "htm") || !_strnicmp (temp, "htm", 3))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "text/html");
		  
  else if (!_stricmp (temp, "wav"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "audio/x-wav");
  else if (!_stricmp (temp, "mid"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "audio/midi");
 else if (!_stricmp (temp, "mp3"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "audio/mpeg");
 else if (!_stricmp (temp, "au") || !_stricmp (temp, "snd"))
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "audio/basic");

  else	if (*DefaultContentType)
        SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) DefaultContentType);
  else 
	    SendMessage (hListBox, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "application/octet-stream");
  */
}

/*-- function WinVnAttachDlg ---------------------------------------
 *
 *  Dialog function to handle attachments to postings
 *  pointer to attachment struct should be passed in lParam
 *  jsc 9/24/94
 */

INT_PTR CALLBACK WinVnAttachDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  
  int i, nType, select;
  char temp[MAXINTERNALLINE];
	TypAttachment *thisAttach =  (TypAttachment *) GetWindowLongPtr(hDlg, GWLP_USERDATA); 

  switch (iMessage) 
  {
  case WM_INITDIALOG:
        thisAttach = (TypAttachment *) lParam;
		SetWindowLongPtr(hDlg, GWLP_USERDATA, lParam);

        for (i = 0; i < NUM_CONTENT_TYPES; i++)
          SendDlgItemMessage (hDlg, IDD_CONTENT_TYPE, CB_ADDSTRING, 0, (LPARAM) (LPSTR) ContentTypes[i]);

        // if DefaultContentType is not "other", add the type to the list
        if (*DefaultContentType && _stricmp (DefaultContentType, "Other")) 
		{
          SendDlgItemMessage (hDlg, IDD_CONTENT_TYPE, CB_ADDSTRING, 0, (LPARAM) (LPSTR) DefaultContentType);
          SendDlgItemMessage (hDlg, IDD_CONTENT_TYPE, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) DefaultContentType);
        }
        else 
		{
          SendDlgItemMessage (hDlg, IDD_CONTENT_TYPE, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) "Other");
        }
        CheckDlgButton (hDlg, IDD_MAKE_DEFAULT_CONTENT, 0);
        CheckDlgButton (hDlg, IDD_MAKE_DEFAULT_ENCODING, 0);

        if (thisAttach->encodingType != CODE_NONE)
          nType = SetupEncodingOptions (hDlg, thisAttach->encodingType, FALSE, TRUE);
        else
          nType = SetupEncodingOptions (hDlg, (eEncodingType) DefaultEncodingType, FALSE, TRUE);

		if (nType == CODE_YENC)
		{
			EnableWindow(GetDlgItem(hDlg, IDD_CONTENT_TYPE), FALSE);
			EnableWindow(GetDlgItem(hDlg, IDD_MAKE_DEFAULT_CONTENT), FALSE);
			//CheckDlgButton (hDlg, IDD_ATTACH_NEXT, TRUE);
		}


        if (*(thisAttach->fileName))
          SetDlgItemText (hDlg, IDD_FILENAME, thisAttach->fileName);

        if (*(thisAttach->contentType))
          SetDlgItemText (hDlg, IDD_CONTENT_TYPE, (LPCSTR) thisAttach->contentType);
        else if (*(thisAttach->fileName))
          SelectTypeByExtension (GetDlgItem (hDlg, IDD_CONTENT_TYPE), thisAttach->fileName);

        
        break;

	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNATTACH);
		break;

  case WM_COMMAND:
        switch (LOWORD (wParam)) 
		{

		case IDD_FILENAME:
          if (GET_WM_COMMAND_CMD (wParam, lParam) == EN_KILLFOCUS) {
                GetDlgItemText (hDlg, IDD_CONTENT_TYPE, (LPSTR) str, MAXINTERNALLINE);
                if (*str == '\0') {
                  GetDlgItemText (hDlg, IDD_FILENAME, str, MAXINTERNALLINE);
                  SelectTypeByExtension (GetDlgItem (hDlg, IDD_CONTENT_TYPE), str);
                }
          }
          break;
		case IDD_CODING_TYPE:
			if ((GET_WM_COMMAND_CMD (wParam, lParam) == CBN_SELENDOK))
			{

				i = (int) SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
				if (i != CB_ERR)
				{
					SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETLBTEXT, (WPARAM) i, (LPARAM) (LPSTR) temp);

					nType = EncodingStrToType (temp);
					EnableWindow(GetDlgItem(hDlg, IDD_CONTENT_TYPE), (nType != CODE_YENC));
					EnableWindow(GetDlgItem(hDlg, IDD_MAKE_DEFAULT_CONTENT), (nType != CODE_YENC));

				}

			}

		break;
        case IDOK:
          GetDlgItemText (hDlg, IDD_FILENAME, thisAttach->fileName, MAXINTERNALLINE);
          if (*(thisAttach->fileName) == '\0') 
		  {
                WVMessageBox (hDlg, IDS_WVCNCM_ENTER_ATTACH, IDS_WVCNCM_FILENAME_ERROR, MB_OK | MB_ICONSTOP);
                break;
          }
//              if (_access(thisAttach->fileName, 0) < 0) {
          if ((thisAttach->numBytes = GetFileLength (thisAttach->fileName)) == 0) 
		  {
                WVArgMessageBox (hDlg, IDS_WVCNCM_ATTACH_ERROR, IDS_WVCNCM_ATTACH_FILE, MB_OK | MB_ICONSTOP, thisAttach->fileName);
                break;
          }

          GetDlgItemText (hDlg, IDD_CONTENT_TYPE, (LPSTR) thisAttach->contentType, MAXINTERNALLINE);
          if (IsDlgButtonChecked (hDlg, IDD_MAKE_DEFAULT_CONTENT))
                strcpy (DefaultContentType, thisAttach->contentType);

          select = (int) SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
          if (select != CB_ERR)
		  {
                SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETLBTEXT, (WPARAM) select, (LPARAM) temp );
				thisAttach->encodingType = EncodingStrToType(temp);
		  }
          if (IsDlgButtonChecked (hDlg, IDD_MAKE_DEFAULT_ENCODING))
                DefaultEncodingType = thisAttach->encodingType;

          thisAttach->attachInNewArt = DefaultAttachInNewArt;

          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case ID_BROWSE:
          if (!*thisAttach->fileName)
			 strntcpy(thisAttach->fileName, AttachPath, MAXFILENAME); 
		  if (AskForExistingFileName (hDlg, thisAttach->fileName, "Open File To Attach") == SUCCESS) {
                SetDlgItemText (hDlg, IDD_FILENAME, thisAttach->fileName);
                SelectTypeByExtension (GetDlgItem (hDlg, IDD_CONTENT_TYPE), thisAttach->fileName);
          }
          break;

        default:
          return FALSE;
        }

  default:
        return FALSE;
  }
  return TRUE;
}

/*-- function WinVnAttachPrefsDlg ---------------------------------------
 *
 *  Dialog function to handle attachment preferences
 *  jsc 9/24/94
 */

INT_PTR CALLBACK WinVnAttachPrefsDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  char temp[MAXINTERNALLINE];
  extern char *GetFileExtension ();
  extern BOOL isnumber (char *str);
  register int i;
  int genMIME, result, num;
  extern char *ContentTypes[MAXMIMETYPE];
  long newLength, multiplier;
  BOOL bSel = FALSE;

  switch (iMessage) {
  case WM_INITDIALOG:
        CheckDlgButton (hDlg, IDD_ATTACH_NEXT, DefaultNewArtForAttach ? BST_CHECKED : BST_UNCHECKED);

        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM) -1, (LPARAM) (LPSTR) "32000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "60000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "100000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "157500");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "315000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "472500");
		SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "630000");
		SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "787500");
		SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "945000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LENGTH, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "None");

        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "1000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "2500");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "5000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "7500");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "10000");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "12500");
        SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "15000");
		SendDlgItemMessage (hDlg, IDD_ARTICLE_SPLIT_LINES, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) "None");

        num = SetupEncodingOptions (hDlg, (eEncodingType) DefaultEncodingType, TRUE, TRUE);

        if (ArticleSplitLength == 0) 
		{
          SetDlgItemText (hDlg, IDD_ARTICLE_SPLIT_LENGTH, "None");
          SetDlgItemText (hDlg, IDD_ARTICLE_SPLIT_LINES, "None");
        }
        else 
		{
			SetDlgItemText (hDlg, IDD_ARTICLE_SPLIT_LENGTH, _ltoa (ArticleSplitLength, str, 10));
			multiplier = 63;
			if (num == CODE_YENC)
				multiplier = 130;
			newLength = ArticleSplitLength / multiplier;
			SetDlgItemText (hDlg, IDD_ARTICLE_SPLIT_LINES, _ltoa (newLength, str, 10));

        }
		SendDlgItemMessage(hDlg, IDD_CUSTOM_TABLE, EM_LIMITTEXT, CODINGTABLESIZE, 0);
        SetDlgItemText (hDlg, IDD_SUBJECT_TEMPLATE, SubjectTemplate);
        CheckDlgButton (hDlg, IDD_GENERATE_MIME, GenerateMIME);
        CheckDlgButton (hDlg, IDD_MIME_USAGE_SUGGESTIONS, MIMEUsageSuggestions);

        if (!GenerateMIME)
		{ 
			EnableWindow (GetDlgItem (hDlg, IDD_CONTENT_TYPE), FALSE);
			EnableWindow (GetDlgItem (hDlg, IDD_MIME_USAGE_SUGGESTIONS), FALSE);
		}

        for (i = 0; i < NUM_CONTENT_TYPES; i++)
          SendDlgItemMessage (hDlg, IDD_CONTENT_TYPE, CB_ADDSTRING, 0, (LPARAM) (LPSTR) ContentTypes[i]);

        if (_stricmp (DefaultContentType, "Other"))
          SendDlgItemMessage (hDlg, IDD_CONTENT_TYPE, CB_ADDSTRING, 0, (LPARAM) (LPSTR) DefaultContentType);

		if (num == CODE_YENC)
		{
			CheckDlgButton (hDlg, IDD_GENERATE_MIME, FALSE);
			CheckDlgButton (hDlg, IDD_MIME_USAGE_SUGGESTIONS, FALSE);
			EnableWindow (GetDlgItem (hDlg, IDD_CONTENT_TYPE), FALSE);
			EnableWindow (GetDlgItem (hDlg, IDD_GENERATE_MIME), FALSE);
			EnableWindow (GetDlgItem (hDlg, IDD_MIME_USAGE_SUGGESTIONS), FALSE);
		}

        return TRUE;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)410); //IDD_WINVNATTACHPREFS
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) 
		{

		case IDHELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)410); //IDD_WINVNATTACHPREFS
		break;

        case IDOK:
          DefaultNewArtForAttach  = IsDlgButtonChecked (hDlg, IDD_ATTACH_NEXT) ? TRUE : FALSE;
          if (ProcessEncodingOptions (hDlg, &DefaultEncodingType) == FAIL)
                break;

          GetDlgItemText (hDlg, IDD_ARTICLE_SPLIT_LENGTH, temp, MAXINTERNALLINE);
          if (!_stricmp (temp, "None")) 
		  {
                ArticleSplitLength = 0;
          }
          else 
		  {
                if (isnumber (temp)) 
				{
                  newLength = atol (temp);
                }
                else 
				{
                  WVMessageBox (hDlg, IDS_WVCNCM_SPLIT_HELP, IDS_WVCNCM_SPLIT_LEN_ERROR, MB_OK | MB_ICONSTOP);
                  break;
                }
                if (newLength > 0L && newLength < 4096L)  // allow 0
				{      

                  WVMessageBox (hDlg, IDS_WVCNCM_SPLIT_4K, IDS_WVCNCM_ART_LEN_ERROR, MB_OK | MB_ICONSTOP);
                  break;
                }
                //if (newLength > 60000L &&
                //    WVMessageBox (hDlg, IDS_WVCNCM_ART_60K, IDS_WVCNCM_ART_LEN_WARN, MB_YESNO | MB_ICONINFORMATION) == IDNO) {
                //  break;
                //}
                if (newLength > 499000L &&
                    WVMessageBox (hDlg, IDS_WVCNCM_ART_500K, IDS_WVCNCM_ART_LEN_WARN, MB_YESNO | MB_ICONINFORMATION) == IDNO) {
                  break;
                }

                ArticleSplitLength = newLength;
          }

          GetDlgItemText (hDlg, IDD_SUBJECT_TEMPLATE, SubjectTemplate, MAXINTERNALLINE);

          GenerateMIME = IsDlgButtonChecked (hDlg, IDD_GENERATE_MIME);
//        GetDlgItemText (hDlg, IDD_MIME_BOUNDARY, MIMEBoundary, MAXBOUNDARYLEN);

          // *** should check here that characters in boundary are all valid
          GetDlgItemText (hDlg, IDD_CONTENT_TYPE, (LPSTR) DefaultContentType, MAXINTERNALLINE);

          MIMEUsageSuggestions = IsDlgButtonChecked (hDlg, IDD_MIME_USAGE_SUGGESTIONS);
          if (MIMEUsageSuggestions) 
		  {
                
                if (GenerateMIME && DefaultEncodingType != CODE_NONE && DefaultEncodingType != CODE_BASE64) 
				{
                  result = WVArgMessageBox (hDlg, IDS_WVCNCM_DISABLE_MIME, IDS_WVCNCM_MIME_USE,
                                            MB_YESNOCANCEL | MB_ICONINFORMATION, EncodingTypeToStr (DefaultEncodingType) );
                  if (result == IDYES)
                        GenerateMIME = FALSE;
                  else if (result == IDCANCEL)
                        break;

                }
                if (!GenerateMIME && DefaultEncodingType == CODE_BASE64) 
				{
                  result = WVMessageBox (hDlg, IDS_WVCNCM_ENABLE_MIME, IDS_WVCNCM_MIME_USE, MB_YESNOCANCEL | MB_ICONINFORMATION);
                  if (result == IDYES)
                        GenerateMIME = TRUE;
                  else if (result == IDCANCEL)
                        break;
                }
          }

          EndDialog (hDlg, TRUE);
          break;

        case IDD_GENERATE_MIME:
          genMIME = (BOOL) IsDlgButtonChecked (hDlg, IDD_GENERATE_MIME);
          EnableWindow (GetDlgItem (hDlg, IDD_CONTENT_TYPE), genMIME);
		  EnableWindow (GetDlgItem (hDlg, IDD_MIME_USAGE_SUGGESTIONS), genMIME);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;
		case IDD_CODING_TYPE:
		case IDD_ARTICLE_SPLIT_LENGTH:
		case IDD_ARTICLE_SPLIT_LINES:
			bSel = (GET_WM_COMMAND_CMD (wParam, lParam) == CBN_SELENDOK);
			
			if ( bSel || GET_WM_COMMAND_CMD (wParam, lParam) == CBN_KILLFOCUS ||
						 GET_WM_COMMAND_CMD (wParam, lParam) == CBN_EDITCHANGE ) 
			{
				if (GetDlgItemText (hDlg, IDD_CODING_TYPE, temp, MAXINTERNALLINE) )
				{
					
					UINT nControlID = GET_WM_COMMAND_ID(wParam, lParam);
					UINT nOtherControl = IDD_ARTICLE_SPLIT_LINES;

					if (nControlID == IDD_CODING_TYPE)
					{
						bSel = FALSE;
						nControlID = IDD_ARTICLE_SPLIT_LENGTH;
						
						num = (int) SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
						if (num != CB_ERR)
							SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETLBTEXT, (WPARAM) num, (LPARAM) (LPSTR) temp);
					}

					if (nControlID == IDD_ARTICLE_SPLIT_LINES )
						nOtherControl = IDD_ARTICLE_SPLIT_LENGTH;

					num = EncodingStrToType (temp);
					multiplier = 63;
					if (num == CODE_YENC)
					{
						multiplier = 130;

						CheckDlgButton (hDlg, IDD_GENERATE_MIME, FALSE);
						CheckDlgButton (hDlg, IDD_MIME_USAGE_SUGGESTIONS, FALSE);
						EnableWindow (GetDlgItem (hDlg, IDD_CONTENT_TYPE), FALSE);
						EnableWindow (GetDlgItem (hDlg, IDD_GENERATE_MIME), FALSE);
						EnableWindow (GetDlgItem (hDlg, IDD_MIME_USAGE_SUGGESTIONS), FALSE);
						
					}
					else
					{

						CheckDlgButton (hDlg, IDD_GENERATE_MIME, GenerateMIME);
						CheckDlgButton (hDlg, IDD_MIME_USAGE_SUGGESTIONS, MIMEUsageSuggestions);
						EnableWindow (GetDlgItem (hDlg, IDD_GENERATE_MIME), TRUE);
						EnableWindow (GetDlgItem (hDlg, IDD_CONTENT_TYPE), GenerateMIME);
						EnableWindow (GetDlgItem (hDlg, IDD_MIME_USAGE_SUGGESTIONS), GenerateMIME);

					}
					
					*temp = '\0';
					newLength = 0;

					if (bSel)
					{
						num = (int) SendDlgItemMessage (hDlg, nControlID, CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
						if (num != CB_ERR)
							SendDlgItemMessage (hDlg, nControlID, CB_GETLBTEXT, (WPARAM) num, (LPARAM) (LPSTR) temp);
					}
					else
					{
						GetDlgItemText (hDlg, nControlID, temp, MAXINTERNALLINE);
					}

					if (isnumber (temp)) 
					{
						newLength = atol (temp);
						if (newLength > 0)
						{
							if (nControlID == IDD_ARTICLE_SPLIT_LENGTH)
							{
								newLength /= multiplier;
								if (newLength == 0)
									newLength = 1;
							}
							else
								newLength *= multiplier;
							SetDlgItemText (hDlg, nOtherControl, _ltoa (newLength, temp, 10));
						}
						else
						{
							SetDlgItemText (hDlg, nOtherControl, "None");
						}


					}
					else
					{
						SetDlgItemText (hDlg, nOtherControl, "None");
					}


							 
				}

			}

			break;


        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}
/*-- function WinVnEncodeDlg ---------------------------------------
 *
 *  Dialog function to handle encoding to a file
 *  (JSC)
 */

INT_PTR CALLBACK WinVnEncodeDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  static TypAttachment *thisAttach;

  switch (iMessage) {
  case WM_INITDIALOG:
        thisAttach = (TypAttachment *) lParam;
        // include custom, but do not show "none" in the type-list
        SetupEncodingOptions (hDlg, DefaultEncodingType, TRUE, FALSE);
        return TRUE;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNENCODE);
		break;

  case WM_COMMAND:

        switch (GET_WM_COMMAND_ID(wParam, lParam)) 
		{
			case IDD_CODING_TYPE:
			{
				if ( GET_WM_COMMAND_CMD (wParam, lParam) == CBN_SELENDOK)
				{
					HWND hwndComboBox = (HWND) lParam;

					int nSel = ComboBox_GetCurSel(hwndComboBox);
					if (nSel != CB_ERR)
					{
						TCHAR buf[100];
						ComboBox_GetLBText(hwndComboBox, nSel, buf);
						HWND hCtrl = GetDlgItem(hDlg, IDD_CUSTOM_TABLE);
						if (hCtrl)
						{
							EnableWindow(hCtrl, EncodingStrToType( buf) == CODE_CUSTOM );
						}
					}
				}
			}
			break;

        case IDOK:
          GetDlgItemText (hDlg, IDD_FILENAME, thisAttach->fileName, MAXFILENAME - 1);
          if (*(thisAttach->fileName) == '\0') 
		  {
                WVMessageBox (hDlg, IDS_WVCNCM_ENTER_ENCODE, IDS_WVCNCM_FILENAME_ERROR, MB_OK | MB_ICONSTOP);
                break;
          }

          if (_access (thisAttach->fileName, 0) < 0) 
		  {
                WVArgMessageBox (hDlg, IDS_WVCNCM_BAD_FILE, IDS_WVCNCM_FILENAME_ERROR, MB_OK | MB_ICONSTOP,thisAttach->fileName);
                break;
          }

          if (ProcessEncodingOptions (hDlg, &thisAttach->encodingType) == FAIL)
                break;

          if (IsDlgButtonChecked (hDlg, IDD_MAKE_DEFAULT_ENCODING))
                DefaultEncodingType =  thisAttach->encodingType;

          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case ID_BROWSE:
          if (AskForExistingFileName (hDlg, thisAttach->fileName, "Open File To Be Encoded") == SUCCESS)
                SetDlgItemText (hDlg, IDD_FILENAME, thisAttach->fileName);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*----------------------------------------------------------------------
 * Encoding options functions for use by two dialogs
 * wvattachdlg and wvencodedlg
 * (JSC)
 */
eEncodingType SetupEncodingOptions (HWND hDlg, eEncodingType type, BOOL includeCustom, BOOL showNone)
{
	register int i;

	if (type == CODE_NONE)
	  type =  (eEncodingType) DefaultEncodingType;

	// This combo box is NOSORT, so entries can be indexed in order they 
	// added here. But BE CAREFUL!
	SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_LIMITTEXT, 100, (LPARAM) 0);

	for (i = 0; i < NUM_ENCODING_TYPES; i++) 
	{
		if (!includeCustom && (eEncodingType) i == CODE_CUSTOM)
			continue;
		if (showNone || (eEncodingType) i != CODE_NONE  ) 
		  SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_INSERTSTRING, (WPARAM)-1, (LPARAM) (LPSTR) EncodingTypes[i]);
	}

	if (includeCustom && UserCodingTable[0] != '\0')
		SetDlgItemText (hDlg, IDD_CUSTOM_TABLE, UserCodingTable);

	if (includeCustom)
		SendDlgItemMessage(hDlg, IDD_CUSTOM_TABLE, EM_LIMITTEXT, CODINGTABLESIZE, 0);

	SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_SELECTSTRING, (WPARAM) - 1, (LPARAM) (LPSTR) EncodingTypes[type]);

	return type;
}

BOOL ProcessEncodingOptions (HWND hDlg, eEncodingType  *newEncodingType)
{
  char temp[MAXINTERNALLINE] = {0};
  int select, x;
  char dummyMap[CODINGMAPSIZE];

  select = (int) SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
  if (select != CB_ERR)
        SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETLBTEXT, (WPARAM) select, (LPARAM) (LPSTR) temp);

  if (!_stricmp (temp, "Custom"))
        if (GetDlgItemText (hDlg, IDD_CUSTOM_TABLE, UserCodingTable, CODINGTABLESIZE + 1)) 
		{
          if (strlen (UserCodingTable) != CODINGTABLESIZE) 
		  {
                WVMessageBox (hDlg, IDS_WVCNCM_INVALID_TABLE, IDS_WVCNCM_CUSTOM_CODING, MB_OK | MB_ICONSTOP);
                return (FAIL);
          }
          if ((x = CreateCodingMap (dummyMap, UserCodingTable)) != -1) 
		  {
                sprintf (temp, "%c", x);
                WVArgMessageBox (hDlg, IDS_WVCNCM_DUPLICATE_TABLE, IDS_WVCNCM_CUSTOM_CODING, MB_OK | MB_ICONSTOP, temp);
                return (FAIL);
          }
        }
        else 
		{
          WVMessageBox (hDlg, IDS_WVCNCM_CODING_HELP, IDS_WVCNCM_CUSTOM_CODING, MB_OK | MB_ICONERROR);
          return (FAIL);
        }

  *newEncodingType = EncodingStrToType (temp);

  return (SUCCESS);
}


/*-- function WinVnExitDlg---------------------------------------
 *
 *  Dialog function to handle exit from WinVn
 *  Sets globals SaveNewsrc and SaveConfig - leaves actual saving up to caller
 *  (JSC 1/8/94)
 */

INT_PTR CALLBACK WinVnExitDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  switch (iMessage) {
  case WM_INITDIALOG:
        CheckDlgButton (hDlg, IDD_SAVE_NEWSRC, 1);
        CheckDlgButton (hDlg, IDD_SAVE_CONFIG, 1);
        return TRUE;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNEXIT);
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
          SaveNewsrc = IsDlgButtonChecked (hDlg, IDD_SAVE_NEWSRC);
          SaveConfig = IsDlgButtonChecked (hDlg, IDD_SAVE_CONFIG);
          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*-- function WinVnFindDlg ---------------------------------------
 *
 *  Dialog function to handle Search dialog box.
 */

INT_PTR CALLBACK WinVnFindDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
//  static int MyAppend;

  switch (iMessage) {

  case WM_INITDIALOG:
        SetDlgItemText (hDlg, IDD_SEARCH_STRING, FindDoc->SearchStr);
        return TRUE;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNFIND);
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
          GetDlgItemText (hDlg, IDD_SEARCH_STRING, FindDoc->SearchStr, MAXFINDSTRING - 1);

          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*--- Function WinVnPersonalInfoDlg ----------------------------------
 *
 *  Dialog function to obtain personal configuration info
 *  (Name, email address, etc.) from the user.
 */

INT_PTR CALLBACK WinVnPersonalInfoDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  switch (iMessage) {
  case WM_INITDIALOG:
        SetDlgItemText (hDlg, ID_CONFIG_EMAIL, MailAddress);
        SetDlgItemText (hDlg, ID_CONFIG_NAME, UserName);
        SetDlgItemText (hDlg, IDD_REPLY_TO, ReplyTo);
        SetDlgItemText (hDlg, ID_CONFIG_ORG, Organization);
        return TRUE;
        break;

	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNPERSONAL);
		break;


  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
          GetDlgItemText (hDlg, ID_CONFIG_EMAIL, MailAddress, MAILLEN - 1);
          GetDlgItemText (hDlg, ID_CONFIG_NAME, UserName, MAILLEN - 1);
          GetDlgItemText (hDlg, IDD_REPLY_TO, ReplyTo, MAILLEN - 1);
          GetDlgItemText (hDlg, ID_CONFIG_ORG, Organization, MAILLEN - 1);

          if (!strcmp (MailAddress, ReplyTo)) {         /* clear identical reply-to */
                WVMessageBox(hDlg, IDS_WVCNCM_NO_REPLYTO, IDS_WVCNCM_CLEAR_REPLYTO, MB_OK | MB_ICONINFORMATION);
                *ReplyTo = '\0';
                SetDlgItemText(hDlg, IDD_REPLY_TO, "");
                break;
          }

          if (!ValidEmailAddress(MailAddress)) {          /* Validate E-mail address */
                WVMessageBox(hDlg, IDS_WVCNCM_INVALID_EMAIL_HELP, IDS_WVCNCM_INVALID_EMAIL, MB_OK | MB_ICONERROR);
        //      *MailAddress = '\0';
                break;
          }

          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

// Configure Execute Dialog for setting up Universal Resource Locator (URL)
// interface between WinVN and World Wide Web (WWW) or other browsers.
//
//                                                     JD 7/23/95

INT_PTR CALLBACK WinVnExecuteInfoDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  char *dlgname;
  int id;
  char temp[MAXFILENAME], browserpath[MAXFILENAME];

  switch (iMessage) {
  case WM_INITDIALOG:
        SetDlgItemText (hDlg, ID_CONFIG_URL_HTTP,HttpClient);
        SetDlgItemText (hDlg, ID_CONFIG_URL_FTP,FtpClient);
        SetDlgItemText (hDlg, ID_CONFIG_URL_GOPHER,GopherClient);
        SetDlgItemText (hDlg, ID_CONFIG_URL_WAIS, WaisClient);
        SetDlgItemText (hDlg, IDC_CONFIG_URL_DDE_ID_STRING, DdeServName);
        CheckDlgButton (hDlg, IDC_CONFIG_URL_DDE, UsingDDE);
        CheckRadioButton (hDlg, IDC_CONFIG_URL_DDE_RADIO, IDC_CONFIG_URL_DDE_RADIO4,
                                        DdeServID + IDC_CONFIG_URL_DDE_RADIO);
        EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO),  UsingDDE);
        EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO1), UsingDDE);
        EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO2), UsingDDE);
        EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO3), UsingDDE);
        EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO4), UsingDDE);
        if (IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO1) != 0)
			EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_ID_STRING), UsingDDE);
        return TRUE;
        break;

  	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) 416); //IDD_WINVNEXECUTE
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
                
          GetDlgItemText (hDlg, ID_CONFIG_URL_HTTP, HttpClient, MAXFILENAME-1);
          GetDlgItemText (hDlg, ID_CONFIG_URL_FTP, FtpClient, MAXFILENAME-1);
          GetDlgItemText (hDlg, ID_CONFIG_URL_GOPHER, GopherClient, MAXFILENAME-1);
          GetDlgItemText (hDlg, ID_CONFIG_URL_WAIS, WaisClient, MAXFILENAME-1);
          UsingDDE = (IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0);
          if (UsingDDE) {
                DdeServID = IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO1) ? 1 :
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO2) ? 2 : 
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO3) ? 3 :
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO4) ? 4 : 0;

        if (IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO1) != 0)
                   GetDlgItemText (hDlg, IDC_CONFIG_URL_DDE_ID_STRING , DdeServName, MAXFILENAME-1);
          }
          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case IDC_CONFIG_URL_DDE:
          EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO),
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0);
          EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO1),
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0);
          EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO2),
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0);
          EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO3),
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0);
          EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_RADIO4),
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0);
          EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_ID_STRING),
                                        (IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE) != 0 &&
                                        IsDlgButtonChecked (hDlg, IDC_CONFIG_URL_DDE_RADIO1) != 0));
          return FALSE;

        case IDC_CONFIG_URL_DDE_RADIO4:
        case IDC_CONFIG_URL_DDE_RADIO2:
        case IDC_CONFIG_URL_DDE_RADIO3:
        case IDC_CONFIG_URL_DDE_RADIO:
			EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_ID_STRING), FALSE);
          return FALSE;

        case IDC_CONFIG_URL_DDE_RADIO1:
			EnableWindow (GetDlgItem (hDlg, IDC_CONFIG_URL_DDE_ID_STRING), TRUE);
          return FALSE;

        case IDC_CONFIG_URL_BUTTON1:
                dlgname = "Select WWW Browser";
                id = ID_CONFIG_URL_HTTP;
                goto ExecBrowse;
        case IDC_CONFIG_URL_BUTTON2:
                dlgname = "Select FTP Browser";
                id = ID_CONFIG_URL_FTP;
                goto ExecBrowse;
        case IDC_CONFIG_URL_BUTTON3:
                dlgname = "Select Gopher Browser";
                id = ID_CONFIG_URL_GOPHER;
                goto ExecBrowse;
        case IDC_CONFIG_URL_BUTTON4:
                dlgname = "Select WAIS Browser";
                id = ID_CONFIG_URL_WAIS;
ExecBrowse:
          if (AskForExistingFileName (hDlg, temp, dlgname) == SUCCESS) {
                if (strchr(temp, ' ')) {
                        sprintf(browserpath, "\"%s\" %%u", temp);
                } else {
                        sprintf(browserpath, "%s %%u", temp);
                }
                SetDlgItemText (hDlg, id, browserpath);
          }
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*--- Function WinVnComposePrefsDlg ---------------------------------------------
 *
 * Composition prefs
 *
 * jsc 9/28/94
 */

INT_PTR CALLBACK WinVnComposePrefsDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  static int MyShowFrom, MyShowOrg, MyShowReplyTo, MyShowKeywords, MyShowSummary,
    MyShowDist, MyShowFollowupTo;
  char temp[MAXFILENAME];
  static BOOL bLastMatch = TRUE;
  switch (iMessage) {
  case WM_INITDIALOG:
#ifdef RFC1522
        CheckDlgButton (hDlg, IDD_ENCODE_RFC1522, EncodeRFC1522);
#else
        EnableWindow(GetDlgItem (hDlg, IDD_ENCODE_RFC1522), FALSE);          
#endif  
        CheckDlgButton (hDlg, IDD_WORD_WRAP, WordWrap);
        CheckDlgButton (hDlg, IDD_PREFILL_CC, PrefillCcAddress);
        CheckDlgButton (hDlg, IDD_SHOW_FROM_HDR, ShowFromHdr);
        CheckDlgButton (hDlg, IDD_SHOW_ORG_HDR, ShowOrgHdr);
        CheckDlgButton (hDlg, IDD_SHOW_REPLYTO_HDR, ShowReplyToHdr);
        CheckDlgButton (hDlg, IDD_SHOW_KEYWORDS_HDR, ShowKeywordsHdr);
        CheckDlgButton (hDlg, IDD_SHOW_SUMMARY_HDR, ShowSummaryHdr);
        CheckDlgButton (hDlg, IDD_SHOW_DISTRIBUTION_HDR, ShowDistributionHdr);
        CheckDlgButton (hDlg, IDD_SHOW_FOLLOWUPTO_HDR, ShowFollowupToHdr);
        CheckDlgButton (hDlg, IDD_ENABLE_SIG, EnableSig);
        CheckDlgButton (hDlg, IDD_X_NO_ARCHIVE, XNoArchive);
		CheckDlgButton (hDlg, IDC_STRIP_SIG, TruncateSignatureFollowup);
		CheckDlgButton (hDlg, IDC_CB_NEWSREADER, NoXNewsreader);
        SetDlgItemText (hDlg, IDD_FILENAME, SigFileName);
        SetDlgItemText (hDlg, IDD_FOLLOWUP_TEMPLATE, FollowupSaysTemplate);
        SetDlgItemText (hDlg, IDD_REPLY_TEMPLATE, ReplySaysTemplate);
		SetDlgItemText (hDlg, ID_CONFIG_TOKEN, IDToken);
		SetDlgItemText (hDlg, ID_CONFIG_HOSTNAME, MyOwnHost);
		Edit_LimitText(GetDlgItem(hDlg, IDD_FILENAME), MAXFILENAME);
		Edit_LimitText(GetDlgItem(hDlg, IDD_REPLY_TEMPLATE), MAXINTERNALLINE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_TOKEN), MAXINTERNALLINE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_HOSTNAME), MAXHOSTNAMESIZE);
		SetDlgItemText (hDlg, IDC_EB_CANCELSECRET, CancelKey);
		Edit_LimitText(GetDlgItem(hDlg, IDC_EB_CANCELSECRET), MAXINTERNALLINE);
		CheckDlgButton (hDlg, IDC_USE_CANCELLOCK, UseCancelKey ? 1 : 0);

        MyShowFrom = ShowFromHdr;
        MyShowOrg = ShowOrgHdr;
        MyShowReplyTo = ShowReplyToHdr;
        MyShowKeywords = ShowKeywordsHdr;
        MyShowSummary = ShowSummaryHdr;
        MyShowDist = ShowDistributionHdr;
        MyShowFollowupTo = ShowFollowupToHdr;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) 409); //IDD_WINVNCOMPOSEPREFS
		break;
	case WM_CTLCOLOREDIT:
		{
			HWND hEdit = GetDlgItem(hDlg, ID_CONFIG_HOSTNAME);
			if (hEdit == (HWND) lParam)
			{
				char buf[MAXHOSTNAMESIZE] = {0};
				if (GetDlgItemText (hDlg, ID_CONFIG_HOSTNAME, buf, MAXHOSTNAMESIZE) &&
					!_stricmp(MyOwnHost, buf) )
				{
				
					HDC hdc = (HDC)wParam;
					SetTextColor(hdc, GetSysColor(COLOR_GRAYTEXT)); //disabled
					SetBkColor(hdc, GetSysColor(COLOR_WINDOW) );    //normal
					return (LPARAM) GetSysColorBrush(COLOR_WINDOW);   // default
				}
			}
			return 0;
		}
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) 
		{

		case ID_CONFIG_HOSTNAME:
			if ( GET_WM_COMMAND_CMD(wParam, lParam) == EN_UPDATE)
			{
				char buf[MAXHOSTNAMESIZE] = {0};
				if (GetDlgItemText (hDlg, ID_CONFIG_HOSTNAME, buf, MAXHOSTNAMESIZE) &&
					!_stricmp(MyOwnHost, buf) )
				{
					if (bLastMatch)
					{
						if (IsWindow((HWND) lParam)	)
							InvalidateRect( (HWND) lParam, NULL, TRUE);
						bLastMatch = FALSE;								
					}
				}
				else if (!bLastMatch)
				{
					if (IsWindow((HWND) lParam)	)
						InvalidateRect( (HWND) lParam, NULL, TRUE);
					bLastMatch = TRUE;
				}

				return 1;
			}
			break;

        case IDOK:
#ifdef RFC1522
          EncodeRFC1522 = (IsDlgButtonChecked (hDlg, IDD_ENCODE_RFC1522) != 0);
#endif   
          WordWrap = (IsDlgButtonChecked (hDlg, IDD_WORD_WRAP) != 0);
          PrefillCcAddress = (IsDlgButtonChecked (hDlg, IDD_PREFILL_CC) != 0);
          ShowFromHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_FROM_HDR) != 0);
          ShowOrgHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_ORG_HDR) != 0);
          ShowReplyToHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_REPLYTO_HDR) != 0);
          ShowKeywordsHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_KEYWORDS_HDR) != 0);
          ShowSummaryHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_SUMMARY_HDR) != 0);
          ShowDistributionHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_DISTRIBUTION_HDR) != 0);
          ShowFollowupToHdr = (IsDlgButtonChecked (hDlg, IDD_SHOW_FOLLOWUPTO_HDR) != 0);
          XNoArchive = (IsDlgButtonChecked (hDlg, IDD_X_NO_ARCHIVE) != 0);
		  TruncateSignatureFollowup = (IsDlgButtonChecked (hDlg, IDC_STRIP_SIG ) != 0);
		  NoXNewsreader = (IsDlgButtonChecked (hDlg, IDC_CB_NEWSREADER ) != 0);
          GetDlgItemText (hDlg, IDD_FOLLOWUP_TEMPLATE, FollowupSaysTemplate, MAXINTERNALLINE - 1);
          GetDlgItemText (hDlg, IDD_REPLY_TEMPLATE, ReplySaysTemplate, MAXINTERNALLINE - 1);
          GetDlgItemText (hDlg, ID_CONFIG_TOKEN, IDToken, MAXINTERNALLINE - 1);
		  {
			IDToken[MAXINTERNALLINE - 1] = '\0';
			for (size_t i = 0; i < strlen(IDToken); i++)
			{
				if (isspace((unsigned char) IDToken[i]) || IDToken[i] == '<' || IDToken[i] == '>' || IDToken[i] == '@' || !isprint(IDToken[i]))
					IDToken[i] = '_';
			}
		  }
		  
		  //validate hostname
		  if (GetDlgItemText (hDlg, ID_CONFIG_HOSTNAME, temp, MAXFILENAME - 1))
		  {
			char buf[MAXHOSTNAMESIZE] = {0};
			char *p = buf;
			char *lastdot = buf;
			for (size_t i = 0; i < strlen(temp) && (p-buf) < MAXHOSTNAMESIZE; i++)
			{
				if ( isspace((unsigned char) temp[i]) || (!isalnum(temp[i]) && temp[i] != '-' && temp[i] != '.' ) )
					continue; //only A-Z, a-z, 0-9, '.', '-'

				if ((temp[i] == '-' || temp[i] == '.') && p == buf)	
					continue; //no leading '-', '.'

				if (temp[i] == '.' && p>buf && *(p-1) == '.')
					continue; //no adjacent dots

				if (temp[i] == '-' && p>buf && *(p-1) == '-')
					continue; //no adjacent hyphen

				if (temp[i] == '.')	
					lastdot = p;

				if (p-lastdot < 63) //max component 63
					*p++ = temp[i];
									
			}
			*p++ = '\0';
			//no trailing '-', '.'
			while ( buf[strlen(buf) - 1] == '-' || buf[strlen(buf) - 1] == '.') 
				*(--p) = '\0';
				
			if (_stricmp(temp, buf))
			{
                  if (strlen(buf) == 0)
					fakeHostname(buf);
				  
				  if (WVArgMessageBox (hDlg, IDS_WVCNCM_WARN_HOSTNAME, IDS_WVCNCM_HOSTNAME_INVALID,
                                  MB_YESNO | MB_ICONQUESTION, buf) == IDNO) 
				  {
					return 0;
				  }
				
			}
			
			if (strlen(buf) > 0 && _stricmp(MyOwnHost, buf))
				strcpy(MyOwnHost, buf);

		  }


		  GetDlgItemText (hDlg, IDC_EB_CANCELSECRET, CancelKey, MAXINTERNALLINE - 1);
		  UseCancelKey = IsDlgButtonChecked (hDlg, IDC_USE_CANCELLOCK);
		  if (UseCancelKey && !*CancelKey)
		  {
                 WVMessageBox (hDlg, IDS_WVCNCM_INVALID_KEY, IDS_WVCNCM_KEY_TITLE, MB_OK | MB_ICONSTOP);
				 UseCancelKey = FALSE;

		  }

          if (MyShowFrom != ShowFromHdr ||
                  MyShowOrg != ShowOrgHdr ||
                  MyShowReplyTo != ShowReplyToHdr ||
                  MyShowKeywords != ShowKeywordsHdr ||
                  MyShowSummary != ShowSummaryHdr ||
                  MyShowFollowupTo != ShowFollowupToHdr ||
                  MyShowDist != ShowDistributionHdr) {
                RefreshComposeWnds ();
          }

          EnableSig = IsDlgButtonChecked (hDlg, IDD_ENABLE_SIG);
          GetDlgItemText (hDlg, IDD_FILENAME, temp, MAXFILENAME - 1);
          if (EnableSig) {
                if (*temp == '\0' || _access (temp, 0) < 0) {
                  WVMessageBox (hDlg, IDS_WVCNCM_DISABLE_SIGNATURE, IDS_WVCNCM_INVALID_FILENAME, MB_OK | MB_ICONSTOP);
                  EnableSig = FALSE;
                  break;
                }
                ResetTextBlock (Signature);
                if (ReadFileToTextBlock (hDlg, Signature, temp) == FAIL)
                  break;

                if (Signature->numLines > BIG_SIG_FILE) {
                  sprintf (str, "%lu", Signature->numLines);
                  if (WVArgMessageBox (hDlg, IDS_WVCNCM_SIGNATURE_LINES, IDS_WVCNCM_BIG_SIGNATURE,
                                  MB_YESNO | MB_ICONQUESTION, str) == IDNO) {
                        ResetTextBlock (Signature);
                        break;
                  }
                }
          }
          strcpy (SigFileName, temp);

          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case ID_BROWSE:
          if (AskForExistingFileName (hDlg, temp, "Select Signature File") == SUCCESS) {
                SetDlgItemText (hDlg, IDD_FILENAME, temp);
          }
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;

}

/*--- Function WinVnConfigArticleDlg ---------------------------------------------
 *
 * Article prefs
 *
 * jsc 9/28/94
 */
INT_PTR CALLBACK WinVnConfigArticleDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  int ok, num;
  static int MyItalicizeQuotes;

  switch (iMessage) {
  case WM_INITDIALOG:
		CenterWindow (hDlg, NULL );
        CheckDlgButton (hDlg, ID_WRAP_INCOMING_TEXT, WrapIncomingArticleText);
        SetDlgItemInt (hDlg, ID_WRAP_INCOMING_TEXT_LIMIT, WrapIncomingArticleTextLength, TRUE);
        CheckDlgButton (hDlg, ID_TRIM_HEADERS, TrimHeaders);
#ifdef RFC1522
        CheckDlgButton (hDlg, ID_USE_RFC1522, UseRFC1522);
#else
        EnableWindow(GetDlgItem (hDlg, ID_USE_RFC1522), FALSE);          
#endif
#ifdef VISUAL1521
        CheckDlgButton (hDlg, ID_USE_VISUAL1521, UseVISUAL1521);
#else
        EnableWindow(GetDlgItem (hDlg, ID_USE_VISUAL1521), FALSE);          
#endif
        CheckDlgButton (hDlg, ID_TRUNCATE_SIGNATURES, TruncateSignatures);
        CheckDlgButton (hDlg, ID_CONFIG_NEW_WND_ARTICLE, NewArticleWindow);
        CheckDlgButton (hDlg, ID_SCROLL_PAST_HEADERS, ScrollPastHeaders);
        CheckDlgButton (hDlg, ID_SEARCH_UNREADGROUP, ConfigJumpGroup);
/* Ray Dunn:99/10 */
        CheckDlgButton (hDlg, ID_SHOW_AUTHOR_NAME, ShowAuthorName);
/* Ray Dunn:99/10:End */
		CheckDlgButton (hDlg, ID_SHOW_XFACE, ShowXFace);
#ifndef _WIN32
		EnableWindow(GetDlgItem (hDlg, ID_SHOW_XFACE), FALSE);
#endif
        CheckDlgButton (hDlg, ID_QUOTES_IN_ITALICS, ItalicizeQuotes);
        MyItalicizeQuotes = ItalicizeQuotes;
		CheckRadioButton (hDlg, IDC_RB_TOOLBAR_SM, IDC_RB_TOOLBAR_AUTO, IDC_RB_TOOLBAR_SM+nToolbarArt);
        break;

  case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) 408); //IDD_WINVNARTICLEPREFS
		break;
  
  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
          WrapIncomingArticleText = (IsDlgButtonChecked (hDlg, ID_WRAP_INCOMING_TEXT) != 0);
          num = GetDlgItemInt (hDlg, ID_WRAP_INCOMING_TEXT_LIMIT, &ok, TRUE);
          if (num && (num < 15 || num > 150)) {
                WVMessageBox (hDlg, IDS_WVCNCM_WRAP_LEN_HELP, IDS_WVCNCM_INVALID_WRAP, MB_OK | MB_ICONSTOP);
                break;
          }
          WrapIncomingArticleTextLength = num;
          if (!WrapIncomingArticleTextLength) {
                WrapIncomingArticleText = FALSE;
          }
          TrimHeaders = (IsDlgButtonChecked (hDlg, ID_TRIM_HEADERS) != 0);
#ifdef RFC1522
          UseRFC1522 = (IsDlgButtonChecked (hDlg, ID_USE_RFC1522) != 0);
#endif
#ifdef VISUAL1521
          UseVISUAL1521 = (IsDlgButtonChecked (hDlg, ID_USE_VISUAL1521) != 0);
#endif
          TruncateSignatures = (IsDlgButtonChecked (hDlg, ID_TRUNCATE_SIGNATURES) != 0);
          CheckDlgButton (hDlg, ID_SEARCH_UNREADGROUP, ConfigJumpGroup);
          NewArticleWindow = (IsDlgButtonChecked (hDlg, ID_CONFIG_NEW_WND_ARTICLE) != 0);
          ScrollPastHeaders = (IsDlgButtonChecked (hDlg, ID_SCROLL_PAST_HEADERS) != 0);
          ItalicizeQuotes = (IsDlgButtonChecked (hDlg, ID_QUOTES_IN_ITALICS) != 0);
          if (ItalicizeQuotes != MyItalicizeQuotes)
                RefreshArticleWnds ();
/* Ray Dunn:99/10 */
          ShowAuthorName = (IsDlgButtonChecked (hDlg, ID_SHOW_AUTHOR_NAME) != 0);
          /* will only change when next article is read (there's no quick way to have
             it redisplayed */
/* Ray Dunn:99/10:End */
		  ShowXFace = (IsDlgButtonChecked (hDlg, ID_SHOW_XFACE) != 0);
		  {
		    int nTemp = nToolbarArt;

			nToolbarArt = IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_SM) ? 0 :
					    IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_MD) ? 1 : 
					    IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_LG) ? 2 : 
						IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_AUTO) ? 3 : 0;


			if (nTemp != nToolbarArt)
			{
				int j;

				for (j = MAXARTICLEWNDS - 1; j >= 0; j--) 
				{
				  if (ArticleDocs[j].InUse) 
				  {
					
					PostMessage( ArticleDocs[j].hWndFrame, WM_RETHINKTOOLBAR, 0, 0);
				  }
				}
				
			}
		  }

          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}


/*--- Function WinVnConfigArticleListDlg ---------------------------------------------
 *
 * Article-list (for a group) prefs
 *
 * jsc 9/28/94
 */
INT_PTR CALLBACK WinVnConfigArticleListDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  char numStr[20];
  static int MyFullSubject;
  static char MyDepth;
/* Ray Dunn:99/10 */
  static int MySortWithAlphaOnly;
/* Ray Dunn:99/10:End */
  static WORD MyDefaultSort;
  static HMENU MySortMenu;

  switch (iMessage) {
  case WM_INITDIALOG:
		CenterWindow (hDlg, NULL );
        if (article_threshold == INT_MAX)
			SetDlgItemText (hDlg, IDD_ART_THRESHOLD, "-1");
		else
			SetDlgItemText (hDlg, IDD_ART_THRESHOLD, _ltoa (article_threshold, numStr, 10));
        SetDlgItemText (hDlg, IDD_MIN_TO_READ, _ltoa (min_to_retrieve, numStr, 10));
        CheckDlgButton (hDlg, ID_CONFIG_SHOWUNREADONLY, ShowUnreadOnly);
        CheckDlgButton (hDlg, ID_CONFIG_NEW_WND_GROUP, ViewNew);
        CheckDlgButton (hDlg, ID_CONFIG_MULTI_SELECT, ArtListMultiSelect);
        CheckDlgButton (hDlg, ID_CONFIG_SAVE_NEWSRC_ON_CLOSE, SaveNewsrcOnClose);
        CheckDlgButton (hDlg, ID_CONFIG_CROSSPOST, TrackSubscribedCrossposts);
        CheckDlgButton (hDlg, ID_CONFIG_CROSSPOST_UNSUB, TrackUnsubscribedCrossposts);
        CheckDlgButton (hDlg, ID_CONFIG_FULLNAMEFROM, FullNameFrom);
        CheckDlgButton (hDlg, ID_CONFIG_THREADS, threadp);
        CheckDlgButton (hDlg, ID_CONFIG_THREADS_FULL_SUBJECT, ThreadFullSubject);
        CheckDlgButton (hDlg, ID_ENABLE_KILLFILE, bEnableArticleAction);
/* Ray Dunn:99/10 */
        CheckDlgButton (hDlg, ID_SORT_SUBJECT_PURE_ALPHA, SortWithAlphaOnly);
/* Ray Dunn:99/10:End */
		CheckDlgButton (hDlg, IDC_CB_RIGHTMOUSE, RMDeselectOnMark);

		CheckRadioButton (hDlg, IDC_RB_TOOLBAR_SM, IDC_RB_TOOLBAR_AUTO, IDC_RB_TOOLBAR_SM+nToolbarView);

        SendDlgItemMessage (hDlg, ID_THREAD_DEPTH_INDICATOR, EM_LIMITTEXT, (WPARAM) 1, 0L);
        SetDlgItemText (hDlg, ID_THREAD_DEPTH_INDICATOR, ThreadDepthIndicator);

        MyFullSubject = ThreadFullSubject;
        MyDepth = *ThreadDepthIndicator;
/* Ray Dunn:99/10 */
        MySortWithAlphaOnly = SortWithAlphaOnly;
/* Ray Dunn:99/10:End */
        MyDefaultSort = ReadSortOption("","");
        MySortMenu = NULL;
        break;

  case WM_INITMENU:
    if (MySortMenu)
    {
      UncheckAllSortMenuItems(MySortMenu);
      CheckSortMenuItem(MySortMenu, MyDefaultSort, MF_CHECKED);
    }

    break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) 407); //IDD_WINVNARTICLELISTPREFS
		break;
  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDOK:
          ShowUnreadOnly = (IsDlgButtonChecked (hDlg, ID_CONFIG_SHOWUNREADONLY) != 0);
          ViewNew = (IsDlgButtonChecked (hDlg, ID_CONFIG_NEW_WND_GROUP) != 0);
          ArtListMultiSelect = (IsDlgButtonChecked (hDlg, ID_CONFIG_MULTI_SELECT) != 0);
          SaveNewsrcOnClose = (IsDlgButtonChecked (hDlg, ID_CONFIG_SAVE_NEWSRC_ON_CLOSE) != 0);
          TrackSubscribedCrossposts = (IsDlgButtonChecked (hDlg, ID_CONFIG_CROSSPOST) != 0);
          TrackUnsubscribedCrossposts = (IsDlgButtonChecked (hDlg, ID_CONFIG_CROSSPOST_UNSUB) != 0);
          FullNameFrom = (IsDlgButtonChecked (hDlg, ID_CONFIG_FULLNAMEFROM) != 0);
          threadp = (IsDlgButtonChecked (hDlg, ID_CONFIG_THREADS) != 0);
          bEnableArticleAction = (IsDlgButtonChecked (hDlg, ID_ENABLE_KILLFILE) != 0);
          ThreadFullSubject = (IsDlgButtonChecked (hDlg, ID_CONFIG_THREADS_FULL_SUBJECT) != 0);
          GetDlgItemText (hDlg, ID_THREAD_DEPTH_INDICATOR, ThreadDepthIndicator, 2);
          ThreadDepthIndicator[1] = '\0';
/* Ray Dunn:99/10 */
          SortWithAlphaOnly = (IsDlgButtonChecked (hDlg, ID_SORT_SUBJECT_PURE_ALPHA) != 0);
          if (MyDefaultSort)
          {
            WriteDefaultSortOption(MyDefaultSort);
          }
          if (ThreadFullSubject != MyFullSubject || *ThreadDepthIndicator != MyDepth ||
              MySortWithAlphaOnly != SortWithAlphaOnly)
          {
                RefreshGroupWnds (TRUE);
          }
		  RMDeselectOnMark = (IsDlgButtonChecked( hDlg, IDC_CB_RIGHTMOUSE ) != 0);

/* Ray Dunn:99/10:End */
		  {
		    int nTemp = nToolbarView;

			nToolbarView = IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_SM) ? 0 :
					    IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_MD) ? 1 : 
					    IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_LG) ? 2 : 
						IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_AUTO) ? 3 : 0;

			if (nTemp != nToolbarView)
			{
				int j;

				for (j = MAXGROUPWNDS - 1; j >= 0; j--) 
				{
				  if (GroupDocs[j].InUse) 
				  {
					
					PostMessage( GroupDocs[j].hWndFrame, WM_RETHINKTOOLBAR, 0, 0);
				  }
				}
				
			}
		  }
          GetDlgItemText (hDlg, IDD_ART_THRESHOLD, numStr, 20);
		  {
             article_threshold = atol (numStr);
             GetDlgItemText (hDlg, IDD_MIN_TO_READ, numStr, 20);
             min_to_retrieve = atol (numStr);

            /* 0 or a bogus value means they don't want a threshold */
            if (article_threshold < 0)
                article_threshold = INT_MAX;
			EndDialog (hDlg, TRUE);
          }
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case ID_SET_DEFAULT_SORT:
          {
            
            HMENU hSortMenu;
            MySortMenu = LoadMenu(hInst, "VIEWMENU");
            if (MySortMenu)
            {
              hSortMenu = GetSubMenu(MySortMenu, 1);
              if (hSortMenu)
              {
                POINT pt;
                GetCursorPos(&pt);
                //replace "filters" menu with something
                DeleteMenu(hSortMenu, 0, MF_BYPOSITION);
			    InsertMenu(hSortMenu, 0, MF_BYPOSITION, (UINT_PTR)-1, "Choose Default Sorting");
				//replace Scroll to next selected
				ModifyMenu(hSortMenu, IDM_VIEW_NEXT_SEL, MF_BYCOMMAND | MF_STRING , -1, " ");
               
                //but disable it
                EnableMenuItem(hSortMenu, 0, MF_BYPOSITION | MF_GRAYED);
                EnableMenuItem(hSortMenu, 1, MF_BYPOSITION | MF_GRAYED);
                TrackPopupMenu(hSortMenu, TPM_LEFTALIGN, pt.x, pt.y, 0, hDlg, NULL);
                DestroyMenu(MySortMenu);
                MySortMenu = NULL;
              }
            }
          }

          break;
        
        case IDM_DONT_SORT:
        case IDM_SORT_DATE_TIME:
        case IDM_SORT_DATE_SUBJECT:
        case IDM_SORT_DATE_LINES:
        case IDM_SORT_DATE_ARTNUM:
        case IDM_SORT_DATE_FROM:
		case IDM_SORT_DATE_FILENAME:
        case IDM_SORT_SUBJECT_DATE:
        case IDM_SORT_SUBJECT_LINES:
        case IDM_SORT_SUBJECT_ARTNUM:
        case IDM_SORT_SUBJECT_FROM:
        case IDM_SORT_THREADS:
        case IDM_SORT_THREADSUB:
        case IDM_SORT_LINES:
        case IDM_SORT_ARTNUM:
        case IDM_SORT_FROM_SUBJECT:
        case IDM_SORT_FROM_DATE:
        case IDM_SORT_FROM_LINES:
        case IDM_SORT_FROM_ARTNUM:
		case IDM_SORT_FROM_FILENAME:
		case IDM_SORT_FILENAME:
          MyDefaultSort = LOWORD(wParam);
          break;
        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*--- Function WinVnConfigGroupListDlg ---------------------------------------------
 *
 * Group-list (the usenet window) prefs
 *
 * jsc 9/28/94
 */
INT_PTR CALLBACK WinVnConfigGroupListDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  int temp, item;

  switch (iMessage) {
  case WM_INITDIALOG:
		CenterWindow (hDlg, NULL );
        CheckRadioButton (hDlg, ID_DOLIST_BASE, ID_DOLIST_ASK, DoList + ID_DOLIST_BASE);
        CheckDlgButton (hDlg, ID_CONFIG_MULTI_SELECT, GroupListMultiSelect);
        CheckDlgButton (hDlg, ID_CONFIG_SHOWUNSUB, ShowUnsubscribed);
        CheckDlgButton (hDlg, ID_CONFIG_SORT_GROUPLIST, SortGroupList);
		CheckRadioButton (hDlg, IDC_RB_TOOLBAR_SM, IDC_RB_TOOLBAR_AUTO, IDC_RB_TOOLBAR_SM+nToolbarMain);
        CheckDlgButton (hDlg, IDC_CB_SHOWUNREAD, ShowUnreadCount);
		break;

  case WM_HELP:
	DoHelp (hDlg, HELP_CONTEXT, (DWORD) 406); //IDD_WINVNGROUPLIST
	break;
  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {
        case IDOK:
          GroupListMultiSelect = (IsDlgButtonChecked (hDlg, ID_CONFIG_MULTI_SELECT) != 0);

          for (item = ID_DOLIST_BASE; item <= ID_DOLIST_ASK; item++) {
                if (IsDlgButtonChecked (hDlg, item)) {
                  DoList = item - ID_DOLIST_BASE;
                }
          }
          /* If the user has changed the ShowUnsubscribed option, we must
           * recompute which lines are active and redisplay.  
           * Reset the window to the top to make sure that everything
           * will display OK.
           * There is some question in my mind whether this code will
           * work OK if the first screen's worth of groups are unsubscribed,
           * but it *should* work.
           */
          temp = (IsDlgButtonChecked (hDlg, ID_CONFIG_SHOWUNSUB) != 0);
          if (temp != ShowUnsubscribed) 
		  {
                ShowUnsubscribed = temp;
                NetDoc.LongestLine = 0;
                SetGroupActiveLines ();
                ScreenToTop (&NetDoc);
                InvalidateRect (NetDoc.hDocWnd, NULL, FALSE);
                SendMessage (NetDoc.hWndTB, TB_CHECKBUTTON, IDB_TOGGLE_VIEW_UNSUB, ShowUnsubscribed);
          }
          SortGroupList = IsDlgButtonChecked (hDlg, ID_CONFIG_SORT_GROUPLIST);
		  temp = IsDlgButtonChecked (hDlg, IDC_CB_SHOWUNREAD);
		  if (temp != ShowUnreadCount)
		  {
		      //refresh main wnd
			  ShowUnreadCount = temp;
			  InvalidateRect (NetDoc.hDocWnd, NULL, FALSE);
		  }
		  { int nTemp = nToolbarMain;
			nToolbarMain = IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_SM) ? 0 :
					    IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_MD) ? 1 : 
					    IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_LG) ? 2 : 
						IsDlgButtonChecked (hDlg, IDC_RB_TOOLBAR_AUTO) ? 3 : 0;

			if (nTemp != nToolbarMain)
				PostMessage( GetParent(hDlg), WM_RETHINKTOOLBAR, 0 , 0);
		  }
		  EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*--- Function WinVnConfigCodingPrefsDlg ---------------------------------------------
 *
 * Decoding prefs
 *
 * jsc 9/28/94
 */
INT_PTR CALLBACK WinVnConfigCodingPrefsDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  static int MyAlwaysOnTop;
  int nSel;
  char szEntry[_MAX_PATH];

  switch (iMessage) {
  case WM_INITDIALOG:
        {
          char szExtension[256];
          char *this_hop,*next_hop;
          HWND hListBox;

          CheckDlgButton (hDlg, ID_STATUSALWAYSONTOP, BlockCodingStatusAlwaysOnTop);
          CheckDlgButton (hDlg, IDD_VERBOSE_STATUS, CodingStatusVerbose);
          CheckDlgButton (hDlg, IDD_MINIMIZE_CODING_STATUS, MinimizeStatusWindows);
          CheckDlgButton (hDlg, IDD_KEEP_HEADER_VISIBLE, KeepArticleHeaderVisible);
          CheckDlgButton (hDlg, IDD_EXECUTE_DECODED, ExecuteDecodedFiles);
          CheckDlgButton (hDlg, IDD_DUMB_DECODE, DumbDecode);
          CheckDlgButton (hDlg, IDD_INCLUDE_OPEN_ARTS, AlsoDecodeOpenArticles);
		  CheckDlgButton (hDlg, IDC_CB_DECODE_NOEXE, NeverExeWarnFiles);
          MyAlwaysOnTop = BlockCodingStatusAlwaysOnTop;
          EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), FALSE);
          EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), FALSE);
          Edit_LimitText(GetDlgItem (hDlg, IDC_EB_DECODE_EDITWARN), 12);

		  CheckDlgButton(hDlg, IDC_CB_PLAYSOUND, EnableDownloadSnd);
		  if (!EnableDownloadSnd)
		  {
			EnableWindow(GetDlgItem (hDlg, IDC_PB_CHOOSESND), FALSE);
			EnableWindow(GetDlgItem (hDlg, IDC_EB_SOUND), FALSE);
			
		  }
		  SetDlgItemText (hDlg, IDC_EB_SOUND, szDownloadSnd);

          GetPrivateProfileString(CODING, WARNEXTENTIONS, DEF_WarnOnEXE, 
                                  szExtension, 256, szAppProFile);
          
          hListBox = GetDlgItem (hDlg, IDC_LB_DECODE_WARNLIST);
          if (hListBox)
          {
            next_hop = this_hop = szExtension;
            while (this_hop && *this_hop)
            {
              next_hop = strchr (this_hop, ',');
              if (next_hop)
                *(next_hop++) = '\0';
              
              while( isspace((unsigned char)*this_hop))
                this_hop++;

              ListBox_AddString(hListBox, this_hop);
              this_hop = next_hop;

            }
          }
        }
        break;

  case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) 411); //IDD_WINVNCODINGPREFS
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {

        case IDOK:
          {
            int nCount;
            HWND hListbox = GetDlgItem (hDlg, IDC_LB_DECODE_WARNLIST);
            char szExtension[256];
            *szExtension = '\0';
             
            BlockCodingStatusAlwaysOnTop = (IsDlgButtonChecked (hDlg, ID_STATUSALWAYSONTOP) != 0);
            CodingStatusVerbose = (IsDlgButtonChecked (hDlg, IDD_VERBOSE_STATUS) != 0);
            MinimizeStatusWindows = (IsDlgButtonChecked (hDlg, IDD_MINIMIZE_CODING_STATUS) != 0);
            KeepArticleHeaderVisible = (IsDlgButtonChecked (hDlg, IDD_KEEP_HEADER_VISIBLE) != 0);
            ExecuteDecodedFiles = (IsDlgButtonChecked (hDlg, IDD_EXECUTE_DECODED) != 0);
            DumbDecode = IsDlgButtonChecked (hDlg, IDD_DUMB_DECODE);
            AlsoDecodeOpenArticles = (IsDlgButtonChecked (hDlg, IDD_INCLUDE_OPEN_ARTS) != 0);
            NeverExeWarnFiles = (IsDlgButtonChecked (hDlg, IDC_CB_DECODE_NOEXE ) != 0);

            nCount = ListBox_GetCount(hListbox);
            nSel = 0;
            while (nCount-- > 0)
            {
              int nLength;
              nLength = ListBox_GetText(hListbox, nSel++, szEntry);
              if (nLength > 0 && (strlen( szExtension) + nLength  < 256))
              { 
                strcat(szExtension, szEntry);
                strcat(szExtension, ",");
              }
              
            }
            if (nSel)
              szExtension[strlen( szExtension)-1] = '\0';
            WritePrivateProfileString (CODING, WARNEXTENTIONS, szExtension, szAppProFile);
            
            if (BlockCodingStatusAlwaysOnTop != MyAlwaysOnTop)
                  RefreshCodedBlockWnd ();

			if (IsDlgButtonChecked (hDlg, IDC_CB_PLAYSOUND))
			{
				EnableDownloadSnd = 1;
				*szEntry = '\0';
				GetDlgItemText (hDlg, IDC_EB_SOUND, szEntry, 255);
				
				if (*szEntry && (_access( szEntry, 0 ) == 0 || strchr(szEntry, '%')))
					strcpy(szDownloadSnd, szEntry);
			}
			else
			{
				EnableDownloadSnd = 0;
			}


            EndDialog (hDlg, TRUE);
          }
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;
		case IDC_CB_PLAYSOUND:
		  {
			BOOL bEnable = IsDlgButtonChecked (hDlg, IDC_CB_PLAYSOUND);
			EnableWindow(GetDlgItem (hDlg, IDC_PB_CHOOSESND), bEnable);
			EnableWindow(GetDlgItem (hDlg, IDC_EB_SOUND), bEnable);
			if (bEnable)
			{
				*szEntry = '\0';
				GetDlgItemText (hDlg, IDC_EB_SOUND, szEntry, 255);
				if (*szEntry && (_access( szEntry, 0 ) == 0 || strchr(szEntry, '%')) )
					break;

			}
			else
			{
				break;
			}
		  }
		  //fall through
		case IDC_PB_CHOOSESND:
		{
		  OPENFILENAME ofn;
		  char szFile[_MAX_FNAME];
		  char szPath[_MAX_PATH];
		  char szDrive[_MAX_DRIVE];
		  char szDir[_MAX_DIR];
		  char szExtn[_MAX_EXT];
		  
		  
		  szFile[0] = '\0';
		  szPath[0] = '\0';
		  GetDlgItemText (hDlg, IDC_EB_SOUND, szEntry, 255);
		  if (*szEntry)
		  {
			_splitpath( szEntry, szDrive, szDir, szFile, szExtn);
			_makepath( szPath, szDrive, szDir, NULL, NULL);
			strcat(szFile, szExtn);
		  }

		  memset (&ofn, 0, sizeof (OPENFILENAME));
		  ofn.lStructSize = sizeof(OPENFILENAME);
		  ofn.lpstrTitle = "Choose Sound";
		  ofn.lStructSize = sizeof (OPENFILENAME);
		  ofn.hwndOwner = hDlg;
		  ofn.lpstrFilter = "All Files (*.*)\0*.*\0Sound files (*.WAV)\0*.wav\0\0";
		  ofn.nFilterIndex = 2;
		  ofn.lpstrFile = szFile;
		  ofn.nMaxFile = _MAX_PATH;
		  ofn.lpstrInitialDir = szPath;
#ifdef _WIN32
		  ofn.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_HIDEREADONLY;
#else
		  ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
#endif

		  if (GetOpenFileName (&ofn) == 0)
			return FALSE;
		  SetDlgItemText (hDlg, IDC_EB_SOUND, szFile);
 
		}
		break;


        case IDC_LB_DECODE_WARNLIST:
          {
            if (GET_WM_COMMAND_CMD(wParam, lParam) == LBN_SELCHANGE)
            {

              HWND hListbox = GET_WM_COMMAND_HWND(wParam, lParam);
              nSel = ListBox_GetCurSel(hListbox);
              if (nSel != LB_ERR)
              {
                ListBox_GetText(hListbox, nSel, szEntry);
                SetDlgItemText(hDlg, IDC_EB_DECODE_EDITWARN, szEntry);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), FALSE);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), TRUE);
              }
            }
          }
          break;
        case IDC_PB_DECODE_DEL:
          {
            HWND hListbox = GetDlgItem (hDlg, IDC_LB_DECODE_WARNLIST);
            nSel = ListBox_GetCurSel(hListbox);
            if (nSel != LB_ERR)
            {
              ListBox_DeleteString(hListbox, nSel);
              if (nSel > 0)
                nSel--;
              if (ListBox_GetCount(hListbox))
              {
                ListBox_SetCurSel(hListbox, nSel);
                ListBox_GetText(hListbox, nSel, szEntry);
                SetDlgItemText(hDlg, IDC_EB_DECODE_EDITWARN, szEntry);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), FALSE);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), TRUE);
              }
              else
              {
                SetDlgItemText(hDlg, IDC_EB_DECODE_EDITWARN, "");
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), FALSE);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), FALSE);

              }
            }
            
          }
          break;
        case IDC_PB_DECODE_ADD:
          {
            char *p;

            HWND hListbox = GetDlgItem (hDlg, IDC_LB_DECODE_WARNLIST);
            HWND hEdit = GetDlgItem (hDlg, IDC_EB_DECODE_EDITWARN);
            Edit_GetText(hEdit, szEntry, 255);
            RemoveTrailingWhiteSpace(szEntry);
            p = szEntry;
            while (isspace((unsigned char)*p) || *p == '.')
              p++;

            nSel = ListBox_FindStringExact(hListbox, -1, szEntry);
            if (nSel == LB_ERR)
            {
              nSel = ListBox_AddString(hListbox, p);
              ListBox_SetCurSel(hListbox, nSel);
              SetDlgItemText(hDlg, IDC_EB_DECODE_EDITWARN, "");
            }
            else
            {
              MessageBeep((UINT) -1);
              SetDlgItemText(hDlg, IDC_EB_DECODE_EDITWARN, szEntry);  
              ListBox_SetCurSel(hListbox, nSel);
            }
          }
          break;
        case IDC_PB_DECODE_RESET:
          {
            char *this_hop, *next_hop;
            HWND hListBox = GetDlgItem (hDlg, IDC_LB_DECODE_WARNLIST);
            if (WVMessageBox(hDlg, IDS_WVCNCM_CONFIRM_RESET, IDS_WINVN_CONFIRM1, MB_ICONQUESTION | MB_YESNO) == IDNO)
              break;
            if (hListBox)
            {
              strcpy(szEntry, DEF_WarnOnEXE);
              ListBox_ResetContent(hListBox);
              next_hop = this_hop = szEntry;
              while (this_hop && *this_hop)
              {
                next_hop = strchr (this_hop, ',');
                if (next_hop)
                  *(next_hop++) = '\0';
              
                while( isspace((unsigned char)*this_hop))
                  this_hop++;

                ListBox_AddString(hListBox, this_hop);
                this_hop = next_hop;

              }
              SetDlgItemText(hDlg, IDC_EB_DECODE_EDITWARN, "");
              EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), FALSE);
              EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), FALSE);
            }
          }
          break;
        case IDC_EB_DECODE_EDITWARN:
          {
            
            if (GET_WM_COMMAND_CMD(wParam, lParam) == EN_CHANGE)
            {
             
              HWND hListbox = GetDlgItem (hDlg, IDC_LB_DECODE_WARNLIST);
              HWND hEdit = GET_WM_COMMAND_HWND(wParam, lParam);
              Edit_GetText(hEdit, szEntry, 255);
              nSel = ListBox_FindStringExact(hListbox, -1, szEntry);
              if (nSel == LB_ERR)
              {
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), TRUE);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), FALSE);
              }
              else
              {
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_ADD), FALSE);
                EnableWindow(GetDlgItem (hDlg, IDC_PB_DECODE_DEL), TRUE);
                ListBox_SetCurSel(hListbox, nSel);
              }
            }

          }
          break;
		case IDC_CB_DECODE_NOEXE:
          {
		  }
		  break;
	
        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}
  
/*--- Function WinVnConfigConfirmationDlg ---------------------------------------------
 *
 * Confirmations prefs
 *
 * jsc 9/28/94
 */
INT_PTR CALLBACK WinVnConfigConfirmationDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
	HWND hCtrl;
#ifdef OFFLINE  // TANAKA Goh
  char* pGenSockDLL;
#endif

  switch (iMessage) {
  case WM_INITDIALOG:
		hCtrl = GetDlgItem (hDlg, ID_CONFIG_CONFIRM_DELETE_ARTICLE);
        CheckDlgButton (hDlg, ID_CONFIG_CONFIRM_BATCH, ConfirmBatchOps);
        CheckDlgButton (hDlg, ID_CONFIRM_DISCONNECT, ConfirmDisconnect);
        CheckDlgButton (hDlg, ID_CONFIG_CONFIRM_REPLY_TO, ConfirmReplyTo);
        CheckDlgButton (hDlg, ID_CONFIG_CONFIRM_EXIT, ConfirmSaveOnExit);
		CheckDlgButton(hDlg, ID_CONFIRM_EXITACTIVE, ConfirmExitActive);
/* Ray Dunn:99/10 */
        CheckDlgButton (hDlg, ID_CONFIG_CONFIRM_XPOSTING, ConfirmXPosting);
/* Ray Dunn:99/10:End */

#ifdef OFFLINE  // TANAKA Goh
        CheckDlgButton (hDlg, ID_CONFIG_CONFIRM_DELETE_ARTICLE, ConfirmDeleteArticle);
        
        if ((pGenSockDLL = strrchr(GenSockDLL, '\\')) == NULL) 
		{
          pGenSockDLL = GenSockDLL;
        } 
		else 
		{
          pGenSockDLL++;
        }
        
        if (stricmp(pGenSockDLL, "gwssoup.dll") && stricmp(pGenSockDLL, "gsoup32.dll") && stricmp(pGenSockDLL, "ggnspool.dll") && stricmp(pGenSockDLL, "gspool32.dll")) {
          EnableWindow (hCtrl, DISABLE);
        }
#else
		if (hCtrl)
		{
			EnableWindow (hCtrl, DISABLE);
			ShowWindow(hCtrl, SW_HIDE);
		}
#endif
        break;

	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) 405); //IDD_WINVNCONFIRMATIONS
		break;


  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) 
		{


        case IDOK:
          ConfirmBatchOps = (IsDlgButtonChecked (hDlg, ID_CONFIG_CONFIRM_BATCH) != 0);
          ConfirmDisconnect = (IsDlgButtonChecked (hDlg, ID_CONFIRM_DISCONNECT) != 0);
          ConfirmReplyTo = (IsDlgButtonChecked (hDlg, ID_CONFIG_CONFIRM_REPLY_TO) != 0);
          ConfirmSaveOnExit = (IsDlgButtonChecked (hDlg, ID_CONFIG_CONFIRM_EXIT) != 0);
          ConfirmExitActive = (IsDlgButtonChecked (hDlg, ID_CONFIRM_EXITACTIVE) != 0);
/* Ray Dunn:99/10 */
          ConfirmXPosting = (IsDlgButtonChecked (hDlg, ID_CONFIG_CONFIRM_XPOSTING) != 0);
/* Ray Dunn:99/10:End */

#ifdef OFFLINE  // TANAKA Goh
          ConfirmDeleteArticle = (IsDlgButtonChecked (hDlg, ID_CONFIG_CONFIRM_DELETE_ARTICLE) != 0);
#endif
          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*-- function WinVnEditThreshold ---------------------------------------
 *
 *  Dialog function to set button values for threshold dialog
 */

#define MAX_CUSTOM_ARTS 6

INT_PTR CALLBACK WinVnEditThreshold(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{

	TCHAR numreqStr[20];
	TCHAR numStr[20];
	int * nMsgCount = (int *) GetWindowLongPtr(hDlg, GWLP_USERDATA);
	int i;
	int nDefMsgCount[MAX_CUSTOM_ARTS] = { 100,250,500,1000,10000,100000}; 


	switch (iMessage)
	{
		case WM_INITDIALOG:
			SetWindowLongPtr(hDlg, GWLP_USERDATA, lParam);
			nMsgCount = (int *) lParam;
			if (!nMsgCount)
				return FALSE;

			for (i = 0; i < MAX_CUSTOM_ARTS; i++)
			{
				HWND hWnd = GetDlgItem(hDlg, IDC_EB_BUTTON1+i);
				wsprintf(numreqStr, "%d", nMsgCount[i]);

				if (hWnd)
					SetWindowText(hWnd, numreqStr);

			}


			break;
		case WM_HELP:
			DoHelp (hDlg, HELP_CONTEXT, (DWORD) IDD_WVEDIT_THRESHOLD);

			break;
		case WM_COMMAND:
			switch (GET_WM_COMMAND_ID(wParam, lParam))
			{

				case IDC_PB_DEFAULT:
				{
					for (i = 0; i < MAX_CUSTOM_ARTS; i++)
					{
						HWND hWnd = GetDlgItem(hDlg, IDC_EB_BUTTON1+i);
						wsprintf(numreqStr, "%d", nDefMsgCount[i]);

						if (hWnd)
							SetWindowText(hWnd, numreqStr);

					}

				}
				break;
				case IDOK:
					{
						
						for (i = 0; i < MAX_CUSTOM_ARTS; i++)
						{
							int nTemp = -1;
							HWND hWnd = GetDlgItem(hDlg, IDC_EB_BUTTON1+i);
							if (GetWindowText(hWnd, numreqStr, (sizeof(numreqStr)/sizeof(numreqStr[0])) ))
							{
								nTemp = _ttoi(numreqStr);
								
							}
							if (nTemp > 99999999)  //yeah, like you'll be able to get 99M
								nTemp = 0;
							if (nTemp > 0)
							{
								for (int j = 0; j < i; j++)
								{
									if (nTemp == nMsgCount[j])
									{
										nTemp = 0;
										break;
									}
								}
							}
							if (nTemp > 0)
							{
								nMsgCount[i] = nTemp;
								wsprintf(numStr, "Threshold%01d", i+1);
								wsprintf(numreqStr, "%d", nTemp);
							}
							if (nTemp == nDefMsgCount[i] || nTemp < 1)	
								WritePrivateProfileString (ARTLIST, numStr, 0, szAppProFile);
							else
								WritePrivateProfileString (ARTLIST, numStr, numreqStr, szAppProFile);
							

						}

						EndDialog (hDlg, IDOK);
					}
					break;
				case IDCANCEL:
					EndDialog (hDlg, FALSE);
					break;
				default:
					return FALSE;
			}
		default:
			return FALSE;
	}

  return TRUE;

}
/*-- function WinVnThresholdDlg ---------------------------------------
 *
 *  Dialog function to ask how many article headers we
 *  want to retrieve.
 */


INT_PTR CALLBACK WinVnThresholdDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  char numStr[32];
  char numreqStr[32];
  char tstr1[32];
  char tstr2[32];
  static int radio_id = 1;
  static int nMsgCount[MAX_CUSTOM_ARTS] = { 100,250,500,1000,10000,100000};

  switch (iMessage) 
  {

  case WM_INITDIALOG:
/* Ray Dunn:99/10: Add the number of articles that will be loaded for first unseen
   if different from number unseen - so if there's one unseen way back, the user knows
   that he will be loading a long list to get it
*/
        //CenterWindow(hDlg, GetParent(hDlg));
		{
			char szEntry[200];
			if (GetPrivateProfileString (WVINTERFACE, "ThresholdDlgPos", "", szEntry, 200, szAppProFile) > 5)
			{
				POINT ptSave;

				if (sscanf (szEntry, "%d, %d", &ptSave.x, &ptSave.y) == 2)
				{
					SetRelativeWindowPosition(GetParent(hDlg), hDlg, ptSave);
				}
			}
		}


		FormatNumber(arts_to_retrieve, str);
		//sprintf (str, "%I64u", arts_to_retrieve);
		FormatNumber(est_num_unread, numStr);
        //sprintf (numStr, "%I64u", est_num_unread);
        if (arts_reqd_for_first_unseen > 0 && est_num_unread != arts_reqd_for_first_unseen)
        {
          //sprintf (numreqStr, "%I64u", arts_reqd_for_first_unseen);
		  FormatNumber(arts_reqd_for_first_unseen, numreqStr);
 
          WVArgXSetWindowText(hDlg, IDS_WVCNCM_UNSEEN2, str, numStr, numreqStr);
        }
        else
          WVArgXSetWindowText (hDlg, IDS_WVCNCM_UNSEEN, str, numStr);
/* Ray Dunn:99/10:End */        
/* Ray Dunn:99/11: No Sort Enhancement */
        InhibitSort = FALSE;
        CheckDlgButton (hDlg, IDC_INHIBIT_SORT, InhibitSort);

        EnableWindow(GetDlgItem(hDlg, IDOK), FALSE);
/* Ray Dunn:99/11:End */
		CheckRadioButton(hDlg, IDC_RB_LASTEST, IDC_RB_RANGE, IDC_RB_LASTEST);
		radio_id = 1;
		
		BIGINTtoa(art_num, numStr, 10);
		SetDlgItemText(hDlg, IDC_EB_START, numStr);

		EnableWindow(GetDlgItem(hDlg, IDC_EB_START), FALSE);
		FormatNumber(server_first, tstr1); 
		FormatNumber(server_last, tstr2);
		WVArgXSetWindowText(GetDlgItem(hDlg, IDC_ST_RANGE), IDS_WVCNCM_AVAILABLE, tstr1, tstr2);
	
		FormatNumber(server_last-(max(arts_reqd_for_first_unseen, est_num_unread)), tstr1);
		WVArgXSetWindowText(GetDlgItem(hDlg, IDC_RB_NEXTUNSEEN), IDS_RB_NEXTUNSEEN, tstr1 );
		if (max(arts_reqd_for_first_unseen, est_num_unread) == 0)
			EnableWindow(GetDlgItem(hDlg, IDC_RB_NEXTUNSEEN), FALSE);
	
		{
			for (int i = 0; i < MAX_CUSTOM_ARTS; i++)
			{
				HWND hWnd = GetDlgItem(hDlg, ID_ARTS_1+i);
				EnableWindow(hWnd, TRUE);

				wsprintf(numreqStr, "Threshold%01d", i+1);
				int nTemp = GetPrivateProfileInt (ARTLIST, numreqStr, 0, szAppProFile);
				if (nTemp > 9 )
				{
					nMsgCount[i] = nTemp;
				}
				nTemp = nMsgCount[i];
				if (nTemp > 9999)
					nTemp = nTemp /1000;
				_itoa(nTemp, numreqStr+1, 10);
				if (nMsgCount[i] > 9999)
					strcat(numreqStr, "K");
				*numreqStr = '&';
				SetWindowText(hWnd, numreqStr);

				
				if (hWnd && nMsgCount[i] >= server_last - server_first)
					EnableWindow(hWnd, FALSE);
					
			}
		}
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD) IDD_THRESHOLD);
		break; 

  case WM_COMMAND:
/* Ray Dunn:99/12: Use GET_WM_COMMAND_ID */
    switch (GET_WM_COMMAND_ID(wParam, lParam)) 
	{
       
		case IDOK:
          
		  GetDlgItemText (hDlg, ID_ARTS_TO_GRAB, numStr, 20);
          arts_to_retrieve = atoBIGINT (numStr);
          if (	radio_id == IDC_RB_RANGE)
		  {
			  UBIGINT val;
			  GetDlgItemText (hDlg, IDC_EB_START, numStr, 20);
			  val = atoBIGINT (numStr);
			  if (val < server_first || val > server_last)
			  {
			    WVMessageBox (hDlg, IDS_WVCNCM_OUT_OF_RANGE, IDS_WVCNCM_OUT_OF_RANGE_TITLE, MB_OK | MB_ICONERROR);	
			    if (val < server_first)
				  SetDlgItemText(hDlg, IDC_EB_START, BIGINTtoa(server_first, numStr, 10));
			   
			    break;
			  }
			  server_first = val;
		   }
#ifdef _WIN64
		   if (arts_to_retrieve > 4000000)
		   {
			    if (WVMessageBox (hDlg, IDS_WVCNCM_LOTSOARTS4, IDS_WVCNCM_LOTSOARTS_TITLE, MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2) == IDCANCEL)
					break;
		   }
#else 	   
		   if (arts_to_retrieve > 2000000)
		   {
			    if (WVMessageBox (hDlg, IDS_WVCNCM_LOTSOARTS, IDS_WVCNCM_LOTSOARTS_TITLE, MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2) == IDCANCEL)
					break;
		   }
#endif


		  {
			POINT ptSave;
			if (GetRelativeWindowPosition(GetParent(hDlg), hDlg, &ptSave))
			{
				
                  char szEntry[80];
                  wsprintf(szEntry, "%d, %d", ptSave.x, ptSave.y);
                  WritePrivateProfileString(WVINTERFACE, "ThresholdDlgPos", szEntry, szAppProFile);

				
			}
		  }
		  if (arts_to_retrieve > 0)
				EndDialog (hDlg, radio_id);
		  else
		  {
			arts_to_retrieve = 0;
			EndDialog (hDlg, TRUE); // Heirich 19991017 should work like ID_THRESHOLD_UNREAD not ID_CANCEL 
		  }


          break;

        case IDC_INHIBIT_SORT:
          InhibitSort = IsDlgButtonChecked (hDlg, IDC_INHIBIT_SORT) != 0;
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

		case ID_ARTS_1:
		case ID_ARTS_2:
		case ID_ARTS_3:
		case ID_ARTS_4:
		case ID_ARTS_5:
		case ID_ARTS_6:
		case ID_ARTS_7:
		{
			arts_to_retrieve = nMsgCount[ GET_WM_COMMAND_ID(wParam, lParam) - ID_ARTS_1];

			if (radio_id == 1)
				SetDlgItemText(hDlg, IDC_EB_START, BIGINTtoa(server_last - arts_to_retrieve, numStr, 10));
			SetDlgItemText(hDlg, ID_ARTS_TO_GRAB, BIGINTtoa(arts_to_retrieve, numStr, 10));
			PostMessage(hDlg, WM_COMMAND, (WPARAM)IDOK, (LPARAM)hDlg); 
		}
        break;

        case ID_THRESHOLD_ALL:
		  SetDlgItemText(hDlg, IDC_EB_START, BIGINTtoa(server_first, numStr, 10));
#ifndef _WIN64
		   if (server_last-server_first > 2000000)
		   {
			    if (WVMessageBox (hDlg, IDS_WVCNCM_LOTSOARTS, IDS_WVCNCM_LOTSOARTS_TITLE, MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2) == IDCANCEL)
					break;
		   }
#else
		   if (server_last-server_first > 4000000)
		   {
			    if (WVMessageBox (hDlg, IDS_WVCNCM_LOTSOARTS4, IDS_WVCNCM_LOTSOARTS_TITLE, MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2) == IDCANCEL)
					break;
		   }
#endif
		  EndDialog (hDlg, ID_THRESHOLD_ALL);
          break;

        case ID_THRESHOLD_UNREAD:
          if (est_num_unread > 0 || min_to_retrieve > 0) //MDS don't ask for 0 articles, unless fetch min is set
		  {
#ifndef _WIN64
		   if (est_num_unread > 2000000)
		   {
			    if (WVMessageBox (hDlg, IDS_WVCNCM_LOTSOARTS, IDS_WVCNCM_LOTSOARTS_TITLE, MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2) == IDCANCEL)
					break;
		   }
#else
		   if (est_num_unread > 4000000)
		   {
			    if (WVMessageBox (hDlg, IDS_WVCNCM_LOTSOARTS4, IDS_WVCNCM_LOTSOARTS_TITLE, MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2) == IDCANCEL)
					break;
		   }
#endif

            EndDialog (hDlg, ID_THRESHOLD_UNREAD);
		  }
          break;

        case ID_ARTS_TO_GRAB:
          // if user fills a number to load,
          // change the default button to the OK buton
          if (GET_WM_COMMAND_CMD(wParam, lParam) == EN_CHANGE)
          { char buf[64];

            GetDlgItemText(hDlg, ID_ARTS_TO_GRAB, buf, sizeof(buf));
            if (*buf == '\0' || strncmp(buf, "                      ", strlen(buf)) == 0)
            {
              EnableWindow(GetDlgItem(hDlg, IDOK), FALSE);
              SendMessage(hDlg, DM_SETDEFID, (WPARAM)ID_THRESHOLD_UNREAD, (LPARAM) 0);
            }
            else
            {
				UBIGINT first;
				EnableWindow(GetDlgItem(hDlg, IDOK), TRUE);
				SendMessage(hDlg, DM_SETDEFID, (WPARAM)IDOK, (LPARAM) 0);
				first = atoBIGINT(buf);

				if (radio_id == 1)
				{
					
					if (first > server_last-server_first)
						first = server_first;
					else
						first = server_last - first;
					
					SetDlgItemText(hDlg, IDC_EB_START, BIGINTtoa(first, numStr, 10));
				}

				
            }
          }
          break;

		case IDC_RB_RANGE:
			EnableWindow(GetDlgItem(hDlg, IDC_EB_START), TRUE);
			radio_id = IDC_RB_RANGE; 
			break;
		case IDC_RB_LASTEST:
			radio_id = 1;
			EnableWindow(GetDlgItem(hDlg, IDC_EB_START), FALSE);
			break;
		case IDC_RB_EARLIEST:
		    radio_id = IDC_RB_EARLIEST;
			SetDlgItemText(hDlg, IDC_EB_START, BIGINTtoa(server_first, numStr, 10));
			EnableWindow(GetDlgItem(hDlg, IDC_EB_START), FALSE);
			break;
		case IDC_RB_NEXTUNSEEN:
			radio_id = IDC_RB_NEXTUNSEEN;
			SetDlgItemText(hDlg, IDC_EB_START, BIGINTtoa(server_last-(max(arts_reqd_for_first_unseen, est_num_unread)), numStr, 10));
			EnableWindow(GetDlgItem(hDlg, IDC_EB_START), FALSE);
			break;
		case IDC_PB_EDITVAL:
			{
				UINT uRet = DialogBoxParam (hInst, MAKEINTRESOURCE(IDD_WVEDIT_THRESHOLD), hDlg, (DLGPROC) &WinVnEditThreshold, (DWORD_PTR) &nMsgCount);
				if (uRet == IDOK)
				{
					WinVnThresholdDlg(hDlg, WM_INITDIALOG,0, 0);

				}

			}
			break;
        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}


/*--- Function WinVnLogOptDlg ---------------------------------------------
 *
 * Logging prefs
 *
 * jsc 9/28/94
 */
INT_PTR CALLBACK WinVnLogOptDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  char fileName[MAXFILENAME];
  UINT mode;
  OFSTRUCT ofs;
  HFILE hFile;

  switch (iMessage) {

  case WM_INITDIALOG:
        CheckDlgButton (hDlg, IDD_MAILLOG, MailLog);
        CheckDlgButton (hDlg, IDC_MAIL_ATTACH, MailLogAttach);
        CheckDlgButton (hDlg, IDD_POSTLOG, PostLog);
        CheckDlgButton (hDlg, IDC_POST_ATTACH, PostLogAttach);
        SetDlgItemText (hDlg, IDD_MAILNAME, MailLogFile);
        SetDlgItemText (hDlg, IDD_POSTNAME, PostLogFile);

        /* mail logging only works for SMTP-mail at present */
        EnableWindow (GetDlgItem (hDlg, IDD_MAILLOG), (MailCtrl.MailType == MT_SMTP));
        EnableWindow (GetDlgItem (hDlg, IDC_MAIL_ATTACH), (MailCtrl.MailType == MT_SMTP));
        EnableWindow (GetDlgItem (hDlg, IDD_MAILNAME), (MailCtrl.MailType == MT_SMTP));
        EnableWindow (GetDlgItem (hDlg, ID_BROWSEMAIL), (MailCtrl.MailType == MT_SMTP));
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)403); //IDD_WINVNLOGOPTS
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {

        case IDOK:
          GetDlgItemText (hDlg, IDD_MAILNAME, fileName, MAXFILENAME - 1);
          mode = (OpenFile (fileName, &ofs, OF_EXIST) == HFILE_ERROR) ? OF_CREATE : OF_WRITE;
          if ((hFile = OpenFile (fileName, &ofs, mode)) == HFILE_ERROR) {
                WVArgMessageBox (hDlg, IDS_WVCNCM_DISABLE_MAILLOG, IDS_WVCNCM_INVALID_FILE, MB_OK | MB_ICONSTOP, fileName);
                CheckDlgButton (hDlg, IDD_MAILLOG, FALSE);
                break;
          }
          _lclose (hFile);
          strcpy (MailLogFile, fileName);

          GetDlgItemText (hDlg, IDD_POSTNAME, fileName, MAXFILENAME - 1);
          mode = (OpenFile (fileName, &ofs, OF_EXIST) == HFILE_ERROR) ? OF_CREATE : OF_WRITE;
          if ((hFile = OpenFile (fileName, &ofs, mode)) == HFILE_ERROR) {
                WVArgMessageBox (hDlg, IDS_WVCNCM_DISABLE_POSTLOG, IDS_WVCNCM_INVALID_FILE, MB_OK | MB_ICONSTOP, fileName);
                CheckDlgButton (hDlg, IDD_POSTLOG, FALSE);
                break;
          }
          _lclose (hFile);
          strcpy (PostLogFile, fileName);

          MailLog = (IsDlgButtonChecked (hDlg, IDD_MAILLOG) != 0);
          MailLogAttach = (IsDlgButtonChecked (hDlg, IDC_MAIL_ATTACH) != 0);
          PostLog = (IsDlgButtonChecked (hDlg, IDD_POSTLOG) != 0);
          PostLogAttach = (IsDlgButtonChecked (hDlg, IDC_POST_ATTACH) != 0);
          EndDialog (hDlg, TRUE);
          break;

        case IDCANCEL:
          EndDialog (hDlg, FALSE);
          break;

        case ID_BROWSEPOST:
          fileName[0] = '\0';
          if (AskForNewFileName (hDlg, fileName, "", TRUE) == SUCCESS)
                SetDlgItemText (hDlg, IDD_POSTNAME, fileName);
          break;

        case ID_BROWSEMAIL:
          fileName[0] = '\0';
          if (AskForNewFileName (hDlg, fileName, "", TRUE) == SUCCESS)
                SetDlgItemText (hDlg, IDD_MAILNAME, fileName);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

/*-- function WinVnMailDialog ---------------------------------------
 *
 *  Dialog function to query for mail destination, and manage list
 *  of mail addresses
 *
 *  Returns mail address(es) in DialogString
 *  (JSC 2/1/94)
 */

INT_PTR CALLBACK WinVnMailDlg (HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  static HWND hMailList;                /* Handle to child list box window. */
  register int j;
  int count, len, startLen, found;
  char *ptr;
  char mybuf[MAXDIALOGSTRING];

  switch (iMessage) {
  case WM_INITDIALOG:
        ptr = (char *) lParam;
        if (ptr && *ptr) {
          SetDlgItemText (hDlg, IDD_MAIL_DEST, ptr);
        }

        hMailList = GetDlgItem (hDlg, IDD_MAIL_LIST);

        SendMessage (hMailList, WM_SETREDRAW, FALSE, 0L);
        for (j = 0; j < (int) MailList->numLines; j++)
          SendMessage (hMailList, LB_ADDSTRING, 0, (LPARAM) (LPSTR) TextBlockLine (MailList, j));

        SendMessage (hMailList, WM_SETREDRAW, TRUE, 0L);
        EnableWindow (GetDlgItem (hDlg, IDD_DELETE), FALSE);
        EnableWindow (GetDlgItem (hDlg, IDD_ADD), FALSE);
        return TRUE;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNMAIL);
		break;

  case WM_COMMAND:
        switch (GET_WM_COMMAND_ID(wParam, lParam)) {


        case IDD_MAIL_LIST:
          switch (GET_WM_COMMAND_CMD (wParam, lParam)) {
          case LBN_SELCHANGE:
                EnableWindow (GetDlgItem (hDlg, IDD_DELETE), TRUE);
                break;

          case LBN_DBLCLK:
                // a double click means they want to add a name to the to-line
                // only add it if it's not already on the to-line

                j = (int) SendMessage (hMailList, LB_GETCARETINDEX, 0, 0L);
                SendMessage (hMailList, LB_GETTEXT, j, (LPARAM) (LPSTR) mybuf);

                GetDlgItemText (hDlg, IDD_MAIL_DEST, DialogString, MAXDIALOGSTRING - 1);
                strcpy (str, DialogString);
                // test if name already on "To:" line
                // can't to a test with strstr() because mybuf may be a substring
                // of another address (i.e. 'jcoop' is a substr of 'jcooper@apl.com')
                for (found = FALSE, ptr = str; *ptr; ptr += len + 1) {
                  // if there's only one token left, then len will = startLen, 
                  // and we'll iterate once only
                  startLen = strlen (ptr);
                  if ((len = strcspn (ptr, " ,\n\t\r")) != startLen) {
                        ptr[len] = '\0';        // replace delim with NULL char

                        while (strchr (" ,\n\t\r", ptr[len + 1]))       // eat white space

                          ptr[len++] = '\0';
                  }
                  if (!strcmp (ptr, mybuf)) {
                        found = TRUE;
                        break;
                  }
                  if (len == startLen)  // last token, we're done

                        break;
                }
                if (!found) {
                  if (strlen (mybuf) + strlen (DialogString) + 2 > MAXDIALOGSTRING - 1) {
                        WVMessageBox (hDlg, IDS_WVCNCM_ADD_ADDRESS, IDS_WVCNCM_LONG_ADDRESS, MB_OK | MB_ICONERROR);
                        return FALSE;
                  }
                  if (DialogString[0])  // if this isn't the first one, prepend a comma

                        strcat (DialogString, ", ");
                  strcat (DialogString, mybuf);
                  SetDlgItemText (hDlg, IDD_MAIL_DEST, DialogString);
                }
          }
          break;

        case IDD_MAIL_DEST:
          GetDlgItemText (hDlg, IDD_MAIL_DEST, mybuf, MAXDIALOGSTRING - 1);
          EnableWindow (GetDlgItem (hDlg, IDD_ADD), mybuf[0]);
          return FALSE;                         /* let default handler act on these events */
          break;

        case IDD_ADD:
          // check addresses listed on to-line, add each one to list box 
          // (if not already in the list)
          GetDlgItemText (hDlg, IDD_MAIL_DEST, DialogString, MAXDIALOGSTRING - 1);
          for (ptr = DialogString; *ptr; ptr += len + 1) {
                // if there's only one token left, then len will = startLen, 
                // and we'll iterate once only
                startLen = strlen (ptr);
                if ((len = strcspn (ptr, " ,\n\t\r")) != startLen) {
                  ptr[len] = '\0';              // replace delim with NULL char

                  while (strchr (" ,\n\t\r", ptr[len + 1]))             // eat white space

                        ptr[len++] = '\0';
                }
                if (*ptr != '\0')               // if not a blank
                 {
                  // check if it's already in the list
                  count = (int) SendMessage (hMailList, LB_GETCOUNT, 0, 0L);
                  for (j = 0; j < count; j++) {
                        SendMessage (hMailList, LB_GETTEXT, j, (LPARAM) (LPSTR) mybuf);
                        if (!_stricmp (ptr, mybuf))
                          break;
                  }
                  if (j == count)               // if not already in list, add it

                        SendMessage (hMailList, LB_ADDSTRING, 0, (LPARAM) (LPSTR) ptr);
                }
                if (len == startLen)    // last token, we're done

                  break;
          }
          break;

        case IDD_DELETE:
          // remove all selected addresses from list box
          count = (int) SendMessage (hMailList, LB_GETCOUNT, 0, 0L);

          SendMessage (hMailList, WM_SETREDRAW, FALSE, 0L);

          // working backwards, delete selected items
          for (j = count - 1; j >= 0; j--)
                if (SendMessage (hMailList, LB_GETSEL, j, 0L))
                  SendMessage (hMailList, LB_DELETESTRING, j, 0L);

          SendMessage (hMailList, WM_SETREDRAW, TRUE, 0L);
          EnableWindow (GetDlgItem (hDlg, IDD_DELETE), FALSE);
          break;

        case IDOK:
          GetDlgItemText (hDlg, IDD_MAIL_DEST, mybuf, MAXDIALOGSTRING - 1);

          // make sure the address (if more than one) is comma separated
          DialogString[0] = '\0';
          for (ptr = mybuf; *ptr; ptr += len + 1) {
                // if there's only one token left, then len will = startLen, 
                // and we'll iterate once only
                startLen = strlen (ptr);
                if ((len = strcspn (ptr, " ,\n\t\r")) != startLen) {
                  ptr[len] = '\0';              // replace delim with NULL char

                  while (strchr (" ,\n\t\r", ptr[len + 1]))             // eat white space

                        ptr[len++] = '\0';
                }

                strcat (DialogString, ptr);

                if (len == startLen)    // last token, we're done

                  break;
                else
                  strcat (DialogString, ", ");
          }

          // commit changes in listbox to internal MailList
          ResetTextBlock (MailList);
          count = (int) SendMessage (hMailList, LB_GETCOUNT, 0, 0L);
          for (j = 0; j < count; j++) {
                SendMessage (hMailList, LB_GETTEXT, j, (LPARAM) (LPSTR) mybuf);
                AddLineToTextBlock (MailList, mybuf);
          }

          EndDialog (hDlg, TRUE);
          break;


        case IDCANCEL:
          // changes to MailList are _not_ committed on Cancel
          EndDialog (hDlg, FALSE);
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}


/*-- function WinVnSmartFilerDialog ---------------------------------------
 *
 *  Manages smart filer config
 *  jsc 9/10/94 -- and 7500 mile tuneup 9/30/94
 */

INT_PTR CALLBACK WinVnSmartFilerDlg (HWND hDlg, unsigned int iMessage, WPARAM wParam, LPARAM lParam)
{
  static HWND hMapList;                 /* extension mapping combobox */
  static HWND hDupeList, hShortenList;  /* options dropllists */
  static int MyEnableExtensionConversion;
  register int j;
  int count, n, e, tabStop[10];
  char sBuff1[MAXDIALOGSTRING];
  char sBuff2[MAXDIALOGSTRING];
  char sBuff3[MAXDIALOGSTRING];
  //char mybuf[MAXDIALOGSTRING];
  RECT rect;
  BOOL ok;

  switch (iMessage) {
  case WM_INITDIALOG:
        hMapList = GetDlgItem (hDlg, IDD_EXT_MAP_LIST);
        hDupeList = GetDlgItem (hDlg, IDD_AVOID_DUPES);
        hShortenList = GetDlgItem (hDlg, IDD_NAME_SHORTEN);

        /* set tab stop at half width (width/2) of listbox.
         * we need # of dlg units to get half width.
         * a dlg unit is (baseUnit/4).  so half posn in dlg units is...
         *      (width/2) / (baseUnit/4) ==> (2*cx)/baseUnit
         *
         * then, set a few more evenly spaced after that in case 
         * of really long source extension in list
         */
        GetWindowRect (hMapList, &rect);
        tabStop[0] = (2 * (RectWidth (rect)) / LOWORD (GetDialogBaseUnits ()));
        for (j = 1; j < 10; j++) {
          tabStop[j] = tabStop[j - 1] + 2 * LOWORD (GetDialogBaseUnits ());
        }
        SendMessage (hMapList, LB_SETTABSTOPS, 10, (LPARAM) tabStop);

        SetDlgItemInt (hDlg, IDD_MAX_NAME_LEN, MaxFileNameLen, TRUE);
        SetDlgItemInt (hDlg, IDD_MAX_EXT_LEN, MaxFileExtLen, TRUE);

        CheckDlgButton (hDlg, IDD_ENABLE_CONVERSION, EnableExtensionConversion);
		CheckDlgButton (hDlg, IDC_CB_NOSPACE, SpaceProcessing);
        EnableWindow (hMapList, EnableExtensionConversion);
        EnableWindow (GetDlgItem (hDlg, IDD_SOURCE_EXT), EnableExtensionConversion);
        EnableWindow (GetDlgItem (hDlg, IDD_DOS_EXT), EnableExtensionConversion);

        EnableWindow (GetDlgItem (hDlg, IDD_ADD), FALSE);
        EnableWindow (GetDlgItem (hDlg, IDD_DELETE), FALSE);

        SendMessage (hMapList, WM_SETREDRAW, FALSE, 0L);
        SendMessage (hDupeList, WM_SETREDRAW, FALSE, 0L);
        SendMessage (hShortenList, WM_SETREDRAW, FALSE, 0L);
        for (j = 0; j < (int) ExtMapSourceList->numLines; j++) {
          _snprintf (sBuff1, MAXDIALOGSTRING, "%s\t%s",
          TextBlockLine (ExtMapSourceList, j), TextBlockLine (ExtMapDosList, j));
          SendMessage (hMapList, LB_ADDSTRING, 0, (LPARAM) (LPCSTR) sBuff1);
        }
    LoadString(hInst, IDS_SFPRONEWFIL, sBuff1, sizeof(sBuff1)); // "Prompt for new file name"
        SendMessage (hDupeList, CB_INSERTSTRING, (WPARAM) DUPE_AVOID_NONE, (LPARAM) (LPCSTR) sBuff1);
    LoadString(hInst, IDS_SFREPEXTNUM, sBuff2, sizeof(sBuff2)); // "Replace extension with number"
        SendMessage (hDupeList, CB_INSERTSTRING, (WPARAM) DUPE_AVOID_NUMBER_EXT, (LPARAM) (LPCSTR) sBuff2);
    LoadString(hInst, IDS_SFPRENUMNAM, sBuff2, sizeof(sBuff2)); // "Preserve extension, prepend number to name"
        SendMessage (hDupeList, CB_INSERTSTRING, (WPARAM) DUPE_AVOID_PREPEND_NUM, (LPARAM) (LPCSTR) sBuff2);
    LoadString(hInst, IDS_SFAPPNUMNAM, sBuff2, sizeof(sBuff2)); // "Preserve extension, append number to name"
        SendMessage (hDupeList, CB_INSERTSTRING, (WPARAM) DUPE_AVOID_APPEND_NUM, (LPARAM) (LPCSTR) sBuff2);

        SendMessage (hShortenList, CB_INSERTSTRING, (WPARAM) SHORTEN_NONE, (LPARAM) (LPCSTR) sBuff1);
    LoadString(hInst, IDS_SFTRUMAXLEN, sBuff2, sizeof(sBuff2)); // "Truncate at max name length"
        SendMessage (hShortenList, CB_INSERTSTRING, (WPARAM) SHORTEN_TRUNCATE, (LPARAM) (LPCSTR) sBuff2);
    LoadString(hInst, IDS_SFCONSKPPUN, sBuff2, sizeof(sBuff2)); // "Condense (skip vowels, punctuation)"
        SendMessage (hShortenList, CB_INSERTSTRING, (WPARAM) SHORTEN_SKIP_VOWELS, (LPARAM) (LPCSTR) sBuff2);

        MyEnableExtensionConversion = EnableExtensionConversion;

        SendMessage (hDupeList, CB_SETCURSEL, (WPARAM) OnDupeName, 0L);
        SendMessage (hShortenList, CB_SETCURSEL, (WPARAM) OnNameTooLong, 0L);

        SendMessage (hMapList, WM_SETREDRAW, TRUE, 0L);
        SendMessage (hDupeList, WM_SETREDRAW, TRUE, 0L);
        SendMessage (hShortenList, WM_SETREDRAW, TRUE, 0L);

        return TRUE;
        break;
	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)404); //IDD_WINVNSMARTFILER
		break;


  case WM_COMMAND:
        switch (LOWORD (wParam)) {


        case IDD_EXT_MAP_LIST:
          switch (GET_WM_COMMAND_CMD (wParam, lParam)) {
          case LBN_SELCHANGE:
                EnableWindow (GetDlgItem (hDlg, IDD_DELETE), TRUE);
                return FALSE;                   /* let the default handler do it */
                break;
          }
          break;

        case IDD_SOURCE_EXT:
        case IDD_DOS_EXT:
          GetDlgItemText (hDlg, IDD_SOURCE_EXT, str, sizeof(str) - 1);
      strcpy(sBuff1, ".");
      strcat(sBuff1, ('.' == str[0]) ? &str[1] : &str[0]);
          GetDlgItemText (hDlg, IDD_DOS_EXT, str, sizeof(str) - 1);
      strcpy(sBuff2, ".");
      strcat(sBuff2, ('.' == str[0]) ? &str[1] : &str[0]);
          EnableWindow (GetDlgItem (hDlg, IDD_ADD), (sBuff1[1] || sBuff2[1]));
          return FALSE;                         /* let default handler act on these events */
          break;

        case IDD_ADD:
          GetDlgItemText (hDlg, IDD_SOURCE_EXT, str, sizeof(str) - 1);
      strcpy(sBuff1, ".");
      strcat(sBuff1, ('.' == str[0]) ? &str[1] : &str[0]);
          GetDlgItemText (hDlg, IDD_DOS_EXT, str, sizeof(str) - 1);
      strcpy(sBuff2, ".");
      strcat(sBuff2, ('.' == str[0]) ? &str[1] : &str[0]);
          _snprintf(sBuff3, sizeof(sBuff3), "%s\t%s", sBuff1, sBuff2);

          /* check if it's already in the list */
          count = (int) SendMessage (hMapList, LB_GETCOUNT, 0, 0L);
          for (j = 0; j < count; j++) {
                SendMessage (hMapList, LB_GETTEXT, (WPARAM) j, (LPARAM) (LPSTR) str);
                /* is the source ext already in the list somewhere? */
                if (!_strnicmp (sBuff3, str, strlen(sBuff1) + 1))
                  break;
          }
          if (j == count) {                     /* if not already in list, add it */
                SendMessage (hMapList, LB_ADDSTRING, 0, (LPARAM) (LPSTR) sBuff3);
          }
          else {                                        /* if already in list, modify the dos ex */
                SendMessage (hMapList, LB_DELETESTRING, (WPARAM) j, 0L);
                SendMessage (hMapList, LB_INSERTSTRING, (WPARAM) j, (LPARAM) (LPSTR) sBuff3);
          }
          break;

        case IDD_DELETE:
          j = (int) SendMessage (hMapList, LB_GETCURSEL, 0, 0L);
          SendMessage (hMapList, LB_DELETESTRING, (WPARAM) j, 0L);
          EnableWindow (GetDlgItem (hDlg, IDD_DELETE), FALSE);
          break;

        case IDOK:
          n = GetDlgItemInt (hDlg, IDD_MAX_NAME_LEN, &ok, TRUE);
          e = GetDlgItemInt (hDlg, IDD_MAX_EXT_LEN, &ok, TRUE);
#ifdef _WIN32
          if (n + e <= 0 || n + e > 255) {
          WVMessageBox (hDlg, IDS_SFNAMEWRONGLEN1, IDS_SFNAMEERR, MB_OK | MB_ICONERROR);
                break;
          }
          if (e == 0 && MyEnableExtensionConversion) {
                if (WVMessageBox (hDlg, IDS_SFNAMEWRONGLEN2, IDS_SFWARNING, MB_YESNO | MB_ICONQUESTION) == IDNO)
                  break;
                else
                  MyEnableExtensionConversion = FALSE;
          }

#else
          if (n <= 0 || n > 8) {
                WVMessageBox (hDlg, IDS_SFDOSNAMLEN, IDS_SFFILNAMLERR, MB_OK | MB_ICONERROR);
                break;
          }
          if (e <= 0 || e > 3) {
                WVMessageBox (hDlg, IDS_SFDOSEXTLEN, IDS_SFFILEXTLERR, MB_OK | MB_ICONERROR);
                break;
          }
#endif /* _WIN32 */
          MaxFileNameLen = n;
          MaxFileExtLen = e;
          OnDupeName = (int) SendMessage (hDupeList, CB_GETCURSEL, 0, 0L);
          OnNameTooLong = (int) SendMessage (hShortenList, CB_GETCURSEL, 0, 0L);
          EnableExtensionConversion = MyEnableExtensionConversion;
		  SpaceProcessing = (IsDlgButtonChecked (hDlg, IDC_CB_NOSPACE) != 0);
          
		  /* commit changes in listbox to internal lists */
          ResetTextBlock (ExtMapSourceList);
          ResetTextBlock (ExtMapDosList);
          count = (int) SendMessage (hMapList, LB_GETCOUNT, 0, 0L);
          for (j = 0; j < count; j++) {
                SendMessage (hMapList, LB_GETTEXT, j, (LPARAM) (LPSTR) sBuff1);
                sscanf (sBuff1, "%s\t%s", sBuff2, sBuff3);
                AddLineToTextBlock (ExtMapSourceList, sBuff2);
                AddLineToTextBlock (ExtMapDosList, sBuff3);
          }

          EndDialog (hDlg, TRUE);
          break;


        case IDCANCEL:
          /* changes to lists are _not_ committed on Cancel */
          EndDialog (hDlg, FALSE);
          break;

        case IDD_ENABLE_CONVERSION:
          MyEnableExtensionConversion = !MyEnableExtensionConversion;
          CheckDlgButton (hDlg, IDD_ENABLE_CONVERSION, MyEnableExtensionConversion);
          SendMessage (hMapList, LB_SETCURSEL, (WPARAM) - 1, 0L);       /* deselect */
          EnableWindow (hMapList, MyEnableExtensionConversion);
          EnableWindow (GetDlgItem (hDlg, IDD_SOURCE_EXT), MyEnableExtensionConversion);
          EnableWindow (GetDlgItem (hDlg, IDD_DOS_EXT), MyEnableExtensionConversion);
          if (!MyEnableExtensionConversion) {
                EnableWindow (GetDlgItem (hDlg, IDD_ADD), FALSE);
                EnableWindow (GetDlgItem (hDlg, IDD_DELETE), FALSE);
          }
          break;

        default:
          return FALSE;
        }
        break;

  default:
        return FALSE;
        break;
  }
  return TRUE;
}

INT_PTR CALLBACK WinVnSMTPDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
#define MAXSTR  32


	char SMTPPassword[MAXNNTPSIZE];

	static HFONT hDlgFont = NULL;
	

	switch (iMessage) 
	{

	case WM_INITDIALOG:
		CenterWindow (hDlg, GetParent(hDlg) );
		/* Get dialog font and create non-bold version */ 
		if (g_bIsXP && !hDlgFont)
		{  //fix password font
			LOGFONT lFont;
			lFont.lfHeight = 14;
			lFont.lfWidth = 0;
			lFont.lfEscapement = 0;
			lFont.lfOrientation = 0;
			lFont.lfWeight = 200; // non-bold font weight
			lFont.lfItalic = 0;
			lFont.lfUnderline = 0;
			lFont.lfStrikeOut = 0;
			lFont.lfCharSet = ANSI_CHARSET;
			lFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
			lFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
			lFont.lfQuality = DEFAULT_QUALITY;
			lFont.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
			strcpy(lFont.lfFaceName, "Microsoft Sans Serif");
			hDlgFont = CreateFontIndirect(&lFont);

			SendDlgItemMessage(hDlg, ID_CONFIG_AUTH_PASSWORD, WM_SETFONT,  (WPARAM)hDlgFont, (DWORD)TRUE);
			// Send WM_SETFONT message to desired controls

		}

		CheckDlgButton (hDlg, ID_CONFIG_USESSL, UseSSL);

		SetDlgItemText (hDlg, ID_CONFIG_SMTP_SERVER, SMTPHost);
		SetDlgItemText (hDlg, ID_CONFIG_SMTP_PORT, SMTPService);

		SetDlgItemText (hDlg, ID_SMTP_USER, SMTPUserName);
		MRRDecrypt (SMTPPasswordEncrypted, (unsigned char *) SMTPPassword, MAXNNTPSIZE);
		SetDlgItemText (hDlg, ID_SMTP_PASS, SMTPPassword);

		
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_SMTP_SERVER), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_SMTP_PORT), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_CONFIG_SMTP_SERVER), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_SMTP_USER), MAXNNTPSIZE);
		Edit_LimitText(GetDlgItem(hDlg, ID_SMTP_PASS), MAXNNTPSIZE);

#ifdef _INCLSSL
		CheckRadioButton (hDlg, ID_CONFIG_SMTP, ID_CONFIG_SMTPTLS, ID_CONFIG_SMTP+SMTPUseSSL);
#else
		CheckRadioButton (hDlg, ID_CONFIG_SMTP, ID_CONFIG_SMTPTLS, ID_CONFIG_SMTP);
		
		EnableWindow(GetDlgItem(hDlg, ID_CONFIG_SMTPSSL), 0);
		EnableWindow(GetDlgItem(hDlg, ID_CONFIG_SMTPTLS), 0);
#endif

		// PCT, 10/05/94
		CheckDlgButton (hDlg, ID_SMTP_SAVEPASS, SMTPSavePassword);

		if (lParam)
		{
			SetFocus( GetDlgItem (hDlg, ID_SMTP_PASS));
			return FALSE;

		}
		return TRUE;
		break;

		case WM_HELP:
			{
				LPHELPINFO lphi = (LPHELPINFO) lParam; 
				
				DoHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, HELP_CONTEXT, (DWORD)IDD_WINVNSMTP);

				if (lphi->iContextType == HELPINFO_WINDOW && lphi->iCtrlId != 9 )
				{
					DWORD dwHelp[4] = {	lphi->iCtrlId, lphi->iCtrlId + 0x10000, 0,0};
					//dwHelp[0] = 401;
					//dwHelp[1] = 401 + 0x10000;
					//WinHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, mybuf, HELP_WM_HELP, (DWORD)(LPVOID)dwHelp);
				}

			}
			break;

		case WM_COMMAND:
		switch (wParam) 
		{
			case IDHELP:
				DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNSMTP);
				break;

			case IDOK:

				SMTPUseSSL = (IsDlgButtonChecked (hDlg, ID_CONFIG_SMTP) ?  0 : 
						IsDlgButtonChecked (hDlg, ID_CONFIG_SMTPSSL) ?  1 :
						IsDlgButtonChecked (hDlg, ID_CONFIG_SMTPTLS) ?  2 : 0);
				
				GetDlgItemText (hDlg, ID_CONFIG_SMTP_SERVER, SMTPHost, MAXNNTPSIZE);
				if (*SMTPHost == '\0') 
				{
					WVMessageBox (hDlg, IDS_WVCNCM_INVALID_MAIL, IDS_WVCNCM_INVALID_SMTP, MB_OK | MB_ICONSTOP);
					break;
				}
				GetDlgItemText (hDlg, ID_CONFIG_SMTP_PORT, SMTPService, MAXNNTPSIZE);
				if (*SMTPService == '\0') 
				{
					WVMessageBox (hDlg, IDS_WVCNCM_ENTER_SMTPPORT, IDS_WVCNCM_INVALID_SMTPPORT, MB_OK | MB_ICONSTOP);
					break;
				}

				// PCT, 10/05/94
				SMTPSavePassword = IsDlgButtonChecked (hDlg, ID_SMTP_SAVEPASS);
				GetDlgItemText (hDlg, ID_SMTP_USER, SMTPUserName, MAXNNTPSIZE);
				GetDlgItemText (hDlg, ID_SMTP_PASS, SMTPPassword, MAXNNTPSIZE);
				if (*SMTPPassword)
						MRREncrypt ((unsigned char *) SMTPPassword, strlen (SMTPPassword) + 1, SMTPPasswordEncrypted);
				else
					*SMTPPasswordEncrypted = '\0';
				if (hDlgFont)
				{
					SendDlgItemMessage(hDlg, ID_CONFIG_AUTH_PASSWORD, WM_SETFONT,  (WPARAM)SendMessage(hDlg, WM_GETFONT,0,0), (DWORD)TRUE);
					DeleteObject(hDlgFont);
					hDlgFont = NULL;
				}

				EndDialog (hDlg, TRUE);
			break;

			case IDCANCEL:
				if (hDlgFont)
				{
					SendDlgItemMessage(hDlg, ID_CONFIG_AUTH_PASSWORD, WM_SETFONT,  (WPARAM)SendMessage(hDlg, WM_GETFONT,0,0), (DWORD)TRUE);

					DeleteObject(hDlgFont);
					hDlgFont = NULL;
				}
				EndDialog (hDlg, FALSE);
				break;

			case ID_CONFIG_SMTP:
				SetDlgItemText (hDlg, ID_CONFIG_SMTP_PORT, "smtp");	//25
				break;
			case ID_CONFIG_SMTPSSL:
				SetDlgItemText (hDlg, ID_CONFIG_SMTP_PORT, "465"); //smtps 
				break;
			case ID_CONFIG_SMTPTLS:
				SetDlgItemText (hDlg, ID_CONFIG_SMTP_PORT, "587"); //submission
				break;

			default:
				return FALSE;
		}
		break;

	default:
			return FALSE;
			break;
	}
	return TRUE;
}



INT_PTR CALLBACK WinVnMergeDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{


	switch (iMessage) 
	{

	case WM_INITDIALOG:
		CenterWindow (hDlg, GetParent(hDlg) );
		return FALSE;
		break;

		case WM_HELP:
			{
				LPHELPINFO lphi = (LPHELPINFO) lParam; 
				
				DoHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, HELP_CONTEXT, (DWORD)IDD_MERGE);

				if (lphi->iContextType == HELPINFO_WINDOW && lphi->iCtrlId != 9 )
				{
					DWORD dwHelp[4] = {	lphi->iCtrlId, lphi->iCtrlId + 0x10000, 0,0};
					//dwHelp[0] = 401;
					//dwHelp[1] = 401 + 0x10000;
					//WinHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, mybuf, HELP_WM_HELP, (DWORD)(LPVOID)dwHelp);
				}

			}
			break;

		case WM_COMMAND:
		switch (wParam) 
		{
			case IDHELP:
				DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_MERGE);
				break;

			case IDOK:
			case IDCANCEL:
			case IDIGNORE:
				EndDialog (hDlg, wParam);
				break;

			default:
				return FALSE;
		}
		break;

	default:
			return FALSE;
			break;
	}
	return TRUE;
}


INT_PTR CALLBACK WinVnAppendDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
	switch (iMessage) 
	{

	case WM_INITDIALOG:
		{
			//because this dialog can come up after a standard message box, the
			//mouse can be positioned over the overwrite button.
			//if you accidentally click again, you could overwrite so we move
			//the mouse pointer off of the button
			RECT r;
			POINT pt;
			CenterWindow (hDlg, GetParent(hDlg) );
			GetWindowRect(GetDlgItem(hDlg, IDIGNORE), &r);
			GetCursorPos(&pt);
			if (PtInRect(&r, pt))
			{
				SetCursorPos( pt.x, r.top-5); 
			}

		}
		return FALSE;
		break;

		case WM_HELP:
			{
				LPHELPINFO lphi = (LPHELPINFO) lParam; 
				
				DoHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, HELP_CONTEXT, (DWORD)IDD_APPENDDLG);

				if (lphi->iContextType == HELPINFO_WINDOW && lphi->iCtrlId != 9 )
				{
					DWORD dwHelp[4] = {	lphi->iCtrlId, lphi->iCtrlId + 0x10000, 0,0};
					//dwHelp[0] = 401;
					//dwHelp[1] = 401 + 0x10000;
					//WinHelp ((HWND)lphi->hItemHandle/*NetDoc.hDocWnd*/, mybuf, HELP_WM_HELP, (DWORD)(LPVOID)dwHelp);
				}

			}
			break;

		case WM_COMMAND:
		switch (wParam) 
		{
			case IDHELP:
				DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_APPENDDLG);
				break;

			case IDOK:
			case IDCANCEL:
			case IDIGNORE:
				EndDialog (hDlg, wParam);
				break;

			default:
				return FALSE;
		}
		break;

	default:
			return FALSE;
			break;
	}
	return TRUE;

}


/////////////////////////////////////////////////////////////////////////////
//  Support functions for multiple attachment list dialog
//

//storage for customized combobox 
struct MyComboData
{
	BOOL m_bVK_ESCAPE;
	int m_nSubItem;
	int m_nItem;
};

#define MIN_COLUMN_WIDTH 10
#define WM_COMBOSETCELL WM_USER+200
#define kComboID 1890
#define kColFilename 0
#define kColSize 1
#define kColMIMEType 2
#define kColEnc 3

const short	   kFeedbackLineWidth = 2;
const COLORREF kFeedbackColor = RGB(0,0,0);
const COLORREF kEraseColor = RGB(255,255,255);

//list control header titles
const TCHAR *szColName[] = {"Filename", "Size", "MIME Type", "Encoding", "\0"};

WNDPROC lpfnComboWndProc = NULL;
static WNDPROC oldListProc = NULL;

//customized combobox for cell of report-style list control
LRESULT CALLBACK ComboWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	MyComboData* pData = (MyComboData*) GetWindowLongPtr(hwnd, GWLP_USERDATA);

	if (!pData)
	{
		MyComboData* pData = new MyComboData;
		ZeroMemory(pData, sizeof(MyComboData));
		SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR ) pData);

	}
	switch (msg) 
    {

		case WM_NCDESTROY:
			if (pData)
				delete pData;

			if (lpfnComboWndProc)
			{
				LRESULT lres = CallWindowProc(lpfnComboWndProc, hwnd, msg, wParam, lParam);
				SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR) lpfnComboWndProc);
				lpfnComboWndProc = NULL;
				return lres;

			}
			break;
		case WM_CHAR:
		{
			UINT nChar = (UINT) wParam;

			if(nChar == VK_ESCAPE || nChar == VK_RETURN)	
			{		
				if( nChar == VK_ESCAPE)
					pData->m_bVK_ESCAPE = 1;
				SetFocus(GetParent(hwnd));		
				return 0;	
			}
			break;
		}
		case WM_COMBOSETCELL: //our custom message to tell combo where it is
		{
			if (pData)
			{
				pData->m_nItem = (int) wParam;
				pData->m_nSubItem = (int) lParam;
				return 1;
			}
		}
		break;
		case WM_KILLFOCUS:
		{
			int nIndex = ComboBox_GetCurSel(hwnd);
			LRESULT lResult = DefWindowProc(hwnd, msg, wParam, lParam);
			HWND hList = GetParent(hwnd);
			HWND hDlg = GetParent(hList);
			TCHAR str[255];
			GetWindowText(hwnd, str, 255);
			str[254]=0;
			// Send Notification to parent of ListView ctrl	
			LV_DISPINFO lvDispinfo;
			lvDispinfo.hdr.hwndFrom = hList;
			lvDispinfo.hdr.idFrom = GetDlgCtrlID(hList);
			lvDispinfo.hdr.code = LVN_ENDLABELEDIT;
			lvDispinfo.item.mask = LVIF_TEXT | LVIF_PARAM;	
			lvDispinfo.item.iItem = pData ? pData->m_nItem : 0;
			lvDispinfo.item.iSubItem = pData->m_nSubItem;
			lvDispinfo.item.pszText = pData->m_bVK_ESCAPE ? NULL : LPTSTR((LPCTSTR)str);
			lvDispinfo.item.cchTextMax = _tcslen(str);
			lvDispinfo.item.lParam = nIndex >= 0 ? ComboBox_GetItemData(hwnd, nIndex) : NULL;
			
			if ( nIndex != CB_ERR )
				SendMessage(hDlg, WM_NOTIFY, GetDlgCtrlID(hList), (LPARAM)&lvDispinfo);
			PostMessage(hwnd, WM_CLOSE, 0,0);
			return lResult;

		}
		break;
	}

	return CallWindowProc(lpfnComboWndProc, hwnd, msg, wParam, lParam); 
} 

//scroll report-style list control to expose desired cell
void ScrollToView(HWND hList, int nCol, LPRECT prCell)
{
	// Now scroll if we need to expose the column
	RECT rClient;
	SIZE sizeScroll = {0};

	int nColWidth = ListView_GetColumnWidth(hList, nCol);
	HWND hHeader = ListView_GetHeader(hList);
	if (hHeader)
	{
		int nColCount = Header_GetItemCount(hHeader);
		GetClientRect(hList, &rClient);

		if (prCell->right > rClient.right)
			sizeScroll.cx -= prCell->right -rClient.right;
		if (prCell->left < rClient.left)
			sizeScroll.cx += prCell->left-rClient.left;

		if (prCell->bottom > rClient.bottom)
			sizeScroll.cy -= prCell->bottom -rClient.bottom;
		if (prCell->top < rClient.top)
			sizeScroll.cy += prCell->top-rClient.top;
			

		ListView_Scroll(hList, -sizeScroll.cx, -sizeScroll.cy);
		
		//move cell rect as window has scrolled
		OffsetRect(prCell, sizeScroll.cx, sizeScroll.cy);
	}

}

BOOL CalculateCellRect(HWND hList, int nCol, int nRow, LPRECT pCell)
{
	
	if (ListView_GetSubItemRect(hList, nRow, nCol, LVIR_BOUNDS, pCell))
	{
		RECT rClient;
		GetClientRect(hList, &rClient);

		//can't have combo width larger than entire list client size!
		if (RectWidth((*pCell)) > RectWidth(rClient))
			pCell->right = pCell->left + RectWidth(rClient);	
	
		ScrollToView(hList, nCol, pCell);
		return TRUE;
	}
	return FALSE;
}

//create a combo box to be placed in the cell of a report list control
HWND ShowInPlaceCombo(HWND hList, int nRow, int nCol, UINT nID)
{

	//ensure visible
	if (!ListView_EnsureVisible (hList, nRow, 1))
		return FALSE;

	HWND hHeader = ListView_GetHeader(hList);

	int nColCount = Header_GetItemCount(hHeader);
	if ( nCol >= nColCount || ListView_GetColumnWidth(hList, nCol) < MIN_COLUMN_WIDTH)
		return FALSE;
	RECT rCell = {0};

	if (lpfnComboWndProc)
	{
		//what! do we have another one of these around?
		HWND hOld = GetDlgItem(hList, nID);
		if (hOld)
		{
			DestroyWindow(hOld);
		}
	}
	
	CalculateCellRect(hList,  nCol, nRow, &rCell);

	DWORD dwStyle = WS_BORDER | WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | ES_AUTOVSCROLL | 
							CBS_DROPDOWNLIST | CBS_DISABLENOSCROLL;

	HWND hCombo = CreateWindow("COMBOBOX", "", dwStyle, rCell.left, rCell.top, RectWidth(rCell), 300,  //drop height
		hList, (HMENU) nID, hInst, NULL);

	if (hCombo)
	{
		//subclass it
		lpfnComboWndProc = (WNDPROC) SetWindowLongPtr(hCombo, GWLP_WNDPROC, (LONG_PTR) ComboWindowProc);
	
		HFONT hFont = GetWindowFont(hList);
		SetWindowFont(hCombo, hFont, false);
	
	}
				
	return hCombo; 

}

// convert list control clicks into row & column
BOOL ListHitTest(HWND hList, LPPOINT pPt, int *pRow, int *pCol)
{

	if (!pRow || !pCol)
		return FALSE;

	// Make sure that the ListView is in LVS_REPORT
	if ((GetWindowLongPtr(hList, GWL_STYLE) & LVS_TYPEMASK) != LVS_REPORT)
		return FALSE;

	LVHITTESTINFO hti;
	hti.pt = *pPt;

	*pRow = (int) ListView_HitTest(hList, &hti);

	if (*pRow >= 0 && ListView_SubItemHitTest(hList, &hti) >= 0)
	{
		*pCol = hti.iSubItem;
		return TRUE;
	}

	return FALSE;

}

void ListDrawFeedbackLine(HWND hList, long nItem, bool bBefore, COLORREF nColor)
{
	if ( nItem < 0 )
		return;

	RECT rCell;
	ListView_GetItemRect(hList, nItem, &rCell,LVIR_BOUNDS );
	if ( bBefore )
	{
		rCell.bottom = rCell.top + kFeedbackLineWidth;
		OffsetRect(&rCell, 0, -1 );	// Fugde a bit
	}
	else
	{
		rCell.top = rCell.bottom - kFeedbackLineWidth;
		OffsetRect(&rCell, 0,1 );	// Fugde a bit
	}

		// Make the line as wide as the list
	RECT rClient;
	GetClientRect(hList,  &rClient );
	rCell.right = rCell.left + RectWidth(rClient);


	HDC hDC = GetDC(hList);
	if (hDC)
	{
		HBRUSH hbr = CreateSolidBrush(nColor);

		FillRect(hDC, &rCell, hbr );
		DeleteObject(hbr);
		
		if (nColor == kEraseColor)
		{
			//just let windows redraw it.
			InvalidateRect(hList, &rCell, TRUE);
		}
		ReleaseDC(hList, hDC );
	}
}

HIMAGELIST makeDragImage(HWND hList)
{
	HIMAGELIST iList;
	int nCount = 0;
	int iItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
	while (iItem != -1)
	{
		nCount++;
		iItem = ListView_GetNextItem(hList, iItem, LVNI_SELECTED);
	}
	
		
	iList = ImageList_Create(32, 32, ILC_MASK, 1, 0);

	HICON hDrag = LoadIcon(hInst, (nCount > 1 ? "WVCSTAT2" : "WVCSTAT1"));

	ImageList_AddIcon( iList, hDrag);
	DestroyIcon(hDrag);

    return iList;
}

// Set list entry with data from attachment
int AddAttachmentToList(HWND hList, TypAttachment * pAttach, int pos = -1)
{
	if (!pAttach)
		return -1;

	LVITEM item = {0};
	item.iItem = pos < 0 ? ListView_GetItemCount(hList) : pos;
	item.mask = LVIF_TEXT | LVIF_PARAM;
	item.pszText = pAttach->fileName;
	item.cchTextMax = MAXFILENAME;
	item.lParam = (LPARAM) pAttach;

	int nIndex = ListView_InsertItem(hList, &item);

	if (nIndex >= 0)
	{
		TCHAR szFile[MAXFILENAME] = {0};
		NameWithoutPath( szFile, pAttach->fileName);
		AddLCText(nIndex, kColFilename, szFile, hList);
		AddLCText(nIndex, kColMIMEType, pAttach->contentType, hList);
		wsprintf(szFile, "%d", pAttach->numBytes);
		AddLCText(nIndex, kColSize, szFile, hList);
		AddLCText(nIndex, kColEnc, EncodingTypeToStr(pAttach->encodingType), hList);

	}

	return nIndex;

}



HIMAGELIST  hDragImage = NULL;
int		nItemBeingDragged = -1;
int		nItemDroppedOn = -1;
bool	bDropBefore = false;
POINT   ptMouse = {0};

//custom wndproc for List Control to handle click processing and combo box creation
LRESULT CALLBACK ListWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch(msg)
	{
	    case WM_DROPFILES:
			return SendMessage( GetParent(hwnd), msg, wParam, lParam);
			break;
		case WM_LBUTTONDOWN:
		{
			
			POINT pt;
			int nRow, nCol;
			pt.x = GET_X_LPARAM(lParam);
			pt.y = GET_Y_LPARAM(lParam);
			RECT rList;
			GetClientRect(hwnd, &rList);
			
			if ( nItemBeingDragged == -1 && PtInRect(&rList, pt))
			{
				if (ListHitTest(hwnd, &pt, &nRow, &nCol) && nRow >= 0 && nCol >= 0)
				{
					TCHAR str[256];

					LRESULT lRes = CallWindowProc(oldListProc, hwnd, msg, wParam, lParam);
				
					ListView_GetItemText(hwnd, nRow, nCol, str, 255);

					if ( nCol == kColMIMEType && (ListView_GetItemState(hwnd, nRow, LVIS_FOCUSED ) & LVIS_FOCUSED) == LVIS_FOCUSED)
					{
						HWND hCombo = ShowInPlaceCombo(hwnd, nRow, nCol,  kComboID);
						if (hCombo)
						{
							//fill MIMEtypes combo
							SendMessage(hCombo, WM_COMBOSETCELL, nRow, nCol);
		
							for (int i = 0; i < MAXMIMETYPE; i++)
							  ComboBox_AddString(hCombo, (LPSTR) ContentTypes[i]);							
							
							
							ListView_GetItemText(hwnd, nRow, nCol, str, 255);
							ComboBox_SelectString(hCombo, -1, str);
							SetFocus(hCombo);
						}
					}
					else if (nCol == kColEnc && (ListView_GetItemState(hwnd, nRow, LVIS_FOCUSED ) & LVIS_FOCUSED) == LVIS_FOCUSED) 
					{
						HWND hCombo = ShowInPlaceCombo(hwnd, nRow, nCol,  kComboID);
						if (hCombo)
						{
							//fill encoding types combo
							SendMessage(hCombo, WM_COMBOSETCELL, nRow, nCol);
		
							for (int i = 0; i < NUM_ENCODING_TYPES-1; i++)
							  ComboBox_AddString(hCombo, (LPSTR) EncodingTypes[i]);							
							
							
							ListView_GetItemText(hwnd, nRow, nCol, str, 255);
							ComboBox_SelectString(hCombo, -1, str);
							SetFocus(hCombo);
						}

					}
	
				
					return lRes;
				}

			}

		}
		break;
		case WM_NOTIFY:
		{
			LPNMHDR lpnmh = (LPNMHDR) lParam;
			if (lpnmh->idFrom == IDC_LIST_FILES)
			{
				switch(lpnmh->code)
				{

					case LVN_BEGINDRAG:
					{
						TRACE("Begin drag\r\n");
						LPNMLISTVIEW pNMListView = (LPNMLISTVIEW)lParam;
						long nItem = pNMListView->iItem;
						RECT rClient;

						nItemBeingDragged = nItem;
						nItemDroppedOn = nItemBeingDragged;
						bDropBefore = false;
						POINT pt;
						pt.x = pNMListView->ptAction.x;
						pt.y = pNMListView->ptAction.y;

						ClientToScreen(GetParent(hwnd), &pt);
						ScreenToClient(hwnd, &pt); 

						hDragImage = makeDragImage(hwnd);
						ImageList_BeginDrag(hDragImage, 0, 4, 12);
						
						ImageList_DragEnter(hwnd, pt.x, pt.y); 
						GetWindowRect(hwnd, &rClient);
						SetCapture(hwnd);
						ClipCursor(&rClient);
						return 0L;

					}
				}
			}
		}
		break;

	case WM_KILLFOCUS:
		if (nItemBeingDragged >= 0)
		{
			//lost focus while dragging?
			ClipCursor(NULL);
			ImageList_DragLeave(hwnd);
			ImageList_EndDrag();
			ImageList_Destroy(hDragImage);
			hDragImage = NULL;
			ReleaseCapture();
			nItemBeingDragged = -1;

		}
		break;

	case WM_LBUTTONUP:
		if (nItemBeingDragged >= 0)
		{
			ClipCursor(NULL);
			ImageList_DragLeave(hwnd);
			ImageList_EndDrag();
			ImageList_Destroy(hDragImage);
			hDragImage = NULL;
			ReleaseCapture();
			
			// Clear last feedback
			ListDrawFeedbackLine( hwnd, nItemDroppedOn, bDropBefore,kEraseColor );

			//If we are dropping before the next item or dropping after the previous item
			//or on the current item it is the same as dropping on ourself!
			if ( nItemDroppedOn != nItemBeingDragged &&
				 nItemDroppedOn + (bDropBefore ? -1 : 1) != nItemBeingDragged)
			{

				// For simplicity, find the index _before_ which we want to drop
				if ( !bDropBefore )
					nItemDroppedOn++;

				
				TypAttachment* pSelected[MAX_NUM_ATTACHMENTS] = {0};
				
				int nCount = 0;
				int iItem = ListView_GetNextItem(hwnd, -1, LVNI_SELECTED);
				while (iItem != -1)
				{
					
					LVITEM item = {0};
					item.iItem = iItem;
					item.mask = LVIF_PARAM;

					if (ListView_GetItem(hwnd, &item))
					{
						pSelected[nCount++] = (TypAttachment*) item.lParam;						

					}
					if (iItem < nItemDroppedOn)
						nItemDroppedOn--;
					
					
					iItem = ListView_GetNextItem(hwnd, iItem, LVNI_SELECTED);
				}

				while ( (iItem = ListView_GetNextItem(hwnd, -1, LVNI_SELECTED)) >= 0)
					ListView_DeleteItem(hwnd, iItem);


				for (iItem = 0; iItem < nCount; iItem++)
				{
					int ndx = AddAttachmentToList(hwnd, pSelected[iItem], nItemDroppedOn);
					if (iItem == 0)
						ListView_SetItemState( hwnd, ndx, 0, LVIS_FOCUSED );
					nItemDroppedOn++;
				}




				
				//ItemDropped(m_nItemBeingDragged,m_nItemDroppedOn);
			}

			nItemBeingDragged = -1;
			nItemDroppedOn = -1;
			bDropBefore = false;


		}
		break;
	case WM_MOUSEMOVE:
		if (nItemBeingDragged >= 0)
		{
			POINT pt;
			pt.x = GET_X_LPARAM(lParam); 
			pt.y = GET_Y_LPARAM(lParam);
			int nFlags = (int) wParam;

			if (GetCapture() != hwnd && (nFlags & MK_LBUTTON))
				SetCapture(hwnd);

			if ( !(nFlags & MK_LBUTTON) )
			{
				//missed WM_LBUTTONUP?
				ClipCursor(NULL);
				ImageList_DragLeave(hwnd);
				ImageList_EndDrag();
				ImageList_Destroy(hDragImage);
				hDragImage = NULL;
				ReleaseCapture();
				nItemBeingDragged = -1;

			}

			POINT ptDrag = pt;
			if (hDragImage)
				ImageList_DragMove(	ptDrag.x, ptDrag.y);
				


			LVHITTESTINFO hti;
			hti.pt = pt;

			int nOver = ListView_HitTest(hwnd, &hti);
			int vDiff = ptMouse.y - pt.y;
			RECT rClient;
			bool bAutoVScroll = false;
			bool bDir = false;
			ptMouse = pt;
			GetClientRect(hwnd, &rClient);

			//scroll if we're at the border
			if (vDiff && pt.y <= rClient.top+4)
			{
				ptMouse.y = rClient.top+2;
				bAutoVScroll = TRUE;
				bDir = FALSE;
			}
			if (vDiff && pt.y >= rClient.bottom-4)
			{
				ptMouse.y = rClient.bottom-2;
				bAutoVScroll = TRUE;
				bDir = TRUE;
			}

			long nOldDrop = nItemDroppedOn;
			bool bOldBefore = bDropBefore;
			int nMaxDragIndex = ListView_GetItemCount(hwnd);
			
			// If the last item is reserved, don't let anyone drag after that item
			if ( ( nOver == -1) || (nMaxDragIndex >= 0 && nOver >= nMaxDragIndex) )
			{
				if (!bAutoVScroll)
					return 0;
			}
			else
			{
				nItemDroppedOn = nOver;
			}


			ListView_GetItemRect(hwnd,  nItemDroppedOn, &rClient ,LVIR_BOUNDS );
			
				// Figure out if the mouse is closer to top or bottom of line,
				// and based on that create the highlight rect
			long vDifFromTop, vDiffFromBottom;
			vDifFromTop = pt.y - rClient.top;
			vDiffFromBottom = rClient.bottom - pt.y;

			if ( vDifFromTop < vDiffFromBottom )
				bDropBefore = TRUE;
			else
				bDropBefore = FALSE;

			
			//TEMPORARILY UNLOCK WINDOW UPDATES
			if (hDragImage)
				ImageList_DragShowNolock(FALSE);

			if ( (nOldDrop != nItemDroppedOn) || (bOldBefore != bDropBefore) ||
				 bAutoVScroll )
			{
				ListDrawFeedbackLine(hwnd, nOldDrop,bOldBefore,kEraseColor );

				if (bAutoVScroll)
				{
					
					InvalidateRect(hwnd, NULL, false);			
					ListView_Scroll(hwnd,  0, (bDir ? RectHeight(rClient) : -RectHeight(rClient) ) );
					UpdateWindow(hwnd);
				}

				ListDrawFeedbackLine(hwnd, nItemDroppedOn, bDropBefore, kFeedbackColor );
			}
			
			//LOCK WINDOW UPDATES
			if (hDragImage)
				ImageList_DragShowNolock( TRUE);

			if (bAutoVScroll)
			{
				POINT ptNew = ptMouse;
				ClientToScreen(hwnd, &ptNew);
				SetCursorPos(ptNew.x, ptNew.y);        
			}


		}
		break;


		case WM_HSCROLL:
		case WM_VSCROLL:
		{
			HWND hFocus = GetFocus();
			if (hFocus != hwnd)
				SetFocus(hwnd);
		}
		break;
		case WM_COMMAND:
			if (GET_WM_COMMAND_CMD (wParam, lParam) == CBN_CLOSEUP)
			{
				SetFocus(GetParent(hwnd));
				return 1;
			}
		break;
 
	}
	return CallWindowProc(oldListProc, hwnd, msg, wParam, lParam);
}

int AddFileToList(HWND hList, char * szFile, TypAttachment **attachments, eEncodingType defaultEncoding)
{
	BOOL bDupe = FALSE;
	int i = 0;

	if (!attachments || !szFile || !*szFile || !IsWindow(hList))
		return -1;


	for (i = 0; i < ListView_GetItemCount(hList); i++)
	{
		
		LVITEM item = {0};
		item.iItem = i;
		item.mask = LVIF_PARAM;

		if (ListView_GetItem(hList, &item))
		{
			TypAttachment* pAttach = (TypAttachment*) item.lParam;						

			if (pAttach && !_stricmp(pAttach->fileName, szFile))
			{
				bDupe = TRUE;
				SetListSelectedItem(hList, i, TRUE);
				break;
			}
		}
	}
	if (!bDupe)
	{
		//we don't allow 0 byte files
		UINT numBytes = GetFileLength(szFile);
		if (numBytes != 0)
		{
			//find an empty list position
			for (int i = 0; i < MAX_NUM_ATTACHMENTS; i++)
			{
				if (!attachments[i])
				{
					attachments[i] =  new TypAttachment;
					if (attachments[i])
					{
						ZeroMemory(attachments[i], sizeof(TypAttachment));
						_tcscpy(attachments[i]->fileName, szFile);
						_tcscpy(attachments[i]->contentType, WVGetMIMETypeForFile(szFile));
						attachments[i]->encodingType = defaultEncoding;
						attachments[i]->attachInNewArt = DefaultAttachInNewArt;
						attachments[i]->numBytes = numBytes;

						AddAttachmentToList(hList, attachments[i]);

					}
					break;

				}
			}
		}
		else
		{
			WVArgMessageBox (GetParent(hList), IDS_WVCNCM_ATTACH_ERROR, IDS_WVCNCM_ATTACH_FILE, MB_OK | MB_ICONSTOP, szFile);

		} 

	}
	return i;

}

/////////////////////////////////////////////////////////////////////////////
// WinVnAttachesDlg - multiple file attachmnet management dialog
// IDD_ATTACH
//
struct	MyAttachDlgData
{
	TypAttachment **origAttach;
	TypAttachment **dlgAttach;
	POINT	ptMin;
	POINT	ptLast;
	int		nItems;
	eEncodingType Encoding;
	
};

INT_PTR CALLBACK WinVnAttachesDlg(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
  
	int i;
	char temp[MAXINTERNALLINE];
	HWND hList = GetDlgItem(hDlg, IDC_LIST_FILES);
	
	MyAttachDlgData* pDlgData =  (MyAttachDlgData*) GetWindowLongPtr(hDlg, GWLP_USERDATA);
	TypAttachment **attachments = NULL;

	if (pDlgData)
		attachments = pDlgData->dlgAttach;


  switch (iMessage) 
  {
      case WM_INITDIALOG:
      {
		RECT rSize = {0};
		int nItems = 0;

		if (!lParam)
		{
			EndDialog(hDlg, -1);
			break;
		}
		//make some dialog variable storage
		pDlgData = new MyAttachDlgData;
		pDlgData->origAttach = (TypAttachment **) lParam;
		pDlgData->dlgAttach = new TypAttachment*[MAX_NUM_ATTACHMENTS];
		SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR ) pDlgData);

		//store original window size
		GetWindowRect(hDlg, &rSize);
		pDlgData->ptMin.x = RectWidth(rSize);
		pDlgData->ptMin.y = RectHeight(rSize);
		pDlgData->ptLast = pDlgData->ptMin;

		//make a copy of the original attachments
		TypAttachment ** thisAttach = (TypAttachment **) lParam;
		attachments = pDlgData->dlgAttach;

		
		//remember attach #0 is the message body
		for ( i = 1; i < MAX_NUM_ATTACHMENTS; i++)
		{
			if ( thisAttach[i] && thisAttach[i]->fileName[0] != 0)
			{
				attachments[nItems] =  new TypAttachment;
				if (!attachments[nItems])
					break;
				memcpy( attachments[nItems], thisAttach[i], sizeof(TypAttachment));
				nItems++; 
			}
		}
		for (i = nItems; i < MAX_NUM_ATTACHMENTS; i++)
			attachments[i] = NULL; 

		if (hList)
		{
			TCHAR szFile[MAXFILENAME] = {0};
			oldListProc = (WNDPROC) SetWindowLongPtr(hList, GWLP_WNDPROC, (LONG_PTR) ListWindowProc);
			
			
			LV_COLUMN lvColumn;
			RECT rCtrl;
			DWORD dwStype = ListView_GetExtendedListViewStyle(hList);
			dwStype |= LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES;
			ListView_SetExtendedListViewStyle(hList, dwStype);

			ListView_DeleteAllItems (hList);

			GetWindowRect( hList, &rCtrl);
			int nWidth = rCtrl.right-rCtrl.left;// - ::GetSystemMetrics(SM_CXVSCROLL);

			// Initialize the columns in the list view.
			lvColumn.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT;
			lvColumn.fmt = LVCFMT_LEFT;
			lvColumn.cx = (int)(nWidth * 0.35)-2;
			lvColumn.pszText = (TCHAR*) szColName[kColFilename];
			ListView_InsertColumn (hList, kColFilename, &lvColumn);


			lvColumn.fmt = LVCFMT_RIGHT;
			lvColumn.cx = (int)(nWidth * 0.15);
			lvColumn.pszText = (TCHAR*)szColName[kColSize];
			ListView_InsertColumn (hList, kColSize, &lvColumn);

			lvColumn.fmt = LVCFMT_LEFT;
			lvColumn.cx = (int)(nWidth * 0.20);
			lvColumn.pszText = (TCHAR*)szColName[kColMIMEType];
			ListView_InsertColumn (hList, kColMIMEType, &lvColumn);

			lvColumn.fmt = LVCFMT_LEFT;
			lvColumn.cx = (int) (nWidth * 0.15);
			lvColumn.pszText = (TCHAR*)szColName[kColEnc];
			ListView_InsertColumn (hList, kColEnc, &lvColumn);


			ListView_SetItemCount(hList, nItems);
			pDlgData->nItems = nItems;
			
			//To Set Item height in List Control with using owner-draw
			//1. Create an ImageList
			//2. Change the ImageSize property on the ImageList from 16x16 to 1xN [w=1,h=N] - N obviously being the height you'd like your rows to be.
			//3. Set the SmallImageList property on your ListView to the ImageList you added in Step 1.
			//Want row height big enough for combobox
			GetWindowRect(GetDlgItem(hDlg, IDD_CODING_TYPE), &rCtrl);
			ListView_SetImageList(hList, ImageList_Create(2, RectHeight(rCtrl), ILC_COLOR , 1, 0), LVSIL_SMALL ); 


			for (int i = 0; i < nItems; i++)
				AddAttachmentToList(hList, attachments[i]);

			SetListSelectedItem(hList, 0);
					
		}
		CheckDlgButton (hDlg, IDD_ATTACH_NEXT, DefaultNewArtForAttach ? BST_CHECKED : BST_UNCHECKED);

        if (attachments[0] && attachments[0]->encodingType)
          pDlgData->Encoding = SetupEncodingOptions (hDlg, attachments[0]->encodingType, FALSE, TRUE);
        else
          pDlgData->Encoding = SetupEncodingOptions (hDlg, (eEncodingType) DefaultEncodingType, FALSE, TRUE);

		  DragAcceptFiles(hList, true);

        }
		break;
	case WM_DROPFILES:
		{
			HDROP hDrop = (HDROP) wParam;
			UINT nFiles = DragQueryFile(hDrop, (UINT)-1, NULL, 0);
			TCHAR buf[MAXFILENAME];
			for (UINT i = 0; i < nFiles; i++)
			{
				if (DragQueryFile(hDrop, i, buf, MAXFILENAME ) >0)
				{
					if (AddFileToList(hList, buf, attachments, pDlgData->Encoding) >= 0)
					{
						pDlgData->nItems++;
					}
	
				}
			}
			DragFinish(hDrop);
			return 0L;


		}
		break;
	case WM_DESTROY:
		if (oldListProc)
		{
			//restore original listctrl wndproc
			SetWindowLongPtr(hList, GWLP_WNDPROC, (LONG_PTR) oldListProc);
			oldListProc = NULL;
		}
			
		break;
	case WM_NCHITTEST: 
		{
			//for resizing gripper hit test
			LRESULT ht = DefWindowProc(hDlg, iMessage, wParam, lParam); 
			if( ht == HTCLIENT ) 
			{ 
				POINT pt;
				RECT rc;
				pt.x = GET_X_LPARAM(lParam);  // horizontal position of cursor 
				pt.y = GET_Y_LPARAM(lParam);  // vertical position of cursor

				GetWindowRect(hDlg, &rc ); 
				rc.left = rc.right - GetSystemMetrics(SM_CXHSCROLL); 
				rc.top = rc.bottom - GetSystemMetrics(SM_CYVSCROLL); 
				if( PtInRect( &rc, pt ) ) 
					ht = HTBOTTOMRIGHT; 
			}
			//need to return a value for this message
			SetWindowLongPtr(hDlg, DWLP_MSGRESULT, ht); 
			return TRUE; 
			
		}
		break;
	case WM_GETMINMAXINFO:
		{
			//allow dlg to be resized, but only down to original size
			LPMINMAXINFO lpmmi = (LPMINMAXINFO) lParam;
			lpmmi->ptMinTrackSize = pDlgData->ptMin;
			return 0;
		}
		break;
	case WM_PAINT:
		{
			
		    PAINTSTRUCT ps;	
			RECT rc;
			HDC hdc = BeginPaint(hDlg,&ps);

			//draw the resize grip
			GetClientRect(hDlg, &rc ); 
			rc.left = rc.right - GetSystemMetrics(SM_CXHSCROLL); 
			rc.top = rc.bottom - GetSystemMetrics(SM_CYVSCROLL); 

			if( g_xpStyle.IsThemeActive() )   
			{   
				HTHEME hTheme = g_xpStyle.OpenThemeData( hDlg, L"SCROLLBAR" );
				if (hTheme)
				{
					g_xpStyle.DrawThemeBackground( hTheme, hdc, SBP_SIZEBOX, SZB_RIGHTALIGN, &rc, NULL);   
					g_xpStyle.CloseThemeData( hTheme );   
				}
				else
					DrawFrameControl( hdc, &rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP );

			}   
			else   
			{   
				DrawFrameControl( hdc, &rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP );
			}   

			EndPaint(hDlg,&ps);
			return(TRUE);
		}
		break;
	case WM_SIZE:
		{
			//resize/move controls in dialog
			RECT rect;
			POINT ptCur;
			int  cx,cy;

			if ( wParam != (WPARAM) SIZE_RESTORED && wParam != (WPARAM) SIZE_MAXIMIZED)
				return TRUE;

			if ( pDlgData->ptMin.x == 0 && pDlgData->ptMin.y == 0) 
				return TRUE;
			
			cx = LOWORD(lParam); 
			cy = HIWORD(lParam);

			if (cx <= 0 || cy <= 0)
				return TRUE;

			GetWindowRect(hDlg, &rect);

			ptCur.x = rect.right-rect.left;
			ptCur.y = rect.bottom-rect.top;
			
			cx = ptCur.x - pDlgData->ptLast.x;
			cy = ptCur.y - pDlgData->ptLast.y;

			cx &= ~0x01; //prevent accumulation of roundoff errors

			pDlgData->ptLast.x += cx;  
			pDlgData->ptLast.y += cy;


			//move dialog controls to new positon/size
			MoveControl(hDlg, IDOK, cx, 0);
			MoveControl(hDlg, IDCANCEL, cx, 0);
			MoveControl(hDlg, IDHELP, cx, 0);
			MoveControl(hDlg, ID_BROWSE, cx, 0);
			MoveControl(hDlg, IDC_PB_DELETE, cx, 0);
			
			
			MoveControl(hDlg, IDC_ST_LABEL, 0, cy);
			MoveControl(hDlg, IDD_ATTACH_NEXT, 0, cy);
			MoveControl(hDlg, IDD_CODING_TYPE, 0, cy);
   
			GrowWindow(hDlg, IDC_LIST_FILES, cx, cy);
			
			InvalidateRect(hDlg, NULL, true); //erase resize ctrl

		}
		break;

	case WM_HELP:
		DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_WINVNATTACH);
		break;
	case WM_NCDESTROY:
		if (attachments)
		{
			for (int i = 0; i < MAX_NUM_ATTACHMENTS; i++)
		    {
				if (attachments[i])
				{
					delete attachments[i];
					attachments[i] = NULL;
				}
			}

		}
		break;
	case WM_NOTIFY:
		{
			LPNMHDR lpnmh = (LPNMHDR) lParam;
			if (lpnmh->idFrom == IDC_LIST_FILES)
			{
				switch(lpnmh->code)
				{
					default:
						//TRACE("WM_NOTIFY %x\r\n", lpnmh->code);
						break;
					case NM_DBLCLK:
					    {
							int nRow = 0, nCol = 0;
							POINT pt;
							GetCursorPos(&pt);
							ScreenToClient(hList, &pt);
							 
							if (ListHitTest(hList, &pt, &nRow, &nCol) && nCol == 0)
							{
								LVITEM item = {0};
								item.iItem = nRow;
								item.mask = LVIF_PARAM;

								if (ListView_GetItem(hList, &item))
								{
									TypAttachment* pAttach = (TypAttachment*) item.lParam;						

									if (pAttach)
									{
										//what to do?  Run attachment?  modify file? 
										TRACE("DoubleClick %s\r\n", pAttach->fileName);

									}
								}
										
							}
							
						}
						break;
					case NM_CLICK:
						break;
					case LVN_BEGINDRAG:
						{
							//turn off combo if we're starting to drag
							HWND hOld = GetDlgItem(hList, kComboID);
							if (hOld)
								DestroyWindow(hOld);
							
							return SendMessage(hList, iMessage, wParam, lParam);
						}
						break;
					case LVN_BEGINLABELEDIT:
						{
							NMLVDISPINFO* pdspinfo = (NMLVDISPINFO*) lParam;
							TRACE("LVN_BEGINLABELEDIT\r\n");
							//don't want default edit behavior
							SetWindowLongPtr(hDlg, DWLP_MSGRESULT, 1); 
							return 1;
						}
						break;

					case LVN_ENDLABELEDIT:
						{
							NMLVDISPINFO* pdspinfo = (NMLVDISPINFO*) lParam;
							TRACE("LVN_ENDLABELEDIT\r\n");
							if (pdspinfo->item.iItem < ListView_GetItemCount(hList) && pdspinfo->item.pszText)
							{
							
								LVITEM lvItem = {0};
								lvItem.iItem = pdspinfo->item.iItem;
								lvItem.mask =  LVIF_PARAM;

								if (ListView_GetItem(hList, &lvItem))
								{
									TypAttachment* pAttach = (TypAttachment*) lvItem.lParam;
									if (pAttach)
									{
										switch(pdspinfo->item.iSubItem)
										{
											case kColFilename:
												break;
											case kColMIMEType:
												strncpy(pAttach->contentType, pdspinfo->item.pszText , MAXCONTENTTYPELEN);
												AddLCText(pdspinfo->item.iItem, kColMIMEType, pAttach->contentType, hList);
												break;
											case kColEnc:
												{
													eEncodingType type = EncodingStrToType(pdspinfo->item.pszText);
													if (type < CODE_CUSTOM)
													{
														pAttach->encodingType = type;
														AddLCText(pdspinfo->item.iItem, kColEnc, pdspinfo->item.pszText, hList);

													}
													for (int i = 0; i < ListView_GetItemCount(hList); i++)
													{
														if (i != pdspinfo->item.iItem && ListView_GetItemState(hList, i, LVIS_SELECTED ) != 0)
														{
															LVITEM item = {0};
															item.iItem = i;
															item.mask = LVIF_PARAM;
															ListView_GetItem(hList, &item);
															TypAttachment* pAttach = (TypAttachment*) item.lParam;
															if (pAttach)
															{
																pAttach->encodingType = type;
																AddLCText(i, kColEnc, pdspinfo->item.pszText, hList);
															}
														}
													}


												}
												break;
											default:
												TRACE("unknown update\r\n");
										}

									}
								}
								return 1L;
							}
						} // LVN_ENDLABELEDIT
						break;

				} //switch
			}
		} //WM_NOTIFY
		break;


  case WM_COMMAND:
        switch (LOWORD (wParam)) 
		{

		case IDD_FILENAME:
          if (GET_WM_COMMAND_CMD (wParam, lParam) == EN_KILLFOCUS) {
                GetDlgItemText (hDlg, IDD_CONTENT_TYPE, (LPSTR) str, MAXINTERNALLINE);
                if (*str == '\0') {
                  GetDlgItemText (hDlg, IDD_FILENAME, str, MAXINTERNALLINE);
                  SelectTypeByExtension (GetDlgItem (hDlg, IDD_CONTENT_TYPE), str);
                }
          }
          break;
		case IDD_CODING_TYPE:
			
			if ((GET_WM_COMMAND_CMD (wParam, lParam) == CBN_SELENDOK))
			{

				int i = (int) SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0);
				if (i != CB_ERR)
				{
					SendDlgItemMessage (hDlg, IDD_CODING_TYPE, CB_GETLBTEXT, (WPARAM) i, (LPARAM) (LPSTR) temp);
					pDlgData->Encoding = EncodingStrToType (temp);
					if (pDlgData->Encoding == CODE_YENC)
						CheckDlgButton (hDlg, IDD_ATTACH_NEXT, BST_CHECKED);
					else
						CheckDlgButton (hDlg, IDD_ATTACH_NEXT, DefaultNewArtForAttach ? BST_CHECKED : BST_UNCHECKED);

				}

			}
		break;
		case IDC_LIST_FILES:
		break;
        case IDOK:
			DefaultEncodingType = pDlgData->Encoding;
			DefaultNewArtForAttach = (IsDlgButtonChecked (hDlg, IDD_ATTACH_NEXT) ? TRUE : FALSE);

			if (attachments)
			{
				int nTarget = 1;
				int i;
				
				//clear out original attachments (remember, #0 is message body)
				for ( i = 1; i < MAX_NUM_ATTACHMENTS; i++)
				{
					if (pDlgData->origAttach[i])
					{
						GlobalFreePtr( pDlgData->origAttach[i]);
						pDlgData->origAttach[i] = NULL;
					}
				}

				//copy in any new attachments, in _list_ order
				for (i = 0; i < ListView_GetItemCount(hList) ; i++)
				{
					LVITEM lvItem = {0};
					lvItem.iItem = i;
					lvItem.mask =  LVIF_PARAM;

					if (ListView_GetItem(hList, &lvItem))
					{
						TypAttachment* pAttach = (TypAttachment*) lvItem.lParam;
					
						if ( pAttach && pAttach->fileName[0] != 0)
						{
							pDlgData->origAttach[nTarget] = (TypAttachment*) GlobalAllocPtr (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (TypAttachment));
							memcpy(pDlgData->origAttach[nTarget] ,pAttach, sizeof (TypAttachment));
							//fixup
							pDlgData->origAttach[nTarget]->attachInNewArt = DefaultAttachInNewArt;
							delete attachments[i];
							attachments[i] = NULL;
							nTarget++;
						}
					}
				}
				//free attachments now
				for ( i = 0; i < MAX_NUM_ATTACHMENTS; i++)
				{
					if ( attachments[i])
					{
						delete attachments[i];
						attachments[i] = NULL;
					}

				}


			}


		  //fall through


		case IDCANCEL:
		  { for (int i = 0; i < MAX_NUM_ATTACHMENTS; i++)
		    {
				if (attachments[i])
				{
					delete attachments[i];
					attachments[i] = NULL;
				}
			}
			EndDialog (hDlg, LOWORD (wParam) == IDOK);
          }
		  break;
		case IDHELP:
			DoHelp (hDlg, HELP_CONTEXT, (DWORD)IDD_ATTACH);
			break;

		case IDC_PB_DELETE:
		  {
			int i = 0;

			while (i < ListView_GetItemCount(hList))
			{
				if (ListView_GetItemState(hList, i, LVIS_SELECTED ) != 0)
				{
					LVITEM item = {0};
					item.iItem = i;
					item.mask = LVIF_PARAM;


					ListView_GetItem(hList, &item);
					TypAttachment* pAttach = (TypAttachment*) item.lParam;
					if (pAttach)
					{
						for (int i = 0; i < MAX_NUM_ATTACHMENTS; i++)
						{
							if (pAttach == attachments[i])
							{
								delete pAttach;
								attachments[i] = NULL;
								pDlgData->nItems--;
								break;
							}
						}
					}

					ListView_DeleteItem(hList, i);
				}
				else
					i++;
			}
		  }
		  break;

        case ID_BROWSE:
		  {
			TCHAR szFile[MAXFILENAME] = {0};
		  	TCHAR *pBuf = NULL;
			if (AskForExistingFileNames (hDlg, szFile, _T("Select File(s) To Attach"), &pBuf) == SUCCESS) 
			{
				TCHAR *szPath = pBuf;
				TCHAR *szcurFile = pBuf + _tcslen(pBuf) +1;
				TCHAR *pFile;


				TCHAR fullPath[MAXFILENAME];
				_tcscpy(fullPath, szPath);
				pFile = fullPath + _tcslen(fullPath);

				if (*(pFile-1) != _T('\\'))
				{
					*pFile++ = _T('\\');
					*pFile = NULL;
				}

				while (*szcurFile)
				{
					_tcscpy(pFile, szcurFile);

					
					if ( AddFileToList( hList, fullPath, attachments, pDlgData->Encoding) >= 0)
						pDlgData->nItems++;


					szcurFile += _tcslen(szcurFile) +1;
				}
			
				delete [] pBuf;
			}
		  }
          break;

        default:
          return FALSE;
        }

  default:
        return FALSE;
  }
  return TRUE;
}

