unit Main;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
//  Roland,
  StdCtrls, ToolWin, Menus, Buttons, MailParser, FMInfo, FMTips, FMEnviro,
  FMMailOptions, FMAccount, PXStuff, INIFiles, FMFolder, Registry, FileCtrl,
  FMOnline, ShellAPI, ClipBrd, ExtCtrls, ComCtrls, FMSelectMail,
  FMAddress, FMDirectory, ImgList,
  EnhListView, ExtListView, FMSearch, FMEditAdr, DialUp, StatusBarEx,
  FMSelBook, FMStdMail, TDOnline, RichEdit2,RichEdit, GradForm,
  TB97Ctls, TB97, TB97Tlbr, ActnList, FMMoveMessage, OleCtnrs, Printers,
  PMTreeview, PMComboBox, PMListBox, RxCombos, OleCtrls, IEConst,activex,
  DHTMLEDLib_TLB, MSHTML_TLB, TB97Tlwn;
const
  MapFileName = 'SICQ_ROSTER';

type
  PMapRosterHead = ^TMapRosterHead;
  TMapRosterHead = packed record
    wFlag: Word;
    wSize: Word;
  end;

  TGetInputArg = procedure(Sender : TObject; var pVarIn : OleVariant; var FuncResult : boolean) of object;
  TClearInputArg = procedure(Sender : TObject; var pVarIn : OleVariant) of object;

  TMainForm = class(TForm)
    MainMenu1: TMainMenu;
    Help1: TMenuItem;
    AboutPhoenix1: TMenuItem;
    PanelClientWindow: TPanel;
    ImageList1: TImageList;
    ImageList2: TImageList;
    Folder1: TMenuItem;
    Enhanced1: TMenuItem;
    EmptyTrashBin1: TMenuItem;
    PopupMenu1: TPopupMenu;
    PopNewFolder: TMenuItem;
    PopDeleteFolder: TMenuItem;
    N4: TMenuItem;
    NewAccount1: TMenuItem;
    PopDeleteAccount: TMenuItem;
    N5: TMenuItem;
    EmptyTrashBin2: TMenuItem;
    N6: TMenuItem;
    PopProperties: TMenuItem;
    menuExit: TMenuItem;
    OpenDialog1: TOpenDialog;
    menMessage: TMenuItem;
    menNew: TMenuItem;
    N8: TMenuItem;
    menReplay: TMenuItem;
    ReplayQuoted1: TMenuItem;
    N10: TMenuItem;
    Attachment1: TMenuItem;
    Open2: TMenuItem;
    Save1: TMenuItem;
    N9: TMenuItem;
    AddFile1: TMenuItem;
    DeleteFile1: TMenuItem;
    menPopupMenu3: TPopupMenu;
    NewMessage1: TMenuItem;
    DeleteMessage1: TMenuItem;
    popReplay: TMenuItem;
    ReplayQuoted2: TMenuItem;
    N12: TMenuItem;
    ToggleReadUnreadFlag1: TMenuItem;
    Properties5: TMenuItem;
    PopupMenu4: TPopupMenu;
    Cut1: TMenuItem;
    Copy1: TMenuItem;
    Paste1: TMenuItem;
    Delete5: TMenuItem;
    N13: TMenuItem;
    SelectAll1: TMenuItem;
    menEdit: TMenuItem;
    menCopy: TMenuItem;
    menFile: TMenuItem;
    N16: TMenuItem;
    N19: TMenuItem;
    TipoftheDay1: TMenuItem;
    AddressBook1: TMenuItem;
    N22: TMenuItem;
    menPrint: TMenuItem;
    PrinterSetupDialog1: TPrinterSetupDialog;
    PrintDialog1: TPrintDialog;
    Contents1: TMenuItem;
    PhoenixMailHomePage1: TMenuItem;
    N23: TMenuItem;
    Signature1: TMenuItem;
    menForward: TMenuItem;
    Redirect1: TMenuItem;
    Redirect2: TMenuItem;
    Timer1: TTimer;
    PanelBitmaps: TPanel;
    Image2: TImage;
    PopupMenu6: TPopupMenu;
    ShowPhoenixMail1: TMenuItem;
    MenuItem2: TMenuItem;
    MenuItem3: TMenuItem;
    Image3: TImage;
    N24: TMenuItem;
    FetchSendMails1: TMenuItem;
    N25: TMenuItem;
    NewMessage2: TMenuItem;
    AddressBook2: TMenuItem;
    SearchMessage1: TMenuItem;
    SaveAs2: TMenuItem;
    SaveDialog1: TSaveDialog;
    N28: TMenuItem;
    Image5: TImage;
    N15: TMenuItem;
    AddtoAdressbook2: TMenuItem;
    Timer2: TTimer;
    QuickView2: TMenuItem;
    Image6: TImage;
    Image7: TImage;
    ImageList3: TImageList;
    DialUp1: TDialUp;
    EmptyRepository1: TMenuItem;
    EmptyRepository2: TMenuItem;
    StatusBar1: TStatusBarEx;
    Image9: TImage;
    PaintBox1: TPaintBox;
    Image4: TImage;
    actlMain: TActionList;
    actFileFetchSendMail: TAction;
    actFileCancelOnlineOperation: TAction;
    actFilePrint: TAction;
    actFilePrinterSetup: TAction;
    actFileExit: TAction;
    actEditUndo: TAction;
    actEditRedo: TAction;
    actEditCut: TAction;
    actEditCopy: TAction;
    actEditPaste: TAction;
    actEditDelete: TAction;
    actEditSelectAll: TAction;
    actAccountFetchMail: TAction;
    actAccountSendMail: TAction;
    actAccountNew: TAction;
    actAccountDelete: TAction;
    actAccountProperties: TAction;
    actFolderNew: TAction;
    actFolderDelete: TAction;
    actFolderProperties: TAction;
    actMessageNew: TAction;
    actMessageDelete: TAction;
    actMessageForward1: TAction;
    actMessageRedirect: TAction;
    actMessageReply1: TAction;
    actMessageReplyQuoted: TAction;
    actMessageAttOpen: TAction;
    actMessageAttCopy: TAction;
    actMessageAttQuickView: TAction;
    actMessageAttSaveAs: TAction;
    actMessageAttAddFile: TAction;
    actMessageAttDelete: TAction;
    actMessageSignature: TAction;
    actMessageToggleRead: TAction;
    actMessageAddToAddrbook: TAction;
    actMessageSearch: TAction;
    actMessageProperties: TAction;
    actEnhancedAddessBook: TAction;
    actEnhancedOptions: TAction;
    actHelpContents: TAction;
    actHelpTopOfDay: TAction;
    actHelpHomepage: TAction;
    actHelpAbout: TAction;
    imlToolbar: TImageList;
    N30: TMenuItem;
    Selectall3: TMenuItem;
    Redo2: TMenuItem;
    actUpdateStatusbar: TAction;
    actFileSaveAs: TAction;
    N20: TMenuItem;
    FileSaveAs: TMenuItem;
    EnvironmentOpions1: TMenuItem;
    CancelOnlineOperation2: TMenuItem;
    actMessageScanVirus: TAction;
    ScanforVirus1: TMenuItem;
    actMessageAttTextView: TAction;
    ViewwithTextviewer1: TMenuItem;
    N31: TMenuItem;
    N32: TMenuItem;
    actViewTBStandard: TAction;
    actViewTBMessage: TAction;
    actViewStatusbar: TAction;
    menView: TMenuItem;
    Toolbars1: TMenuItem;
    actViewTBStandard1: TMenuItem;
    actViewTBMessage1: TMenuItem;
    menViewStatusbar: TMenuItem;
    actFolderEmpty: TAction;
    N35: TMenuItem;
    EmptyFolder1: TMenuItem;
    EmptyFolder2: TMenuItem;
    actViewLastLog: TAction;
    imgOnline: TImage;
    actMessageAttViewWith: TAction;
    Viewwith1: TMenuItem;
    actFileFetchAll: TAction;
    actFileSendAll: TAction;
    Fetchall2: TMenuItem;
    Sendall2: TMenuItem;
    N38: TMenuItem;
    actMessageMove: TAction;
    actMessageCopy: TAction;
    N39: TMenuItem;
    N40: TMenuItem;
    Copyto2: TMenuItem;
    Moveto2: TMenuItem;
    actMessageAttPicView: TAction;
    ViewwithPictureviewer1: TMenuItem;
    menOrdneruebersicht: TMenuItem;
    N14: TMenuItem;
    Signature2: TMenuItem;
    NeueAdresse1: TMenuItem;
    Anlage1: TMenuItem;
    N44: TMenuItem;
    actEnhandedSearchName: TAction;
    actEditSearch: TAction;
    FindDialog: TFindDialog;
    Suchen2: TMenuItem;
    N45: TMenuItem;
    N46: TMenuItem;
    actEditReverse: TAction;
    Rckwrts1: TMenuItem;
    SendenEmpfangen1: TMenuItem;
    actViewTBSendReceive: TAction;
    SignaturManager1: TMenuItem;
    Addessbook1: TMenuItem;
    EMailsuchen2: TMenuItem;
    N47: TMenuItem;
    PopupMenuSendR: TPopupMenu;
    EMailsfraktPostfachKontoempfangen1: TMenuItem;
    EMailsvonaktPostfachKontosenden1: TMenuItem;
    N49: TMenuItem;
    Alleempfangen1: TMenuItem;
    Allesenden1: TMenuItem;
    ViewMessage: TMenuItem;
    actMessageQuickView: TAction;
    Schnellansicht1: TMenuItem;
    actFileSave: TAction;
    N50: TMenuItem;
    N51: TMenuItem;
    Classic1: TMenuItem;
    actViewTBClassic: TAction;
    Adressesuchen2: TMenuItem;
    actMessageMakeEditable: TAction;
    actViewTest: TAction;
    actAccountSetAsDefault: TAction;
    PopDefault: TMenuItem;
    actAccountShowDefault: TAction;
    Standardanzeigen2: TMenuItem;
    N52: TMenuItem;
    AddLabel: TMenuItem;
    CLabel1: TMenuItem;
    CLabel2: TMenuItem;
    actMessageReplyToAll1: TAction;
    menReplyAll: TMenuItem;
    popReplytoAllRE: TMenuItem;
    actEditPasteasQuote: TAction;
    Pasteasquote2: TMenuItem;
    ActEditDeleteLine: TAction;
    CLabel0: TMenuItem;
    N53: TMenuItem;
    CLabel3: TMenuItem;
    CLabel4: TMenuItem;
    CLabel5: TMenuItem;
    CLabel6: TMenuItem;
    CLabel7: TMenuItem;
    N54: TMenuItem;
    Changelabel1: TMenuItem;
    MLabel0: TMenuItem;
    MLabel1: TMenuItem;
    MLabel2: TMenuItem;
    N55: TMenuItem;
    MLabel3: TMenuItem;
    MLabel4: TMenuItem;
    MLabel5: TMenuItem;
    MLabel6: TMenuItem;
    MLabel7: TMenuItem;
    actViewToDoList: TAction;
    N56: TMenuItem;
    ToDolist1: TMenuItem;
    ToDoList: TMenuItem;
    N57: TMenuItem;
    CLabel8: TMenuItem;
    CLabel9: TMenuItem;
    N58: TMenuItem;
    MLabel8: TMenuItem;
    MLabel9: TMenuItem;
    actMessageTemplate: TAction;
    Salutation1: TMenuItem;
    menFileImport: TMenuItem;
    N59: TMenuItem;
    OpenDialog2: TOpenDialog;
    actMessageAdvanced: TAction;
    RetrieveSendmailfromselectedaccount1: TMenuItem;
    Alleempfangensenden2: TMenuItem;
    imlStateIcons: TImageList;
    actMessageQueue: TAction;
    N61: TMenuItem;
    Markasunqueuedqueued1: TMenuItem;
    Markasunqueuedqueued2: TMenuItem;
    actAccountFetchSendMail: TAction;
    actAccountPauseScheduler: TAction;
    actEnhancedToolBars: TAction;
    N63: TMenuItem;
    Customizetoolbars1: TMenuItem;
    actMessageSendSelected: TAction;
    Sendselectednow1: TMenuItem;
    Sendselectednow2: TMenuItem;
    actMessageAttProperties: TAction;
    N65: TMenuItem;
    Properties7: TMenuItem;
    menMailHeaders: TMenuItem;
    actNavigationUp: TAction;
    actNavigationDown: TAction;
    actNavigationBack: TAction;
    actNavigationForward: TAction;
    N21: TMenuItem;
    Navigation1: TMenuItem;
    GoBack1: TMenuItem;
    GoForward1: TMenuItem;
    N26: TMenuItem;
    PreviousMessage1: TMenuItem;
    NextMessage1: TMenuItem;
    Navigation2: TMenuItem;
    PreviousMessage2: TMenuItem;
    NextMessage2: TMenuItem;
    N67: TMenuItem;
    GoBack2: TMenuItem;
    GoForward2: TMenuItem;
    timerTree: TTimer;
    actEnhSaveToolbarImages: TAction;
    actMessageShowHeaders: TAction;
    N68: TMenuItem;
    Viewrawmessage1: TMenuItem;
    N69: TMenuItem;
    Viewrawmessage2: TMenuItem;
    ToolbarImages: TImageList;
    Newfolder3: TMenuItem;
    Deletefolder3: TMenuItem;
    Folderproperties2: TMenuItem;
    N1: TMenuItem;
    PanelOrdneruebersicht: TPanel;
    Splitter1: TSplitter;
    Panel1: TPanel;
    PanelNewsText: TPanel;
    RichEdit1: TRichEdit98;
    lbRecentMessage: TPMListBox;
    PanelTop: TPanel;
    Image8: TImage;
    Image10: TImage;
    ListView1: TdfsExtListView;
    Splitter4: TSplitter;
    ListView2: TListView;
    PopupMenu2: TPopupMenu;
    Open1: TMenuItem;
    QuickView1: TMenuItem;
    actMessageAttTextView1: TMenuItem;
    ViewwithPictureviewer2: TMenuItem;
    Viewwith2: TMenuItem;
    N34: TMenuItem;
    Saveas1: TMenuItem;
    SaveAs3: TMenuItem;
    N33: TMenuItem;
    ScanforVirus3: TMenuItem;
    N7: TMenuItem;
    Add1: TMenuItem;
    Delete3: TMenuItem;
    Saveas4: TMenuItem;
    N64: TMenuItem;
    Properties6: TMenuItem;
    Image11: TImage;
    ImageListForAttach: TImageList;
    menFind: TMenuItem;
    menSearchAddressbook: TMenuItem;
    menFindEmail: TMenuItem;
    N81: TMenuItem;
    menCopyto: TMenuItem;
    menMoveto: TMenuItem;
    N17: TMenuItem;
    menDeleteEmail: TMenuItem;
    N82: TMenuItem;
    Nfolder: TMenuItem;
    NEmail: TMenuItem;
    N41: TMenuItem;
    N83: TMenuItem;
    N84: TMenuItem;
    Newfolder: TMenuItem;
    Deletefolder9: TMenuItem;
    N60: TMenuItem;
    menProperties1: TMenuItem;
    N85: TMenuItem;
    ToggleReadUnread1: TMenuItem;
    menSelectAll: TMenuItem;
    N87: TMenuItem;
    N88: TMenuItem;
    menDelete: TMenuItem;
    PopupMenu7: TPopupMenu;
    N90: TMenuItem;
    Receiveall2: TMenuItem;
    Sendall3: TMenuItem;
    menRetrieveSendall2: TMenuItem;
    PopupMenu8: TPopupMenu;
    PopSearchAddressbook: TMenuItem;
    menFindEmail2: TMenuItem;
    PopupMenu9: TPopupMenu;
    N36: TMenuItem;
    N43: TMenuItem;
    N92: TMenuItem;
    ImageListForEnable: TImageList;
    ImageListForDisable: TImageList;
    PopupMenu10: TPopupMenu;
    menSaveAttach: TMenuItem;
    menCancelOnlineOperation1: TMenuItem;
    menMailLetter: TMenuItem;
    ImageListForTree: TImageList;
    CoolBar1: TCoolBar;
    ToolBar1: TToolBar;
    ToolButton1: TToolButton;
    btnReply: TToolButton;
    btnReplyToAll: TToolButton;
    btnReplyF: TToolButton;
    ToolButton10: TToolButton;
    BtnPrint: TToolButton;
    btnDelete: TToolButton;
    ToolButton11: TToolButton;
    ToolbarButton9746: TToolButton;
    ToolButton12: TToolButton;
    ToolbarButton9731: TToolButton;
    ToolButton9: TToolButton;
    N27: TMenuItem;
    menSendR: TMenuItem;
    N3: TMenuItem;
    S2: TMenuItem;
    R1: TMenuItem;
    menRetrieveSendall: TMenuItem;
    N42: TMenuItem;
    menAddressbook: TMenuItem;
    D1: TMenuItem;
    N48: TMenuItem;
    menSettings: TMenuItem;
    N37: TMenuItem;
    R2: TMenuItem;
    E1: TMenuItem;
    N86: TMenuItem;
    menPre: TMenuItem;
    menNextMail: TMenuItem;
    Panel3: TPanel;
    menFileHead: TMenuItem;
    Label5: TLabel;
    Label4: TLabel;
    ImageList4: TImageList;
    PanelNewsTextCaption: TPanel;
    Label1: TLabel;
    ASpeedButton1: TSpeedButton;
    lblSubject: TSpeedButton;
    PopupMenu11: TPopupMenu;
    MenuItem1: TMenuItem;
    MenuItem4: TMenuItem;
    MenuItem5: TMenuItem;
    MenuItem6: TMenuItem;
    MenuItem7: TMenuItem;
    MenuItem8: TMenuItem;
    MenuItem9: TMenuItem;
    MenuItem10: TMenuItem;
    MenuItem11: TMenuItem;
    MenuItem12: TMenuItem;
    MenuItem13: TMenuItem;
    menAccount: TMenuItem;
    menNewAccount: TMenuItem;
    menDeleteAccount: TMenuItem;
    menSetdefaultAccount: TMenuItem;
    GotodefaultAccount1: TMenuItem;
    N2: TMenuItem;
    P1: TMenuItem;
    menSyc: TMenuItem;
    N71: TMenuItem;
    Panel4: TPanel;
    Panel5: TPanel;
    LblImageTitle: TLabel;
    Image12: TImage;
    PanelHeaders: TPanel;
    Label3: TLabel;
    lblf: TLabel;
    Label8: TLabel;
    outSpeedButton1: TSpeedButton;
    SpeedButton5: TSpeedButton;
    SpeedButton6: TSpeedButton;
    SpeedButton2: TSpeedButton;
    LblT: TLabel;
    lblfrom: TLabel;
    lblto: TLabel;
    lblsubject1: TLabel;
    fldFromHeader: TPMComboBox;
    fldAddresses: TPMComboBox;
    fldSubject: TPMComboBox;
    Panel2: TPanel;
    SpeedButton1: TToolbarButton97;
    popReplyF: TMenuItem;
    Image13: TImage;
    Image14: TImage;
    Image15: TImage;
    Image16: TImage;
    Internet1: TMenuItem;
    E2: TMenuItem;
    OutlookExpressO1: TMenuItem;
    Image17: TImage;
    pnlAccount: TPanel;
    Treeview1: TPMTreeview;
    Splitter2: TSplitter;
    PanelFolderCaption: TPanel;
    Image1: TImage;
    lblLabelFolderPanel: TLabel;
    ToolBar2: TToolBar;
    ToolButton2: TToolButton;
    PnlAddress: TPanel;
    TreeviewAsso: TPMTreeview;
    PnlAssociation: TPanel;
    Image18: TImage;
    Lblacco: TLabel;
    ToolBar3: TToolBar;
    ToolButton3: TToolButton;
    ImgLstForAddress: TImageList;
    menAddress: TMenuItem;
    Timer3: TTimer;
    DHTMLEdit1: TDHTMLEdit;
    PopRename: TMenuItem;
    PopFind: TMenuItem;
    PopEmpty: TMenuItem;
    PopOpen: TMenuItem;
    procedure FormCreate(Sender: TObject);

    //TODO -oMjg:created by mjg
    procedure UpdateCursorPos;
    procedure TreeView1Deletion(Sender: TObject; Node: TTreeNode);
    procedure Enhanced1Click(Sender: TObject);
    procedure EmptyTrashBin1Click(Sender: TObject);
    procedure TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure TreeView1DragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure PopPropertiesClick(Sender: TObject);
    procedure PopupMenu1Popup(Sender: TObject);
    procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Timer1Timer(Sender: TObject);
    procedure ListView1DrawHeader(Control: TWinControl;
      var ACanvas: TCanvas; Index: Integer; var ARect: TRect;
      Selected: Boolean; var DefaultDrawing: Boolean);
    procedure ShowPhoenixMail1Click(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure TreeView1Compare(Sender: TObject; Node1, Node2: TTreeNode;
      Data: Integer; var Compare: Integer);
    procedure Timer2Timer(Sender: TObject);
    procedure StatusBar1DrawPanel(StatusBar: TStatusBar;
      Panel: TStatusPanel; const Rect: TRect);
    procedure DialUp1StatusEvent(Sender: TObject; MessageText: string;
      Error: Boolean);
    procedure EmptyRepository1Click(Sender: TObject);
    procedure ASpeedButton1Click(Sender: TObject);
//    procedure RichEdit1URLClick(Sender: TObject; URL: string);
    procedure actFileFetchSendMailExecute(Sender: TObject);
    procedure actFileCancelOnlineOperationExecute(Sender: TObject);
    procedure actFilePrintExecute(Sender: TObject);
    procedure actFilePrinterSetupExecute(Sender: TObject);
    procedure actFileExitExecute(Sender: TObject);
    procedure actEditDeleteExecute(Sender: TObject);
    procedure actEditSelectAllExecute(Sender: TObject);
    procedure actFileFetchSendMailUpdate(Sender: TObject);
    procedure actFileCancelOnlineOperationUpdate(Sender: TObject);
    procedure actFilePrintUpdate(Sender: TObject);
    procedure actFilePrinterSetupUpdate(Sender: TObject);
    procedure actEditCutUpdate(Sender: TObject);
    procedure actEditCopyUpdate(Sender: TObject);
    procedure actEditPasteUpdate(Sender: TObject);
    procedure actEditDeleteUpdate(Sender: TObject);
    procedure actEditSelectAllUpdate(Sender: TObject);
    procedure actAccountFetchMailExecute(Sender: TObject);
    procedure actAccountSendMailExecute(Sender: TObject);
    procedure actAccountNewExecute(Sender: TObject);
    procedure actAccountDeleteExecute(Sender: TObject);
    procedure actAccountPropertiesExecute(Sender: TObject);
    procedure actAccountFetchMailUpdate(Sender: TObject);
    procedure actAccountNewUpdate(Sender: TObject);
    procedure actAccountDeleteUpdate(Sender: TObject);
    procedure actAccountPropertiesUpdate(Sender: TObject);
    procedure actFolderNewExecute(Sender: TObject);
    procedure actFolderDeleteExecute(Sender: TObject);
    procedure actFolderPropertiesExecute(Sender: TObject);
    procedure actFolderNewUpdate(Sender: TObject);
    procedure actFolderDeleteUpdate(Sender: TObject);
    procedure actFolderPropertiesUpdate(Sender: TObject);
    procedure actMessageNewExecute(Sender: TObject);
    procedure actMessageDeleteExecute(Sender: TObject);
    procedure actMessageForward1Execute(Sender: TObject);
    procedure actMessageRedirectExecute(Sender: TObject);
    procedure actMessageReply1Execute(Sender: TObject);
    procedure actMessageReplyQuotedExecute(Sender: TObject);
    procedure actMessageAttOpenExecute(Sender: TObject);
    procedure actMessageAttCopyExecute(Sender: TObject);
    procedure actMessageAttQuickViewExecute(Sender: TObject);
    procedure actMessageAttSaveAsExecute(Sender: TObject);
    procedure actMessageAttAddFileExecute(Sender: TObject);
    procedure actMessageAttDeleteExecute(Sender: TObject);
    procedure actMessageSignatureExecute(Sender: TObject);
    procedure actMessageToggleReadExecute(Sender: TObject);
    procedure actMessageSelectAllExecute(Sender: TObject);
    procedure actMessageAddToAddrbookExecute(Sender: TObject);
    procedure actMessageSearchExecute(Sender: TObject);
    procedure actMessagePropertiesExecute(Sender: TObject);
    procedure actMessageNewUpdate(Sender: TObject);
    procedure actMessageDeleteUpdate(Sender: TObject);
    procedure actMessageForward1Update(Sender: TObject);
    procedure actMessageRedirectUpdate(Sender: TObject);
    procedure actMessageReply1Update(Sender: TObject);
    procedure actMessageReplyQuotedUpdate(Sender: TObject);
    procedure actMessageAttOpenUpdate(Sender: TObject);
    procedure actMessageAttQuickViewUpdate(Sender: TObject);
    procedure actMessageToggleReadUpdate(Sender: TObject);
    procedure actMessageSelectAllUpdate(Sender: TObject);
    procedure actMessageAddToAddrbookUpdate(Sender: TObject);
    procedure actMessagePropertiesUpdate(Sender: TObject);
    procedure actMessageAttAddFileUpdate(Sender: TObject);
    procedure actUpdateStatusbarUpdate(Sender: TObject);
    procedure actEnhancedAddessBookExecute(Sender: TObject);
    procedure actEnhancedOptionsExecute(Sender: TObject);
    procedure actHelpContentsExecute(Sender: TObject);
    procedure actHelpTopOfDayExecute(Sender: TObject);
    procedure actHelpHomepageExecute(Sender: TObject);
    procedure actHelpAboutExecute(Sender: TObject);
    procedure PopupMenu6Popup(Sender: TObject);
    procedure ListView1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure actFileSaveAsUpdate(Sender: TObject);
    procedure actFileSaveAsExecute(Sender: TObject);
    procedure RichEdit1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure RichEdit1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FormShow(Sender: TObject);
    procedure FormHide(Sender: TObject);
    procedure actMessageScanVirusExecute(Sender: TObject);
    procedure actMessageScanVirusUpdate(Sender: TObject);
    procedure actMessageAttTextViewExecute(Sender: TObject);
    procedure actViewTBStandardUpdate(Sender: TObject);
    procedure actViewTBMessageUpdate(Sender: TObject);
    procedure actViewStatusbarUpdate(Sender: TObject);
    procedure actViewTBStandardExecute(Sender: TObject);
    procedure actViewTBMessageExecute(Sender: TObject);
    procedure actViewStatusbarExecute(Sender: TObject);
    procedure actMessageSignatureUpdate(Sender: TObject);
    procedure actFolderEmptyExecute(Sender: TObject);
    procedure actFolderEmptyUpdate(Sender: TObject);
    procedure ListView1SortBegin(Sender: TObject; SortColumn: Integer;
      Ascending: Boolean);
    procedure actViewLastLogUpdate(Sender: TObject);
    procedure actViewLastLogExecute(Sender: TObject);
    procedure ListView1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ListView2KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ListView2KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ListView1KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure TreeView1KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure actMessageAttTextViewUpdate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure actMessageAttViewWithExecute(Sender: TObject);
    procedure ListView2MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure actFileFetchAllExecute(Sender: TObject);
    procedure actFileSendAllExecute(Sender: TObject);
    procedure actMessageCopyExecute(Sender: TObject);
    procedure actMessageMoveExecute(Sender: TObject);
    procedure ListView2DblClick(Sender: TObject);
    procedure actMessageAttPicViewExecute(Sender: TObject);
    procedure actMessageAttPicViewUpdate(Sender: TObject);
    procedure NeuerKontakt1Click(Sender: TObject);
    procedure menOrdneruebersichtClick(Sender: TObject);
    procedure lblLabelFolderPanelDblClick(Sender: TObject);
    procedure InfoszudieserVersion1Click(Sender: TObject);
    procedure actEnhandedSearchNameExecute(Sender: TObject);
    procedure FindDialogFind(Sender: TObject);
    procedure actEditSearchUpdate(Sender: TObject);
    procedure actEditReverseUpdate(Sender: TObject);
    procedure actEditReverseExecute(Sender: TObject);
    procedure actViewTBSendReceiveUpdate(Sender: TObject);
    procedure actViewTBSendReceiveExecute(Sender: TObject);
    procedure ViewSomething(sFile: string);
    procedure actMessageQuickViewExecute(Sender: TObject);
    procedure actMessageQuickViewUpdate(Sender: TObject);
    procedure Label1DblClick(Sender: TObject);
    procedure actFileSaveUpdate(Sender: TObject);
    procedure actFileSaveExecute(Sender: TObject);
    procedure actViewTBClassicUpdate(Sender: TObject);
    procedure actViewTBClassicExecute(Sender: TObject);
    procedure actMessageMakeEditableExecute(Sender: TObject);
    procedure lblLabelFolderPanelClick(Sender: TObject);
    procedure RichEdit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure actViewTestExecute(Sender: TObject);
    procedure actAccountSetAsDefaultUpdate(Sender: TObject);
    procedure actAccountSetAsDefaultExecute(Sender: TObject);

    procedure UpdateRepository;
    procedure actMessageReplyToAll1Update(Sender: TObject);
    procedure actMessageReplyToAll1Execute(Sender: TObject);
    procedure actEditPasteasQuoteExecute(Sender: TObject);
    procedure actEditPasteasQuoteUpdate(Sender: TObject);
    procedure ActEditDeleteLineExecute(Sender: TObject);
    procedure ActEditDeleteLineUpdate(Sender: TObject);
    procedure CLabel0DrawItem(Sender: TObject; ACanvas: TCanvas;
      ARect: TRect; Selected: Boolean);
    procedure ListView1DrawItem(Control: TWinControl; var ACanvas: TCanvas;
      Index: Integer; ARect: TRect; State: TOwnerDrawState;
      var DefaultDrawing, FullRowSelect: Boolean);
    procedure ListView1DrawSubItem(Control: TWinControl;
      var ACanvas: TCanvas; Index, SubItem: Integer; ARect: TRect;
      State: TOwnerDrawState; var DefaultDrawing: Boolean);
    procedure CLabel0Click(Sender: TObject);
    procedure CLabel0MeasureItem(Sender: TObject; ACanvas: TCanvas;
      var Width, Height: Integer);
    procedure actViewToDoListUpdate(Sender: TObject);
    procedure actViewToDoListExecute(Sender: TObject);
    procedure actMessageTemplateExecute(Sender: TObject);
    procedure actMessageTemplateUpdate(Sender: TObject);
    procedure menFileImportClick(Sender: TObject);
    procedure actMessageAdvancedExecute(Sender: TObject);
    procedure actAccountFetchSendMailExecute(Sender: TObject);
    procedure actMessageQueueExecute(Sender: TObject);
    procedure actMessageQueueUpdate(Sender: TObject);
    procedure RichEdit1Exit(Sender: TObject);
    procedure Label4DblClick(Sender: TObject);
    procedure Treeview1WndCreate(Sender: TObject; var St: TMemoryStream;
      anode: TTreeNode);
    procedure Treeview1WndDestroy(Sender: TObject; var St: TMemoryStream;
      anode: TTreeNode);
    procedure ListView1MeasureItem(Control: TWinControl;
      var AHeight: Cardinal);
    procedure ListView1AfterDefaultDrawItem(Control: TWinControl;
      var ACanvas: TCanvas; Index: Integer; ARect: TRect;
      State: TOwnerDrawState);
    procedure actAccountPauseSchedulerUpdate(Sender: TObject);
    procedure actEnhancedToolBarsExecute(Sender: TObject);
    procedure actMessageSendSelectedUpdate(Sender: TObject);
    procedure actMessageSendSelectedExecute(Sender: TObject);
    procedure menPopupMenu3Popup(Sender: TObject);
    procedure actMessageAttPropertiesUpdate(Sender: TObject);
    procedure actMessageAttPropertiesExecute(Sender: TObject);
    procedure outSpeedButton1Click(Sender: TObject);
    procedure fldFromHeaderEnter(Sender: TObject);
    procedure fldFromHeaderExit(Sender: TObject);
    procedure fldFromHeaderChange(Sender: TObject);
    procedure SpeedButton2Click(Sender: TObject);
    procedure SpeedButton5Click(Sender: TObject);
    procedure SpeedButton6Click(Sender: TObject);
    procedure lbRecentMessageMouseLeave(Sender: TObject);
    procedure lbRecentMessageClick(Sender: TObject);
    procedure menMailHeadersClick(Sender: TObject);
    procedure lblSubjectClick(Sender: TObject);
    procedure actNavigationUpExecute(Sender: TObject);
    procedure actNavigationDownExecute(Sender: TObject);
    procedure actNavigationUpUpdate(Sender: TObject);
    procedure actNavigationDownUpdate(Sender: TObject);
    procedure actNavigationBackExecute(Sender: TObject);
    procedure actNavigationBackUpdate(Sender: TObject);
    procedure actNavigationForwardExecute(Sender: TObject);
    procedure actNavigationForwardUpdate(Sender: TObject);
    procedure timerTreeTimer(Sender: TObject);
    procedure PanelNewsTextResize(Sender: TObject);
    procedure lbRecentMessageMouseMove(Sender: TObject; Shift: TShiftState;
      X, Y: Integer);
    procedure actEnhSaveToolbarImagesExecute(Sender: TObject);
    procedure actMessageShowHeadersExecute(Sender: TObject);
    procedure actMessageShowHeadersUpdate(Sender: TObject);
    procedure DHTMLEdit1DocumentComplete(Sender: TObject);
    procedure ListView1Exit(Sender: TObject);
    procedure Treeview1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure ListView1DblClick(Sender: TObject);
    procedure actAccountShowDefaultExecute(Sender: TObject);
    procedure btnReplyClick(Sender: TObject);
    procedure btnReplyFClick(Sender: TObject);
    procedure btnReplyToAllClick(Sender: TObject);
    procedure BtnPrintClick(Sender: TObject);
    procedure menSelectAllClick(Sender: TObject);
    procedure N87Click(Sender: TObject);
    procedure N88Click(Sender: TObject);
    procedure menDeleteClick(Sender: TObject);
    procedure myclick(Sender: TObject);
    procedure myLetterclick(Sender: TObject);
    procedure myAccountclick(Sender: TObject);
    procedure ListView1Change(Sender: TObject; Item: TListItem;
      Change: TItemChange);
    procedure btnDeleteClick(Sender: TObject);
    procedure ToolbarButton9731Click(Sender: TObject);
    procedure ToolButton9Click(Sender: TObject);
    procedure ToolButton1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure PopupMenu10Popup(Sender: TObject);
    procedure menSaveAttachClick(Sender: TObject);
    procedure E1Click(Sender: TObject);
    procedure menFileHeadClick(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure menReplayClick(Sender: TObject);
    procedure popReplayClick(Sender: TObject);
    procedure menReplyAllClick(Sender: TObject);
    procedure menForwardClick(Sender: TObject);
    procedure popForwardClick(Sender: TObject);
    procedure popReplytoAllREClick(Sender: TObject);
    procedure popReplyFClick(Sender: TObject);
    procedure Internet1Click(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure menAddressClick(Sender: TObject);
    procedure Timer3Timer(Sender: TObject);
    procedure Treeview1CustomDraw(Sender: TCustomTreeView;
      const ARect: TRect; var DefaultDraw: Boolean);
    procedure PopRenameClick(Sender: TObject);
    procedure Treeview1Edited(Sender: TObject; Node: TTreeNode;
      var S: String);
    procedure PopFindClick(Sender: TObject);
  private
    { Private declarations }
    TEIgnoreChange : boolean;
    DocComplete : boolean;
    FUpdating: Boolean;
    MinutesSinceStart, AnimationPosition: Integer;
    AreWeOnline, AnimationToLeft: Boolean;
    BKAttachments1, BKAttachments2: TStringList;
    Label4IsProcessing : Boolean; // AH15
    DragDropDefWndProc, DragDropWndProcInstance: Pointer;
    ReadCounter: Integer;


    CommandTarget : IOleCommandTarget;
    DOMInterface : IHtmlDocument2;


    procedure GetFontNames;
    function CurrText: TTextAttributes98;
    procedure DragDropWndProc(var Message: TMessage);
    procedure DragDropFiles(hDropHandle: HDrop);
    procedure WMTaskIcon(var Message: TMessage); message WM_TASKICON;
    procedure WMSysCommand(var Message: TMessage); message WM_SYSCOMMAND;

    procedure SaveAccountDataToFile(Data: PAccountData);
    procedure SaveFolderDataToFile(Data: PFolderData);
    procedure ActualizeTrash;
    procedure BackupAttachments;
    procedure RestoreAttachments;

    procedure CreateSpikesGradientBitmap(StartPos: Integer; var GBitmap:
              TBitmap);
    procedure CreateRadarGradientBitmap(StartPos: Integer; var GBitmap:
              TBitmap);
    procedure CreateCircleGradientBitmap(StartPos: Integer; var GBitmap:
              TBitmap);
    procedure ReloadDefault;
    procedure ReloadBall;
    procedure ReloadRadar;
    procedure ReloadSpikes;
    procedure DoAnimation(Mode : Integer);
    procedure DoNormalPath;
    procedure DoNoBumpPath;

    procedure UpdateMainForm;

    procedure EnablePopUpMenu(AEnabled: boolean);
    procedure AddToAddressBook;
    procedure AppIdle(Sender: TObject; var Done: Boolean);
    procedure AppIdleDiposit(Sender: TObject; var Done: Boolean);
    procedure AppException(Sender: TObject; E: Exception);

    procedure DeleteMessageForEver;
    function ConfirmDelete(APermanent: boolean): boolean;

    procedure EmptyTrash;
    procedure EmptyReposit;

    procedure ViewAttachment(AProg: string);

    procedure SetFlatStyle;
    procedure AutoMarkReplied; //RR26
    procedure AutoMarkSent; //RR26
  public
    { Public declarations }

    NotifyIconData: TNotifyIconData;
    TrayIcon: HIcon;
    iColumn:integer;

    DefaultFont : TFont;
    Terminating, OnlineThreadTerminated, ReadyToClose, SocketConnecting,
    HeaderChanged : Boolean;
    OnlineThreadCounter: Integer;
    GradientBmp, AniBmp1, AniBmp2: TBitmap;
    procedure SendReceipt(AFrom,ATo,ASubject,ADetail:string);
    procedure RefreshListview;
    procedure GetSubNotes(KNode: TTreeNode);
    procedure GetSubNotesDrafts(KNode: TTreeNode);
    procedure CreateViewMail;
    procedure ScanForAccounts(TreeView: TTreeView);
    function OpenFileWithDoubleExtension(FileName: string): Boolean;
    procedure AddAttachment(aFilename: string);
    function ReadTxtFile(FileName:string):string;
    procedure DoSynchSearch(old, new : string); // AHRK34
    procedure ReplyEmail(ReplyQuote, ReplyAll : Boolean);
    procedure DoEmailReply(var AnEmail : TEmail; DoAll : Boolean);
    function NewEmail(ShowDlg, Signature : Boolean; AnEmail : TEMail;
      NewText : TStringList) : boolean;
    procedure FwdRedEmail(DoForward : Boolean);
    // AH16.A
    function NewTemplate : Boolean;    // AH03
    function NewMessage(ShowDlg, Signat: Boolean; ASubject, ATo, AFrom: string;
      NewText: TStringList): Boolean;
    function OnlineSelectedCount(Node : TTreeNode;
      var TheCommandList : TStringList) : integer; // AHRK74

    procedure OnlineSession(OnlineTyp: TOnlineTyp); // AH03 Moved from Private to Public...
    procedure AppMinimize(Sender: TObject);
    function GetActualAccount: TTreeNode;
    function GetActiveAccount(Anode : TTreeNode) : TTreeNode; //AHRK85..
    function GetUniqueAccountFolder(Name: string): string;
    procedure UpdateListView(AddToHistory : Boolean = True);
    procedure DoMergeStationary(showDialog : Boolean; apath : string; PrevNode : TTreeNode);
    function MergeNewStationary(afilename : string; Node : TTreeNode) : boolean;
    function GetServerStatus(aDoSmtp, aDoPop3 : byte) : integer; // AH09
    procedure SetServerStatus(var Node : TTreeNode; aninteger : integer); // AH09
    procedure MoveQueuedFromDraft(const Node : TTreeNode); //AH13

    function DrawItemColours(index : integer; State : TOwnerDrawState;
      var BrushColor, FontColor : TColor) : integer;
    procedure DoAToolBar(aname : string; tsl : TStringList;
      var NumControls : Word);
    procedure DoLoadToolBars(aFile : TIniFile);
    procedure DoSaveToolBars(afile : TIniFile);
    procedure DoFormDecorations(sender : TObject); //AH16
    procedure CustomMenuToolBarClick(Sender : TObject); // For custom toolbars
    procedure SetPanelHeadersFields(Editable : Boolean); // These just tap the global TEmail.
    procedure SetFldAddresses;
    procedure EnableHeaderFields(aboolean : boolean);
    procedure SetFieldBorders(Editable : Boolean);
    procedure CollectAccountsEmail(PStr : TStrings);
    procedure EnableHeaderButtons;
    function CurrentAddressField : TStringList;
    procedure NavigateTo(AnIndex : Integer);
  protected
    procedure WndProc(var Message: TMessage); override;
  end;

var
  MainForm: TMainForm;
  F:text;
  ActualMailFile: string;
  AddressMode : Byte;

const
    sColRowInfo = 'Line: %3d   Col: %3d';

implementation

{$R *.DFM}

uses
  parserSup,
  ELVSup, Variants,
  DropSource, FMTemplate, FMSearchX, DateSup,hedform,
  pmclasses, FMToDoEx, FMCustomizer, AccountStep1, AccountStep, ViewMail,
  ShowError, NewFold, SearchMail, Rename; //AHRJ01 Added Datesup


var
  TextFile: Text;
   NilVariant : OleVariant;



procedure TMainForm.FormCreate(Sender: TObject);
var
  SHFileInfo: TSHFileInfo;
  I, E: Integer;
  IniFile: TIniFile;
  iLastFolder: integer;
  SList : TStringList; // AH06
  INode,AddressNode : TTreeNode;   // AH06
  s,tmpFileName : string;
  aColumns : array of integer; // AH16
  SearchRec: TSearchRec;
  Found: Integer;
  NewItem: TMenuItem;
  Node: TTreeNode;
  dd:string;
begin
  CoInitialize(nil);
  Caption := Application.Title;
  Icon := Application.Icon;
  MinutesSinceStart := 0;
  AreWeOnline := False;
  Terminating := False;
  ActiveAccount := nil;
  AddressInfo:=TstringList.Create;
  IniFile := TIniFile.Create(sSettingsFile);
  DoLoadToolBars(IniFile);
  IniLoadToolbarPositions(Self, sSettingsFile, 'Toolbars');

  LoadHelperFromIni(TreeView1, IniFile);
  DefaultFont := TFont.Create;
  LoadHelperFromIni(RichEdit1, IniFile);
  DefaultFont.Assign(RichEdit1.Font);
  PanelHeaders.Color := clBtnFace;
  Label3.Font.Color := RichEdit1.Font.Color;
  Label8.Font.Color := RichEdit1.Font.Color;
  fldAddresses.Color := RichEdit1.Color;
  fldFromHeader.Color := RichEdit1.Color;
  fldSubject.Color := RichEdit1.Color;
  fldAddresses.Font.Color := RichEdit1.Font.Color;
  fldFromHeader.Font.Color := RichEdit1.Font.Color;
  fldFromHeader.BorderColor := RichEdit1.Color;
  fldAddresses.BorderColor := RichEdit1.Color;
  fldSubject.BorderColor := RichEdit1.Color;
  fldSubject.Font.Color := RichEdit1.Font.Color;
  lbRecentMessage.Color := RichEdit1.Color;
  lbRecentMessage.Font.Color := RichEdit1.Font.Color;



 //TODO -OMjg:set information of mailbox
  sAccountsCaption := GetMessageString(0);
  sTrashBagCaption := GetMessageString(1);
  sRepositoryCaption := GetMessageString(2);
  sStationaryCaption :=GetMessageString(97);


  if fileExists(GetAppPath + 'PMFolder.BMP') then
    ImageList1.FileLoad(rtBitmap, GetAppPath + 'PMFolder.BMP', clFuchsia) else
    ImageList1.ResourceLoad(rtBitmap, 'PX500', clFuchsia);

  if fileExists(GetAppPath + 'PMToolbar.BMP') then
  begin
    imlToolbar.Clear;
    imlToolbar.FileLoad(rtBitmap, GetAppPath + 'PMToolbar.BMP', clFuchsia);
  end;
  ImageList3.ResourceLoad(rtBitmap, 'PX505', clNone);
  ImageList1.Overlay(20, 0);
  ImageList1.Overlay(26, 1);
  /// These will only be set when resetting computer for now...
  ImageList2.Handle := SHGetFileInfo('', 0, SHFileInfo,
    SizeOf(SHFileInfo),  SHGFI_SYSICONINDEX or iLV2Icons);

  ///////////////////
  ScanForAccounts(TreeView1);

  CollectAccountsEmail(fldFromHeader.Items);
  ActualMailFile := '';
  BKAttachments1 := TStringList.Create;
  BKAttachments2 := TStringList.Create;


  SetLength(aColumns, ListView1.Columns.Count);
  s := IniFile.ReadString('MessageList', 'ColumnOrder', '');
  if pos(',', s) <> 0 then
  begin
    for i := 0 to ListView1.Columns.Count-1 do
    begin
      e := Pos(',', s);
      if e = 0 then e := Length(s)+1;
      acolumns[i] := StrToInt(Copy(s, 1, e-1));
      s := copy(s, e+1, length(s));
      if s = '' then break;
    end;
    ListView1.SetColumnOrder(ListView1.Columns.Count, aColumns); // AH16
  end;

  AColumns := nil;

  // RR04g moved after columnreading...
  ELVReadSettingsFromIniFile(ListView1, 'MessageList', IniFile);
  Statusbar1.Visible := IniFile.ReadBool('View', 'Statusbar',
    true);
  PopupMenu2.Items[iDoubleClickAction].Default := true;

  //Control positions
  Label4.Caption := '';
  Label4.Left := StatusBar1.Panels[0].Width + StatusBar1.Panels[1].Width +6;
  //Label5.Caption := GetMessageString(34);   mjg
  //StatusBar1.Panels[2].Text := GetMessageString(34); //断线
 // Label5.Left := StatusBar1.Panels[0].Width + StatusBar1.Panels[1].Width +
  //  StatusBar1.Panels[2].Width + 22;
  PaintBox1.Left := Label4.Left - 2;
  PaintBox1.Width := StatusBar1.Panels[2].Width - 7;

  label5.Left:=StatusBar1.Panels[0].Width+StatusBar1.Panels[2].Width;
  // AH16 Processing of gradient moved to UpdateForm
  UpdateMainForm;
  //AH16
  AniBmp1 := TBitmap.Create;
  AniBmp2 := TBitmap.Create;
  //AH15
  case iAnimation of
  0 : ReloadDefault;
  1 : ReloadBall;
  2 : ReloadRadar;
  3 : ReloadSpikes;
  end;
  //AH15
  // Tray icon
  SHGetFileInfo(PChar(Application.Exename), 0, SHFileInfo, SizeOf(SHFileInfo),
    SHGFI_ICON or SHGFI_SMALLICON);
  TrayIcon := SHFileInfo.hIcon;
  with NotifyIconData do begin
    cbSize := SizeOf(TNotifyIconData);
    Wnd := Handle;
    uID := 0;
    uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP;
    hIcon := TrayIcon;
    StrPCopy(szTip, 'SMAIL');
    uCallbackMessage := WM_TASKICON;
  end;
  if bStartMin then
    Shell_NotifyIcon(NIM_ADD, @NotifyIconData);

  // Explorer Drag Drop
  DragDropWndProcInstance := MakeObjectInstance(DragDropWndProc);
  DragDropDefWndProc := Pointer(GetWindowLong(ListView2.Handle, GWL_WNDPROC));
  SetWindowLong(ListView2.Handle, GWL_WNDPROC,
    LongInt(DragDropWndProcInstance));
  DragAcceptFiles(ListView2.Handle, True);
  with DialUp1.LangStrList do begin
    Clear;
    Add(GetMessageString(64));
    Add(GetMessageString(65));
    Add(GetMessageString(87));
  end;

{  EmptyTrashBin1.Caption := Format(GetMessageString(84),
    [GetPXTreeNodeName(TrashNode)]);
  EmptyTrashBin2.Caption := Format(GetMessageString(84),
    [GetPXTreeNodeName(TrashNode)]);
  EmptyRepository1.Caption := Format(GetMessageString(85),
    [GetPXTreeNodeName(RepositoryNode)]);
  EmptyRepository2.Caption := Format(GetMessageString(85),
    [GetPXTreeNodeName(RepositoryNode)]);
 }

  SetFlatStyle;

  Application.OnMinimize := AppMinimize;
  if Length(sWriteNewMessage1) > 0 then
    Application.OnIdle := AppIdle;
  Application.OnException := AppException;

  //Timer
  OnlineThreadTerminated := False;
  OnlineThreadCounter := 0;
  Timer1.Enabled := True;
  Timer2.Enabled := True;
  timerTree.Interval := IniFile.ReadInteger('Settings', 'DragDropIntervalMsec',
    100);

  SList := TStringList.Create;
  SList.CommaText := IniFile.ReadString('Settings', 'OpenedFolders', '');
  INode := TreeView1.Items.GetFirstNode;
  if INode <> nil then
  begin
    INode.Expanded := true;
    INode := INode.getFirstChild;
    while INode <> nil do
    begin
      if (SList.IndexOf(IntToStr(INode.AbsoluteIndex)) <> -1) then
      begin
        INode.Expanded := True;
      end;
      INode := Inode.getNext; // AHRK29
    end;
  end;
  SList.Free;

  if bShowDefaultAccount then actAccountShowDefaultExecute(self) else
  begin
    iLastFolder := IniFile.ReadInteger('Settings', 'LastFolderIndex', 0);
    // AHRK155...
    if (iLastFolder > -1) and (iLastFolder < TreeView1.Items.Count) then
    begin
      with TreeView1.Items[iLastFolder] do
      begin
        Selected := True;
        Focused := True;
      end;
    end
  end;



  PanelHeaders.Visible :=
    IniFile.ReadBool('Settings', 'PanelHeaderShown', True);
  menMailHeaders.Checked := PanelHeaders.Visible;

  IniFile.Free;
  // AH Load data from messagefile...
  Label3.Caption := GetMessageString(52) + ':';
  // AH14 END --- Moved and rearranged...
  actNavigationBack.ShortCut := TextToShortCut('Alt+Left');
  actNavigationForward.ShortCut := TextToShortCut('Alt+Right');
  GetFontNames;

  Screen.OnActiveFormChange := DoFormDecorations;



  i:=0;
  Found := FindFirst(sTemplateFolder+'\images\'+'*.jpg', faAnyFile, SearchRec);
  while Found = 0 do begin
    i:=i+1;
    NewItem:=TMenuItem.Create(self);
    NewItem.Caption:='&'+inttostr(i)+' '+copy(SearchRec.Name,1,(pos('.',SearchRec.Name)-1));
    NewItem.OnClick := myLetterclick;
    PopupMenu10.Items.Add(NewItem);
    Found := FindNext(SearchRec);
  end;
  FindClose(SearchRec);

  i:=0;
  Found := FindFirst(sTemplateFolder+'\images\'+'*.jpg', faAnyFile, SearchRec);
  while Found = 0 do begin
    i:=i+1;
    NewItem:=TMenuItem.Create(self);
    NewItem.Caption:='&'+inttostr(i)+' '+copy(SearchRec.Name,1,(pos('.',SearchRec.Name)-1));
    menMailLetter.Add (NewItem);
    NewItem.OnClick := myLetterclick;
    Found := FindNext(SearchRec);
  end;
  FindClose(SearchRec);

  node:= nil;
  if AccountsNode<>nil then
    node:=AccountsNode.GetFirstChild;
  while node<>nil  do begin
    if Node.StateIndex = tnAccount then
        if node.Text=sDefaultAccount then dd:=node.Text+'(默认)' else dd:=node.Text;
    NewItem := TMenuItem.Create(nil);
    NewItem.Caption:=dd;
    menSendR.Add(NewItem);
    NewItem.AutoHotkeys:=maManual;
    NewItem.OnClick := myAccountclick;
    node:=AccountsNode.GetNextChild(node);
  end;


  node:= nil;
  if AccountsNode<>nil then
    node:=AccountsNode.GetFirstChild;
  while node<>nil  do begin
    if Node.StateIndex = tnAccount then
        if node.Text=sDefaultAccount then dd:=node.Text+'(默认)' else dd:=node.Text;
    NewItem := TMenuItem.Create(nil);
    NewItem.Caption:=dd;
    PopupMenu7.Items.Add(NewItem);
    NewItem.AutoHotkeys:=maParent;
    NewItem.OnClick := myAccountclick;
    node:=AccountsNode.GetNextChild(node);
  end;

end;


procedure TMainForm.AppException(Sender: TObject; E: Exception);
var
  cName: string;
begin
  if Sender is TControl then
    cName := ' ' + (Sender as TControl).Name;

  if cName <> ' PanelNewsText' then //kommt von Richedit1 wenn vor www das http:// fehlt
    Application.MessageBox(PChar('Unhandled Exception: ' + E.Message + CrLf +
      'Class: ' + Sender.ClassName + cName), PChar(sAppTitle), MB_ICONEXCLAMATION);

  // AH11 Bring Mouse back to life
  Screen.Cursor := crDefault;
  // AH11

end;



//TODO -oMJG:Scan account and fill the treeview1
procedure TMainForm.ScanForAccounts(TreeView: TTreeView);
var
  SearchRec: TSearchRec;
  Found, Level: Integer;
  Node: TTreeNode;
  F: TINIFile;
  AccountData: PAccountData;
  I, iTask,j : Integer;  //AH09, ITask added
  FolderData: PFolderData;
  FNode,TempNode: TTreeNode;
//  dir:string;

  procedure RecurseDirs(Dir: string);
  var
    i: Integer;
    FNode,TempNode: TTreeNode;
  begin
       TempNode:=Node;
      ////////////////////inbox/////////////////
      F := TINIFile.Create(Dir + '\Account.ini');
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := GetMessageString(5);
      FolderData^.Outbox := F.ReadBool(GetMessageString(5), 'Outbox', False);
      FolderData^.Inbox := F.ReadBool(GetMessageString(5), 'Inbox', False);
      FolderData^.Drafts := F.ReadBool(GetMessageString(5), 'Drafts', False);
      FolderData^.Filter := F.ReadString(GetMessageString(5), 'TakeIn', '');
      F.Free;
      while Node.Level <> (Level) do
        Node := Node.Parent;
      Node := TreeView.Items.AddChild(Node, FolderData^.Name);
      Node.Data := FolderData;
      Node.ImageIndex := 15;
      Node.SelectedIndex := 16;
      Node.StateIndex := tnFolder;
      ////////////////////inbox/////////////////


      ////////////////////outbox/////////////////
      F := TINIFile.Create(Dir + '\Account.ini');
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := GetMessageString(4);
      FolderData^.Outbox := F.ReadBool(GetMessageString(4), 'Outbox', False);
      FolderData^.Inbox := F.ReadBool(GetMessageString(4), 'Inbox', False);
      FolderData^.Drafts := F.ReadBool(GetMessageString(4), 'Drafts', False);
      FolderData^.Filter := F.ReadString(GetMessageString(4), 'TakeIn', '');
      F.Free;
      while Node.Level <> (Level) do
        Node := Node.Parent;
      Node := TreeView.Items.AddChild(Node, FolderData^.Name);
      Node.Data := FolderData;
      Node.ImageIndex := 3;
      Node.SelectedIndex := 4;
      Node.StateIndex := tnFolder;
      ////////////////////outbox/////////////////

      ////////////////////Repositorybox/////////////////
      FNode := TreeView.Items.AddChild(TempNode, GetMessageString(2));
      FNode.StateIndex := tnRepository;
      FNode.ImageIndex := 8;
      FNode.SelectedIndex := 8;
      RepositoryNode := FNode;
      ////////////////////Repositorybox/////////////////

      ////////////////////Trashbox/////////////////
      FNode := TreeView1.Items.AddChild(TempNode, GetMessageString(1));
      FNode.StateIndex := tnThrashBag;
      FNode.ImageIndex := 6;
      FNode.SelectedIndex := 6;
      TrashNode := FNode;
      ////////////////////Trashbox/////////////////




      ////////////////////draftbox/////////////////
      F := TINIFile.Create(Dir + '\Account.ini');
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := GetMessageString(6);
      FolderData^.Outbox := F.ReadBool(GetMessageString(6), 'Outbox', False);
      FolderData^.Inbox := F.ReadBool(GetMessageString(6), 'Inbox', False);
      FolderData^.Drafts := F.ReadBool(GetMessageString(6), 'Drafts', False);
      FolderData^.Filter := F.ReadString(GetMessageString(6), 'TakeIn', '');
      F.Free;
      while Node.Level <> (Level) do
        Node := Node.Parent;
      Node := TreeView.Items.AddChild(Node, FolderData^.Name);
      Node.Data := FolderData;
      Node.ImageIndex := 17;
      Node.SelectedIndex := 18;
      Node.StateIndex := tnFolder;
      ////////////////////draftbox/////////////////

  end;


begin
  TreeView.Items.Clear;
  if not FileExists(sAccountRootFolder+'Fold.st') then exit;
  TreeView.LoadFromFile(sAccountRootFolder+'Fold.st');

  Node:=TreeView1.Items.GetFirstNode;
  while Node<>nil do
  begin
    if Node.Level=0 then begin
      Node.ImageIndex := 7;
      Node.SelectedIndex := 7;
      Node.StateIndex := tnAccounts;
      AccountsNode := Node;
    end
    else if Node.Level=1 then
    begin
        dir:=sAccountRootFolder + Node.Text;
        F := TIniFile.Create(sAccountRootFolder + Node.Text +
          '\Account.ini');
        New(AccountData);
        AccountData^.Path := sAccountRootFolder + Node.Text + '\';
        AccountData^.Name := F.ReadString('Account', 'Name', 'Account Name');
        AccountData^.FromMail := F.ReadString('From', 'EMail', '');
        AccountData^.FromDesc := F.ReadString('From', 'Name', '');
        AccountData^.ReplyMail := F.ReadString('ReplyTo', 'EMail', '');
        AccountData^.ReplyDesc := F.ReadString('ReplyTo', 'Name', '');
        AccountData^.POPServer := F.ReadString('POP3', 'Server', '');
        AccountData^.POPPort := F.ReadString('POP3', 'Port', '110');
        AccountData^.POPUser := F.ReadString('POP3', 'User', '');
        AccountData^.POPPass := MHDecrypt(F.ReadString('POP3', 'Password', ''));
        AccountData^.SMTPServer := F.ReadString('SMTP', 'Server', '');
        AccountData^.SMTPPort := F.ReadString('SMTP', 'Port', '25');
        AccountData^.SMTPAuthenticate := F.ReadBool('SMTP', 'Authenticate',
          false);
        AccountData^.SMTPUserName := F.ReadString('SMTP', 'User', '');
        AccountData^.SMTPPassword := MHDecrypt(F.ReadString('SMTP', 'Password',
          ''));
        AccountData^.Organization := F.ReadString('From', 'Organization', '');
        AccountData^.PromptPassword := F.ReadInteger('POP3', 'PromptPassword',
          0);
        AccountData^.DoSMTP := F.ReadInteger('SMTP', 'DoSMTP', 1);
        AccountData^.DoSMTPAfterPOP := F.ReadInteger('SMTP', 'DoSMTPAfterPOP', 0);
        AccountData^.DoPOP := F.ReadInteger('POP3', 'DoPOP', 1);
        AccountData^.StandardDownload := F.ReadInteger('POP3',
          'StandardDownload', 0);
        AccountData^.KeepFilter := F.ReadString('Filter', 'Keep', '');
        AccountData^.DeleteFilter := F.ReadString('Filter', 'Delete', '');
        AccountData^.ShowDownload := F.ReadInteger('POP3', 'ShowDownload', 0);
        F.Free;
        Node.Data := AccountData;

        itask := GetServerStatus(AccountData^.DoSMTP, AccountData^.DoPop);
        SetServerStatus(Node, itask);
        Node.StateIndex := tnAccount;
        //RecurseDirs(sAccountRootFolder + SearchRec.Name + '\');
    end
    else if Node.Level=2 then
    begin
      TempNode:=Node;
      ////////////////////inbox/////////////////
      if Node.Text=GetMessageString(5) then
      begin
      F := TINIFile.Create(dir + '\Account.ini');
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := GetMessageString(5);
      FolderData^.Outbox := F.ReadBool(GetMessageString(5), 'Outbox', False);
      FolderData^.Inbox := F.ReadBool(GetMessageString(5), 'Inbox', False);
      FolderData^.Drafts := F.ReadBool(GetMessageString(5), 'Drafts', False);
      FolderData^.Filter := F.ReadString(GetMessageString(5), 'TakeIn', '');
      F.Free;
//      while Node.Level <> (Level) do
 //       Node := Node.Parent;
      Node.Data := FolderData;
      Node.ImageIndex := 15;
      Node.SelectedIndex := 16;
      Node.StateIndex := tnFolder;
      end else
      ////////////////////inbox/////////////////


      ////////////////////outbox/////////////////
      if Node.Text=GetMessageString(4) then
      begin
      F := TINIFile.Create(Dir + '\Account.ini');
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := GetMessageString(4);
      FolderData^.Outbox := F.ReadBool(GetMessageString(4), 'Outbox', False);
      FolderData^.Inbox := F.ReadBool(GetMessageString(4), 'Inbox', False);
      FolderData^.Drafts := F.ReadBool(GetMessageString(4), 'Drafts', False);
      FolderData^.Filter := F.ReadString(GetMessageString(4), 'TakeIn', '');
      F.Free;
//      while Node.Level <> (Level) do
//        Node := Node.Parent;
      Node.Data := FolderData;
      Node.ImageIndex := 3;
      Node.SelectedIndex := 4;
      Node.StateIndex := tnFolder;
      end else
      ////////////////////outbox/////////////////

      ////////////////////Repositorybox/////////////////
      if Node.Text=GetMessageString(2) then
      begin
      Node.StateIndex := tnRepository;
      Node.ImageIndex := 8;
      Node.SelectedIndex := 8;
      RepositoryNode := Node;
      end else
      ////////////////////Repositorybox/////////////////

      ////////////////////Trashbox/////////////////
      if Node.Text=GetMessageString(1) then
      begin
      Node.StateIndex := tnThrashBag;
      Node.ImageIndex := 6;
      Node.SelectedIndex := 6;
      TrashNode := Node;
      end else
      ////////////////////Trashbox/////////////////




      ////////////////////draftbox/////////////////
      if Node.Text=GetMessageString(6) then
      begin
      F := TINIFile.Create(Dir + '\Account.ini');
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := GetMessageString(6);
      FolderData^.Outbox := F.ReadBool(GetMessageString(6), 'Outbox', False);
      FolderData^.Inbox := F.ReadBool(GetMessageString(6), 'Inbox', False);
      FolderData^.Drafts := F.ReadBool(GetMessageString(6), 'Drafts', False);
      FolderData^.Filter := F.ReadString(GetMessageString(6), 'TakeIn', '');
      F.Free;
//      while Node.Level <> (Level) do
//        Node := Node.Parent;
      Node.Data := FolderData;
      Node.ImageIndex := 17;
      Node.SelectedIndex := 18;
      Node.StateIndex := tnFolder;
      end else
      begin
      ////////////////////draftbox/////////////////
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := Node.Text;
      FolderData^.Outbox := False;
      FolderData^.Inbox := False;
      FolderData^.Drafts := False;
      FolderData^.Filter :='';

      Node.Data := FolderData;
      Node.ImageIndex := 17;
      Node.SelectedIndex := 18;
      Node.StateIndex := tnFolder;
      end;
    end else
    begin
      New(FolderData);
      FolderData^.Path := Dir;
      FolderData^.Name := Node.Text;
      FolderData^.Outbox := False;
      FolderData^.Inbox := False;
      FolderData^.Drafts := False;
      FolderData^.Filter :='';

      Node.Data := FolderData;
      Node.ImageIndex := 17;
      Node.SelectedIndex := 18;
      Node.StateIndex := tnFolder;

    end;
    Node:=Node.GetNext;
  end;



  for I := 0 to TreeView.Items.Count - 1 do
    SetPXTreeNodeName(TreeView.Items[I]);

end;

function TMainForm.GetActualAccount: TTreeNode;
var
  Node: TTreeNode;
begin
  Result := AccountsNode.GetFirstChild;
  if Assigned(TreeView1.Selected) then begin
    Node := TreeView1.Selected;
    if Node.Level < 1 then
      Exit;
    while Node.Level <> 1 do
      Node := Node.Parent;
    if Node.StateIndex = tnAccount then
      Result := Node;
  end;
end;

//AHRK85.. Same as Above, except for we pass the node here...
function TMainForm.GetActiveAccount(Anode : TTreeNode) : TTreeNode;
var node : TTreeNode;
begin
  result := AccountsNode.GetFirstChild;
  if Assigned(Anode) then
  begin
    Node := Anode;
    if Node.Level < 1 then
      exit;
    while Node.Level <> 1 do
      Node := Node.Parent;
    if Node.StateIndex = tnAccount then
      Result := Node;
  end;
end;

procedure TMainForm.SaveAccountDataToFile(Data: PAccountData);
var
  F: TINIFile;
begin
  F := TINIFile.Create(Data^.Path + 'Account.ini');
  with F do begin
    WriteString('Account', 'Name', Data^.Name);
    WriteString('From', 'EMail', Data^.FromMail);
    WriteString('From', 'Name', Data^.FromDesc);
    WriteString('ReplyTo', 'EMail', Data^.ReplyMail);
    WriteString('ReplyTo', 'Name', Data^.ReplyDesc);
    WriteString('POP3', 'Server', Data^.POPServer);
    WriteString('POP3', 'Port', Data^.POPPort);
    WriteString('POP3', 'User', Data^.POPUser);
    WriteString('POP3', 'Password', MHEncrypt(Data^.POPPass));
    WriteString('SMTP', 'Server', Data^.SMTPServer);
    WriteString('SMTP', 'Port', Data^.SMTPPort);
    WriteBool('SMTP', 'Authenticate', Data^.SMTPAuthenticate);
    WriteString('SMTP', 'User', Data^.SMTPUserName);
    WriteString('SMTP', 'Password', MHEncrypt(Data^.SMTPPassword));
    WriteInteger('SMTP', 'DoSMTPAfterPOP', Data^.DoSMTPAfterPOP);

    WriteString('From', 'Organization', Data^.Organization);
    WriteInteger('POP3', 'PromptPassword', Data^.PromptPassword);
    WriteInteger('SMTP', 'DoSMTP', Data^.DoSMTP);
    WriteInteger('POP3', 'DoPOP', Data^.DoPOP);
    // AHRK19
    WriteInteger('POP3', 'ShowDownload', Data^.ShowDownload);

    WriteInteger('POP3', 'StandardDownload', Data^.StandardDownload);

    WriteString('Filter', 'Keep', Data^.KeepFilter);
    WriteString('Filter', 'Delete', Data^.DeleteFilter);
    Free;
  end;
end;

procedure TMainForm.SaveFolderDataToFile(Data: PFolderData);
var
  F: TINIFile;
begin
  //CreateFolder(Data^.Path);
  F := TINIFile.Create(Data^.Path + 'Account.ini');
  with F do begin
    WriteBool(Data^.Name, 'Outbox', Data^.Outbox);
    WriteBool(Data^.Name, 'Inbox', Data^.Inbox);
    WriteBool(Data^.Name, 'Drafts', Data^.Drafts);
    WriteString(Data^.Name, 'TakeIn', Data^.Filter);
    Free;
  end;
end;

procedure TMainForm.ActualizeTrash;
var
  SearchRec: TSearchRec;
  Found, E: Integer;
begin
{  E := 0;
  Found := FindFirst(sTrashFolder + '*.msg', faAnyFile, SearchRec);
  while Found = 0 do begin
    Inc(E);
    Found := FindNext(SearchRec);
  end;
  FindClose(SearchRec);
  if E > 0 then begin
    TrashNode.ImageIndex := 6;
    TrashNode.SelectedIndex := 6;
  end
  else begin
    TrashNode.ImageIndex := 5;
    TrashNode.SelectedIndex := 5;
  end;
  E := 0;
  Found := FindFirst(sRepositoryFolder + '*.msg', faAnyFile, SearchRec);
  while Found = 0 do begin
    Inc(E);
    Found := FindNext(SearchRec);
  end;
  FindClose(SearchRec);
  if E > 0 then begin
    RepositoryNode.ImageIndex := 8;
    RepositoryNode.SelectedIndex := 8;
  end
  else begin
    RepositoryNode.ImageIndex := 14;
    RepositoryNode.SelectedIndex := 14;
  end;
  actUpdateStatusbarUpdate(Self);
  SetPXTreeNodeName(TrashNode);
  SetPXTreeNodeName(RepositoryNode);
  TreeView1.Repaint;}
end;

function TMainForm.GetUniqueAccountFolder(Name: string): string;
var
  S, T, K: string;
  I: integer;
begin
  T := 'a' + Copy(Name, 1, 5);
  for I := 1 to Length(T) do
    if not (T[I] in [' ', '\', '/', '<', '>', ':', '?', '*', '"', '|', #19])
      then
      K := K + T[I];
  T := K;
  repeat
    S := T;
    for I := 0 to 1 do
      S := S + Chr(Random(10) + 48);
  until DirectoryExists(S) = False;
  Result := S;
end;

procedure TMainForm.TreeView1Deletion(Sender: TObject; Node: TTreeNode);
var
  AccountData: PAccountData;
  FolderData: PFolderData;
begin
  if Assigned(Node.Data) then begin
    if Node.StateIndex = tnAccount then begin
      AccountData := Node.Data;
      Dispose(AccountData);
    end;
    if Node.StateIndex = tnFolder then begin
      FolderData := Node.Data;
      Dispose(FolderData);
    end;
  end;
end;

procedure TMainForm.Enhanced1Click(Sender: TObject);
begin
 { EmptyTrashBin1.Enabled := False;
  EmptyTrashBin1.Caption := Format(GetMessageString(84),
    [GetPXTreeNodeName(TrashNode)]);
  EmptyTrashBin2.Caption := Format(GetMessageString(84),
    [GetPXTreeNodeName(TrashNode)]);
  EmptyRepository1.Enabled := False;
  EmptyRepository1.Caption := Format(GetMessageString(85),
    [GetPXTreeNodeName(RepositoryNode)]);
  EmptyRepository2.Caption := Format(GetMessageString(85),
    [GetPXTreeNodeName(RepositoryNode)]);
  if TrashNode.ImageIndex = 6 then
  begin
    EmptyTrashBin1.Enabled := True;
    EmptyTrashBin2.Enabled := True;
  end;
  if RepositoryNode.ImageIndex = 8 then begin
    EmptyRepository1.Enabled := True;
    EmptyRepository2.Enabled := True;
  end;}
end;

procedure TMainForm.EmptyTrash;
var
  TempIndexFile:file of byte;
  sTempIndexFile:string;
  i,iCount:integer;
begin
  Screen.Cursor := crHourGlass;
  Application.ProcessMessages;
  try
  ActiveAccount := GetActiveAccount(TreeView1.Selected);
  Dir := PAccountData(ActiveAccount.Data)^.Path;
  sTempIndexFile:=Dir+'已删除邮件'+'.IND';
  AssignFile(TempIndexFile,sTempIndexFile);
  Reset(TempIndexFile);
  iCount:=FileSize(TempIndexFile) div sizeof(TIndexData);
  for i:=0 to iCount-1 do
  begin
    BlockRead(TempIndexFile, IndexData, SizeOf(TIndexData));
    if not IndexData.Delete then
    begin
      IndexData.Delete:=true;
      iPosition:=FilePos(TempIndexFile)-SizeOf(TIndexData);
      seek(TempIndexFile,iPosition);
      BlockWrite(TempIndexFile, IndexData, SizeOf(TIndexData));
    end;
  end;
  finally
    Screen.Cursor := crDefault;
    CloseFile(TempIndexFile);
  end;
end;

procedure TMainForm.EmptyTrashBin1Click(Sender: TObject);
begin
  if not ConfirmDelete(true) then Exit;
  EmptyTrash;
  // AHRK165
  if TreeView1.Selected = TrashNode then
    TreeView1Change(Self, TreeView1.Selected);
  ActualizeTrash;
  TreeView1.Invalidate;
end;

procedure TMainForm.TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
var b : Boolean;
begin
  // AHRK147 Timer support...
  b := False;

  if Source = TreeView1 then
    if TreeView1.Selected.StateIndex = tnFolder then
      b := True;
  if Source = ListView1 then
      b := True;

  if b then
    if State = dsDragLeave  then
      timerTree.enabled := false
    else
      timerTree.Enabled := True;
  Accept := b;
end;

procedure TMainForm.DoMergeStationary(showDialog : Boolean; apath : string; PrevNode : TTreeNode);
var StatFile : string;
    x : integer;
    s : string;
begin
  // Copy the file and generate new messagename...
  StatFile := apath + GetUniqueMailName + '.msg';
  FileCopy(nil, ListView1.Selected.SubItems[ciFileName], StatFile);
  TreeView1.Selected := PrevNode;
  // AH19
  s := ClearFolder(sTemporaryFolder, FileMightBeInUse);
  if Trim(s) <> '' then
  begin
    Application.MessageBox(PChar(Format(GetMessageString(159), [
      #13#10+#13#10+ s + #13#10+#13#10])), PChar(sAppTitle),
      MB_ICONEXCLAMATION + MB_OK);
    exit;
  end;
  // AH19
  if MergeNewStationary(StatFile, GetActualAccount) then
  begin
    SetPXTreeNodeName(PrevNode);  // Reread data...
    TreeView1.OnChange(Self, TreeView1.Selected);
    // Select last e-mail...
    for x := 0 to ListView1.Items.Count - 1 do
    begin
      if (AnsiCompareStr(ListView1.Items[x].SubItems[ciFileName], StatFile) = 0) then
      begin
        ListView1.Selected := ListView1.Items[x];
        if ShowDialog then ListView1.OnDblClick(Self);
        break;
      end;
      Application.ProcessMessages;
    end;
  end
  else
    Beep; // This is part of my advanced 'error checking' :-)
end;

function TMainForm.MergeNewStationary(afilename : string; Node : TTreeNode) : boolean;
var x : integer;
    NewEmail : TEmail;
begin
  Result := False;
  if FileExists(afilename) then
  begin
    NewEmail := TEmail.Create;
    NewEmail.ParseMail(afilename, False);
    if StringIndex(NewEmail.From, HMacros) = 2 then
      NewEmail.From := '<'+PAccountData(Node.Data)^.FromMail+'>';
    if StringIndex(NewEmail.From, HMacros) = 4 then
      NewEmail.From := PAccountData(Node.Data)^.FromDesc + '<'
          +PAccountData(Node.Data)^.FromMail+'>';
    // Clear receiver...
    NewEmail.ToReceiver.Clear;

    for x := 0 to NewEmail.Fields.Count -1 do
    begin
      case StringIndex(NewEmail.FieldValues[x], HMacros) of
      0 : NewEmail.FieldValues[x] := '';
      1 : NewEmail.FieldValues[x] := '';
      2 : NewEmail.FieldValues[x] := '<'+PAccountData(Node.Data)^.FromMail+'>';
      3 : NewEmail.FieldValues[x] := PAccountData(Node.Data)^.FromDesc;
      4 : NewEmail.FieldValues[x] := PAccountData(Node.Data)^.FromDesc + '<'
          +PAccountData(Node.Data)^.FromMail+'>';
      5 : NewEmail.FieldValues[x] := PAccountData(Node.Data)^.Organization;
      6 : NewEmail.FieldValues[x] := '';
      end;
    end;
    NewEmail.ADate := Date;
    NewEmail.ATime := Time;
    NewEmail.CompileMsgFileOnDisk(afilename);
    NewEmail.Free;
    Result := True;
  end;
end;


procedure TMainForm.TreeView1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  Node, NodeSel: TTreeNode;
  Data: PFolderData;
  Item: TListItem;
  S, nf : string;  // RR04D
  I, E: Integer;

  procedure SetSubNotesPath(Node: TTreeNode);
  var
    I: Integer;
  begin
    for I := 0 to Node.Count - 1 do begin
      PFolderData(Node.Item[I].Data)^.Path :=
        PFolderData(Node.Item[I].Parent.Data)^.Path +
        GetPXTreeNodeName(Node.Item[I]) + '\';
      if Node.Count > 0 then
        SetSubNotesPath(Node.Item[I]);
    end;
  end;

begin
  ListView1.Invalidate;
  ListView1.Tag := 1;
  TreeView1.Invalidate;
//  SplitterAttach.Invalidate;
  Node := TreeView1.GetNodeAt(X, Y);
  NodeSel := TreeView1.Selected;            // AH03
  if (Node = nil) or (Node = NodeSel) then  // AH03
    Exit;
  if SaveMessage then
//    DoSaveMessage;
  if Node.StateIndex = tnAccount then
    S := PAccountData(Node.Data)^.Path
  else if Node.StateIndex = tnFolder then
    S := PFolderData(Node.Data)^.Path
  else if Node.StateIndex = tnThrashBag then
    S := sTrashFolder
  else if Node.StateIndex = tnRepository then
    S := sRepositoryFolder
  else if Node.StateIndex = tnStationary then
    S := sStationaryFolder;  //AH03

  // Drag Folder
  if Source = TreeView1 then begin
    if TreeView1.Selected = nil then
      Exit;
    if TreeView1.Selected.StateIndex <> tnFolder then                    // CH03 (Cleanup...)
      Exit;                                                              //
    if Node.StateIndex in [tnAccounts, tnRepository, tnStationary] then  // AH03 forbid for Stationary...
      Exit;
    Data := TreeView1.Selected.Data;
    if Node.StateIndex = tnThrashBag then begin
      if MessageDlg(Format(GetMessageString(8),
        [GetPXTreeNodeName(TreeView1.Selected)]), mtConfirmation, [mbYes, mbNo],
        0) = mrYes then begin
        DeleteFolder(PFolderData(TreeView1.Selected.Data)^.Path, sTrashFolder);
        TreeView1.Selected.Delete;
        ActualizeTrash;
        TreeView1.AlphaSort;
      end;
      Exit;
    end;
    S := S + Data^.Name + '\';
    if Data^.Path = S then
      Exit;
    if DirectoryExists(S) then begin
      MessageDlg(Format(GetMessageString(10), [Data^.Name]), mtWarning, [mbOK],
        0);
      Exit;
    end;
    MoveFolder(Data^.Path, S);
    Data^.Path := S;
    Screen.Cursor := crHourGlass;
    MoveTreeViewNode(TreeView1, TreeView1.Selected, Node);
    Screen.Cursor := crDefault;
  end;
  // Drag Message

  if Source = ListView1 then
  begin
    // AH03 THcheck Source directory:
    case NodeSel.StateIndex of
    tnStationary : begin
                     // A message is dragged from stationary directory...
                     if ListView1.SelCount = 1 then
                     begin
                       // Copy the file...
                       DoMergeStationary(True, S, Node);
                     end
                     else
                     begin
                       Application.MessageBox(Pchar(GetMessageString(130)), PChar(GetMessageString(105)), MB_ICONINFORMATION
                         or MB_OK);
                     end;
                   end;
    else
      begin
        // then check Destination directory...
        case Node.StateIndex of
          tnStationary : begin
                           // A message is dropped into a StationaryFolder: Convert to Stationary!

                         end;
          tnAccounts   : exit;
          else
          begin
            if Node.StateIndex = tnThrashBag then if
              not ConfirmDelete(False) then Exit;  //AH03 -- Move to folder Thrash

            I := 0;
            E := ListView1.Items.Count - 1;

            while I <= E do begin
              if ListView1.Items[I].Selected then begin
                Item := ListView1.Items[I];
                // AH11: always generate new name...
                // FileCopy(nil, Item.SubItems[ciFileName], S + GetUniqueMailName + '.msg');
                // FileCopy(nil, Item.SubItems[ciFileName], S + ExtractFileName(Item.SubItems[ciFileName]));
                nf := SkipChar(ExtractFileName(Item.SubItems[ciFileName]), '+');//RR04d
                nf := S + nf;//RR04d AH17
                FileCopy(nil, Item.SubItems[ciFileName], nf);//RR04d

                SetFileAttr(Item.SubItems[ciFileName], False, True, False, False);
                DeleteFile(Item.SubItems[ciFileName]);
                Item.Delete;
                Dec(I);
                Dec(E);
              end;
              Inc(I);
            end;
          end;
        end;
      end;
      // Always update when source was ListView
      Application.ProcessMessages;
      SetPXTreeNodeName(Node);
      SetPXTreeNodeName(TreeView1.Selected);
      ListView1.Tag := 0;
      UpdateListView;
      ActualizeTrash;
    end;
  end;
end;

procedure TMainForm.PopPropertiesClick(Sender: TObject);
begin
  if TreeView1.Selected = nil then
    Exit;
  if TreeView1.Selected.StateIndex = tnAccount then
    actAccountPropertiesExecute(self)
  else if TreeView1.Selected.StateIndex = tnFolder then
  //  Properties2.OnClick(Self);
end;

procedure TMainForm.PopupMenu1Popup(Sender: TObject);
var
  Node: TTreeNode;
begin
{  NewFolder1.Enabled := False;
  DeleteFolder1.Enabled := False;
  EmptyTrashBin2.Enabled := False;
  EmptyRepository2.Enabled := False;
  Properties3.Enabled := False;
  Enhanced1.OnClick(Self);     }
  if TreeView1.Selected = nil then
    Exit;
  Node := TreeView1.Selected;

{  NewFolder1.Enabled := (Node.StateIndex = tnAccount) or
    (Node.StateIndex = tnFolder);
  Properties3.Enabled := (Node.StateIndex = tnAccount) or
    (Node.StateIndex = tnFolder);
  DeleteFolder1.Enabled := Node.StateIndex = tnFolder;}

  // AHRK06 and do another disable when the current selected note
  // is not pointing to the trashbag or repository...
  EmptyTrashBin2.Enabled := (Node.StateIndex = tnThrashBag);
  EmptyRepository2.Enabled := (Node.StateIndex = tnRepository);
  EmptyTrashBin1.Enabled := (Node.StateIndex = tnThrashBag);
  EmptyRepository1.Enabled := (Node.StateIndex = tnRepository);



{  if Node.StateIndex = tnAccount then begin
    NewFolder1.Enabled := True;
    Properties3.Enabled := True;
  end
  else if Node.StateIndex = tnFolder then begin
    NewFolder1.Enabled := True;
    DeleteFolder1.Enabled := True;
    Properties3.Enabled := True;
  end;}

  TreeView1.Selected := Node;
end;

procedure TMainForm.TreeView1Change(Sender: TObject; Node: TTreeNode);
var
  Dir: string;

  SearchRec: TSearchRec;
  Item: TListItem;
  Found, firstind, lastind, lastcol : Integer;
  firstdate, lastDate : TDateTime;
  {AHRK75 reEditable,} curAsc: boolean;
  bmp: TIcon;
  i:integer;



  function getLabelText : string;
  var cl : string;
      p : integer;
  begin
    cl := SearchRec.Name;
    p := StrToIntDef(cl[1], 0);
    case p of
    0 : Result := '';
    1 : Result := sLabel1;
    2 : Result := sLabel2;
    3 : Result := sLabel3;
    4 : Result := sLabel4;
    5 : Result := sLabel5;
    6 : Result := sLabel6;
    7 : Result := sLabel7;
    8: Result := sLabel8;
    9: Result := sLabel9;
    end
  end;

begin

  bmp := TIcon.Create;
  ImageList1.GetIcon(Treeview1.Selected.ImageIndex, bmp);
  Image12.Picture.Icon.Assign(bmp);
  bmp.free;
  i:=pos('(',Treeview1.Selected.Text);
  if i>0 then  LblImageTitle.Caption:=copy(Treeview1.Selected.Text,1,length(Treeview1.Selected.Text)-3) else  LblImageTitle.Caption:=Treeview1.Selected.Text;
  caption:=LblImageTitle.Caption + ' - SMAIL';


  if (csDestroying in ComponentState) then Exit;
  Screen.Cursor := crHourGlass;
  firstdate := 0; lastdate := Now;
  firstind := 0; lastind := 0;
  lastcol := ListView1.LastColumnClicked;
  curAsc := ListView1.CurrentSortAscending;


  ActualMailFile := '';


  ListView1.Tag := 1; // 1 = don't update
  ListView1.Items.Clear;
  ListView1.Tag := 0;
  ListView1.Perform(WM_SETREDRAW, 0, 0); //Lock window
  try
    ListView2.Items.Clear;
    RichEdit1.Lines.Clear;
    RichEdit1.Enabled := False;


    ListView2.Enabled := False;
    Dir := '';
    if (Node = nil) or (Node.StateIndex = tnAccounts) then begin
      actUpdateStatusbarUpdate(Self);
      Screen.Cursor := crDefault;
      Exit;
    end;




    RefreshListview;
    ActualMailFile := '';
    actUpdateStatusbarUpdate(Self);
    lblSubject.Caption := '';
    if bSelectFirstItem and (ListView1.Items.Count > 0) then begin
      if lastind > 0 then
        ListView1.Items[lastind].Selected := true
      else
      begin
        ListView1.Items[0].Selected := true;
        ListView1MouseUp(Sender, mbLeft, [ssLeft], 0, 0);
      end;
    end;

    if bSelectLastItem and (ListView1.Items.Count > 0) then begin
      if firstind > 0 then
        ListView1.Items[firstind].Selected := true
      else
      begin
        ListView1.Items[ListView1.Items.Count -1].Selected := True;
        ListView1MouseUp(Sender, mbLeft, [ssLeft], 0, 0);
      end;
    end;

    if ListView1.AutoColumnsort = acsNoSort then
    begin
      ListView1.AutoColumnSort := acsSortToggle;
      ListView1.LastColumnClicked := lastcol;
      ListView1.CurrentSortAscending := curASc;
      ListView1.BeginUpdate;
      ListView1.Resort;
      ListView1.EndUpdate;
      ListView1MouseUp(Sender, mbLeft, [ssLeft], 0, 0);
    end;
  finally
    ListView1.Perform(WM_SETREDRAW, 1, 0);
    Screen.Cursor := crDefault;
  end;
end;



procedure TMainForm.AddAttachment(aFilename: string);
var
  Item: TListItem;
  SHFileInfo: TSHFileInfo;
  FileTitle: string;
begin
  FileTitle := ExtractFileName(GetLongFileName(aFilename));

  if not FileExists(sTemporaryFolder + FileTitle) then
  begin
    // Don't add a second LV Item, when this file already exists
    CurrentEmail.ContentType := '';
    CurrentEmail.ContentEncoding := '';

    Item := ListView2.Items.Add;
    Item.Caption := FileTitle;
    SHGetFileInfo(PChar(aFilename), 0, SHFileInfo, SizeOf(SHFileInfo),
      SHGFI_SYSICONINDEX or iLV2Icons);
    Item.ImageIndex := SHFileInfo.iIcon;
    ListView2.Visible:=true;
  end;
  CopyFile(PChar(aFilename), PChar(sTemporaryFolder + FileTitle), False);
  SaveMessage := True;
end;


procedure TMainForm.UpdateListView(AddToHistory : Boolean = True);
var
  SearchRec: TSearchRec;
  I, Found,iPos: Integer;
  F: file of byte;
  buf:PChar;
  sTempFile:string;

  SHFileInfo: TSHFileInfo;
  Item: TListItem;
  ScanForVirus, OldWordWrap: Boolean;
  S: string;
  tempTitle,tempDetail:string;
  MsgItem : TMessageHistoryItem;
  shtml:olevariant;
begin

  ReadCounter := 0;
  s := ClearFolder(sTemporaryFolder, FileMightBeInUse);

  actMessageShowHeaders.Checked := False;
  if Trim(s) <> '' then
  begin
    Application.MessageBox(PChar(Format(GetMessageString(159), [
      #13#10+#13#10+ s + #13#10+#13#10])), PChar(sAppTitle),
      MB_ICONEXCLAMATION + MB_OK);
    exit;
  end;

  try
    ListView2.Items.Clear;
    lblfrom.Caption:='';
    lblto.Caption:='';
    lblsubject1.Caption:='';
    ActualMailFile := '';
    Item := ListView1.Selected;

    if ListView1.SelCount > 1 then
    begin
      while Item <> nil do
      begin
        if Item.Focused then break;
        Item := ListView1.GetNextItem(Item, sdAll, [isSelected]);
      end;
    end;

    if (Item = nil) or (csDestroying in ComponentState) then
    begin
      ListView2.Enabled := False;
      actUpdateStatusbarUpdate(Self);
      Exit;
    end;
    Screen.Cursor := crHourGlass;



    /////////////////////////////////fetch mail file depend on indexfile ////////////////////////////////////////////
    if   (ListView1.Selected=nil) or   (ListView1.SelCount>1) then exit else
    begin
      iPosition:=StrToInt(ListView1.Selected.SubItems[6]);
      iPosition:=(iPosition-1)*Sizeof(TIndexData);
      AssignFile(IndexFile,sMailIndexFile);
      Reset(IndexFile);
      Seek(IndexFile,iPosition);
      BlockRead(IndexFile, IndexData, SizeOf(TIndexData));



      iPosition:=IndexData.Position;
      iSize:=IndexData.Size;
      buf := StrAlloc(iSize);


      AssignFile(MailFile,sMailFile);
      Reset(MailFile);

      sTempFile:= sTemplateFolder+'Temp.SML';
      AssignFile(TempMailFile,sTempFile);
      ReWrite(TempMailFile);

      Seek(MailFile,iPosition);
      BlockRead(MailFile,buf^,iSize);
      BlockWrite(TempMailFile,buf^,iSize);

      CloseFile(MailFile);
      CloseFile(TempMailFile);
      StrDispose(buf);


      CurrentEMail.ParseMail(sTempFile, False);
      ActualMailFile := sTempFile;

      shtml:=sTempMessageFile;
      if FileExists(sTempMessageFile) then begin
        if CurrentEMail.MsgType = mtText then
            DHTMLEdit1.DOM.body.innerText:=ReadTxtFile(sTempMessageFile)
        else
            DHTMLEdit1.LoadDocument(shtml);
      end;


      //======================================
      //send return receipt
      if (not IndexData.Read) and (CurrentEMail.DispositionNotification<>'')   then
      begin
        IndexData.Read:=true;
        iPos:=FilePos(IndexFile);
        Seek(IndexFile,iPos-sizeof(TIndexData));
        BlockWrite(IndexFile, IndexData, SizeOf(TIndexData));


        if bReceipt=1 then
        begin
          if Application.MessageBox('邮件发送程序要求您作出响应，以表明您阅读此邮件了。要发送收条吗?', Pchar(Application.Title), MB_YESNO or MB_ICONEXCLAMATION)=6 then
          begin
            tempTitle:='已读:'+ CurrentEMail.Subject;
            tempDetail:='这是邮件收条，收件人:'+ CurrentEMail.ToReceiver[0]+' 于'+ DateToStr(CurrentEMail.ADate) + ' ' + TimeToStr(CurrentEMail.ATime)+'收到。'+ #10#13+'此收条表明收件人的计算机上曾显示此邮件，显示时间:'+DateTimeToStr(Now);
            SendReceipt(CurrentEMail.From,CurrentEMail.ToReceiver[0],tempTitle,tempDetail);
          end;
        end;
      end;
   CloseFile(IndexFile);
      //======================================
   end;




    SetPanelHeadersFields(false);

    Found := FindFirst(sTemporaryFolder + '*.*', faReadOnly + faHidden + faArchive
      + faSysFile, SearchRec);
    ListView2.Visible:=false;
    while Found = 0 do begin
      if sTemporaryFolder + SearchRec.Name <> sTempMessageFile then begin
        Item := ListView2.Items.Add;
        Item.Caption := SearchRec.Name;
        SHGetFileInfo(PChar(sTemporaryFolder + SearchRec.Name), 0, SHFileInfo,
          SizeOf(SHFileInfo), SHGFI_SYSICONINDEX or iLV2Icons);
        Item.ImageIndex := SHFileInfo.iIcon;
        ListView2.Visible:=true;
      end;
      Found := FindNext(SearchRec);
    end;
    FindClose(SearchRec);

    if (ScanForVirus = True) then
      actMessageScanVirusExecute(Self);

    S := 'Unknown E-mailer';
    for I := 0 to CurrentEMail.Fields.Count - 1 do
      if (LowerCase(CurrentEMail.Fields[I]) = 'x-mailer') or
         (LowerCase(CurrentEMail.Fields[I]) = 'user-agent') then
        S :=CurrentEMail.FieldValues[I];
  finally
  end;



  actUpdateStatusbarUpdate(Self);
  StatusBar1.Refresh;
  Screen.Cursor := crDefault;
end;

// AH03
function TMainForm.NewTemplate : Boolean;
var Node : TTreeNode;
    Item : TListItem;
    fle : string;
    i : integer;
begin
  Result := False;
  Node := TreeView1.Selected;
  if Assigned(Node) and (Node.StateIndex = tnStationary) then
  begin
    //AH19
    fle := ClearFolder(sTemporaryFolder, FileMightBeInUse);
    if Trim(fle) <> '' then
    begin
      Application.MessageBox(PChar(Format(GetMessageString(159), [
        #13#10+#13#10+ fle + #13#10+#13#10])), PChar(sAppTitle),
        MB_ICONEXCLAMATION + MB_OK);
      exit;
    end;
    //AH19

    // Fill default field values...
    with CurrentEMail do begin
      Clear;
      // Fill To header with macro
{             ('%RECEIVER%'),
             ('%RECEIVERFULL%'),
             ('%SENDER%'),
             ('%SENDERNAME%'),
             ('%SENDERFULL%'),
             ('%ORGANIZATION%'),
             ('%SUBJECT%'));}

      CommataStringToStringList('%RECEIVER%', ToReceiver);
      From := '%SENDER%';
      Priority := 'Normal';
      Subject := GetMessageString(96);
      Fields.Add('Organization');
      FieldValues.Add('%ORGANIZATION%');
      Fields.Add('X-mailer');
      //AH11
      FieldValues.Add(sXMailer + ' (' + IntToStr(Win32MajorVersion) + '.'
                    + IntToStr(Win32MinorVersion) + '/' + InttoStr(Win32BuildNumber) + ')');
    end;
    // Get path...
    fle := sStationaryFolder + GetUniqueMailName + '.msg';
    with MailOptionsForm do
    begin
      // prepare dialog
      SetFields(0);
      LoadMailHeader;
      EditAble := true;
      Screen.Cursor := crHourGlass;
      SaveMessage := False;
      TreeView1.Selected := Node;
      SaveMailHeader;
    end;
    Item := ListView1.Items.Add;
    Item.ImageIndex := -1;
    ListView2.Items.Clear;
    RichEdit1.Lines.Clear;

    CurrentEMail.CompileMsgFileOnDisk(fle);
    SaveMessage := False;
    with Item.SubItems do
    begin
      Add(CurrentEMail.Subject);
      Add(CurrentEMail.From);
      Add(GetCommataStringReceiver);
      Add(DateToStr(CurrentEMail.ADate) + ' ' + TimeToStr(CurrentEMail.ATime));
      Add(FormatByteText(GetFileSize(fle)));
      Add('');
      Add(fle); // invisible
    end;
    ActualMailFile := fle;

    // set actual item
    with ListView1 do begin
      for i := 0 to Items.Count - 1 do
        Items[i].Selected := false;
      Selected := Item;
      Resort;
      Item.MakeVisible(false);
    end;

    UpdateListView;
    SaveMessage := False;
    SetPXTreeNodeName(TreeView1.Selected);
    ShowPhoenixMail1Click(Self);
    with RichEdit1 do begin
      Enabled := true;
      SetFocus;
      SelStart := 0;
    end;
    Screen.Cursor := crDefault;
    Result := True;
  end;
end;



procedure TMainForm.ReplyEmail(ReplyQuote, ReplyAll : Boolean);
var
  SL: TStringList;
  ANewEmail : TEmail;
  T, U : string;
  I : integer;
  Node:TtreeNode;
begin
  if (ListView1.SelCount <> 1) or (ListView1.Selected = nil) then
    Exit;

////////////////////move to default/////////////
  Node := Treeview1.Selected;
  if (sDefaultAccount <> '') and (Node.Level < 1) then
  begin
    actAccountShowDefaultExecute(Self);
    Node := TreeView1.Selected;
  end
  else
  begin
    Node := GetActualAccount;
  end;
  if Node = nil then exit;

  FNode := nil;
  if bUseDrafts then
  begin
    GetSubNotesDrafts(Node)
  end
  else
  begin
    GetSubNotes(Node); // Get first outbox..., sets FNode...
    if TreeView1.Selected <> nil then
    begin
      if TreeView1.Selected.StateIndex = tnFolder then
      begin
        if PFolderData(TreeView1.Selected.Data)^.Drafts then
        begin
          Fnode := TreeView1.Selected; // Store here...
        end
      end;
    end;
  end;
  FNode.Selected:=true;

////////////////////move to default/////////////

  AutoMarkReplied;
  AddToAddressBook;
  ANewEmail := TEmail.Create;

  if Pos(UpperCase(GetMessageString(15)), UpperCase(CurrentEMail.Subject)) <> 1  then
  begin
    T := GetMessageString(15) + ' ' + CurrentEMail.Subject
  end
  else
  begin
    T := CurrentEMail.Subject
  end;

  if ReplyQuote then
  begin

    SL := TStringList.Create;
    SL.add(DHTMLEdit1.DOM.body.outerText);
    SL.Text := NewBreakStringD(SL.text, iLineBreakAt, GetMessageString(92));
    SL.Insert(0, '');

    // Add the greeting...
    U := DateToStr(CurrentEMail.ADate) + ', ' + TimeToStr(CurrentEMail.ATime)
      + ' ' + GetTheRightZone(U); // AHRJ01
    if TrimRight(ExtractEMailName(CurrentEMail.From)) = '' then
    begin
      T := Format(GetMessageString(16), [U])
    end
    else
    begin
      T := Format(GetMessageString(17),  [TrimRight(ExtractEMailName(CurrentEMail.From)), U]);
    end;

    SL.Insert(0, T);
    SL.Add('');
    DoEmailReply(ANewEmail, ReplyAll);
    NewEmail(False, True, ANewEmail, SL);
    SL.Free;
  end
  else
  begin
    DoEmailReply(AnewEmail, ReplyAll);
    NewEmail(False, True, ANewEmail, nil);
  end;
  ANewEmail.Free;
end;

procedure TMainForm.FwdRedEmail(DoForward : Boolean);
var FwdEmail : TEmail;
    SL : TStringList;
    QuoteChar, RealEmail : string;
    Node : TTreeNode;
    Data : PAccountData;
begin
  if (ListView1.SelCount <> 1) or (ListView1.Selected = nil) then
    Exit;
////////////////////move to default/////////////
  Node := Treeview1.Selected;
  if (sDefaultAccount <> '') and (Node.Level < 1) then
  begin
    actAccountShowDefaultExecute(Self);
    Node := TreeView1.Selected;
  end
  else
  begin
    Node := GetActualAccount;
  end;
  if Node = nil then exit;



  FNode := nil;
  if bUseDrafts then
  begin
    GetSubNotesDrafts(Node)
  end
  else
  begin
    GetSubNotes(Node); // Get first outbox..., sets FNode...
    if TreeView1.Selected <> nil then
    begin
      if TreeView1.Selected.StateIndex = tnFolder then
      begin
        if PFolderData(TreeView1.Selected.Data)^.Drafts then
        begin
          Fnode := TreeView1.Selected; // Store here...
        end
      end;
    end;
  end;
  FNode.Selected:=true;



  SL := TStringList.Create;
  FWDEmail := TEmail.Create;
  // Only Redirection...
  if not DoForward then
    AutoMarkReplied; //RR26

  QuoteChar := GetMessageString(92);
  with SL do begin
   // Assign(RichEdit1.Lines);
    text:=DHTMLEdit1.DOM.body.outerText;
    // Forward or Redirect message...
    if DoForward then
      Insert(0, QuoteChar + GetMessageString(30))
    else
      Insert(0, QuoteChar + GetMessageString(32));
    Insert(1, QuoteChar);
    Insert(2, QuoteChar + GetMessageString(21) + ' ' + CurrentEMail.From);
    Insert(3, QuoteChar + GetMessageString(22) + ' ' +
      StringListToCommataString(CurrentEMail.ToReceiver, False));
    Insert(4, QuoteChar + GetMessageString(23) + ' ' +
      DateToStr(CurrentEMail.ADate) +
      '  ' + TimeToStr(CurrentEMail.ATime));
    Insert(5, QuoteChar + GetMessageString(20) + ' ' + CurrentEMail.Subject);
    Insert(6, '');
  end;

  BackupAttachments;
  if DoForward then
  begin
    FWDEmail.Subject := NumberReplies(CurrentEmail.Subject,
       GetMessageString(31));
    // AHRK24.
    Node := GetActualAccount;
    if Assigned(Node) then
    begin
      if Assigned(Node.Data) then
      begin
        // Only if there's an actual account,
        // which should be normal...
        Data := Node.Data;
        // AHRK118
        RealEmail := Trim(Data^.FromDesc + ' <'+ Data^.FromMail + '>');
      end;
    end;
    FWDEmail.From := RealEmail;
  end
  else
  begin
    FWDEmail.Subject := NumberReplies(CurrentEmail.Subject,
      GetMessageString(33));
    FWDEmail.ToReceiver.Assign(CurrentEmail.ToReceiver);
  end;


  // Hold on to the the contenttype and encoding...
  FWDEmail.ContentType := CurrentEmail.ContentType;
  FWDEmail.ContentEncoding := CurrentEmail.ContentEncoding;

  if NewEmail(DoForward, False, FWDEmail, SL) then
  begin
    RestoreAttachments;
    SaveMessage := True;  // AH11 //AH16 Bug resolved for REDIRECT.
  end;

  SL.Free;
  FWdEmail.Free;
end;

procedure TMainForm.DoEmailReply(var AnEmail : TEmail; DoAll : Boolean);
var K, L : integer;
    S, T, email : string;
    Node : TTreeNode;
    Data : PAccountData;
begin
  // mjg New section starts...
  k := CurrentEmail.Fields.IndexOf('reply-to');
  if k > -1 then
    s := ExtractEmailAddress(CurrentEmail.FieldValues.Strings[K]);

  if s = '' then
    S := CurrentEMail.From;

  if DoAll then
  begin
    // Reply to all of them...
    // Check if there are more fields in to...
    Node := GetActualAccount;
    if Assigned(Node) then
    begin
      if Assigned(Node.Data) then
      begin
        // Only if there's an actual account,
        // which should be normal...
        Data := Node.Data;
        email := Data^.FromMail;
        k := CurrentEmail.Fields.IndexOf('List-Post');
        if k > -1 then
          s := ExtractEmailAddress(CurrentEmail.FieldValues.Strings[K])
        else
        begin
          // Add all the receivers to CC.
          if CurrentEmail.ToReceiver.Count > 0 then
          begin
            AnEmail.CC.Assign(CurrentEmail.ToReceiver);
          end;
          // Add CC to the CC.
          if CurrentEmail.CC.Count > 0 then
          begin
            AnEmail.CC.AddStrings(CurrentEmail.CC);
          end;

          // AH 17Delete yourself, by checking with email...
          for l := 0 to AnEmail.CC.Count - 1 do
          begin
            if (pos(lowercase(email), lowercase(AnEmail.CC.Strings[l])) = 0) then
            begin
              t := t + AnEmail.CC.Strings[l] + #13#10;
            end;
          end;
          AnEmail.CC.Text := t;
          // AH17
        end;
      end;
    end;
  end;
  // Add the From to the To...
  AnEmail.ToReceiver.Add(S);

  AnEmail.ContentType := CurrentEmail.ContentType;
  AnEmail.ContentEncoding := CurrentEmail.ContentEncoding;

  // AHRJ02
  AnEmail.Subject := NumberReplies(CurrentEmail.Subject, GetMessageString(15));

  // These will always be added: check back later for additional
  // processing...
  k := CurrentEmail.Fields.IndexOf('Message-Id');
  if k > -1 then
  begin
    AnEmail.Fields.Add('References');
    // AHRJ02 --
    T := '';
    L := CurrentEmail.Fields.IndexOf('References');
    if l > -1 then
    begin
      T := CurrentEmail.FieldValues.Strings[l];
    end;
    // AHRJ02 -- Add extra references e-mail... + Extra Trim + skipchar
    AnEmail.FieldValues.Add(TrimLeft(
       SkipChar(T + CurrentEmail.FieldValues.Strings[k], ' ')
       ));
    // AHRJ02 --
    AnEmail.Fields.Add('In-Reply-To');
    AnEmail.FieldValues.Add(CurrentEmail.FieldValues.Strings[k]);
  end;
end;


function TMainForm.NewEmail(ShowDlg, Signature : Boolean; AnEmail : TEMail;
  NewText : TStringList) : boolean;
var
  Item: TListItem;
  Node, FNode: TTreeNode;
  S, TS, acname : string; // WipWap added TS //AH11 acName added...
  I, E : Integer;
  SL, NL: TStringList;
  procedure GetSubNotes(KNode: TTreeNode);
  var
    I: Integer;
  begin
    for I := 0 to KNode.Count - 1 do
    begin
      if assigned(Fnode) then exit;
      if PFolderData(KNode.Item[I].Data)^.Outbox then
      begin
        FNode := KNode.Item[I];
        exit;
      end;
      if KNode.Item[I].HasChildren then
        GetSubNotes(KNode.Item[I]); // AHRK68
    end;
  end;

  procedure GetSubNotesDrafts(KNode: TTreeNode);
  var
    I: Integer;
  begin
    for I := 0 to KNode.Count - 1 do
    begin
      if assigned(Fnode) then exit;
      if PFolderData(KNode.Item[I].Data)^.Drafts then
      begin
        FNode := KNode.Item[I];
        exit;
      end;
      if KNode.Item[I].HasChildren then
        GetSubNotesDrafts(KNode.Item[I]); // AHRK68
    end;
  end;
  // AH17
begin
  bNewDoc:=true;
  Result := False;
  if SaveMessage then
  s := ClearFolder(sTemporaryFolder, FileMightBeInUse);
  if Trim(s) <> '' then
  begin
    Application.MessageBox(PChar(Format(GetMessageString(159), [
      #13#10+#13#10+ s + #13#10+#13#10])), PChar(sAppTitle),
      MB_ICONEXCLAMATION + MB_OK);
    exit;
  end;

  // get outbox folder
  Node := Treeview1.Selected;
  if (sDefaultAccount <> '') and (Node.Level < 1) then
  begin
    actAccountShowDefaultExecute(Self);
    Node := TreeView1.Selected;
  end
  else
  begin
    Node := GetActualAccount;
  end;
  //AH15--- DefaultAccount processing

  if Node = nil then exit;

  FNode := nil;
  if bUseDrafts then
  begin
    // Old behaviour... Always start in Draft...
    GetSubNotesDrafts(Node)
  end
  else
  begin
    GetSubNotes(Node); // Get first outbox..., sets FNode...
    // AH11 New behaviour
    // Check if in Draft folder... if not, go to
    // first Outbox.
    if TreeView1.Selected <> nil then
    begin
      if TreeView1.Selected.StateIndex = tnFolder then
      begin
        if PFolderData(TreeView1.Selected.Data)^.Drafts then
        begin
          Fnode := TreeView1.Selected; // Store here...
        end
      end;
    end;

  end;
  // clear up

  with CurrentEMail do begin
    Clear;

    // Set the default e-mail headers first...
    From := PAccountData(Node.Data)^.FromDesc + ' <' +
          PAccountData(Node.Data)^.FromMail + '>';
    Priority := 'Normal';
    Subject := GetMessageString(96);

    if PAccountData(Node.Data)^.Organization <> '' then
    begin
      Fields.Add('Organization');
      FieldValues.Add(PAccountData(Node.Data)^.Organization);
    end;

    // We may have to take over the Reply-To header
    if From = '' then
    begin
      if PAccountData(Node.Data)^.ReplyMail <> '' then
      begin
        Fields.Add('Reply-to');
        FieldValues.Add(PAccountData(Node.Data)^.ReplyDesc + ' <' +
          PAccountData(Node.Data)^.ReplyMail + '>');
      end;
    end;

    // if there was an E-mail object passed continue seperate
    // processing of headers...
    if anEmail <> nil then
    begin
      // For replying these will be set...
      CurrentEmail.ContentType := AnEmail.ContentType;
      CurrentEmail.ContentEncoding := AnEmail.ContentEncoding;

      if AnEmail.ToReceiver.Count > 0 then
      begin
        ToReceiver.Assign(AnEmail.ToReceiver);
      end;

      if AnEmail.CC.Count > 0 then
      begin
        CC.Assign(AnEmail.CC);
      end;

      // Probably for forwarding...
      if AnEmail.From <> '' then
        From := AnEmail.From;

      if Length(AnEmail.Subject) > 0 then
        Subject := AnEmail.Subject;

      // IndexOf is Case insensitive according the docs...
      if (AnEmail.Fields.IndexOf('References') > -1) and
      (AnEmail.Fields.IndexOf('In-Reply-To') > -1) then
      begin
        // Currently only check those...
        Fields.Add('References');
        FieldValues.Add(AnEmail.FieldValues.Strings[
          AnEmail.Fields.IndexOf('References')]);
        Fields.Add('In-Reply-To');
        FieldValues.Add(AnEmail.FieldValues.Strings[
          AnEmail.Fields.IndexOf('In-Reply-To')]);
      end;
    end;
    Fields.Add('X-mailer');
    // AH11
    FieldValues.Add(sXMailer + ' (' + IntToStr(Win32MajorVersion) + '.'
      + IntToStr(Win32MinorVersion) + '/' + InttoStr(Win32BuildNumber) + ')');
  end;
  // get outbox path


  if FNode = nil then
  begin
    S := PAccountData(Node.Data)^.Path + GetUniqueMailName + '.msg';
  end
  else
  begin
    S := PFolderData(FNode.Data)^.Path + GetUniqueMailName + '.msg'
  end;


  acName := PAccountData(Node.Data)^.Name;
{  with MailOptionsForm do begin
    Caption := GetMessageString(0) + ' ' + acName;
    SetFields(0);
    LoadMailHeader;
    EditAble := true;
    if ShowDlg then begin
      if ShowModal <> mrOK then begin
        SaveMessage := False;
        UpdateListView;
        SaveMessage := False;
        Screen.Cursor := crDefault;
        Exit;
      end;
      TS := ComboBoxTemplate.Text; //wipwap
    end;

    Screen.Cursor := crHourGlass;
    // switch to outbox folder
    SaveMessage := False;
    TreeView1.Selected := FNode;
    // get mailheader again

    SaveMailHeader;
  end;}


  // clear message display
  ListView2.Items.Clear;

  //New text
  SL := TStringList.Create;
  NL := TStringList.Create;
  if NewText <> nil then
    SL.Assign(NewText);
  E := 0;

  TS := GetParsedTemplateString(sTemplateFolder+TS+'.txt',
    GetCommataStringReceiver, CurrentEMail.Subject);//AH04
  if TS <> '' then SL.Add(TS);


  if Signature then
  begin
    if FileExists(PAccountData(Node.Data)^.Path + 'signat.txt') then begin
      NL.LoadFromFile(PAccountData(Node.Data)^.Path + 'signat.txt');
      E := Length(NL.Text) - 2;
      SL.Add('');
      for I := 0 to NL.Count - 1 do
        SL.Add(NL.Strings[I]);
    end;
  end;

  ClearFolder(sTemporaryFolder, FileMightBeInUse);

  SL.SaveToFile(sTempMessageFile);
  SL.Free;
  NL.Free;
  // create message file
  CurrentEMail.CompileMsgFileOnDisk(S);
  ActualMailFile := S;

//  UpdateListView;
  SetPXTreeNodeName(TreeView1.Selected);
//  ShowPhoenixMail1Click(Self);
  Screen.Cursor := crDefault;
  Result := True;
end;

function TMainForm.NewMessage(ShowDlg, Signat: Boolean; ASubject, ATo, AFrom:
  string; NewText: TStringList): Boolean;
var
  Item: TListItem;
  Node: TTreeNode;
  S, TS, acname : string; // WipWap added TS
  I, E : Integer;
  SL, NL: TStringList;
begin

//////////////////////////////////1set mailbox param///////////////////////////////////
  Result := False;
  s := ClearFolder(sTemporaryFolder, FileMightBeInUse);
  if Trim(s) <> '' then
  begin
    Application.MessageBox(PChar(Format(GetMessageString(159), [   //下面的文件正在用：: %s 请先关闭这些文件.
      #13#10+#13#10+ s + #13#10+#13#10])), PChar(sAppTitle),
      MB_ICONEXCLAMATION + MB_OK);
    exit;
  end;
  // get outbox folder
  Node := Treeview1.Selected;
  if (sDefaultAccount <> '') and (Node.Level < 1) then
  begin
    actAccountShowDefaultExecute(Self);
    Node := TreeView1.Selected;
  end
  else
  begin
    Node := GetActualAccount;
  end;
  if Node = nil then exit;


  FNode := nil;
  if bUseDrafts then
  begin
    GetSubNotesDrafts(Node)
  end
  else
  begin
    GetSubNotes(Node); // Get first outbox..., sets FNode...
    if TreeView1.Selected <> nil then
    begin
      if TreeView1.Selected.StateIndex = tnFolder then
      begin
        if PFolderData(TreeView1.Selected.Data)^.Drafts then
        begin
          Fnode := TreeView1.Selected; // Store here...
        end
      end;
    end;
  end;
//////////////////////////////////1set mailbox param///////////////////////////////////




  with CurrentEMail do begin
    Clear;
    sAccountPath:=PAccountData(Node.Data)^.Path;
    if ATo <> '' then
    begin
        CommataStringToStringList(ATo, ToReceiver)
    end;

    if AFrom = '' then
      From := PAccountData(Node.Data)^.FromDesc + ' <' +
        PAccountData(Node.Data)^.FromMail + '>'
    else
      From := AFrom;
    Priority := 'Normal';
    if Length(ASubject) > 0 then
      Subject := ASubject
    else
      Subject := GetMessageString(96);
    if PAccountData(Node.Data)^.Organization <> '' then begin
      Fields.Add('Organization');
      FieldValues.Add(PAccountData(Node.Data)^.Organization);
    end;
    if AFrom = '' then
      if PAccountData(Node.Data)^.ReplyMail <> '' then begin
        Fields.Add('Reply-to');
        FieldValues.Add(PAccountData(Node.Data)^.ReplyDesc + ' <' +
          PAccountData(Node.Data)^.ReplyMail + '>');
      end;
    Fields.Add('X-mailer');
    // AH11
    FieldValues.Add(sXMailer + ' (' + IntToStr(Win32MajorVersion) + '.'
                    + IntToStr(Win32MinorVersion) + '/' + InttoStr(Win32BuildNumber) + ')');
  end;


  if FNode = nil then
  begin
    S := MakeValidDirName(PAccountData(Node.Data)^.Path) + GetUniqueMailName + '.msg';
  end
  else
  begin
    S := MakeValidDirName(PFolderData(FNode.Data)^.Path) + GetUniqueMailName + '.msg'
  end;
  acName := PAccountData(Node.Data)^.Name;


    Screen.Cursor := crHourGlass;
    TreeView1.Selected := FNode;
//    SaveMailHeader;

  // clear message display
  ListView2.Items.Clear;
  SL := TStringList.Create;
  NL := TStringList.Create;
  if NewText <> nil then
    SL.Assign(NewText);
  E := 0;

  TS := GetParsedTemplateString(sTemplateFolder+TS+'.txt',
    GetCommataStringReceiver, CurrentEMail.Subject);//AH04
  if TS <> '' then SL.Add(TS);

  if Signat then
  begin
    if FileExists(PAccountData(Node.Data)^.Path + 'signat.txt') then begin
      NL.LoadFromFile(PAccountData(Node.Data)^.Path + 'signat.txt');
      E := Length(NL.Text) - 2;
      SL.Add('');
      for I := 0 to NL.Count - 1 do
        SL.Add(NL.Strings[I]);
    end;
  end;

  ClearFolder(sTemporaryFolder,FileMightBeInUse);
  sl.Add('    ');
  SL.SaveToFile(sTempMessageFile);

  SL.Free;
  NL.Free;

  CurrentEMail.CompileMsgFileOnDisk(S);
  ActualMailFile := S;

  Screen.Cursor := crDefault;
  Result := True;
end;

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
  IniFile: TIniFile;
  SList : TStringList;
  L : TTreeNode;
begin
  Treeview1.SaveToFile(sAccountRootFolder+'Fold.st');
  if SaveMessage then
  if bEmptyRepositWhenExit then
    EmptyReposit;
  if bEmptyTrashWhenExit then
    EmptyTrash;
  if bClearSearchHisWhenExit then begin
    if FileExists(GetAppPath + 'mfhis.txt') then
      DeleteFile(GetAppPath + 'mfhis.txt');
    if FileExists(GetAppPath + 'afhis.txt') then
      DeleteFile(GetAppPath + 'afhis.txt');
  end;
  // save settings
  try
    BKAttachments1.Free;
    BKAttachments2.Free;
    DefaultFont.Free;
  except end;
  AddressInfo.Free;
  // Tray icon
  Shell_NotifyIcon(NIM_DELETE, @NotifyIconData);
  DestroyIcon(TrayIcon);
  // Explorer Drag drop
  DragAcceptFiles(ListView2.Handle, False);
  SetWindowLong(ListView2.Handle, GWL_WNDPROC, LongInt(DragDropDefWndProc));
  FreeObjectInstance(DragDropWndProcInstance);

  IniFile := TIniFile.Create(sSettingsFile);
  DoSaveToolBars(IniFile);
  IniSaveToolbarPositions(Self, sSettingsFile, 'Toolbars');

  with IniFile do begin
    // Form Position
    if WindowState = wsNormal then begin
      WriteInteger('Position', 'MainState', 1);
      WriteInteger('Position', 'MainWidth', Width);
      WriteInteger('Position', 'MainHeight', Height);
      WriteInteger('Position', 'MainTop', Top);
      WriteInteger('Position', 'MainLeft', Left);
    end;
    if WindowState = wsMaximized then
      WriteInteger('Position', 'MainState', 2);
    // AH09
    WriteInteger('Splitter', 'FolderView', PanelOrdnerUebersicht.Width);
    WriteInteger('Splitter', 'MessageList', PanelNewsText.Height);
    // AH09
    // AHRK134..
    IniFile.WriteBool('Settings', 'PanelHeaderShown', PanelHeaders.Visible);

    if TreeView1.Selected <> nil then // AH05 (small correction)
        WriteInteger('Settings', 'LastFolderIndex',
          TreeView1.Selected.AbsoluteIndex);

    WriteBool('View', 'Statusbar', Statusbar1.Visible);
    WriteBool('Style', 'AutoDetectURL', (MainForm.RichEdit1.AutoURLDetect =
      adDefault));
    WriteInteger('Style', 'Undolimit', MainForm.RichEdit1.UndoLimit);
    WriteBool('Style', 'SelectionBar', MainForm.RichEdit1.ShowSelectionBar);
    // AH06...
    SList := TStringList.Create;
    L := TreeView1.Items.GetFirstNode;
    L := l.getFirstChild;
    while l <> nil do
    begin
      if L.HasChildren and l.Expanded then // AHRK29
        SList.Add(IntToStr(L.AbsoluteIndex));
      l := l.getNext; // AHRK29
    end;
    IniFile.WriteString('Settings', 'OpenedFolders', Trim(SList.CommaText));

    SaveHelperToIni(TreeView1, IniFile);
    SaveHelperToIni(RichEdit1, IniFile);

    SList.Free;
    //AH06
    Free;
  end;
  ListView1.WriteSettings;
  AniBmp1.Free;
  AniBmp2.Free;
  ShowWindow(Handle, SW_SHOWMINIMIZED);
end;

procedure TMainForm.BackupAttachments;
var
  I: Integer;
  A, B: array[0..MAX_PATH - 1] of Char;
  S: string;
begin
  BKAttachments1.Clear;
  BKAttachments2.Clear;
  for I := 0 to ListView2.Items.Count - 1 do begin
    BKAttachments1.Add(sTemporaryFolder + ListView2.Items[I].Caption);
    GetTempPath(MAX_PATH, @A);
    GetTempFileName(@A, 'PXA', 0, @B);
    S := B;
    BKAttachments2.Add(S);
    SetFileAttr(BKAttachments1.Strings[I], False, True, False, False);
    CopyFile(PChar(BKAttachments1.Strings[I]), PChar(BKAttachments2.Strings[I]),
      False);
  end;
end;

procedure TMainForm.RestoreAttachments;
var
  I: Integer;
  Item: TListItem;
  SHFileInfo: TSHFileInfo;
begin
  for I := 0 to BKAttachments1.Count - 1 do begin
    CopyFile(PChar(BKAttachments2.Strings[I]), PChar(BKAttachments1.Strings[I]),
      False);
    DeleteFile(PChar(BKAttachments2.Strings[I]));
    Item := ListView2.Items.Add;
    Item.Caption := ExtractFileName(BKAttachments1.Strings[I]);
    SHGetFileInfo(PChar(BKAttachments1.Strings[I]), 0, SHFileInfo,
      SizeOf(SHFileInfo), SHGFI_SYSICONINDEX or iLV2Icons);
    Item.ImageIndex := SHFileInfo.iIcon;
  end;
  BKAttachments1.Clear;
  BKAttachments2.Clear;
end;

procedure TMainForm.Timer1Timer(Sender: TObject);
begin
  if (csDestroying in ComponentState) or (csLoading in ComponentState) then
    Exit;
  //OnlineThread
  Inc(OnlineThreadCounter, Timer1.Interval);
  if OnlineThreadCounter > 1000 then
    OnlineThreadCounter := 0;
  if OnlineThreadTerminated then begin
    if (OnlineThreadCounter > 400) then begin
      Timer1.Enabled := False;
      OnlineThreadTerminated := False;
      OnlineThreadCounter := 0;
      Screen.Cursor := crHourGlass;
      try
        if OnlineForm <> nil then
          OnlineForm.Free;
        if OnlineThread <> nil then
          OnlineThread.Free;
        OnlineForm := nil;
        OnlineThread := nil;
        if SelectMailForm <> nil then
          SelectMailForm.Free;
        SelectMailForm := nil;
        // AHRK80--
        // rest tray icon
        StrPCopy(NotifyIconData.szTip, 'SMAIL');
        NotifyIconData.hIcon := TrayIcon;
        Shell_NotifyIcon(NIM_MODIFY, @NotifyIconData);
        PaintBox1.Visible := False;
        AreWeOnline := False;
        Label4.Caption := '';
        StatusBar1.Panels[2].Text := '';
        StatusBar1.Panels[3].Text := '';
      finally
        if bDUNNormalQuit then
          DialUp1.GoOffline;
        Screen.Cursor := crDefault;
        ReadyToClose := True;
        Timer1.Enabled := True;
      end;
    end;
  end;
  // Read/Unread Flag
  // AH11----
  if (ListView1.SelCount = 1) and (ListView1.Selected <> nil) and
    (ListView1.Selected.ImageIndex=1) then
  begin
      Inc(ReadCounter, Timer1.Interval);
      if ReadCounter > (iMarkAsReadSec * 1000) then
      begin
        ReadCounter := 0;
          actMessageToggleReadExecute(Self);
      end;
  end;

  //Animation
  if AreWeOnline then begin
    if Label4.Caption <> '' then begin
      PaintBox1.Visible := False;
      Exit;
    end;
    if not bHideAnimations then
    begin
      PaintBox1.Visible := True;
      //AH15 Deleted a lot here...
      DoAnimation(iAnimation);
    end;
  end;
end;

procedure TMainForm.ListView1DrawHeader(Control: TWinControl; var ACanvas:
  TCanvas; Index: Integer; var ARect: TRect; Selected: Boolean; var
  DefaultDrawing: Boolean);
begin
  if csDestroying in ComponentState then
    Exit;
  if Index = 0 then begin
    DefaultDrawing := False;
    ACanvas.BrushCopy(Rect(ARect.Left + 17, ARect.Top, ARect.Left + 33, ARect.Top
      + 16), Image2.Picture.Bitmap, Rect(0, 0, 16, 16), clFuchsia);
  end
  else if Index = 6 then begin
    DefaultDrawing := False;
    ACanvas.BrushCopy(Rect(ARect.Left+4, ARect.Top, ARect.Left + 20, ARect.Top
      + 16), Image17.Picture.Bitmap, Rect(0, 0, 16, 16), clFuchsia);
  end
  else if Index = 3 then begin
    DefaultDrawing := False;
    ACanvas.BrushCopy(Rect(ARect.Left + 7, ARect.Top, ARect.Left + 23, ARect.Top
      + 16), Image14.Picture.Bitmap, Rect(0, 0, 16, 16), clFuchsia);
  end

  else
    DefaultDrawing := True;{}
end;

procedure TMainForm.AppMinimize(Sender: TObject);
begin
  ShowWindow(Application.Handle, SW_HIDE);
  Visible := False;
end;

procedure TMainForm.WMTaskIcon(var Message: TMessage);
var
  P: TPoint;
begin
  case Message.lParam of
    WM_LBUTTONDBLCLK: begin
      end;
    WM_LBUTTONUP: begin
        ShowPhoenixMail1Click(Self);
      end;
    WM_RBUTTONUP: begin
        GetCursorPos(P);
        PopUpMenu6.PopUp(P.X, P.Y);
      end;
  end;
end;

procedure TMainForm.WMSysCommand(var Message: TMessage);
begin
  if (Message.WParam = SC_MINIMIZE) then begin
    ShowWindow(Application.Handle, SW_HIDE);
    Visible := False;
  end
  else
    inherited;
end;

procedure TMainForm.ShowPhoenixMail1Click(Sender: TObject);
begin
  Visible := True;
  ShowWindow(Application.Handle, SW_RESTORE);
  SetForegroundWindow(Application.Handle);
  SetForegroundWindow(Handle);
  if OnlineForm <> nil then try
    SetForegroundWindow(OnlineForm.Handle);
  except end;
end;

procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var s : string;
begin
  if AreWeOnline then
  begin
    //if MessageDlg(GetMessageString(90), mtWarning, [mbYes, mbNo], 0) = mrYes then
    if Application.MessageBox('已经发送和接收邮件，确定要退出吗?', Pchar(Application.Title), MB_YESNO or MB_ICONEXCLAMATION)=6 then
    begin
      Terminating := True;
      if Assigned(OnlineThread) then // AHRK57 (I think <g>)
      begin
        OnlineThread.ShowError(GetMessageString(82));
        repeat Application.HandleMessage;
        until ReadyToClose;
        OnlineThread.Free;  // AHRK57
        OnlineThread := nil; // AHRK57
      end;
      CanClose := True;
    end
    else
      CanClose := False;
  end
  else
  begin
    Terminating := True;
    s := ClearFolder(sTemporaryFolder, FileMightBeInUse);
    if s <> '' then
    begin
      if MessageDlg(Format(GetMessageString(159), [
        #13#10+#13#10+ s + #13#10+#13#10]), mtWarning,
        [MBOK], 0) = mrOK then
      begin
        CanClose := False;
      end;
    end;
  end;
end;

procedure TMainForm.MoveQueuedFromDraft(const Node : TTreeNode);
var SearchRec : TSearchRec;
    I, found : integer;
    OutFolder : string;
    OutNode : TTreeNode;
begin
  // Find the first Outbox...
  OutNode := nil;
  for I := 0 to Node.Count - 1 do
  begin
    if not ((Node.Item[i].StateIndex=tnRepository) or (Node.Item[i].StateIndex=tnThrashBag)) then begin
    if PFolderData(Node.Item[i].Data)^.Outbox then
    begin
      OutNode := Node.Item[i];
    end;
    end;
  end;

  if OutNode = nil then
    exit;

  OutFolder := PFolderData(OutNode.Data)^.Path;

  for I := 0 to Node.Count -1 do
  begin
    if not ((Node.Item[i].StateIndex=tnRepository) or (Node.Item[i].StateIndex=tnThrashBag)) then begin
    if PFolderData(Node.Item[i].Data)^.Drafts then
    begin
      found := FindFirst(PFolderData(Node.Item[i].Data)^.Path + '*.msg',
        faAnyFile, SearchRec);
      while found = 0 do
      begin
        if pos('+', SearchRec.Name) > 0 then
        begin
          // AHRK67 --
          FileCopy(nil, PFolderData(Node.Item[i].Data)^.Path + SearchRec.Name,
                     OutFolder + SearchRec.Name);
          DeleteFile(PFolderData(Node.Item[i].Data)^.Path + SearchRec.Name);
          SetPXTreeNodeName(Node.Item[i]);
          SetPXTreeNodeName(OutNode);
          // AH17...
          if Node.Item[i] = Treeview1.Selected then
          begin
            DeleteItemListView(ciFileName,
              PFolderData(Node.Item[i].Data)^.Path + SearchRec.Name);
          end;
          ActualizeTrash;
        end;
        found := FindNext(SearchRec);
        Application.ProcessMessages; // AH13
      end;
      FindClose(SearchRec);
    end;
    end;
  end;
end;

function TMainForm.OnlineSelectedCount(Node : TTreeNode;
  var TheCommandList : TStringList) : integer;
var sendlist : TStringList;
    ThisItem : TListItem;
begin
    Result := 0;
    sendlist := TStringList.Create;
    sendlist.Add(sTemplateFolder+'Temp.SML');

    // Make sure that POP goes first in that SMTP after Pop case.
    if (PAccountData(Node.Data)^.DoSMTPAfterPOP = 1) then
    begin
      AddPop3Command(Node, TheCommandList);
    end;

    AddSMTPCommand(Node, TheCommandList, sendlist);
    result := SendList.Count;
    sendlist.Free;
end;

procedure TMainForm.OnlineSession(OnlineTyp: TOnlineTyp);
var
  Node: TTreeNode;
  I, ToSendCount,iFilePosition : Integer;
  //TODO -omjg:create temporary for sending
  function GetSubNotes(Node: TTreeNode; var SL: TStringList): Integer;
  var
    SearchRec: TSearchRec;
    I, j,Found: Integer;
    sMailName,sIndexName,sTemp,sStatFile,sUniqueName,sSentIndexName,sSentMailName:string;
    MailFile,IndexFile,StatFile,SentMailFile,SentIndexFile:file of byte;
  begin
    Result := 0;
    for I := 0 to Node.Count - 1 do begin
      if not ((Node.Item[i].StateIndex=tnRepository) or (Node.Item[i].StateIndex=tnThrashBag)) then begin
      if PFolderData(Node.Item[I].Data)^.OutBox then begin

        sMailName := PAccountData(Node.Data)^.Path+trim(PFolderData(Node.Item[I].Data)^.Name)+'.SML';
        sIndexName:= PAccountData(Node.Data)^.Path+trim(PFolderData(Node.Item[I].Data)^.Name)+'.IND';
        sSentMailName:= PAccountData(Node.Data)^.Path+'已发送邮件.SML';
        sSentIndexName:= PAccountData(Node.Data)^.Path+'已发送邮件.IND';


        AssignFile(IndexFile,sIndexName);
        if FileExists(sIndexName) then Reset(IndexFile) else ReWrite(IndexFile);

        j:=0;
        sUniqueName:=GetUniqueMailName;
        sStatFile := PAccountData(Node.Data)^.Path + sUniqueName + '.msg';
        AssignFile(StatFile,sStatFile);
 //       ReWrite(StatFile);
        while not EOF(IndexFile) do begin


          BlockRead(IndexFile, IndexData, SizeOf(TIndexData));
          if IndexData.Delete then Continue;


          //open sent index file and sent mail file
          AssignFile(SentIndexFile,sSentIndexName);
          if FileExists(sSentIndexName) then Reset(SentIndexFile) else ReWrite(SentIndexFile);
          Seek(SentIndexFile,FileSize(SentIndexFile));
          AssignFile(SentMailFile,sSentMailName);
          if FileExists(sSentMailName) then Reset(SentMailFile) else ReWrite(SentMailFile);
          Seek(SentMailFile,FileSize(SentMailFile));
          BlockWrite(SentMailFile,'****************',16);
          iFilePosition:=FilePos(SentMailFile);


           //delete index file in outbox
          IndexData.Delete:=true;
          Seek(IndexFile,FilePos(IndexFile)-SizeOf(TIndexData));
          BlockWrite(IndexFile,IndexData,SizeOf(TIndexData));


          ReWrite(StatFile);
          j:=j+1;
          iPosition:=IndexData.Position;
          iSize:=IndexData.Size;
          buf := StrAlloc(iSize);
          AssignFile(MailFile,sMailName);
          Reset(MailFile);
          Seek(MailFile,iPosition);
          BlockRead(MailFile,buf^,iSize);

          BlockWrite(StatFile,buf^,iSize);
          BlockWrite(SentMailFile,buf^,iSize);
          CloseFile(StatFile);


           /////////////////////write sent index file /////////////////////////////
          CurrentEMail.Clear;
          CurrentEMail.ParseMail(sStatFile,true);
          IndexData.Index:=(FileSize(SentIndexFile) div sizeof(TIndexData))+1;
          IndexData.delete:=false;
          IndexData.Address:=CurrentEMail.ToReceiver[0];
          IndexData.Subject:=CurrentEMail.Subject;
          IndexData.SDate:=CurrentEMail.ADate;
          IndexData.STime:=CurrentEMail.ATime;
          IndexData.Priority:=CurrentEMail.Priority;
          IndexData.Read:=true;
          IndexData.Attach:=CurrentEMail.cntAttachments;
          IndexData.Position:=iFilePosition;
          IndexData.Size:=iSize;
//          IndexData.Edit:=true;
          BlockWrite(SentIndexFile, IndexData,sizeof(TIndexData));
           /////////////////////write sent index file /////////////////////////////

          sTemp:=PAccountData(Node.Data)^.Path + sUniqueName +InttoStr(j)+ '.msg' ;
          FileCopy(nil, sStatFile,sTemp);
          SL.Add(sTemp);
          Inc(Result);
          StrDispose(buf);
          CloseFile(MailFile);
          CloseFile(SentIndexFile);
          CloseFile(SentMailFile);

        end;
        CloseFile(IndexFile);
        DeleteFile(sStatFile);
      end;
      if Node.Count > 0 then
        GetSubNotes(Node.Item[I], SL);
      end;
    end;
  end;

  procedure AddAccountData(Node: TTreeNode);
  var
    SL: TStringList;
    POPDone : Boolean;
  begin
    PopDone := False; // PopDone has to be set DUDE.
    if (OnlineTyp in [otFetchSendOne, otSendMail, otGoOnline, otScheduled,
      otSendAll]) and  (PAccountData(Node.Data)^.DoSMTP = 1) then
    begin
      SL := TStringList.Create;
  //    MoveQueuedFromDraft(Node); // AH13 Move all queued from Draft to outbox
      GetSubNotes(Node, SL);
      ToSendCount := SL.Count;
      if SL.Count > 0 then
      begin
        if (PAccountData(Node.Data)^.DoSMTPAfterPOP = 1) and
         (PAccountData(Node.Data)^.DoPOP = 1) then
        begin
          AddPop3Command(Node, OnlineForm.CommandList);
          PopDone := True;
        end;
        AddSMTPCommand(Node, OnlineForm.CommandList, SL);
      end;
      SL.Free;
    end;

    if (OnlineTyp in [otFetchSendOne,otFetchMail, otGoOnline,
      otScheduled, otFetchAll]) and (PAccountData(Node.Data)^.DoPOP = 1) then
    begin
      if Not PopDone then
        AddPop3Command(Node, OnlineForm.CommandList);
    end;
  end;
begin
  MainForm.Label5.Caption:='';
  if AreWeOnline then Exit;
  FetchedMailCount := 0;
  SendMailCount := 0;
  AvailableMailCount := 0;
  ToSendCount := 0;
  Node := GetActualAccount;
  if Assigned(Node) = False then Exit;
  if Assigned(Node.Data) = False then Exit;
  if not (OnlineTyp in [4, 8]) then
  begin
    lblSubject.Caption := '';
    ListView1.Selected := nil;
    UpdateListView;
  end;
  Screen.Cursor := crHourGlass;
  StrPCopy(NotifyIconData.szTip, 'SMAIL - ' + GetMessageString(36));

  NotifyIconData.hIcon := imgOnline.Picture.Icon.Handle;
  Shell_NotifyIcon(NIM_MODIFY, @NotifyIconData);

  AreWeOnline := True;
  ReadyToClose := False;
  Abort := False;
  AnimationToLeft := True;
  AnimationPosition := -AniBmp1.Width + 3;
  if not bHideAnimations then PaintBox1.Visible := True;

  OnlineForm := TOnlineForm.Create(Self);
  FrmShowError:= TFrmShowError.Create(self);

  if Assigned(LangHolder) then
  begin
    if LangHolder.Language <> '' then   LangHolder.Translate([OnlineForm]);
  end;
  OnlineForm.OnlineTyp := OnlineTyp;

  if OnlineTyp = otSendSelected then
  begin
    ToSendCount := OnlineSelectedCount(Node, OnlineForm.CommandList);
  end;
  if OnlineTyp in [otFetchSendOne, otFetchMail, otSendMail] then
    AddAccountData(Node); // just one Account
  if OnlineTyp in [otGoOnline, otScheduled, otFetchAll, otSendAll] then begin
    for I := 0 to TreeView1.Items.Count - 1 do // all Accounts
      if TreeView1.Items[I].StateIndex = tnAccount then
        AddAccountData(TreeView1.Items[I]);
  end;

  //  Recreate just to make sure...
  if SelectMailForm <> nil then
  begin
    SelectMailForm.Free;
    SelectMailForm := nil;
  end;
  SelectMailForm := TSelectMailForm.Create(Self);
  if Assigned(LangHolder) then
  begin
      if LangHolder.Language <> '' then
         LangHolder.Translate([SelectMailForm]);
  end;

  // I want to make sure we bail out if there's really nothing to send
//  ToSendCount:=1;//mjg
  if (OnlineTyp in [otSendMail, otSendSelected]) and (ToSendCount = 0) then
  begin
    try
      OnlineForm.ShowStatusMessage;
    except
    end;
    Exit;
  end;

  FrmShowError.Show;
  OnlineThread := TOnlineThread.Create;
  OnlineThread.CommandCount := OnlineForm.CommandList.Count;
  OnlineForm.DialUpNetwork;
  if Abort then Exit;
  OnlineThread.Resume;
end;

procedure TMainForm.DragDropWndProc(var Message: TMessage);
begin
  with Message do begin
    if Msg = WM_DROPFILES then
      DragDropFiles(HDrop(wParam))
    else
      Result := CallWindowProc(DragDropDefWndProc, ListView2.Handle, Msg,
        WParam, LParam);
  end;
end;

procedure TMainForm.DragDropFiles(hDropHandle: HDrop);
var
  PFilename: PChar;
  I, Count: Integer;
begin
  if (ListView1.SelCount <> 1) or (ListView1.Selected = nil) then
    Exit;
  GetMem(PFilename, 256);
  Count := DragQueryFile(hDropHandle, $FFFFFFFF, nil, 255);
  for I := 0 to Count - 1 do begin
    DragQueryFile(hDropHandle, I, PFilename, 255);
    AddAttachment(StrPas(PFilename));
  end;
  FreeMem(PFilename, 256);
end;

procedure TMainForm.WndProc(var Message: TMessage);
var SL: TStringList;
    x : integer;

  procedure clearParams;
  begin
    sWriteNewMessage1 := '';
    sWriteNewMessage2 := '';
    sWriteNewMessage3 := '';
    iParamCommand := -1;
  end;

  procedure ReadFile;
  begin
    try
      AssignFile(TextFile, sTempNewMessageFile);
      Reset(TextFile);
      ReadLn(TextFile, sWriteNewMessage1);
      ReadLn(TextFile, sWriteNewMessage2);
      ReadLn(TextFile, sWriteNewMessage3);
      CloseFile(TextFile);
      DeleteFile(sTempNewMessageFile);
    except
    end;
  end;

begin
  case message.msg of
    WM_PREVINSTRUN :
    begin
      case message.WParam of
        paMailEmptyEmail , paMailCompleteEmail :
        begin
          if message.WParam = 1 then
          begin
            ReadFile;
          end;
          ShowPhoenixMail1Click(Self);

          if (sWriteNewMessage1 <> '') then
          begin
            if sWriteNewMessage3 <> '' then
            begin
              SL := TStringList.Create;
              SL.Add(sWriteNewMessage3);
              NewMessage(false, True, sWriteNewMessage2,
                sWriteNewMessage1, '', SL);
              SL.Free;
            end
            else
              NewMessage(false, True, sWriteNewMessage2,
                sWriteNewMessage1, '', nil);
            clearParams;
          end;
        end;
        paMailAttachEmail :
        begin
          // AH13 handling of attached mails...
          ReadFile;
          if sWriteNewMessage1 <> '' then
          begin
            SL := TStringList.Create;
            SL.CommaText := sWriteNewMessage1;
            ShowPhoenixMail1Click(Self);
            NewMessage(false, True, '', '', '', nil);
            for x := 0 to SL.Count -1 do
            begin
              if FileExists(Sl.Strings[x]) then
              begin
                AddAttachment(SL.Strings[x]);
              end;
            end;
            SL.Free;
            // AH14 Update filesize
            ListView1.Selected.SubItems[ciSize] :=
              FormatByteText(GetFileSize(ListView1.Selected.SubItems[ciFileName]));
            clearParams;
          end;
        end;
      end;
    end;
    WM_GETFORMHANDLES :
    begin
      StdMailForm.Free;
    end;
    else
    begin
      inherited WndProc(Message);
    end;
  end;
end;

procedure TMainForm.TreeView1Compare(Sender: TObject; Node1, Node2: TTreeNode;
  Data: Integer; var Compare: Integer);
begin
  Compare := AnsiStrIComp(PChar(GetPXTreeNodeName(Node1)),
    PChar(GetPXTreeNodeName(Node2)));
  if Node1 = AccountsNode then
    Compare := 0
  else if Node1 = TrashNode then
    Compare := 0
  else if Node1 = RepositoryNode then
    Compare := 0;
end;

procedure TMainForm.Timer2Timer(Sender: TObject);
var
  B: Boolean;
  Hour1, Min1, Hour2, Min2, Sec, MSec: Word;
begin
  if (csDestroying in ComponentState) or (csLoading in ComponentState) then
    Exit;
  //Auto Quit
  if (bDUNAutoQuit = True) and (AreWeOnline) then begin
    Inc(OnlineCounter);
    if OnlineCounter >= iDUNAutoQuitTime then begin
      OnlineThread.ShowError(Format(GetMessageString(81),
        [IntToStr(iDUNAutoQuitTime)]));
      Application.ProcessMessages;
      DialUp1.GoOffline;
    end;
  end;
  //Schedule
  Inc(MinutesSinceStart);

  if MinutesSinceStart > 30001 then
    MinutesSinceStart := 0;
  if MinutesSinceStart = sScheduleS1 then begin
    MinutesSinceStart := 0;
    B := True;
  end
  else
    B := False;
  if AreWeOnline then
    Exit;
  if bScheduleC5 then
    if MainForm.DialUp1.CurrentConnection = '' then
      Exit;
  if bScheduleC1 then
  begin
    if B { AHRK59 and (not ToolbarButton9743.Down)} then
      OnlineSession(otScheduled);
  end;

  if bScheduleC2 = False then
    Exit;
  DecodeTime(Time, Hour1, Min1, Sec, MSec);
  if bScheduleC3 then begin
    DecodeTime(StrToTime(sScheduleS2), Hour2, Min2, Sec, MSec);
    if (Hour1 = Hour2) and (Min1 = Min2) {AHRK59 and (not actAccountPauseScheduler.Checked)}
    then
      OnlineSession(otScheduled);
  end;
  if bScheduleC4 then begin
    DecodeTime(StrToTime(sScheduleS3), Hour2, Min2, Sec, MSec);
    if (Hour1 = Hour2) and (Min1 = Min2) { AHRK59 and
      (not actAccountPauseScheduler.Checked)} then
      OnlineSession(otScheduled);
  end;
end;

procedure TMainForm.StatusBar1DrawPanel(StatusBar: TStatusBar;
  Panel: TStatusPanel; const Rect: TRect);
begin
  if Panel = StatusBar1.Panels[0] then begin
    StatusBar.Canvas.TextOut(Rect.Left + 19, Rect.Top + 1, Panel.Text);
    StatusBar.Canvas.Draw(Rect.Left, Rect.Top, Image6.Picture.Bitmap);
  end
  else if Panel = StatusBar1.Panels[1] then begin
    StatusBar.Canvas.TextOut(Rect.Left + 19, Rect.Top + 1, Panel.Text);
    StatusBar.Canvas.Draw(Rect.Left + 1, Rect.Top, Image7.Picture.Bitmap);
  end
  else if Panel = StatusBar1.Panels[2] then begin
    StatusBar.Canvas.TextOut(Rect.Left, Rect.Top + 1, Panel.Text);
  end
  else if Panel = StatusBar1.Panels[3] then
  begin
    if Panel.Text <> '' then
    begin
      StatusBar.Canvas.Draw(Rect.Left + 1, Rect.Top, Image9.Picture.Bitmap);
    end;

  end;
end;


procedure TMainForm.DialUp1StatusEvent(Sender: TObject; MessageText: string;
  Error: Boolean);
begin
  if (OnlineThread <> nil) and (OnlineForm <> nil) then begin
    OnlineThread.SetStatusString(-1, MessageText, '');
    if Error then begin
      DialUp1.GoOffline;
      OnlineThread.ShowError(MessageText);
    end;
  end;
end;

procedure TMainForm.EmptyReposit;
var
  SearchRec: TSearchRec;
  Found: Integer;
begin
  Screen.Cursor := crHourGlass;
  Application.ProcessMessages;
  try
    // AH10
    Found := FindFirst(sRepositoryFolder + '*.msg', faAnyFile, SearchRec);
    while Found = 0 do begin
      SetFileAttr(sRepositoryFolder + SearchRec.Name, False, True, False, False);
      DeleteFile(sRepositoryFolder + SearchRec.Name);
      DoSynchSearch(sRepositoryFolder + SearchRec.Name, ''); // AHRK34
      Found := FindNext(SearchRec);
    end;
    FindClose(SearchRec);
  finally
    Screen.Cursor := crDefault;
  end;
end;

procedure TMainForm.EmptyRepository1Click(Sender: TObject);
begin
  if not ConfirmDelete(true) then Exit;
  EmptyReposit;
  // AHRK165--
  if TreeView1.Selected = RepositoryNode then
    TreeView1Change(Self, TreeView1.Selected);
  ActualizeTrash;
  TreeView1.Invalidate;
end;

procedure TMainForm.ASpeedButton1Click(Sender: TObject);
var
  P: TPoint;
begin
  P := ASpeedButton1.ClientToScreen(Point(ASpeedButton1.Width, 0));
  if ASpeedButton1.Enabled then
    PopUpMenu2.Popup(P.X, P.Y);
end;

{procedure TMainForm.RichEdit1URLClick(Sender: TObject; URL: string);
var
  wStr, lStr, Address, Subject, ABody: string;
begin
  ParseMailto(URL, Address, Subject, ABody);
  lStr := Copy(URL, 0, 7);
  if (LowerCase(lStr) = 'mailto:') then begin
    NewMessage(false, True, Subject, Address, '', nil);
    exit;
  end;

  wStr := lowercase(URL);
  if pos('www', wStr) = 1 then URL := 'http://' + URL;
  ShellExecute(0, 'open', PChar(URL), '', '', SW_SHOWMAXIMIZED);
end;}

procedure TMainForm.actFileFetchSendMailExecute(Sender: TObject);
begin
  OnlineSession(otGoOnline);
end;

procedure TMainForm.actFileCancelOnlineOperationExecute(Sender: TObject);
begin
//  if not AreWeOnline then
//    Exit;
 // OnlineThread.ShowError(GetMessageString(82));
   menCancelOnlineOperation1.Checked:=not menCancelOnlineOperation1.Checked;
end;

procedure TMainForm.actFilePrintExecute(Sender: TObject);
var
  withui: OleVariant;
begin
  withui := true;
  DHTMLEdit1.PrintDocument(withui);
end;


procedure TMainForm.actFilePrinterSetupExecute(Sender: TObject);
begin
{  // RR
  if not (Printer <> nil) and (Printer.Printers.Count>0) then
  begin
    MessageDlg(GetMessageString(18), mtError, [mbOk], 0);
    Exit;
  end;
  // RR
 }
 DHTMLEdit1.PrintDocument;
end;

procedure TMainForm.actFileExitExecute(Sender: TObject);
begin
  Close;
end;


procedure TMainForm.actEditDeleteExecute(Sender: TObject);
begin
  if (RichEdit1.Enabled) then
    RichEdit1.ClearSelection;
end;

procedure TMainForm.actEditSelectAllExecute(Sender: TObject);
var i : integer;
begin
  if (RichEdit1.Enabled) and (RichEdit1.Focused) then
    RichEdit1.SelectAll;

  if (ListView1.Focused) and (ListView1.Items.Count > 0) then
  begin
    for I := 0 to ListView1.Items.Count - 1 do
      ListView1.Items[I].Selected := True;
  end;

  if (ListView2.Focused) and (ListView2.Items.Count > 0) then
  begin
    for I := 0 to ListView2.Items.Count - 1 do
      ListView2.Items[I].Selected := True;
  end;
end;

procedure TMainForm.actFileFetchSendMailUpdate(Sender: TObject);
begin
  // AHRK85 --- Was GetActualAccount
  (Sender as TAction).Enabled := not ((ActiveAccount = nil) or
    (AreWeOnline));
end;

procedure TMainForm.actFileCancelOnlineOperationUpdate(Sender: TObject);
begin
  //(Sender as TAction).Enabled := AreWeOnline and not SocketConnecting;
end;

procedure TMainForm.actFilePrintUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (Printer <> nil) and (Printer.Printers.Count>0) and
    (RichEdit1.Enabled);
end;

procedure TMainForm.actFilePrinterSetupUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (Printer <> nil) and (Printer.Printers.Count>0);
end;



procedure TMainForm.AppIdleDiposit(Sender: TObject; var Done: Boolean);
var
  SL: TStringList;
  U: string;
begin
  Application.OnIdle := nil;

  if (not bIgnoreDipositRequest) and
    (Length(CurrentEmail.DispositionNotification) > 0) then begin
    Application.ProcessMessages;
    if
      Application.MessageBox(Pchar(GetMessageString(131) +  CrLf +
      GetMessageString(132)), PChar(sAppTitle), MB_ICONQUESTION +
        MB_YESNO) = IDYES then begin

      SL := TStringList.Create;
      try
        U := DateToStr(CurrentEMail.ADate) + ' at ' +
          TimeToStr(CurrentEMail.ATime) + ' ';
        SL.Add(Format(GetMessageString(94),
          [StringListToCommataString(CurrentEMail.ToReceiver, false), U]));
        SL.Add('');
        U := DateToStr(Date) + ' at ' + TimeToStr(Time) + ' ';
        SL.Add(Format(GetMessageString(95), [U]));
        U := Format(GetMessageString(93), [CurrentEMail.Subject]);
        NewMessage(false, true, U, CurrentEmail.DispositionNotification, '',
          SL);
      finally
        SL.Free;
      end;
    end;
  end;
end;

procedure TMainForm.actEditCutUpdate(Sender: TObject);
begin
//  (Sender as TAction).Enabled := not RichEdit1.ReadOnly;
end;

procedure TMainForm.actEditCopyUpdate(Sender: TObject);
begin
//  (Sender as TAction).Enabled := not RichEdit1.ReadOnly;
end;

procedure TMainForm.actEditPasteUpdate(Sender: TObject);
begin
//    (Sender as TAction).Enabled := NOT RichEdit1.ReadOnly;
end;

procedure TMainForm.actEditDeleteUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (RichEdit1.SelLength > 0) and
    not RichEdit1.ReadOnly;
end;

procedure TMainForm.actEditSelectAllUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (RichEdit1.Enabled)
    or (ListView1.SelCount > 0) or (ListView2.SelCount > 0);
end;

procedure TMainForm.actAccountFetchMailExecute(Sender: TObject);
var
  dofetch: Byte;
begin
  if GetActualAccount = nil then Exit;
  dofetch := PAccountData(GetActualAccount.Data)^.DoPOP;
  PAccountData(GetActualAccount.Data)^.DoPOP := 1;
  OnlineSession(otFetchMail);
  PAccountData(GetActualAccount.Data)^.DoPOP := dofetch;
end;

procedure TMainForm.actAccountSendMailExecute(Sender: TObject);
var
  dosend: Byte;
begin
  if GetActualAccount = nil then Exit;
  dosend := PAccountData(GetActualAccount.Data)^.DoSMTP;
  PAccountData(GetActualAccount.Data)^.DoSMTP := 1;
  OnlineSession(otSendMail);
  PAccountData(GetActualAccount.Data)^.DoSMTP := dosend;
end;



//create new account
procedure TMainForm.actAccountNewExecute(Sender: TObject);
var
  Node, FNode: TTreeNode;
  Data: PAccountData;
  Folder: PFolderData;
  StdIni: TIniFile;
  iTask : integer;
begin
  iSuccess:=false;
  stepform:=Tstepform.Create(self);
  stepform.ShowModal;
  try
    New(Data);
    Data^.Name := GetMessageString(3);
    Data^.POPPort := '110';
    Data^.SMTPPort := '25';
    Data^.DoSMTP := 1;
    Data^.DoPOP := 1;
    Data^.ShowDownload := 0;
    Data^.DoSMTPAfterPOP := 0;
    Data^.StandardDownload := 0;
    Data^.PromptPassword := 0;
    Data^.SMTPAuthenticate := false;

    if FileExists(sStandardAccountDataFile) then
    begin
      StdIni := TIniFile.Create(sStandardAccountDataFile);
      with StdIni do begin
        Data^.Name := ReadString('Account', 'Name', GetMessageString(3));
        Data^.FromMail := ReadString('From', 'EMail', '');
        Data^.FromDesc := ReadString('From', 'Name', '');
        Data^.ReplyMail := ReadString('ReplyTo', 'EMail', '');
        Data^.ReplyDesc := ReadString('ReplyTo', 'Name', '');
        Data^.POPServer := ReadString('POP3', 'Server', '');
        Data^.POPPort := ReadString('POP3', 'Port', '110');
        Data^.POPUser := ReadString('POP3', 'User', '');
        Data^.POPPass := MHDecrypt(ReadString('POP3', 'Password', ''));
        Data^.SMTPServer := ReadString('SMTP', 'Server', '');
        Data^.SMTPPort := ReadString('SMTP', 'Port', '25');
        Data^.Organization := ReadString('From', 'Organization', '');
        Data^.PromptPassword := ReadInteger('POP3', 'PromptPassword', 0);
        Data^.DoSMTP := ReadInteger('SMTP', 'DoSMTP', 1);
        Data^.DoPOP := ReadInteger('POP3', 'DoPOP', 1);

        Data^.ShowDownload := ReadInteger('POP3', 'ShowDownload', 0);
        Data^.StandardDownload := ReadInteger('POP3', 'StandardDownload', 0);
        Data^.KeepFilter := ReadString('Filter', 'Keep', '');
        Data^.DeleteFilter := ReadString('Filter', 'Delete', '');
        Data^.SMTPAuthenticate := ReadBool('SMTP', 'Auth', false);
        Data^.SMTPUserName := ReadString('SMTP', 'AuthUser', '');
        Data^.SMTPPassword := MHDecrypt(ReadString('SMTP', 'AuthPassword', ''));
        Data^.DoSMTPAfterPOP := ReadInteger('SMTP', 'SMTPAfterPOP', 0);
        Free;
      end;
    end;

    if iSuccess = true then
    begin
      stepform.SaveAccountData(Data);

      SaveAccountDataToFile(Data);


      Node := TreeView1.Items.AddChild(AccountsNode, Data^.Name);
      Node.Data := Data;
      Node.StateIndex := tnAccount;
      Node.ImageIndex := 0;
      Node.SelectedIndex := 0;
      // Child folders
      New(Folder);
      Folder^.Name := GetMessageString(5);
      Folder^.Outbox := False;
      Folder^.Inbox := True;
      Folder^.Drafts := False;
      Folder^.Path := Data^.Path;
      SaveFolderDataToFile(Folder);
      FNode := TreeView1.Items.AddChild(Node, Folder^.Name);
      FNode.Data := Folder;
      FNode.StateIndex := tnFolder;
      FNode.ImageIndex := 15;
      FNode.SelectedIndex := 16;


      New(Folder);
      Folder^.Name := GetMessageString(4);
      Folder^.Outbox := True;
      Folder^.Inbox := False;
      Folder^.Drafts := False;
      Folder^.Path := Data^.Path;
//      CreateFolder(Folder^.Path);
      SaveFolderDataToFile(Folder);
      FNode := TreeView1.Items.AddChild(Node, Folder^.Name);
      FNode.Data := Folder;
      FNode.StateIndex := tnFolder;
      FNode.ImageIndex := 3;
      FNode.SelectedIndex := 4;



      //Repository
      FNode := TreeView1.Items.AddChild(Node, GetMessageString(2));
      FNode.StateIndex := tnRepository;
      FNode.ImageIndex := 8;
      FNode.SelectedIndex := 8;
      RepositoryNode := FNode;


      //Trash bag
      FNode := TreeView1.Items.AddChild(Node, GetMessageString(1));
      FNode.StateIndex := tnThrashBag;
      FNode.ImageIndex := 6;
      FNode.SelectedIndex := 6;
      TrashNode := FNode;



      New(Folder);
      Folder^.Name := GetMessageString(6);
      Folder^.Outbox := False;
      Folder^.Inbox := False;
      Folder^.Drafts := True;
      Folder^.Path := Data^.Path;
      SaveFolderDataToFile(Folder);
      FNode := TreeView1.Items.AddChild(Node, Folder^.Name);
      FNode.Data := Folder;
      FNode.StateIndex := tnFolder;
      FNode.ImageIndex := 17;
      FNode.SelectedIndex := 18;

      // AH15 Set account node icon when creating new account
      itask := GetServerStatus(Data^.DoSMTP, Data^.DoPop);
      SetServerStatus(Node, itask);

      Node.Expanded := True;
      TreeView1.SetFocus;
      Node.Selected := True;
      TreeView1.Selected := Node;
//      TreeView1.AlphaSort;
      CollectAccountsEmail(fldFromHeader.Items);
    end
    else
       Dispose(Data);
  finally
    stepform.Free;
  end;
  Treeview1.SaveToFile(sAccountRootFolder+'Fold.st');
end;

procedure TMainForm.actAccountDeleteExecute(Sender: TObject);
var
  Node: TTreeNode;
  Data: PAccountData;
begin
  Node := GetActualAccount;
  if Assigned(Node) then
  begin
    if Assigned(Node.Data) then
    begin
      if MessageBox(Handle,PChar(Format(GetMessageString(9),
        [GetPXTreeNodeName(Node)])),  Pchar(GetMessageString(141)),
        mb_YesNo or mb_IconWarning or mb_DefButton2) = mrYes then
      begin
        Data := Node.Data;
        DeleteFolder(Data^.Path, sTrashFolder);
        Node.Delete;
        ActiveAccount := GetActualAccount;
  //      ActualizeTrash;
//        TreeView1.AlphaSort;
        CollectAccountsEmail(fldFromHeader.Items); // AHRK130
      end;
    end;
  end;
  Treeview1.SaveToFile(sAccountRootFolder+'Fold.st');
end;

procedure TMainForm.actAccountPropertiesExecute(Sender: TObject);
var
  Node: TTreeNode;
  Data: PAccountData;
  itask : integer; // AH09
begin
  Node := GetActualAccount;
  if Assigned(Node) then
    if Assigned(Node.Data) then begin
      AccountForm := TAccountForm.Create(Self);
      if Assigned(LangHolder) then
      begin
        if LangHolder.Language <> '' then
          LangHolder.Translate([AccountForm]);
      end;
      try
        Data := Node.Data;
        AccountForm.CreateNewAccount := False;
        AccountForm.LoadAccountData(Data);
        if AccountForm.ShowModal = mrOK then
        begin
          AccountForm.SaveAccountData(Data);
          itask := GetServerStatus(Data^.DoSMTP, Data^.DoPop); //AH09
          SetServerStatus(Node, itask); //AH09
          SaveAccountDataToFile(Data);
          SetPXTreeNodeName(Node);
          TreeView1.AlphaSort;
        end;
      finally
        AccountForm.Free;
      end;
    end;
end;

procedure TMainForm.actAccountFetchMailUpdate(Sender: TObject);
var
  // AHRK85  Node: TTreeNode;
  r : Boolean; // We don't want the update process blink the button...
begin
  r := False;
  // AHRK85 Node := GetActualAccount;
  if Assigned(ActiveAccount) then
  begin
    if Assigned(ActiveAccount.Data) then
    begin
      if AreWeOnline = False then
      begin
        r := true;
      end;
    end;
  end;
  (Sender as TAction).Enabled := r;
end;

procedure TMainForm.actAccountNewUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := true;
end;

procedure TMainForm.actAccountDeleteUpdate(Sender: TObject);
var abool : Boolean;
begin
  //AH17
  abool := False;
  // AH17--- pointed out by Igor.
  if Assigned(TreeView1.Selected) then
    if not IsTypeOfFolder(TreeView1.Selected, setSysFolders) then
      abool := True;
  (Sender as TAction).Enabled := abool;      
end;

procedure TMainForm.actAccountPropertiesUpdate(Sender: TObject);
var
  // AHRK85  Node: TTreeNode;
  abool : boolean;
begin
  abool := False;
  // AHRK85  Node := GetActualAccount;
  if Assigned(ActiveAccount) then
    if Assigned(ActiveAccount.Data) then
      abool := True;
  (Sender as TAction).Enabled := Abool;
end;

procedure TMainForm.actFolderNewExecute(Sender: TObject);
var
  Node: TTreeNode;
  Data: PFolderData;
begin
  if Assigned(TreeView1.Selected) then
    Node := TreeView1.Selected
  else
    Node := TreeView1.TopItem;

  if Assigned(Node) then
    if Node.StateIndex in [tnAccount, tnFolder] then
      if Assigned(Node.Data) then begin
        FrmNewFold := TFrmNewFold.Create(Self);
        if Assigned(LangHolder) then
        begin
          if LangHolder.Language <> '' then
              LangHolder.Translate([FolderForm]);
        end;
        try
          New(Data);
          if FrmNewFold.ShowModal = mrOK then begin
            FrmNewFold.SaveFolderData(Data);
            Node := TreeView1.Items.AddChild(Treeview1.Items[iNodeCount], Data^.Name);
            Node.Data := Data;
            Node.StateIndex := tnFolder;
            Node.ImageIndex := 17;
            Node.SelectedIndex := 18;
            Node.Parent.Expanded := True;
            TreeView1.SetFocus;
            Node.Selected := True;
            TreeView1.Selected := node;
          end
          else
            Dispose(Data);
        finally
          FolderForm.Free;
        end;
        Treeview1.SaveToFile(sAccountRootFolder+'Fold.st');
  //      TreeView1.AlphaSort;
      end;
end;

procedure TMainForm.actFolderDeleteExecute(Sender: TObject);
var
  Node, AcNode, lpNode: TTreeNode;
  Data: PFolderData;
  flInBox, flOutBox, flDraft : integer;
  sum : Boolean;
  sFolder : string;
begin
  Node := TreeView1.Selected;
  if Assigned(Node) then
  begin
    if Node.StateIndex = tnFolder then
    begin
      flInBox := 0; flOutbox := 0; flDraft := 0;
      acNode := GetSelectedAccountNode(Node);
      if AcNode  <> nil then
      begin
         lpNode :=
           WalkAccountChildren(AcNode, AcNode, [tnFolder]);
         while lpNode <> nil do
         begin
           case lpNode.ImageIndex of
           3  : inc(flOutbox);
           15 : inc(flInbox);
           17 : inc(flDraft);
           end;
           lpNode := WalkAccountChildren(acNode, lpNode.GetNext, [tnFolder]);
         end;
      end;

      if Assigned(Node.Data) then
      begin
        sFolder := '';
        case Node.ImageIndex of
        3  :  begin
                dec(flOutBox);
                sFolder := ' (' + GetMessageString(4) + ')';
              end;
        15 :  begin
                dec(flInbox);
                sFolder := ' (' + GetMessageString(5) + ')';
              end;
        17 :  begin
               dec(flDraft);
               sFolder := ' (' + GetMessageString(6) + ')';
              end;
        end;

        Sum := (flOutBox > 0) and (flInbox > 0) and (flDraft > 0);

        if Sum then
        begin
          if MessageBox(Handle,PChar(Format(GetMessageString(8),
           [GetPXTreeNodeName(Node) + sFolder])),Pchar(GetMessageString(141)),
           mb_YesNo or mb_IconQuestion or mb_DefButton2) = mrYes then
          begin
            Data := Node.Data;
            DeleteFolder(Data^.Path, sTrashFolder);
            DoSynchSearch(Data^.Path, '');
            Node.Delete;
            ActualizeTrash;
            TreeView1.AlphaSort;
          end;
        end;
      end;
    end;
  end;
  Treeview1.SaveToFile(sAccountRootFolder+'Fold.st');
end;

procedure TMainForm.actFolderPropertiesExecute(Sender: TObject);
var
  Node: TTreeNode;
  Data: PFolderData;
  S: string;
begin
  Node := TreeView1.Selected;
  if Assigned(Node) then
    if Node.StateIndex = tnFolder then
      if Assigned(Node.Data) then begin
        FolderForm := TFolderForm.Create(Self);
        if Assigned(LangHolder) then
        begin
          if LangHolder.Language <> '' then
            LangHolder.Translate([FolderForm]);
        end;
        try
          Data := Node.Data;
          S := Data^.Path;
          FolderForm.LoadFolderData(Data);
          if FolderForm.ShowModal = mrOK then begin
            FolderForm.SaveFolderData(Data);
            MoveFolder(S, Data^.Path);
            SaveFolderDataToFile(Data);
            if Data^.OutBox then
            begin
              Node.ImageIndex := 3;
              Node.SelectedIndex := 4;
            end
            else if Data^.InBox then begin
              Node.ImageIndex := 15;
              Node.SelectedIndex := 16;
            end
            else
            begin
                if Data^.Drafts then
                begin
                  Node.ImageIndex := 17;
                  Node.SelectedIndex := 18;
                end
                else
                begin
                  Node.ImageIndex :=  1;
                  Node.SelectedIndex := 2
                end;
            end;
            SetPXTreeNodeName(Node);
            TreeView1.AlphaSort;
            // AH15, moved only update when mrOK
            Node := TreeView1.Selected;
            TreeView1.Selected := nil;
            TreeView1.Selected := Node
          end;
        finally
          FolderForm.Free;
        end;
        // AH15
        // Node := TreeView1.Selected;
        // TreeView1.Selected := nil;
        // TreeView1.Selected := Node
      end;end;

procedure TMainForm.actFolderNewUpdate(Sender: TObject);
var
  Node: TTreeNode;
  abool : Boolean;
begin
  abool := False;
  Node := TreeView1.Selected;
  if Assigned(Node) then
    if Assigned(Node.Data) then begin
      if Node.StateIndex = tnFolder then begin
        abool := True;
      end;
      if Node.StateIndex = tnAccount then begin
        abool := True;
      end;
    end;
  (Sender as TACtion).Enabled := abool;
end;

procedure TMainForm.actFolderDeleteUpdate(Sender: TObject);
var
  Node: TTreeNode;
  abool : Boolean;
begin
  aBool := false;
  Node := TreeView1.Selected;
  if Assigned(Node) then
    if Assigned(Node.Data) then begin
      if Node.StateIndex = tnFolder then begin
        abool := True;
      end;
    end;
  (Sender as TACtion).Enabled := aBool;
end;

procedure TMainForm.actFolderPropertiesUpdate(Sender: TObject);
var
  Node: TTreeNode;
  abool : Boolean;
begin
  abool := False;
  Node := TreeView1.Selected;
  if Assigned(Node) then
    if Assigned(Node.Data) then begin
      if Node.StateIndex = tnFolder then begin
        abool := True;
      end;
    end;
  (Sender as TACtion).Enabled := abool;
end;

procedure TMainForm.actMessageNewExecute(Sender: TObject);
var
  loadStr: array[0..255] of char;
   ViewMailFrm:TViewMailFrm;
begin
  bEdit:=true;
  bNewDoc:=true;
  UseHtml:=true;
  GetProfileString(AttSection, 'Attachment', '', loadStr, sizeOf(loadStr));
  sZipOutFileName := loadStr;
  EnablePopUpMenu(false);
    if IsTypeOfFolder(TreeView1.Selected, setSysFolders) then
       actAccountShowDefaultExecute(Sender);
    if PanelHeaders.Visible then
    begin
      NewMessage(False, True, '', '', '', nil);
    end
    else
    begin
      NewMessage(True, True, '', '', '', nil);
    end;

  EnablePopUpMenu(true);
  if sZipOutFileName <> '' then
  begin
    if FileExists(sZipOutFileName) then
      AddAttachment(sZipOutFileName);
    sZipOutFileName := '';
    WriteProfileString(AttSection, 'Attachment', nil);
  end;

  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;

end;

procedure TMainForm.actMessageDeleteExecute(Sender: TObject);
var
  Item: TListItem;
  S: string;
  I, E,iIndexPosition: Integer;
  TempMailFile,TempIndexFile:file of byte;
  sTempMailFile,sTempIndexFile:string;
  isTrash:Boolean;

begin
  if ListView1.Selected=nil  then exit;
  if not ConfirmDelete((TreeView1.Selected.StateIndex = tnThrashBag)) then Exit;
  isTrash:=(TreeView1.Selected.StateIndex = tnThrashBag);
///////////////////////////////delete mail////////////////
  ActiveAccount := GetActiveAccount(TreeView1.Selected);
  Dir := PAccountData(ActiveAccount.Data)^.Path;
  sTempIndexFile:=Dir+'已删除邮件'+'.IND';
  sTempMailFile:=Dir+'已删除邮件'+'.SML';
  I := 0;
  E := ListView1.Items.Count - 1;
  while I <= E do begin
    if ListView1.Items[I].Selected then begin
      with ListView1.Items[I] do begin
        iIndexPosition:=StrToInt(SubItems[6]);
      end;
      iIndexPosition:=(iIndexPosition-1)*Sizeof(TIndexData);
      AssignFile(IndexFile,sMailIndexFile);
      Reset(IndexFile);
      Seek(IndexFile,iIndexPosition);
      BlockRead(IndexFile, IndexData, SizeOf(TIndexData));

      if not isTrash then
      begin
        AssignFile(TempMailFile,sTempMailFile);
        if FileExists(sTempMailFile) then Reset(TempMailFile) else ReWrite(TempMailFile);
        Seek(TempMailFile,FileSize(TempMailFile));
        //read the responding mail file and write to destination mail file


        iPosition:=IndexData.Position;
        iSize:=IndexData.Size;
        buf := StrAlloc(iSize);

        AssignFile(MailFile,sMailFile);
        Reset(MailFile);
        Seek(MailFile,iPosition);
        BlockRead(MailFile,buf^,iSize);


        BlockWrite(TempMailFile,'****************',16);
        iPosition:=FilePos(TempMailFile);
        BlockWrite(TempMailFile,buf^,iSize);
        //write into destination indexfile
        AssignFile(TempIndexFile,sTempIndexFile);
        if FileExists(sTempIndexFile) then Reset(TempIndexFile) else ReWrite(TempIndexFile);
        Seek(TempIndexFile,FileSize(TempIndexFile));
        IndexData.Index:=(FileSize(TempIndexFile) div sizeof(TIndexData))+1;
        IndexData.Position:=iPosition;
        IndexData.Size:=iSize;
        BlockWrite(TempIndexFile, IndexData, SizeOf(TIndexData));
        CloseFile(TempIndexFile);
        CloseFile(TempMailFile);
        CloseFile(MailFile);
        StrDispose(buf);
      end;
      //modify source index file
      IndexData.Delete:=true;
      Seek(IndexFile,iIndexPosition);
      BlockWrite(IndexFile,IndexData,sizeof(TIndexData));
      CloseFile(IndexFile);
    end;
    inc(i);
  end;
  RefreshListview;
end;
///////////////////////////////delete mail////////////////

procedure TMainForm.actMessageForward1Execute(Sender: TObject);
begin
  FwdRedEmail(True);
end;

procedure TMainForm.actMessageRedirectExecute(Sender: TObject);
begin
  FwdRedEMail(False); // AH16
  actMessageQueue.Execute;
end;

procedure TMainForm.actMessageReply1Execute(Sender: TObject);
begin
  ReplyEmail(False, False);
end;

procedure TMainForm.actMessageReplyQuotedExecute(Sender: TObject);
begin
  ReplyEMail(True, False);
  actMessageQueue.Execute;
end;

procedure TMainForm.actMessageAttOpenExecute(Sender: TObject);
var
  I: Integer;
begin
  if ListView2.SelCount = 0 then Exit;
  for I := 0 to ListView2.Items.Count - 1 do
    if ListView2.Items[I].Selected then
    begin
      if not OpenFileWithDoubleExtension(sTemporaryFolder +
        ListView2.Items[I].Caption) then exit;
      FileMightBeInUse := True;
      if ShellExecute(Handle, 'open', PChar(sTemporaryFolder +
        ListView2.Items[I].Caption), '', PChar(sTemporaryFolder), SW_SHOWNORMAL)
        <= 32 then
      begin
        ShellExecute(Handle, 'open', PChar(sQuickViewer), PChar(sTemporaryFolder
          + ListView2.Items[I].Caption), PChar(sTemporaryFolder), SW_SHOWNORMAL);
      end;
    end;
end;

procedure TMainForm.actMessageAttCopyExecute(Sender: TObject);
var
  I: Integer;
  D: string;
begin
  if ListView2.SelCount = 0 then
    Exit;
  DirectoryForm := TDirectoryForm.Create(Self);
  if Assigned(LangHolder) then
  begin
    if LangHolder.Language <> '' then
      LangHolder.Translate([DirectoryForm]);
  end;

  if DirectoryExists(sLastAttSaveDir) then
    DirectoryForm.RzDirectoryListBox1.Directory := sLastAttSaveDir
  else
    DirectoryForm.RzDirectoryListBox1.Directory :=
      ExtractFileDir(Application.Exename);
  if DirectoryForm.ShowModal = mrOK then begin
    D := MakeValidDirname(DirectoryForm.RzDirectoryListBox1.Directory);
    sLastAttSaveDir := D;
    for I := 0 to ListView2.Items.Count - 1 do
      if ListView2.Items[I].Selected then begin
        SetFileAttr(sTemporaryFolder + ListView2.Items[I].Caption, False, True,
          False, False);
        if FileExists(D + ListView2.Items[I].Caption) then begin
          case MessageDlg(Format(GetMessageString(13),
            [ListView2.Items[I].Caption]), mtWarning, [mbYes, mbNo, mbCancel], 0)
            of
            mrYes: CopyFile(PChar(sTemporaryFolder +
                ListView2.Items[I].Caption), PChar(D +
                ListView2.Items[I].Caption),
                False);
            mrNo: ; //nothing
            mrCancel: Exit;
          end;
        end
        else
          CopyFile(PChar(sTemporaryFolder + ListView2.Items[I].Caption), PChar(D
            + ListView2.Items[I].Caption), False);
      end;
  end;
  DirectoryForm.Free;
end;

procedure TMainForm.actMessageAttQuickViewExecute(Sender: TObject);
begin
  ViewAttachment(sQuickViewer);
end;

procedure TMainForm.actMessageAttSaveAsExecute(Sender: TObject);
begin
  if ListView2.SelCount <> 1 then
    Exit;
  if DirectoryExists(sLastAttSaveDir) then
    SaveDialog1.InitialDir := sLastAttSaveDir
  else
    SaveDialog1.InitialDir := ExtractFileDir(Application.Exename);
  SaveDialog1.Filename := ListView2.Selected.Caption;
  if SaveDialog1.Execute then begin
    sLastAttSaveDir := MakeValidDirname(ExtractFilePath(SaveDialog1.Filename));
    SetFileAttr(sTemporaryFolder + ListView2.Selected.Caption, False, True,
      False, False);
    CopyFile(PChar(sTemporaryFolder + ListView2.Selected.Caption),
      PChar(SaveDialog1.Filename), False);
  end;
end;

procedure TMainForm.actMessageAttAddFileExecute(Sender: TObject);
var
  I: Integer;
begin
  if (ListView1.SelCount <> 1) or (ListView1.Selected = nil) then
    Exit;
  if DirectoryExists(sLastAttOpenDir) then
    OpenDialog1.InitialDir := sLastAttOpenDir
  else
    OpenDialog1.InitialDir := ExtractFileDir(Application.Exename);
  if OpenDialog1.Execute then
  begin
    CurrentEmail.ContentType := '';
    CurrentEmail.ContentEncoding := '';
    sLastAttOpenDir := ExtractFileDir(OpenDialog1.Filename);
    for I := 0 to OpenDialog1.Files.Count - 1 do
    begin
       AddAttachment(OpenDialog1.Files[I]);
    end;
    ListView1.Selected.SubItems[ciSize] :=
      FormatByteText(GetFileSize(ListView1.Selected.SubItems[ciFileName]));
  end;

end;

procedure TMainForm.actMessageAttDeleteExecute(Sender: TObject);
var
  I: Integer;
begin
  if ListView2.SelCount = 0 then
    Exit;
  // AHRK95 -- CLean up of label..
  i := 0;
  while i < ListView2.Items.Count do
  begin
    if ListView2.Items[i].Selected then
    begin
      case MessageDlg(Format(GetMessageString(14),
        [ListView2.Items[I].Caption]),
        mtWarning, [mbYes, mbNo, mbCancel], 0) of
        mrYes: begin
            DeleteFile(PChar(sTemporaryFolder + ListView2.Items[I].Caption));
            ListView2.Items[I].Delete;
            SaveMessage := true;
          end;
        mrNo: ; //nothing
        mrCancel: Exit;
      end;
    end;
    inc(i);
  end;

  if SaveMessage then
  ListView1.Selected.SubItems[ciSize] :=
    FormatByteText(GetFileSize(ListView1.Selected.SubItems[ciFileName]));
end;

procedure TMainForm.actMessageSignatureExecute(Sender: TObject);
var
  G: Integer;
  IsNormalFolder : boolean; // AH02
begin
  if TreeView1.Selected <> nil then  // AH02
  begin
    IsNormalFolder := (TreeView1.Selected.StateIndex = tnFolder) and
                      (not (PFolderData(TreeView1.Selected.Data)^.Inbox));     // AH02
    // AHRK07
    TemplateForm := TTemplateForm.Create(Self);
    if Assigned(LangHolder) then
    begin
      if LangHolder.Language <> '' then
        LangHolder.Translate([TemplateForm]);
    end;

    with TemplateForm do
    begin
      DoMode(1);
      if (MainForm.ListView1.SelCount = 1) and (IsNormalFolder) then
        CanAttach := True
      else begin
        Button4.Visible := False;
        Button3.Default := True;
        CanAttach := False;
      end;
      if ShowModal = mrOK then begin
        for G := 0 to Memo1.Lines.Count - 1 do
          RichEdit1.Lines.Add(Memo1.Lines[G]);
      end;
      Free;
    end;
  end;
end;

procedure TMainForm.actMessageToggleReadExecute(Sender: TObject);
var
  Item: TListItem;
  I: Integer;
begin
  ReadCounter := 0;
  for I := 0 to ListView1.Items.Count - 1 do
    if ListView1.Items[I].Selected then
    begin
      ListView1.Items[I].ImageIndex := 0;
      iPosition:=StrToInt(ListView1.Items[I].SubItems[6]);
      iPosition:=(iPosition-1)*Sizeof(TIndexData);
      AssignFile(IndexFile,sMailIndexFile);
      Reset(IndexFile);
      Seek(IndexFile,iPosition);
      BlockRead(IndexFile, IndexData, SizeOf(TIndexData));
      IndexData.Read:=true;
      Seek(IndexFile,iPosition);
      BlockWrite(IndexFile, IndexData, SizeOf(TIndexData));
    end;
  SetPXTreeNodeName(TreeView1.Selected);
  actUpdateStatusbarUpdate(Self);
end;

procedure TMainForm.actMessageQueueExecute(Sender: TObject);
var i : integer;
    Item : TListItem;
    op, nf : string;
begin
  for i := 0 to ListView1.Items.Count - 1 do
  begin
    Item := ListView1.Items[i];
    if Item.Selected then
    begin
      // Check if marked as queued
      op := MakeValidDirName(ExtractFilePath(Item.SubItems[ciFileName]));
      if Item.ImageIndex in [5,6] then
      begin
        //RichEdit1.ReadOnly := false;
        if HaveAttach then   Item.ImageIndex := 2 else Item.ImageIndex := 1 ;
        nf := SkipChar(ExtractFileName(Item.SubItems[ciFileName]), '+'); // just skip the +
      end
      else
      begin
        if  HaveAttach then Item.ImageIndex:=6 else Item.ImageIndex:=5 ;
       // RichEdit1.ReadOnly := True;
        nf := ChangeFileExt(ExtractFileName(Item.SubItems[ciFileName]), '') + '+'; //Add Plus
        nf := nf + '.msg';
      end;
       
      if not FileExists(op+nf) then
      begin
        RenameFile(Item.SubItems[ciFileName], op+nf);
        DoSynchSearch(Item.SubItems[ciFileName], op + nf); //AHRK35
        Item.SubItems[ciFileName] := op+nf;
      end;
    end;
  end;
  // AH15 Update ActualMailFile, only if there's one selected!
  if ListView1.SelCount = 1 then
  begin
    ActualMailFile := ListView1.Selected.SubItems[ciFileName];
    CurrentEmail.FileName := ActualMailFile; //AH16, Assign...
  end;
  SetPXTreeNodeName(TreeView1.Selected); //AH11
  SetPanelHeadersFields(not RichEdit1.ReadOnly);
  actUpdateStatusbarUpdate(Self); //AH11
end;

procedure TMainForm.actMessageSelectAllExecute(Sender: TObject);
var
  I: Integer;
begin
//  ListView1.Items.BeginUpdate;
  for I := 0 to ListView1.Items.Count - 1 do
    ListView1.Items[I].Selected := True;
//  ListView1.Items.EndUpdate;
end;

procedure TMainForm.actMessageAddToAddrbookExecute(Sender: TObject);
var
  I, w: Integer;
  Node: TTreeNode;
begin
  if ListView1.Selected = nil then
    Exit;

  Node := TreeView1.Selected;
  w := ciFrom; //ciTo;
  if (Node.StateIndex = tnFolder) then begin
    if PFolderData(Node.Data)^.Inbox then
      w := ciFrom;
  end
  else if (Node.StateIndex = tnThrashBag) then
    w := ciFrom;

  with ListView1 do begin
    for I := 0 to Items.Count - 1 do
      if Items[I].Selected then begin
        AddressForm.SetAddress(Items[I].SubItems[w]);
      end;
  end;
end;

procedure TMainForm.AddToAddressBook;
var
  I, w: Integer;
  Node: TTreeNode;
begin
  // add to addressbook when replying
  if (ListView1.Selected = nil) or not bAddToAddressBookWhenReply then
    Exit;

  Node := TreeView1.Selected;
  w := ciFrom; //ciTo;
  if (Node.StateIndex = tnFolder) then begin
    if PFolderData(Node.Data)^.Inbox then
      w := ciFrom;
  end
  else if (Node.StateIndex = tnThrashBag) then
    w := ciFrom;

  with ListView1 do begin
    for I := 0 to Items.Count - 1 do
      if Items[I].Selected then begin
        AddressForm.SetAddressSilent(Items[I].SubItems[w]);
      end;
  end;
end;

procedure TMainForm.actMessageSearchExecute(Sender: TObject);
begin
  if FrmSearchMail = nil then
  begin
    FrmSearchMail := TFrmSearchMail.Create(Self);
  end;
  FrmSearchMail.Show;

end;

procedure TMainForm.actMessagePropertiesExecute(Sender: TObject);
var
  Item: TListItem;
  Node: TTreeNode;
  S: string;
  SS:olevariant;
begin
  if (ListView1.SelCount <> 1) or (ListView1.Selected = nil) then
    Exit;
  Item := ListView1.Selected;
  Node := TreeView1.Selected;
  if Node = nil then
    Exit;
  if Item = nil then
    Exit;


  if Node.StateIndex = tnFolder then begin
    if PFolderData(Node.Data)^.OutBox then
      MailOptionsForm.SetFields(0)
    else
      MailOptionsForm.SetFields(1);
    Node := GetActualAccount;
  end
  else begin
    MailOptionsForm.SetFields(1);
  end;
  if Node = nil then
    Exit;

  S := GetPXTreeNodeName(Node);
  with MailOptionsForm do begin
    Caption := GetMessageString(0) + ' ' + S;

    //////////////////////////create by mjg
    LblSubject.Caption:=CurrentEMail.Subject;
    LblAddress.Caption:=CurrentEMail.From;
    Lblclass.Caption:='邮件';
    LblSize.Caption:=FormatByteText(GetFileSize(CurrentEMail.FileName));
    if CurrentEMail.Priority='High' then Lblpriority.Caption:='高';
    if CurrentEMail.Priority='Low' then Lblpriority.Caption:='低' ;
    if CurrentEMail.Priority='Normal' then Lblpriority.Caption:='普通';

    LblSend.Caption:=DateToStr(CurrentEMail.ADate) + ' ' +
          TimeToStr(CurrentEMail.ATime);
    LblRec.Caption:=DateToStr(CurrentEMail.RDate) + ' ' +
          TimeToStr(CurrentEMail.RTime);


    RichEdit1.Lines.LoadFromFile(CurrentEMail.FileName);


    EditAble := not RichEdit1.ReadOnly;
    if ShowModal = mrOK then begin
      with Item do begin
        SubItems[ciSubject] := CurrentEMail.Subject;
        SubItems[ciFrom] := CurrentEMail.From;
        SubItems[ciTo] := GetCommataStringReceiver;
        SubItems[ciDateTime] := DateToStr(CurrentEMail.ADate) + ' ' +
          TimeToStr(CurrentEMail.ATime);
        SubItems[ciSize] := FormatByteText(GetFileSize(CurrentEMail.FileName));
        // AHRK115
        lblSubject.Caption := CurrentEMail.Subject + ', From: '
         + CurrentEMail.From + '';
        SetPanelHeadersFields(Editable);
      end;
    end;
  end;
end;

procedure TMainForm.actMessageNewUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := true;
end;

procedure TMainForm.actMessageDeleteUpdate(Sender: TObject);
begin
  // AH03 currently only drag and drop implementation of Stationaries...
  // Will be reintroduced in JungleJim...
  (Sender as TAction).Enabled := (ListView1.Selected <> nil);
  {---MARKED AS TO BE REINTRODUCED
  if Sender = actMessageCopy then
    (Sender as TAction).Enabled := (ListView1.Selected <> nil);
  if Sender = actMessageMove then
    (Sender as TAction).Enabled := (ListView1.Selected <> nil) and not (TreeView1.Selected.StateIndex = tnStationary);
  ---}
end;

procedure TMainForm.actMessageForward1Update(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil) and (not IsTypeOfFolder(TreeView1.Selected,
    setSysFolders)); // AH17
end;

procedure TMainForm.actMessageRedirectUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil) and (not IsTypeOfFolder(TreeView1.Selected,
    setSysFolders)); //AH17
end;

procedure TMainForm.actMessageReply1Update(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil) and (not IsTypeOfFolder(TreeView1.Selected,
    setSysFolders)); //AH17
end;

procedure TMainForm.actMessageReplyQuotedUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil) and (not IsTypeOfFolder(TreeView1.Selected,
    setSysFolders)); //AH17
end;

procedure TMainForm.actMessageAttOpenUpdate(Sender: TObject);
begin
//  (Sender as TAction).Enabled :=
//    (ListView1.SelCount = 1) and (ListView1.Selected <> nil) and
//    (ViewMailFrm.ListView3.SelCount > 0);
end;

procedure TMainForm.actMessageAttQuickViewUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled :=
    (ListView1.SelCount = 1) and (ListView1.Selected <> nil) and
    (ListView2.SelCount > 0) and (Length(sQuickViewer) > 0);
end;

procedure TMainForm.actMessageToggleReadUpdate(Sender: TObject);
begin
  // AHRK99 Reverted old 'Toggle Read behaviour'.
  (Sender as TAction).Enabled := (ListView1.Selected <> nil);
end;

// AH11
procedure TMainForm.actMessageQueueUpdate(Sender: TObject);
var isQueuableFolder : Boolean;
begin
  // Get current Node...
  isQueuableFolder := False;
  if Assigned(TreeView1.Selected) then
  begin
    if TreeView1.Selected.StateIndex = tnFolder then
    begin
      isQueuableFolder := PFolderData(TreeView1.Selected.Data)^.Drafts or
                          PFolderData(TreeView1.Selected.Data)^.Outbox;
    end;
  end;
  (Sender as TAction).Enabled := (ListView1.Selected <> nil) and (isQueuableFolder);
end;
// AH11

procedure TMainForm.actMessageSelectAllUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.Items.Count > 0);
end;

procedure TMainForm.actMessageAddToAddrbookUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.Selected <> nil);
end;

procedure TMainForm.actMessagePropertiesUpdate(Sender: TObject);
var bool : boolean;
begin
  // AHRK75 -- Rearranged...
  bool := false;
  if ListView1.Selected <> nil then
  begin
    if ListView1.SelCount = 1 then
    begin
      if (not AreWeOnline) then
      begin
        Bool := True;
      end
      else
      begin
        // If Online then you're still allowed to change
        // the properties of other mails... where applies of course.
        if ListView1.Selected.ImageIndex <> 25 then
        begin
          Bool := True;
        end;
      end;
    end;
  end;
  (Sender as TAction).Enabled := bool;
  // AHRK75 -- Rearranged...
end;



procedure TMainForm.actMessageAttAddFileUpdate(Sender: TObject);
begin
 (Sender as TAction).Enabled := not RichEdit1.ReadOnly and
   (ListView1.Selected <> nil);
end;


//TODO -oMJG:update statebar
procedure TMainForm.actUpdateStatusbarUpdate(Sender: TObject);
var
  I, E : Integer;
  isQFolder : boolean;
begin
  isQFolder := False;
  if (TreeView1.Selected <> nil) then
    if TreeView1.Selected.StateIndex = tnFolder then
      if PFolderData(TreeView1.Selected.Data)^.Outbox or
      PFolderData(TreeView1.Selected.Data)^.Drafts then
        isQFolder := True;

  with StatusBar1 do begin
    if ActiveAccount = nil then
    begin
      ActiveAccount := GetActualAccount;
      if ActiveAccount = nil then
      begin
        Panels[0].Text := GetMessageString(26);
        exit;
      end
    end;

 //   Panels[0].Text := GetPXTreeNodeName(ActiveAccount);
    E := 0;
    for I := 0 to ListView1.Items.Count - 1 do
    begin
      if (ListView1.Items[I].ImageIndex in [3,4]) then
        Inc(E);
    end;

    if isQFolder then
      Panels[0].Text := Format(GetMessageString(145), [IntToStr(ListView1.Items.Count),IntToStr(E)
        ])   //%s%s电子邮件排队
    else
      Panels[0].Text := Format(GetMessageString(28),[IntToStr(ListView1.Items.Count),IntToStr(E)
        ]);  //%s/%s 电子邮件未读
  end;

{  if Assigned(ActiveAccount) and (not AreWeOnline) then
  begin
    ActAccountFetchMail.Caption := Format(GetMessageString(147),
      [StatusBar1.Panels[0].Text]);
    ActAccountSendMail.Caption := Format(GetMessageString(148),
      [StatusBar1.Panels[0].Text]);
    actAccountFetchSendMail.Caption := Format(GetMessageString(149),
      [StatusBar1.Panels[0].Text]);
  end;
  //从%s接收电子邮件
//从%s发送电子邮件
//从%s接收/发送电子邮件}

end;

procedure TMainForm.actEnhancedAddessBookExecute(Sender: TObject);
//var AddressForm:TForm;
begin
  EnablePopUpMenu(false);
  if menSearchForm <> nil then menSearchForm.Close;
  if AddressForm.ShowModal = mrOK then
    NewMessage(True, True, '', AddressForm.GetSelAddresses, '', nil);
  EnablePopUpMenu(true);
end;

procedure TMainForm.actEnhancedOptionsExecute(Sender: TObject);
var x, PanelsChanged : integer; // AH16
    anode : TTreeNode;
    oldS : string;
begin
  EnablePopUpMenu(false);
  PanelsChanged := iPanelsStyle;
  oldS := DefaultLanguage;
  EnviroForm := TEnviroForm.Create(Self);
  if Assigned(LangHolder) then
  begin
    if LangHolder.Language <> '' then
      LangHolder.Translate([EnviroForm]);
  end;

  try
    if EnviroForm.ShowModal = mrOK then
    begin
      if iLineBreakAt >= 255 then //RR02c//RR02b
      begin
        RichEdit1.WordWrap := false;
        RichEdit1.ScrollBars := ssBoth;
      end
      else
      begin
        RichEdit1.WordWrap := true;
        RichEdit1.ScrollBars := ssVertical;
      end;

      //AH15.......
      AnimationPosition := 0;
      AnimationToLeft := False;
      case iAnimation of
      0 : ReloadDefault;
      1 : ReloadBall;
      2 : ReloadRadar;
      3 : ReloadSpikes;
      end;
      //AH15....
      ListView1.Tag := 1;
      MainForm.Cursor := crHourGlass;
      iLVBackground :=
        TPanelAppearance(EnviroForm.AppearanceList.Items[0]).BackGround;
      iLVFOntColour :=
        TPanelAppearance(EnviroForm.AppearanceList.Items[0]).Font.Color;
      iLVFOntSize :=
        TPanelAppearance(EnviroForm.AppearanceList.Items[0]).Font.Size;
      fsLVFOntStyle :=
        TPanelAppearance(EnviroForm.AppearanceList.Items[0]).Font.Style;
      sLVFOntName :=
        TPanelAppearance(EnviroForm.AppearanceList.Items[0]).Font.Name;
      TPanelAppearance(EnviroForm.AppearanceList.Items[1]).ApplyColours(
        TreeView1);
      TPanelAppearance(EnviroForm.AppearanceList.Items[2]).ApplyColours(
        RichEdit1);
      PanelHeaders.Color := clBtnFace;
      Label3.Font.Color := RichEdit1.Font.Color;
      Label8.Font.Color := RichEdit1.Font.Color;
      fldAddresses.Color := RichEdit1.Color;
      fldFromHeader.Color := RichEdit1.Color;
      fldSubject.Color := RichEdit1.Color;
      fldAddresses.Font.Color := RichEdit1.Font.Color;
      fldFromHeader.Font.Color := RichEdit1.Font.Color;
      fldFromHeader.BorderColor := RichEdit1.Color;
      fldAddresses.BorderColor := RichEdit1.Color;
      fldSubject.BorderColor := RichEdit1.Color;
      fldSubject.Font.Color := RichEdit1.Font.Color;
      lbRecentMessage.Color := RichEdit1.Color;
      lbRecentMessage.Font.Color := RichEdit1.Font.Color;

      AccountsNode := TreeView1.Items.GetFirstNode;

      ANode := AccountsNode;
      while ANode <> nil do
      begin
        if Anode.StateIndex = tnThrashBag then
          TrashNode := anode;
        if Anode.StateIndex = tnRepository then
          RepositoryNode := anode;
        if Anode.StateIndex = tnStationary then
          StationaryNode := Anode;
        ANode := ANode.getNextSibling;
      end;

      // AH16..
      if iPanelsStyle <> PanelsChanged then
      begin
//        SetPanels(iPanelsStyle);
      end;
      if DefaultLanguage <> oldS then
      begin
        Screen.Cursor := crHourGlass;
        LockWindowUpdate(GetDeskTopWindow);
        // AHOPTIMIZE (marked for optimalization...
        // The routines already support arrays, so push those
        // forms in an array instead of looping through them
        // one by one!
        try
          if DefaultLanguage <> '' then
          begin
            LangHolder.Language := DefaultLanguage;
            for x := 0 to Screen.FormCount -1 do
            begin
              LangHolder.Translate([Screen.Forms[x]]);
            end;
          end
          else
          begin
            LangHolder.Language := '';
            for x := 0 to Screen.FormCount - 1 do
            begin
              LangHolder.InstantTranslation([Screen.Forms[x]]);
            end;
          end;
        finally
          LockWindowUpdate(0);
          Screen.Cursor := crDefault;
        end;
      end;

      UpdateMainForm;
      RichEdit1.Refresh;
      SetFlatStyle;
      ListView1.Tag := 0;
      ListView1.Refresh;
    end;
  finally
    EnviroForm.Free;
    MainForm.Cursor := crDefault;
    EnablePopUpMenu(true); // AHR71
  end;
end;

procedure TMainForm.actHelpContentsExecute(Sender: TObject);
begin
  Application.HelpContext(34);
end;

procedure TMainForm.actHelpTopOfDayExecute(Sender: TObject);
begin
  TipsForm := TTipsForm.Create(Self);
  if Assigned(LangHolder) then
  begin
    if LangHolder.Language <> '' then
      LangHolder.Translate([TipsForm]);
  end;

  try
    TipsForm.ShowModal;
  finally
    TipsForm.Free;
  end;
end;

procedure TMainForm.actHelpHomepageExecute(Sender: TObject);
begin
  ShellExecute(Handle, 'open', PChar(sMHHomepage), '', '', SW_SHOWNORMAL);
end;

procedure TMainForm.actHelpAboutExecute(Sender: TObject);
begin
  InfoForm := TInfoForm.Create(Self);
  if Assigned(LangHolder) then
  begin
    if LangHolder.Language <> '' then
       LangHolder.Translate([InfoForm]);
  end;

  try
    InfoForm.ShowModal;
  finally
    Infoform.Free;
  end;
end;

procedure TMainForm.PopupMenu6Popup(Sender: TObject);
begin
  SetForegroundWindow(Self.Handle);
end;

procedure TMainForm.ListView1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  NewItem: TMenuItem;
  iCount,i:integer;
begin
  if csDestroying in ComponentState then
    Exit;
  if ListView1.SelCount = 1 then
    if ListView1.Selected <> nil then begin
      ListView1.Selected.MakeVisible(false);
      if ListView1.Selected.SubItems[ciFileName] = ActualMailFile then
        Exit;
    end;



  UpdateListView(Sender = ListView1);
  EnableHeaderButtons;

  if (FileGetAttr(ActualMailFile) and faArchive = 0) then
     Application.OnIdle := AppIdleDiposit;

  if HaveAttach then
  begin
    menSaveAttach.Enabled:=true;
    SpeedButton1.Visible:=true;
    PopupMenu9.Items.Clear;
    iCount:=ListView2.Items.Count;
    for i:=0 to iCount-1 do
    begin
      NewItem:=TMenuItem.Create(self);
      NewItem.Caption:=ListView2.Items[i].Caption;
      NewItem.OnClick := myclick;
      PopupMenu9.Items.Add(NewItem);
    end;
      NewItem:=TMenuItem.Create(self);
      NewItem.Caption:='-';
      NewItem.OnClick := myclick;
      PopupMenu9.Items.Add(NewItem);

      NewItem:=TMenuItem.Create(self);
      NewItem.Caption:='保存附件';
      NewItem.OnClick := myclick;
      PopupMenu9.Items.Add(NewItem);
  end
  else
    menSaveAttach.Enabled:=false;
  Screen.Cursor := crDefault;
end;

procedure TMainForm.actFileSaveAsUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil);
end;

procedure TMainForm.actFileSaveAsExecute(Sender: TObject);
var
  pf: string;
  sTemp:olevariant;
begin
  with SaveDialog1 do begin
    InitialDir := sSaveAsFolder;
    FileName := '';
    pf := Filter;
    Filter :=
      '文件类型 (*.msg)|*.msg|Textfiles (*.txt)|*.txt|All Files (*.*)|*.*';
    if Execute then begin
      if FilterIndex = 1 then begin
        if Pos('.msg', LowerCase(FileName)) = 0 then
          FileName := FileName + '.msg';
        FileCopy(nil, Listview1.Selected.Subitems[ciFileName], FileName);
      end
      else begin
        if Pos('.', LowerCase(FileName)) = 0 then
          FileName := FileName + '.txt';
          sTemp:=FileName;
        //RichEdit1.Lines.SaveToFile(FileName);
        DHTMLEdit1.SaveDocument(sTemp)
      end;
    end;
    Filter := pf;
  end;
end;

procedure TMainForm.RichEdit1MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  c: integer;
begin
  if (Button = mbRight) and (RichEdit1.SelLength = 0) then begin
    c := RichEdit1.CharAtPos(Point(X, Y));
    RichEdit1.SelStart := c;
    RichEdit1.SelLength := 0;
  end;
end;

procedure TMainForm.RichEdit1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  p: TPoint;
begin
  if (Button = mbRight) then
  begin
    p := RichEdit1.ClientToScreen(Point(X, Y));
    PopupMenu4.Popup(p.X, p.Y);
  end;
end;

procedure TMainForm.FormShow(Sender: TObject);
var
  SearchRec: TSearchRec;
  Found,i: Integer;
  NewItem: TMenuItem;
  Node: TTreeNode;
  dd:string;
begin
  iColumn:=0;
  Shell_NotifyIcon(NIM_DELETE, @NotifyIconData);
  if firstshow then
  begin
    firstshow := false;
    mainform.Caption :='SMAIL';
  end;
  TEIgnoreChange := true;
  TEIgnoreChange := false;


  if sParamStr='newmail'  then  actMessageNew.Execute;
  if sParamStr='findmail' then  actMessageSearch.Execute;
  if sParamStr='findaddress' then actEnhandedSearchName.Execute;
  if sParamStr='sendreceivemail' then actFileFetchSendMail.Execute;

end;

procedure TMainForm.FormHide(Sender: TObject);
begin
  Shell_NotifyIcon(NIM_ADD, @NotifyIconData);
end;

procedure TMainForm.EnablePopUpMenu(AEnabled: boolean);
begin
  with PopupMenu6 do begin
    Items[0].Enabled := AEnabled;
    Items[2].Enabled := AEnabled;
    Items[3].Enabled := AEnabled;
    Items[7].Enabled := AEnabled;
    Items[9].Enabled := AEnabled;
  end;
end;

procedure TMainForm.actMessageScanVirusExecute(Sender: TObject);
var
  ShortTemp: string;
  ShowCmd: integer;
begin
  // Virus Scan
  if (ListView2.Items.Count > 0) and (sVirusProg <> '') then begin
    ShortTemp := ExtractShortPathName(sTemporaryFolder);
    if bVirusMin then
      ShowCmd := SW_MINIMIZE
    else
      ShowCmd := SW_SHOWNORMAL;

    ShellExecute(Handle, 'open', PChar(sVirusProg),
      PChar(ShortTemp + ' ' + sVirusParams), PChar(ShortTemp), ShowCmd);
  end;
end;

procedure TMainForm.actMessageScanVirusUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView2.Items.Count > 0) and (sVirusProg <>
    '');
end;

procedure TMainForm.AppIdle(Sender: TObject; var Done: Boolean);
var SL: TStringList;
    x : integer;
begin
  // process commandlines
  Application.OnIdle := nil;
  case iParamCommand of
    0, 1 :
    begin
      if sWriteNewMessage3 <> '' then
      begin
        SL := TStringList.Create;
        SL.Add(sWriteNewMessage3);
        NewMessage(false, true, sWriteNewMessage2, sWriteNewMessage1, '', SL);
        SL.Free;
      end
      else
        NewMessage(false, true, sWriteNewMessage2, sWriteNewMessage1, '', nil);
    end;
    2 :
    begin
      if sWriteNewMessage1 <> '' then
      begin
        SL := TStringList.Create;
        SL.CommaText := sWriteNewMessage1;
        showPhoenixMail1Click(self);
        NewMessage(false, True, '', '', '', nil);
        for x := 0 to SL.Count -1 do
        begin
          if FileExists(Sl.Strings[x]) then
          begin
            AddAttachment(SL.Strings[x]);
          end;
        end;
        SL.Free;
        // AH14 Update filesize
        ListView1.Selected.SubItems[ciSize] :=
          FormatByteText(GetFileSize(ListView1.Selected.SubItems[ciFileName]));
      end;
    end;
  end; // End Case
  // Reset parameters...
  sWriteNewMessage1 := '';
  sWriteNewMessage2 := '';
  sWriteNewMessage3 := '';
  iParamCommand := -1;
end;

procedure TMainForm.actMessageAttTextViewExecute(Sender: TObject);
begin
  ViewAttachment(sTextViewer);
end;

procedure TMainForm.actViewTBStandardUpdate(Sender: TObject);
begin
//  (Sender as TAction).Checked := tbStandard.Visible;
end;

procedure TMainForm.actViewTBMessageUpdate(Sender: TObject);
begin
//  (Sender as TAction).Checked := tbMessage.Visible;
end;

procedure TMainForm.actViewStatusbarUpdate(Sender: TObject);
begin
  (Sender as TAction).Checked := StatusBar1.Visible;
end;

procedure TMainForm.actViewTBStandardExecute(Sender: TObject);
begin
//  tbStandard.Visible := not tbStandard.Visible;
end;

procedure TMainForm.actViewTBMessageExecute(Sender: TObject);
begin
//  tbMessage.Visible := not tbMessage.Visible;
end;

procedure TMainForm.actViewStatusbarExecute(Sender: TObject);
begin
  StatusBar1.Visible := not StatusBar1.Visible;
end;

procedure TMainForm.actMessageSignatureUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := true;
end;

procedure TMainForm.actFolderEmptyExecute(Sender: TObject);
var
  S: string;
  i: integer;
begin
  if ListView1.Items.Count = 0 then
    Exit;
  if not ConfirmDelete(true) then Exit;
  Screen.Cursor := crHourGlass;
  Application.ProcessMessages;
  with ListView1 do begin
    for i := 0 to Items.Count - 1 do begin
      S := Items[i].SubItems[ciFileName];
      SetFileAttr(S, False, True, False, False);
      DeleteFile(S);
      DoSynchSearch(s, ''); //AHRK34
    end;
    Items.Clear;
  end;
  SetPXTreeNodeName(TreeView1.Selected);
  TreeView1.Invalidate;
  UpdateListview;
end;

procedure TMainForm.actFolderEmptyUpdate(Sender: TObject);
var
  Node: TTreeNode;
begin
  (Sender as TACtion).Enabled := False;
  Node := TreeView1.Selected;
  if Assigned(Node) then
    if Assigned(Node.Data) then
      if Node.StateIndex = tnFolder then
        (Sender as TACtion).Enabled := (ListView1.Items.Count > 0);
end;

procedure TMainForm.ListView1SortBegin(Sender: TObject;
  SortColumn: Integer; Ascending: Boolean);
begin
  // sorting dates
  if SortColumn >= 4 then
    ListView1.AutoSortStyle := assSmart
  else
    ListView1.AutoSortStyle := assDefault;
end;

procedure TMainForm.actViewLastLogUpdate(Sender: TObject);
begin
  // AHRK72 (Sender as TAction).Enabled := FileExists(sProtocolFile);
  // BTW: doing FIleExists in an Action.Update is a bit too... I mean,
  // suppose we were checking on a Disk. Come on guys give that drive
  // a break <g>.
  (Sender as TAction).Enabled := bMakeProtocol;
end;

procedure TMainForm.actViewLastLogExecute(Sender: TObject);
begin
  // AHRK72...
  if FileExists(sProtocolFile) then
    ShellExecute(Handle, 'open', PChar(sProtocolFile), '',
      PChar(getAppPath), SW_SHOWNORMAL);
end;

procedure TMainForm.ListView1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Ord(Key) = 13 then
    actMessagePropertiesExecute(Self)
end;

procedure TMainForm.ListView2KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Ord(Key) = 13 then
    // AHRK167    actMessageAttQuickViewExecute(Self);
     PopupMenu2.Items[iDoubleClickAction].Action.Execute;
end;

procedure TMainForm.ListView2KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  i: integer;
begin
  if Ord(Key) = 46 then
    actMessageAttDeleteExecute(Self)
  else if (Shift = [ssCtrl]) and (Ord(Key) = 65) then begin
    with ListView2 do
      for i := 0 to Items.Count - 1 do
        Items[i].Selected := true;
  end;
end;

procedure TMainForm.ListView1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
(*  if (Shift = [ssCtrl]) and (Ord(Key) = 65) then
    actMessageSelectAllExecute(Self)
  else  // RR01*)
  //AH16 Added PGDWN/PGUP
  if Key in [VK_UP, VK_DOWN, VK_PRIOR, VK_NEXT] then // select lvitems with the keyboard
    ListView1MouseUp(Sender, mbLeft, [ssLeft], 0, 0) else
  if (Shift = [ssShift]) and (Ord(Key) = 46) then // shift+del
    DeleteMessageForEver else
  if Ord(Key) = 46 then // del
    actMessageDeleteExecute(Self) else
  if Ord(Key) = 116 then // F5 select all
  begin
    actMessageSelectAllExecute(Self); // RR01
   (*    if ListView1.Selected <> nil then
      ListView1.Selected.Selected := false;
    TreeView1Change(Self, TreeView1.Selected);  // RR01*)
  end;

end;

procedure TMainForm.TreeView1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  i: integer;
begin
  if Ord(Key) = 46 then
    actFolderDeleteExecute(Self)
  else if Ord(Key) = 116 then begin
    // F5
    for i := 0 to TreeView1.Items.Count - 1 do
      SetPXTreeNodeName(TreeView1.Items[i]);
  end;
end;

procedure TMainForm.actMessageAttTextViewUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled :=
    (ListView1.SelCount = 1) and (ListView1.Selected <> nil) and
    (ListView2.SelCount > 0) and (Length(sTextViewer) > 0);
end;

procedure TMainForm.DeleteMessageForEver;
var
  Item: TListItem;
  S: string;
  I, E: Integer;
begin
  if ListView1.Selected = nil then
    Exit;

  // confirm delete
  if not ConfirmDelete(true) then Exit;

  I := 0;
  E := ListView1.Items.Count - 1;
//  ListView1.Items.BeginUpdate;
  while I <= E do begin
    if ListView1.Items[I].Selected then begin
      Item := ListView1.Items[I];
      S := Item.SubItems[ciFileName];
      SetFileAttr(S, False, True, False, False);
      DeleteFile(S);
      Item.Delete;
      Dec(I);
      Dec(E);
    end;
    Inc(I);
  end;
//  ListView1.Items.EndUpdate;
  SetPXTreeNodeName(TreeView1.Selected);
  ActualizeTrash;
  Application.ProcessMessages;
  actUpdateStatusbarUpdate(Self);
end;

function TMainForm.ConfirmDelete(APermanent: boolean): boolean;
var
  dlg : TStdMailForm;
  res: TModalResult;
  prompt: string;

  procedure ShowDialog;
  begin
    dlg := TStdMailForm.Create(Self);
    if Assigned(LangHolder) then
    begin
      if LangHolder.Language <> '' then
          LangHolder.Translate([stdMailForm]);
    end;
    with dlg do begin
      try
        Label1.Caption := prompt;
        // AH08
        CheckBox1.Caption := GetMessageString(133);
        Image1.Picture.Icon.Handle := LoadIcon(0, IDI_QUESTION);
        res := ShowModal;
        if APermanent then
          bWarnBeforeDelPermanent := not CheckBox1.Checked
        else
          bWarnBeforeDelToTrash := not CheckBox1.Checked;
      finally
        Free;
      end;
    end;
  end;

begin
  if APermanent then begin
    if bWarnBeforeDelPermanent then begin
      // AH08
      prompt := GetMessageString(121);
      ShowDialog;
    end else res := mrYes;
  end else begin
    // confirm delete to trash
    if bWarnBeforeDelToTrash then begin
      prompt := Format(GetMessageString(134), [sTrashBagCaption]);
      ShowDialog;
    end else res := mrYes;
  end;
  Result := (res = mrYes);
end;

procedure TMainForm.FormDestroy(Sender: TObject);
var IniFile: TIniFile;
    aColumns : array of Integer;
    x : integer;
    s : string;
begin
  CounInitialize;
  IniFile := TIniFile.Create(sSettingsFile);
  // AH14
  SetLength(aColumns, ListView1.Columns.count); // AH16
  ListView1.GetColumnOrder(ListView1.Columns.Count, aColumns); //AH16
  for x := Low(aColumns) to High(aColumns) do
  begin
    s := s + IntToStr(aColumns[x]) + ',';
  end;
  SetLength(s, Length(s)-1);
  IniFile.WriteString('MessageList','ColumnOrder' , s);
  AColumns := nil; // AH16
  // RR04g
  ELVWriteSettingsToIniFile(ListView1, 'MessageList', IniFile);

  // AHRK138.. Save the history file.
//  fldSubject.Items.SaveToFile(GetAppPath + 'hist_subjects.txt');
  // Free the objects...
  for x := 0 to lbRecentMessage.Items.Count -1 do
  begin
    if lbRecentMessage.Items.Objects[x] <> nil then
    begin
      if lbRecentMessage.Items.Objects[x] is TMessageHistoryItem then
      begin
        TMessageHistoryItem(lbRecentMessage.Items.Objects[x]).Free;
      end;
    end;
  end;
  // AHRK161 --
  IniFile.WriteInteger('Settings', 'DragDropIntervalMsec', timerTree.Interval);

  IniFile.Free;
  ListView1.Items.Clear;
  ListView2.Items.Clear;
  imlToolbar.Handle := 0;
  Shell_NotifyIcon(NIM_DELETE, @NotifyIconData);
  DestroyIcon(TrayIcon);
end;

procedure TMainForm.actMessageAttViewWithExecute(Sender: TObject);
var
  s: string;
begin
  if ListView2.SelCount = 1 then
  begin
    // AH02 Use Open with dialog instead of TOpenDialog
    FileMightBeInUse := True;
    s := 'shell32.dll,OpenAs_RunDLL ' + sTemporaryFolder + ListView2.Selected.Caption;
    ShellExecute(Handle, Pchar('Open'), PChar('rundll32.exe'), PChar(s), #0, SW_SHOWNORMAL);
  end;
end;


procedure TMainForm.ListView2MouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
var
  Result: HRESULT;
  OKEffect: LongInt;
  Effect: LongInt;
  DropSource: TDropFileSource;
  i: integer;
  Filename: string;
begin
  if ([ssLeft, ssRight] * Shift = []) or (ListView2.SelCount = 0) then
    exit;

  DropSource := TDropFileSource.Create;
  try
    for i := 0 to ListView2.Items.Count - 1 do
      if (ListView2.Items[I].Selected) then begin
        Filename := sTemporaryFolder + ListView2.Items[I].Caption;
        while (Pos('\\', FileName) > 0) do
          Delete(FileName, Pos('\\', FileName), 1);
        DropSource.Files.Add(Filename);
      end;
    OKEffect := DROPEFFECT_NONE;
    //if (CheckBoxCopy.Checked) then
    OKEffect := OKEffect or DROPEFFECT_COPY;
    //if (CheckBoxMove.Checked) then
    //  OKEffect := OKEffect OR DROPEFFECT_MOVE;
    //if (CheckBoxLink.Checked) then
    //  OKEffect := OKEffect OR DROPEFFECT_LINK;

    Result := DoDragDrop(DropSource as IDataObject, DropSource as IDropSource,
      OKEffect, Effect);
  except
    DropSource.Free;
    raise;
  end;

  case Result of
    DRAGDROP_S_DROP:
      ; //ShowMessage('Drop OK');
    DRAGDROP_S_CANCEL:
      ShowMessage('Drop cancel');
    E_OUTOFMEMORY:
      ShowMessage('Drop out of memory');
    //$800703E6: // E_UNSPEC:
    //  ShowMessage('Drop unexpected');
  else
    ShowMessage('Drop unknown:' + IntToHex(Result, 8));
  end;
end;

procedure TMainForm.actFileFetchAllExecute(Sender: TObject);
begin
  OnlineSession(otFetchAll);
end;

procedure TMainForm.actFileSendAllExecute(Sender: TObject);
begin
  OnlineSession(otSendAll);
end;

procedure TMainForm.actMessageCopyExecute(Sender: TObject);
var
  dlg : TfrmMoveMessage;
  mNode : TTreeNode;
  CopyTo: string;
  NewFileName: string;
  I, E,iIndexPosition: Integer;
  TempMailFile,TempIndexFile:file of byte;
  sTempMailFile,sTempIndexFile:string;
  Item: TListItem;
begin
  dlg := TfrmMoveMessage.Create(Self);

  try
    with dlg.TreeView1 do begin
      Items := TreeView1.Items;
      FullExpand;
    end;
    Self.Cursor := crHourglass;
    mNode := TreeView1.Selected;
    dlg.CurrentDir := GetNodeDirName(MNode);
    Self.Cursor := crDefault;
    dlg.Caption := '复制';
    dlg.Label1.Caption:='将邮件复制到选定文件夹';
    if dlg.ShowModal = mrOK then
    begin
      CopyTo := dlg.TreeView1.Selected.Text;


///////////////////////////////copy to database////////////////
  ActiveAccount := GetActiveAccount(TreeView1.Selected);
  Dir := PAccountData(ActiveAccount.Data)^.Path;
  sTempIndexFile:=Dir+CopyTo+'.IND';
  sTempMailFile:=Dir+CopyTo+'.SML';
  I := 0;
  E := ListView1.Items.Count - 1;
  while I <= E do begin
    if ListView1.Items[I].Selected then begin
      with ListView1.Items[I] do begin
        //open indexfile and read recorder
        iIndexPosition:=StrToInt(SubItems[6]);
      end;
      iIndexPosition:=(iIndexPosition-1)*Sizeof(TIndexData);
      AssignFile(IndexFile,sMailIndexFile);
      Reset(IndexFile);
      Seek(IndexFile,iIndexPosition);
      BlockRead(IndexFile, IndexData, SizeOf(TIndexData));

      AssignFile(TempMailFile,sTempMailFile);
      if FileExists(sTempMailFile) then Reset(TempMailFile) else ReWrite(TempMailFile);
      Seek(TempMailFile,FileSize(TempMailFile));

      //read the responding mail file and write to destination mail file
      iPosition:=IndexData.Position;
      iSize:=IndexData.Size;
      buf := StrAlloc(iSize);
      AssignFile(MailFile,sMailFile);
      Reset(MailFile);
      Seek(MailFile,iPosition);
      BlockRead(MailFile,buf^,iSize);
      BlockWrite(TempMailFile,'****************',16);
      iPosition:=FilePos(TempMailFile);
      BlockWrite(TempMailFile,buf^,iSize);

      //write into destination indexfile
      AssignFile(TempIndexFile,sTempIndexFile);
      if FileExists(sTempIndexFile) then Reset(TempIndexFile) else ReWrite(TempIndexFile);
      Seek(TempIndexFile,FileSize(TempIndexFile));
      IndexData.Index:=(FileSize(TempIndexFile) div sizeof(TIndexData))+1;
      IndexData.Position:=iPosition;
      IndexData.Size:=iSize;
      BlockWrite(TempIndexFile, IndexData, SizeOf(TIndexData));

      CloseFile(IndexFile);
      CloseFile(MailFile);
      CloseFile(TempIndexFile);
      CloseFile(TempMailFile);
      StrDispose(buf);
    end;
    inc(i);
  end;
///////////////////////////////copy to database////////////////


      SetPXTreeNodeName(mNode);
      ActualizeTrash;
      with TreeView1 do
      begin
        for i := 0 to Items.Count - 1 do
          if (Items[i].Data <> nil) and (Items[i].StateIndex = tnFolder) and
            (CompareText(PFolderData(Items[i].Data)^.Path, CopyTo) = 0) then
          begin
            SetPXTreeNodeName(Items[i]);
            Break;
          end;
      end;
    end;
  finally
    dlg.Free;
  end;
end;

procedure TMainForm.actMessageMoveExecute(Sender: TObject);
var
  dlg: TfrmMoveMessage;
  mNode : TTreeNode;
  CopyTo: string;
  NewFileName: string;
  I, E,iIndexPosition: Integer;
  TempMailFile,TempIndexFile:file of byte;
  sTempMailFile,sTempIndexFile:string;
  Item: TListItem;
begin
  if TreeView1.Selected.StateIndex = tnStationary then exit;
  dlg := TfrmMoveMessage.Create(Self);
  try
    with dlg.TreeView1 do begin
      Items := TreeView1.Items;
      FullExpand;
    end;

    Self.Cursor := crHourglass;
    mNode := TreeView1.Selected;
    dlg.CurrentDir := GetNodeDirName(MNode);

    Self.Cursor := crDefault;
    dlg.Caption := '移动';
    dlg.Label1.Caption:='将邮件移动到选定文件夹';
    if dlg.ShowModal = mrOK then begin
      if dlg.GetSelectedPath = sTrashFolder then
        if not ConfirmDelete(False) then Exit;
      CopyTo := dlg.TreeView1.Selected.Text;

///////////////////////////////move to database////////////////
  ActiveAccount := GetActiveAccount(TreeView1.Selected);
  Dir := PAccountData(ActiveAccount.Data)^.Path;
  sTempIndexFile:=Dir+CopyTo+'.IND';
  sTempMailFile:=Dir+CopyTo+'.SML';
  I := 0;
  E := ListView1.Items.Count - 1;
  while I <= E do begin
    if ListView1.Items[I].Selected then begin
      with ListView1.Items[I] do begin
      //open indexfile and read recorder
      //iIndexPosition:=StrToInt(ListView1.Selected.SubItems[6]);
      iIndexPosition:=StrToInt(SubItems[6]);
      end;
      iIndexPosition:=(iIndexPosition-1)*Sizeof(TIndexData);
      AssignFile(IndexFile,sMailIndexFile);
      Reset(IndexFile);
      Seek(IndexFile,iIndexPosition);
      BlockRead(IndexFile, IndexData, SizeOf(TIndexData));

      AssignFile(TempMailFile,sTempMailFile);
      if FileExists(sTempMailFile) then Reset(TempMailFile) else ReWrite(TempMailFile);
      Seek(TempMailFile,FileSize(TempMailFile));

      //read the responding mail file and write to destination mail file
      iPosition:=IndexData.Position;
      iSize:=IndexData.Size;
      buf := StrAlloc(iSize);
      AssignFile(MailFile,sMailFile);
      Reset(MailFile);
      Seek(MailFile,iPosition);
      BlockRead(MailFile,buf^,iSize);
      BlockWrite(TempMailFile,'****************',16);
      iPosition:=FilePos(TempMailFile);
      BlockWrite(TempMailFile,buf^,iSize);

      //write into destination indexfile
      AssignFile(TempIndexFile,sTempIndexFile);
      if FileExists(sTempIndexFile) then Reset(TempIndexFile) else ReWrite(TempIndexFile);
      Seek(TempIndexFile,FileSize(TempIndexFile));
      IndexData.Index:=(FileSize(TempIndexFile) div sizeof(TIndexData))+1;
      IndexData.Position:=iPosition;
      IndexData.Size:=iSize;
      BlockWrite(TempIndexFile, IndexData, SizeOf(TIndexData));

      //modify source index file
      IndexData.Delete:=true;
      Seek(IndexFile,iIndexPosition);
      BlockWrite(IndexFile,IndexData,sizeof(TIndexData));

      Item.Delete;
      CloseFile(IndexFile);
      CloseFile(MailFile);
      CloseFile(TempIndexFile);
      CloseFile(TempMailFile);
      StrDispose(buf);
    end;
    inc(i);
  end;
///////////////////////////////move to database////////////////


      SetPXTreeNodeName(mNode);
      ActualizeTrash;
      with TreeView1 do begin
        for i := 0 to Items.Count - 1 do
          if (Items[i].Data <> nil) and (Items[i].StateIndex = tnFolder) and
            (CompareText(PFolderData(Items[i].Data)^.Path, CopyTo) = 0) then begin
            SetPXTreeNodeName(Items[i]);
            Break;
          end;
      end;
      TreeView1Change(Self, mNode);
    end;
  finally
    dlg.Free;
  end;
end;

procedure TMainForm.ListView2DblClick(Sender: TObject);
begin
  PopupMenu2.Items[iDoubleClickAction].Action.Execute;
end;

procedure TMainForm.actMessageAttPicViewExecute(Sender: TObject);
begin
  ViewAttachment(sPicViewer);
end;

procedure TMainForm.actMessageAttPicViewUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled :=
    (ListView1.SelCount = 1) and (ListView1.Selected <> nil) and
    (ListView2.SelCount > 0) and (Length(sPicViewer) > 0);
end;

procedure TMainForm.ViewAttachment(AProg: string);
var
  I: Integer;
begin
  if ListView2.SelCount = 0 then
    Exit;
  FileMightBeInUse := True;
  for I := 0 to ListView2.Items.Count - 1 do
    if ListView2.Items[I].Selected then
    begin
      if not OpenFileWithDoubleExtension(sTemporaryFolder + ListView2.Items[I].Caption) then exit;
      ShellExecute(Handle, 'open', PChar(AProg), PChar(ExtractShortPathName(sTemporaryFolder + ListView2.Items[I].Caption)), PChar(sTemporaryFolder), SW_SHOWNORMAL);
    end;
end;

procedure TMainForm.NeuerKontakt1Click(Sender: TObject);
begin
  EnablePopUpMenu(false);
  if menSearchForm <> nil then menSearchForm.Close;
  Neuer_Kontakt := true;
  if AddressForm.ShowModal = mrOK then
    NewMessage(True, True, '', AddressForm.GetSelAddresses, '', nil);
  EnablePopUpMenu(true);
  Neuer_Kontakt := false;
end;

procedure TMainForm.menOrdneruebersichtClick(Sender: TObject);
begin
  menOrdneruebersicht.Checked := not menOrdneruebersicht.Checked;
  pnlAccount.visible := menOrdneruebersicht.Checked;
  if pnlAccount.Visible then
    begin
      if pnlAddress.Visible then
      begin
        pnlAccount.Align:=altop;
        pnlAccount.Height:=PanelOrdneruebersicht.Height div 2;
        Splitter2.Visible:=true;
        Splitter2.Top:=pnlAccount.Height+5;
        Splitter2.Align:=altop;
        pnlAddress.Align:=alclient;
      end
      else pnlAccount.Align:=alclient;
  end else
  begin
    if pnlAddress.Visible then
    begin
      Splitter2.Visible:=false;
      pnlAddress.Align:=alclient;
    end;
  end;    

  if pnlAccount.Visible or pnlAddress.Visible then PanelOrdneruebersicht.Visible:=true;
end;

procedure TMainForm.lblLabelFolderPanelDblClick(Sender: TObject);
begin
  menOrdneruebersichtClick(Sender);
end;

procedure TMainForm.InfoszudieserVersion1Click(Sender: TObject);
var s: string;
begin
  s := GetAppPath + 'releasenotes.txt'; //AHRK30
  if FileExists(s) then ShellExecute(Handle, 'open', PChar(s), '',
    PChar(sTemporaryFolder), SW_SHOWNORMAL)
end;

procedure TMainForm.actEnhandedSearchNameExecute(Sender: TObject);
begin
  bSearchName := true;
  actEnhancedAddessBookExecute(Sender);
  bSearchName := false;
end;

procedure TMainForm.FindDialogFind(Sender: TObject);
var
  s, Afind: string;
  from, p: integer;
  Sop: TSearchTypes98;
begin
  Sop := [];
  Afind := FindDialog.FindText;
  RichEdit1.SelStart := RichEdit1.SelStart + RichEdit1.SelLength; // AHRK70
  RichEdit1.SelLength := 0; // AHRK70
  if (frmatchcase in FindDialog.options) then Sop := Sop + [stMatchCase];
  if (frwholeword in FindDialog.options) then Sop := Sop + [stWholeWord];
  from := RichEdit1.SelStart; // AHRK70 -----> + Length(AFind);
  p := RichEdit1.FindText(AFind, from, length(RichEdit1.Text), Sop);
  if (p > 0) and (p < length(RichEdit1.Text))
    then
  begin
    RichEdit1.SelStart := p;
    RichEdit1.SelLength := Length(AFind);
    RichEdit1.SetFocus;
  end
  else
  begin
    s := 'Word "' + AFind + '" not found.';
    MessageDlg(s, mtInformation, [mbOK], 0);
    FindDialog.CloseDialog;
  end;
end;

procedure TMainForm.actEditSearchUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (RichEdit1.Enabled);
end;

procedure TMainForm.actEditReverseUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (RichEdit1.Enabled) and
    not RichEdit1.ReadOnly;
end;

procedure TMainForm.actEditReverseExecute(Sender: TObject);
var s, r: string;
  i, j: Integer;
begin
  if RichEdit1.Text = '' then exit;

  for j := 0 to RichEdit1.Lines.Count - 1 do
  begin
    s := RichEdit1.Lines[j];
    if s <> '' then
    begin
      r := '';
      for i := length(s) downto 1 do  //RR04c
      begin
        r := r + s[i];
      end;
      RichEdit1.Lines[j] := r;
    end;
  end;
end;

procedure TMainForm.actViewTBSendReceiveUpdate(Sender: TObject);
begin
//  (Sender as TAction).Checked := tbSendReceive.Visible;
end;

procedure TMainForm.actViewTBSendReceiveExecute(Sender: TObject);
begin
//  tbSendReceive.visible := not tbSendReceive.visible;
end;

procedure TMainForm.ViewSomething(sFile: string);
var
  sTemp: string;
begin
  sFile := '"' + sFile + '"';
  sTemp := '"' + sTemporaryFolder + '"';
  ShellExecute(Handle, 'open',
    PChar(sQuickViewer),
    PChar(sFile),
    PChar(sTemp),
    SW_SHOWMAXIMIZED
    );
end;


procedure TMainForm.actMessageQuickViewExecute(Sender: TObject);
var { view full message file from richedit popup }
  Item: TListItem;
begin
  Item := ListView1.Selected;
  if Item = nil then exit;
  ViewSomething(Item.SubItems[ciFileName]);
end;

procedure TMainForm.actMessageQuickViewUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil);
end;

procedure TMainForm.Label1DblClick(Sender: TObject);
begin
  actMessageQuickViewExecute(Sender);
end;

procedure TMainForm.actFileSaveUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil);
end;

procedure TMainForm.actFileSaveExecute(Sender: TObject);
begin
  SaveMessage := true;
end;

procedure TMainForm.actViewTBClassicUpdate(Sender: TObject);
begin
//  (Sender as TAction).Checked := tbClassic.Visible;
end;

procedure TMainForm.actViewTBClassicExecute(Sender: TObject);
begin
//  tbClassic.visible := not tbClassic.visible;
end;

procedure TMainForm.actMessageMakeEditableExecute(Sender: TObject);
begin
  RichEdit1.Readonly := false;
  // GLOBAL VAR ALERT!! <g>.
  SetPanelHeadersFields(True);
end;

procedure TMainForm.lblLabelFolderPanelClick(Sender: TObject);
begin
  TreeView1.FullExpand;
end;

procedure TMainForm.SetFlatStyle;
begin
  //RR27a/AH04
{
   Assume Ownerdraw all the time...
   if not bUseColouredLabels then
    ListView1.Style := LVStandard
  else
    ListView1.Style := LVOwnerDrawFixed;}

  if bFlatStyle then
  begin
    ListView1.ExtendedStyles := ListView1.ExtendedStyles + [lvxFlatScrollbar];
    PanelNewsText.BevelOuter := bvNone;
    PanelOrdneruebersicht.BevelOuter := bvNone;
    ListView2.FlatScrollBars := True;
  end else
  begin
    ListView1.ExtendedStyles := ListView1.ExtendedStyles - [lvxFlatScrollbar];
    PanelNewsText.BevelOuter := bvRaised;
    PanelOrdneruebersicht.BevelOuter := bvRaised;
    ListView2.FlatScrollBars := False;
  end;
end;

procedure TMainForm.RichEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if key = vk_return then
  begin
    // AHRJ05----
    RichEdit1.DefAttributes.Color := DefaultFont.Color;
    // AHRK84
    RichEdit1.DefAttributes.BackColor := RichEdit1.Color;
    RichEdit1.DefAttributes.Name := DefaultFont.Name;
    RichEdit1.DefAttributes.Size := DefaultFont.Size;
    RichEdit1.DefAttributes.Style := DefaultFont.Style;
    RichEdit1.SelAttributes.Assign(RichEdit1.DefAttributes);

    if keypressed(vk_control) then
    begin
      PanelOrdneruebersicht.visible := not PanelOrdneruebersicht.visible;
      menOrdneruebersicht.Checked := PanelOrdneruebersicht.visible;
      key := 0;
    end;
    if keypressed(vk_menu) then
    begin
      actMessagePropertiesExecute(Sender);
      key := 0;
    end;
  end;
end;

procedure TMainForm.actViewTestExecute(Sender: TObject);
var s: string;
begin
  s := 'c:\windows\string.folder\string.txt.vbs'; //Zeigt JA
//s:='c:\windows\string.folder\string.vbs'; //Zeigt NEIN
  if DoubleExtension(s) then
    MessageBox(Handle, 'Yes', 'actViewTest-Information', mb_IconInformation) else
    MessageBox(Handle, 'No', 'actViewTest-Information', mb_IconInformation);
end;

function TMainForm.OpenFileWithDoubleExtension(FileName: string): Boolean;
var s: string;
begin
  Result := true;
  if not bWarnOpen then exit;
  if not DoubleExtension(FileName) then exit;
  s := Format(GetMessageString(146), [FileName]);
  if MessageBox(Handle, PChar(s), 'Warning', mb_YesNo or mb_IconExclamation or mb_DefButton2)
    = id_Yes then exit;
  Result := false;
end;

(*procedure TMainForm.UpdateTreeView1;
begin
  SetPXTreeNodeName(TreeView1.Selected);
end;*)


procedure TMainForm.actAccountSetAsDefaultUpdate(Sender: TObject);
begin
  if TreeView1.Selected = nil then exit; //AH05
  (Sender as TACtion).Enabled := TreeView1.Selected.StateIndex = tnAccount;
end;

procedure TMainForm.actAccountSetAsDefaultExecute(Sender: TObject);
var
  acctest : string;
  Node : TTreeNode;
begin
  acctest := sDefaultAccount;
  Node := GetActualAccount;
  if Assigned(Node) then
  begin
    if Assigned(Node.Data) then
    begin
      sDefaultAccount := GetPXTreeNodeName(Node);
      // Reset..., will be caught correctly
      // by 'Noding' down below
      if sDefaultAccount = accTest then
        sDefaultAccount := '';
    end;
  end;

  Node := TreeView1.Items.GetFirstNode;
  if Node <> nil then
  begin
    Node := Node.getFirstChild;
    while Node <> nil do
    begin
      if (AnsiCompareText(Node.Text, sDefaultAccount) = 0) and (Node.Text <> '') then
      begin
        // Do overlay...
        Node.OverlayIndex := 1;
        MessageBox(Handle, PChar(Format(GetMessageString(135),
                   [sDefaultAccount])),
                   Pchar(GetMessageString(105)), mb_IconInformation);
      end
      else
      begin
        Node.OverlayIndex := -1;
      end;
      Node := node.getNextSibling;
    end;
  end;
end;


procedure TMainForm.actAccountShowDefaultExecute(Sender: TObject);
var
  i: Integer;
begin
  if sDefaultAccount = '' then exit;
  for i := 0 to TreeView1.Items.Count - 1 do 
    if TreeView1.Items[I].StateIndex = tnAccount then
    begin
      if (Pos(LowerCase(sDefaultAccount), LowerCase(TreeView1.Items[i].Text)) = 1) then
      begin
        with TreeView1.Items[i] do
        begin
          Selected := True;
          Focused := True;
        end;
        TreeView1.Items[i + 1].MakeVisible; //Expand Subitems of DefaultAccount
        break;
      end;
    end;
end;

Procedure TMainForm.UpdateRepository;
begin
  AutoMarkSent; //RR26
  ActualizeTrash;
end;


procedure TMainForm.actMessageReplyToAll1Update(Sender: TObject);
begin
(Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (ListView1.Selected <> nil) and (not IsTypeOfFolder(TreeView1.Selected,
    setSysFolders)); 
end;

procedure TMainForm.actMessageReplyToAll1Execute(Sender: TObject);
begin
  ReplyEMail(True, False) // AH16
  
end;


{  if keypressed(vk_shift) then
  begin
    ReplyEmail(False, True); // AHRK12 Switched non quoting = shift
  end
  else
  begin
    ReplyEmail(True, True); // AHRK12 So default is always quoting...
  end;}
//end;


procedure TMainForm.actEditPasteasQuoteExecute(Sender: TObject);
begin

  if (actEditPasteasQuote.Enabled) then
  begin
    // Start Quote..

    if bHighLightQuoted then
    begin
      with RichEdit1 do
      begin
        SelAttributes.Color := cColorQuoted;
        SelAttributes.BackColor := cBackColorQuoted;
        SelAttributes.Style := StringToStyle(sQuoteStyles);
      end
    end;

    RichEdit1.SelText := NewBreakStringD(ClipBoard.astext, iLineBreakAt,
      GetMessageString(92));
    // Reset is done in the 'KeyUp event' after enter key...
  end;
end;

procedure TMainForm.actEditPasteasQuoteUpdate(Sender: TObject);
begin
  try
    (Sender as TAction).Enabled := (RichEdit1.Enabled) and
      (Clipboard.HasFormat(CF_TEXT)) and (ClipBoard.AsText <> '') and
      not RichEdit1.ReadOnly;
  except end;
end;

procedure TMainForm.ActEditDeleteLineExecute(Sender: TObject);
var Aline: Integer;
begin
  with RichEdit1 do
  begin
    ALine := Perform(EM_LINEFROMCHAR, -1, 0);
    SetCaret(ALine, 0);
    SelLength := Length(Lines[ALine]) + 1; // RR01
    ClearSelection;
  end;
end;

procedure TMainForm.ActEditDeleteLineUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (RichEdit1.Enabled) and not RichEdit1.ReadOnly;
end;

procedure TMainForm.CLabel0DrawItem(Sender: TObject; ACanvas: TCanvas;
  ARect: TRect; Selected: Boolean);
var spacingm : integer;
begin
  spacingm := ARect.Left + (ARect.Bottom - Arect.Top);  // Arbitrary spacing...
  if (Sender = CLabel0) or (sender = MLabel0) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clHighLight;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighlighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar('[none]'), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clMenu;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clMenuText;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar('[none]'), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end;
  end;
  if (Sender = CLabel1) or (sender = MLabel1) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := $002469FF;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel1), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ARect.Left := spacingm;
      ACanvas.Font.Color := $002469FF;
      Drawtext(ACanvas.Handle, PChar(slabel1), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;
  if (Sender = CLabel2) or (sender = MLabel2) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clRed;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel2), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clRed;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel2), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel3) or (sender = MLabel3) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clFuchsia;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel3), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clFuchsia;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel3), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel4) or (sender = MLabel4) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := $00FF8000;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel4), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := $00FF8000;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel4), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel5) or (sender = MLabel5) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clBlue;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel5), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clBlue;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel5), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel6) or (sender = MLabel6) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clTeal;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel6), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clTeal;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel6), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel7) or (sender = MLabel7) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clGreen;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighLighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel7), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clBtnFace;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clGreen;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel7), -1,  ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel8) or (sender = MLabel8) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clHighLight;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighlighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel8), -1, ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clMenu;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clMenuText;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel8), -1, ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;

  if (Sender = CLabel9) or (sender = MLabel9) then
  begin
    if Selected then
    begin
      ACanvas.Brush.Color := clHighLight;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clHighlighttext;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(sLabel9), -1, ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER)
    end
    else
    begin
      ACanvas.Brush.Color := clMenu;
      ACanvas.FillRect(ARect);
      ACanvas.Font.Color := clMenuText;
      ARect.Left := spacingm;
      Drawtext(ACanvas.Handle, PChar(slabel9), -1, ARect, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
    end
  end;
end;

procedure TMainForm.CLabel0Click(Sender: TObject);
var f, p, c : string;
    s : TListItem;
begin
  s := ListView1.Selected;
  while s <> nil do
  begin
    c := s.SubItems[ciFileName];
    f := ExtractFileName(c);
    p := ExtractFilePath(c);
    if (Sender = CLabel0) or (sender = MLabel0) then
    begin
      f[1] := '0';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := '';
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;
    end;
    if (Sender = CLabel1) or (sender = MLabel1) then
    begin
      f[1] := '1';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel1;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;
    end;
    if (Sender = CLabel2) or (sender = MLabel2) then
    begin
      f[1] := '2';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel2;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;
    end;

    if (Sender = CLabel3) or (sender = MLabel3) then
    begin
      f[1] := '3';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel3;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;

    end;

    if (Sender = CLabel4) or (sender = MLabel4) then
    begin
      f[1] := '4';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel4;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;

    end;

    if (Sender = CLabel5) or (sender = MLabel5) then
    begin
      f[1] := '5';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel5;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;

    end;

    if (Sender = CLabel6) or (sender = MLabel6) then
    begin
      f[1] := '6';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel6;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;

    end;

    if (Sender = CLabel7) or (sender = MLabel7) then
    begin
      f[1] := '7';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel7;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;

    end;

    if (Sender = CLabel8) or (sender = MLabel8) then
    begin
      f[1] := '8';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel8;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end;
    end;

    if (Sender = CLabel9) or (sender = MLabel9) then
    begin
      f[1] := '9';
      if s.SubItems[ciFileName] = p + f then exit; //RR26
      if RenameFile(s.SubItems[ciFileName], p + f) then
      begin
        s.SubItems[ciFileName] := p + f;
        s.SubItems[ciLabel] := sLabel9;
        DoSynchSearch(s.SubItems[ciFileName], p + f); //AHRK35
      end
    end;

    ListView1.UpdateItems(s.Index, s.Index);
    Application.ProcessMessages;
    s := ListView1.GetNextItem(s, sdBelow, [isSelected])
  end;
  // AH15... Update ActualMailFile variable with new filename,
  if ListView1.SelCount = 1 then
  begin
    ActualMailFile := ListView1.Selected.SubItems[ciFileName];
    CurrentEmail.FileName := ActualMailFile; //AH16, Assign...
  end;
end;

procedure TMainForm.CLabel0MeasureItem(Sender: TObject; ACanvas: TCanvas;
  var Width, Height: Integer);
begin
  if (Sender = CLabel1) or (sender = MLabel1) then
  begin
    Width := 16 + ACanvas.TextWidth(sLabel1);
  end;
  if (Sender = CLabel2) or (sender = MLabel2) then
  begin
    Width := 16 + ACanvas.TextWidth(sLabel2);
  end;

  if (Sender = CLabel3) or (sender = MLabel3) then
  begin
    Width := 16 + ACanvas.TextWidth(sLabel3);
  end;

  if (Sender = CLabel4) or (sender = MLabel4) then
  begin
    Width := 16 +  ACanvas.TextWidth(sLabel4);
  end;

  if (Sender = CLabel5) or (sender = MLabel5) then
  begin
    Width := 16 + ACanvas.TextWidth(sLabel5);
  end;

  if (Sender = CLabel6) or (sender = MLabel6) then
  begin
    Width := 16 + ACanvas.TextWidth(sLabel6);
  end;

  if (Sender = CLabel7) or (sender = MLabel7) then
  begin
    Width := 16 + ACanvas.TextWidth(sLabel7);
  end;

end;

// AH16 --------------------------------------------------------------------
function TMainForm.DrawItemColours(index : integer; State : TOwnerDrawState;
  var BrushColor, FontColor : TColor) : integer;
var cl : string;
    t : integer;
begin
  // Procedural programming alert.
  cl := ExtractFileName(ListView1.Items[Index].SubItems[ciFileName]);
//  t := StrToIntDef(cl[1], 0) * Ord(bUseColouredLabels); // Coloured labels
  t:=0;
  BrushColor := iLVBackGround;
  FontColor := iLVFontColour;

  if (not ListView1.Focused) then
  begin
    if odSelected in State then
    begin
      BrushColor := clInActiveBorder;
      FontColor := clWindowText;
    end;
  end
  else
  begin
    BrushColor := ListView1.Color;
    case t of
      0, 8, 9 : begin
            if (odSelected in State) then
            begin
              BrushColor := clHighLight;
              FontColor := clHighLightText;
            end
            else
            begin
              // Since these are variable,
              // make sure to push them in...
              BrushColor := iLVBackGround;
              FontColor := iLVFontColour;
            end;
          end;
      1 : begin
            if (odSelected in State) then
            begin
              BrushColor := $002469FF;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := $002469FF;
            end;
          end;
      2 : begin
            if (odSelected in State) then
            begin
              BrushColor := clRed;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := clRed;
            end;
          end;
      3 : begin
            if (odSelected in State) then
            begin
              BrushColor := clFuchsia;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := clFuchsia;
            end;
          end;
      4 : begin
            if (odSelected in State) then
            begin
              BrushColor := $00FF8000;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := $00FF8000;
            end;
          end;
      5 : begin
            if (odSelected in State) then
            begin
              BrushColor := clBlue;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := clBlue;
            end;
          end;
      6 : begin
            if (odSelected in State) then
            begin
              BrushColor := clTeal;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := clTeal;
            end;
          end;
      7 : begin
            if (odSelected in State) then
            begin
              BrushColor := clGreen;
              FontColor := clHighLightText;
            end
            else
            begin
              FontColor := clGreen;
            end;
          end;
        end;  
  end;
  Result := t;
end;
// AH16 --------------------------------------------------------------------

procedure TMainForm.ListView1DrawItem(Control: TWinControl;
  var ACanvas: TCanvas; Index: Integer; ARect: TRect;
  State: TOwnerDrawState; var DefaultDrawing, FullRowSelect: Boolean);
//var
//  HeadBitmap:TBitmap;
begin
  FullRowSelect := False;
  ACanvas.Font.Style := fsLVFontStyle;
  ACanvas.Font.Size := iLVFontSize;
  ACanvas.Font.Name := sLVFontName;

{    HeadBitmap:=TBitmap.Create;
    ImageListForAttach.GetBitmap(ListView1.Items[iColumn].ImageIndex,HeadBitmap);
    ACanvas.BrushCopy(Rect(ARect.Left + 2, ARect.Top, ARect.Left + 18, ARect.Top
        + 16), HeadBitmap, Rect(0, 0, 16, 16), clFuchsia);
    HeadBitmap.Free;
    iColumn:=iColumn+1;}
    DefaultDrawing := true;
end;

procedure TMainForm.ListView1DrawSubItem(Control: TWinControl;
  var ACanvas: TCanvas; Index, SubItem: Integer; ARect: TRect;
  State: TOwnerDrawState; var DefaultDrawing: Boolean);
var p, t : integer;
    prect : TRect;
    BrushColor, FontColor : TColor;
begin
  p := ListView1.ActualColumn[SubItem + 1].Index;
  prect := ListView1.SubItem_BoundsRect[Index, p];
  t := DrawItemColours(index, State, BrushColor, FontColor);
  if p > 0 then
  begin
    pRect :=  ListView1.SubItem_LabelRect[Index, p ];
    ACanvas.Brush.Color := BrushColor;
    ACanvas.Font.Color := FontColor;
    ACanvas.Font.Style := fsLVFontStyle;
    ACanvas.Font.Size := iLVFontSize;
    ACanvas.Font.Name := sLVFontName;

    ACanvas.FillRect(pRect);
    InflateRect(pRect, -4, 0);
    if p=6 then
    begin
      //if ListView1.Items[index].SubItems[p -1]<>'' then
      if StrtoInt(ListView1.Items[index].SubItems[p -1])>0 then  ACanvas.BrushCopy(Rect(aRect.Left + 4, ARect.Top, ARect.Left + 20, ARect.Top
      + 16), Image13.Picture.Bitmap, Rect(0, 0, 16, 16), clFuchsia);
    end
    else if p=3 then
    begin
      if ListView1.Items[index].SubItems[p -1]='High' then  ACanvas.BrushCopy(Rect(aRect.Left , ARect.Top, ARect.Left + 16, ARect.Top
      + 16), Image15.Picture.Bitmap, Rect(0, 0, 16, 16), clFuchsia)
      else if ListView1.Items[index].SubItems[p -1]='Low' then ACanvas.BrushCopy(Rect(aRect.Left , ARect.Top, ARect.Left + 16, ARect.Top
      + 16), Image16.Picture.Bitmap, Rect(0, 0, 16, 16), clFuchsia);
    end
    else
        DrawTextEx(ACanvas.Handle, PChar(ListView1.Items[index].SubItems[p -1]),
      -1, PRect,  DRAWTEXTEX_FLAGS or
      DRAWTEXTEX_ALIGNMENT[ListView1.ActualColumn[SubItem+1].Alignment],
      nil);
  end
  else
  begin
    if not (t in [0, 8, 9]) and (ListView1.Items[index].ImageIndex < 0) then
    begin
      ACanvas.Brush.Color := BrushColor;
      ACanvas.Font.Color := FontColor;
      ACanvas.FillRect(aRect);
      pRect := ListView1.SubItem_IconRect[Index, p ];
      ACanvas.Pen.Color := clGray;
      ACanvas.Brush.Color := FontColor;
      InflateRect(pRect, -6, -6);
      ACanvas.Ellipse(prect);
    end;
  end;
end;


procedure TMainForm.actViewToDoListUpdate(Sender: TObject);
begin
 (Sender as TAction).Checked := (ToDoEx <> nil) and TodoEx.visible;
end;

procedure TMainForm.actViewToDoListExecute(Sender: TObject);
begin
  if ToDoEx <> nil then
  begin
    if not ToDoEx.Visible then
      ToDoEx.Show
    else
      ToDoEx.Hide;
  end
  else
  begin
    ToDoEx := TToDoEx.Create(Self);
    if Assigned(LangHolder) then
    begin
      if LangHolder.Language <> '' then
        LangHolder.Translate([ToDoEx]);
    end;

    ToDoEx.Show;
  end;
end;

procedure TMainForm.AutoMarkReplied;
begin
  if not bAutoMarkReplied then exit;
  CLabel0Click(CLabel8);
end;

procedure TMainForm.AutoMarkSent;
var
  SearchRec: TSearchRec;
  Found: Integer;
  OldName, NewName: String;
begin
  if not bAutoMarkReplied then exit;
  Found := FindFirst(sRepositoryFolder + '*.msg', faAnyFile, SearchRec); //AH11 was msg
  while Found = 0 do begin
    OldName:=SearchRec.Name;
    OldName[1]:='9';
    NewName:=sRepositoryFolder+OldName;
    OldName:=sRepositoryFolder+SearchRec.Name;
    if OldName<>NewName then RenameFile(OldName,NewName);
    Found := FindNext(SearchRec);
  end;
  FindClose(SearchRec);
end;


procedure TMainForm.actMessageTemplateExecute(Sender: TObject);
var
  IsNormalFolder: boolean;
  S: string;
begin
  if TreeView1.Selected <> nil then
  begin
    IsNormalFolder := (TreeView1.Selected.StateIndex = tnFolder) and
      (not (PFolderData(TreeView1.Selected.Data)^.Inbox));
    TemplateForm := TTemplateForm.Create(Self);
    if Assigned(LangHolder) then
    begin
      if LangHolder.Language <> '' then
        LangHolder.Translate([TemplateForm]);
    end;
    with TemplateForm do
    begin
      // AH10
      DoMode(0);
      if (Self.ListView1.SelCount = 1) and (IsNormalFolder) then
        CanAttach := True
      else begin
        Button4.Visible := False;
        Button3.Default := True;
        CanAttach := False;
      end;
      if ShowModal = mrOK then
      begin
        s := ListView1.Selected.Caption;
        // AH04 Change parameters...
        s := GetParsedTemplateString(sTemplateFolder + s + '.txt', GetCommataStringReceiver, CurrentEMail.Subject);
        if s <> '' then
        begin
          RichEdit1.SelStart := 0;
          RichEdit1.SelText := #13#10 + s +#13#10;
          RichEdit1.SelStart := 0;
          RichEdit1.SetFocus;
        end;
      end;
      Free;
    end;
  end;
end;

procedure TMainForm.actMessageTemplateUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := true;
end;

procedure TMainForm.menFileImportClick(Sender: TObject);
var s, t : string;
    iMails, I: Integer;
begin
  // AH04 starts here
  iMails := 0;
  if OpenDialog2.execute then
  begin
    with OpenDialog2.Files do
    for I := 0 to Count - 1 do
    begin
      s := Strings[i];
      t := ExtractFilename(s);
      t := ChangeFileExt(t, '.msg');
      t := sRepositoryFolder + t;
      CopyFile(Pchar(s), Pchar(t), false); //false=overwrite!
      FileSetAttr(t, faArchive); //mark as read
      inc(iMails);
    end;
    MessageBox(Handle,PChar(Format(GetMessageString(136) + sRepositoryCaption, [IntToStr(iMails)])),
      PChar(GetMessageString(105)),mb_IconInformation);
    UpdateRepository;
  end;
end;

procedure TMainForm.actMessageAdvancedExecute(Sender: TObject);
begin
  if SearchAdvanced = nil then
  begin
    SearchAdvanced := TSearchAdvanced.Create(Self);
    if Assigned(LangHolder) then
    begin
       if LangHolder.Language <> '' then
          LangHolder.Translate([SearchAdvanced]);
    end;
  end;
  with SearchAdvanced do
  begin
    Show;
  end;
end;

procedure TMainForm.actAccountFetchSendMailExecute(Sender: TObject);
begin
  OnlineSession(otFetchSendOne);
end;

// AH09
function TMainForm.GetServerStatus(aDoSmtp, aDoPop3 : byte) : integer;
begin
  Result := aDoSMTP * 2 + aDoPOP3 * 1;
end;

procedure TMainForm.SetServerStatus(var Node : TTreeNode; aninteger : integer);
begin
  Node.ImageIndex := aninteger + 21;
  Node.SelectedIndex := Node.ImageIndex;
end;
//AH11
procedure TMainForm.RichEdit1Exit(Sender: TObject);
begin
end;
//AH11

procedure TMainForm.Label4DblClick(Sender: TObject);
begin
  Label4IsProcessing := False;
end;

// AH15---------------------------------------------------------------------
procedure TMainForm.CreateSpikesGradientBitmap(StartPos: Integer; var GBitmap:
  TBitmap);
var
  I, Steps: Integer;
  Bitmap: TBitmap;
  R, G, B, OldR, OldG, OldB: Real;
  StartC, EndC, OldC: TColor;
begin
  // Creates the 'absolute' Sinus. I'm not happy with the colours yet,
  // but works for now...
  Bitmap := TBitmap.Create;
  with Bitmap do
  begin
    Width := PaintBox1.Width * 4 ;
    Height := GBitmap.Height;
    Canvas.Brush.Color := clBtnFace;
    Canvas.FillRect(Rect(0, 0, Width, Height));
  end;
  Steps := Bitmap.Width;
  StartC := ColorToRGB(lblStartColor);
  EndC := ColorToRGB(LblEndColor);

  R := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  G := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  B := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  OldC := EndC;
  OldR := GetRValue(EndC);
  OldG := GetGValue(EndC);
  OldB := GetBValue(EndC);

  // Draw the last half.
  for I := (Steps div 2) + 1 to Steps do
  begin
    Bitmap.Canvas.Pen.Color := OldC;
    Bitmap.Canvas.Rectangle(I + StartPos,
      Abs(Round(Sin(I) * (Bitmap.Height))),
      I + StartPos + 1, Bitmap.Height);

    OldR := OldR + R;
    OldG := OldG + G;
    OldB := OldB + B;
    if (OldR < 0) or (OldR > 255) then
      OldR := GetRValue(StartC);
    if (OldG < 0) or (OldG > 255) then
      OldG := GetGValue(StartC);
    if (OldB < 0) or (OldB > 255) then
      OldB := GetBValue(StartC);
    OldC := RGB(Round(OldR), Round(OldG), Round(OldB));
  end;

  R := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  G := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  B := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  OldC := EndC;
  OldR := GetRValue(EndC);
  OldG := GetGValue(EndC);
  OldB := GetBValue(EndC);

  // And then draw the first half (maintaining the
  // right gradient (clButtonFace in the 'middle').
  for I := (Steps div 2) downto 0 do
  begin
    Bitmap.Canvas.Pen.Color := OldC;
    Bitmap.Canvas.Rectangle(I + StartPos,
    Abs(Round(Sin(I) * (Bitmap.Height))),
    I + StartPos + 1, Bitmap.Height);

    OldR := OldR + R;
    OldG := OldG + G;
    OldB := OldB + B;
    if (OldR < 0) or (OldR > 255) then
      OldR := GetRValue(StartC);
    if (OldG < 0) or (OldG > 255) then
      OldG := GetGValue(StartC);
    if (OldB < 0) or (OldB > 255) then
      OldB := GetBValue(StartC);
    OldC := RGB(Round(OldR), Round(OldG), Round(OldB));
  end;

  GBitmap.Assign(Bitmap);
  Bitmap.Free;
end;


procedure TMainForm.CreateRadarGradientBitmap(StartPos: Integer; var GBitmap:
  TBitmap);
var
  I, Steps: Integer;
  Bitmap: TBitmap;
  R, G, B, OldR, OldG, OldB: Real;
  StartC, EndC, OldC: TColor;
begin
  // Actually this doesn't have anything to do with radar, but
  // anyways... there it is.
  Bitmap := TBitmap.Create;
  with Bitmap do
  begin
    Width := paintBox1.Width * 3;
    Height := PaintBox1.Height;
    Canvas.Brush.Color := clBtnFace;
    Canvas.FillRect(Rect(0, 0, Width, Height));
  end;
  Steps := Bitmap.Width;
  StartC := ColorToRGB(lblStartColor);
  EndC := ColorToRGB(lblEndColor);

  R := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  G := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  B := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  OldC := EndC;
  OldR := GetRValue(EndC);
  OldG := GetGValue(EndC);
  OldB := GetBValue(EndC);

  // Draw the last half...
  for I := (Steps div 2) + 1 to Steps do
  begin
    Bitmap.Canvas.Pen.Color := OldC;
    Bitmap.Canvas.Rectangle(I + StartPos, 0, I + StartPos + 1,
      Bitmap.Height div 3);
    Bitmap.Canvas.Rectangle(I + StartPos, Bitmap.Height - (Bitmap.height div 3),
      I + StartPos + 1, Bitmap.Height);

    OldR := OldR + R;
    OldG := OldG + G;
    OldB := OldB + B;
    if (OldR < 0) or (OldR > 255) then
      OldR := GetRValue(StartC);
    if (OldG < 0) or (OldG > 255) then
      OldG := GetGValue(StartC);
    if (OldB < 0) or (OldB > 255) then
      OldB := GetBValue(StartC);
    OldC := RGB(Round(OldR), Round(OldG), Round(OldB));
  end;

  R := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  G := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  B := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  OldC := EndC;
  OldR := GetRValue(EndC);
  OldG := GetGValue(EndC);
  OldB := GetBValue(EndC);
  // Draw the first half...
  for I := (Steps div 2) downto 0 do
  begin
    Bitmap.Canvas.Pen.Color := OldC;
    Bitmap.Canvas.Rectangle(I + StartPos, 0, I + StartPos + 1,
      Bitmap.Height div 3);
    Bitmap.Canvas.Rectangle(I + StartPos, Bitmap.Height -
      (Bitmap.height div 3), I + StartPos + 1, Bitmap.Height);
    OldR := OldR + R;
    OldG := OldG + G;
    OldB := OldB + B;
    if (OldR < 0) or (OldR > 255) then
      OldR := GetRValue(StartC);
    if (OldG < 0) or (OldG > 255) then
      OldG := GetGValue(StartC);
    if (OldB < 0) or (OldB > 255) then
      OldB := GetBValue(StartC);
    OldC := RGB(Round(OldR), Round(OldG), Round(OldB));
  end;

  GBitmap.Assign(Bitmap);
  Bitmap.Free;
end;

procedure Tmainform.CreateCircleGradientBitmap(StartPos: Integer; var GBitmap:
  TBitmap);
var
  Steps: Integer;
  Bitmap: TBitmap;
  R, G, B, OldR, OldG, OldB: Real;
  StartC, EndC, OldC: TColor;
  center : TPoint;
  rrect : TRect;
begin
  // Creates a 'gradient' ball. Remark: the bitmap (AniBMP1) is resized
  // five times...
  Bitmap := TBitmap.Create;
  GBitMap.Width := GBitmap.Height * 5;
  GBitMap.Height := GBitmap.Height * 5;
  with Bitmap do begin
    Width := GBitmap.Width;
    Height := GBitmap.Height;
    Canvas.Brush.Color := clBtnFace;
    Canvas.FillRect(Rect(0, 0, Width, Height));
  end;

  center.x := GBitmap.Width div 2;
  center.y := GBitmap.Height div 2;

  Steps := Center.x div 2;

  rrect.Left := 0;
  rrect.Top := 0;
  rrect.Right := GBitMap.Width;
  rrect.Bottom := GBitmap.Height;

  StartC := ColorToRGB(lblStartCOlor);  // clBtnShadow
  EndC := ColorToRGB(lblEndCOlor);      // clBtnFace
  R := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  G := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  B := (GetRValue(StartC) - GetRValue(EndC)) / Steps;
  OldC := EndC;
  OldR := GetRValue(EndC);
  OldG := GetGValue(EndC);
  OldB := GetBValue(endC);

  while rrect.Left < center.x do
  begin
    // Start painting from outside to in and
    // stop when we're over the center of the bitmap.
    Bitmap.Canvas.Pen.Color := OldC;
    Bitmap.Canvas.Brush.Color := OldC;
    Bitmap.Canvas.Ellipse(rrect);
    InflateRect(rrect, -1, -1);
    OldR := OldR + R;
    OldG := OldG + G;
    OldB := OldB + B;
    if (OldR < 0) or (OldR > 255) then
      OldR := GetRValue(StartC);
    if (OldG < 0) or (OldG > 255) then
      OldG := GetGValue(StartC);
    if (OldB < 0) or (OldB > 255) then
      OldB := GetBValue(StartC);
    OldC := RGB(Round(OldR), Round(OldG), Round(OldB));
  end;
  GBitmap.Assign(Bitmap);
  Bitmap.Free;
end;

procedure TMainForm.ReloadRadar;
var BitMap : TBitMap;
begin
  Bitmap := TBitmap.Create;
  Bitmap.Width := 48;
  Bitmap.Height := PaintBox1.Height;
  CreateRadarGradientBitmap(0, Bitmap);
  AniBmp1.Width := Bitmap.Width + 6;
  AniBmp1.Height := Bitmap.Height;
  // Clear...
  with AniBMP1.Canvas do
  begin
    Brush.color:= clBtnFace;
    Pen.color:= clBtnFace;
    FillRect(ClipRect);
  end;

  AniBmp1.Canvas.CopyRect(Rect(3, 0, Bitmap.Width, Bitmap.Height),
    Bitmap.Canvas, Rect(0, 0, Bitmap.Width, Bitmap.Height));
  Bitmap.Free;

  // No need to do something with AniBMP2. If you want to add a second
  // animation 'object', do it here....
end;

procedure TMainForm.ReloadDefault;
var BitMap : TBitMap;
    E, I : integer;
    C : TColor;
begin
  Bitmap := TBitmap.Create;
  Bitmap.Width := 48;
  Bitmap.Height := PaintBox1.Height;
  // AH16---
  CreateGradientBitmap(0, lblStartColor, lblEndColor, Bitmap.Canvas,
    Rect(0,0, Bitmap.Width, Bitmap.Height));

  AniBmp1.Width := Bitmap.Width + 6;
  AniBmp1.Height := Bitmap.Height;
  // Clear...
  with AniBMP1.Canvas do
  begin
    Brush.color:=clBtnFace;
    Pen.color:=clBtnFace;
    FillRect(ClipRect);
  end;


  AniBmp2.Width := Bitmap.Width + 6;
  AniBmp2.Height := Bitmap.Height;

  with AniBMP2.Canvas do
  begin
    Brush.color:= clBtnFace;
    Pen.color:=clBtnFace;
    FillRect(ClipRect);
  end;


  AniBmp1.Canvas.CopyRect(Rect(3, 0, Bitmap.Width, Bitmap.Height),
    Bitmap.Canvas, Rect(0, 0, Bitmap.Width, Bitmap.Height));
  Bitmap.Free;
  E := 0;

  with AniBmp2.Canvas do begin
    for I := AniBmp1.Width - 1 downto 0 do begin
      C := AniBmp1.Canvas.Pixels[I, 0];
      Pen.Color := C;
      MoveTo(E, 0);
      LineTo(E, AniBmp1.Height);
      Inc(E);
    end;
  end;
end;

procedure TMainForm.ReloadSpikes;
var BitMap : TBitMap;
begin
  Bitmap := TBitmap.Create;
  Bitmap.Width := 48;
  Bitmap.Height := PaintBox1.Height;
  CreateSpikesGradientBitmap(0, Bitmap);
  AniBmp1.Width := Bitmap.Width + 6;
  AniBmp1.Height := Bitmap.Height;
  // Clear...
  with AniBMP1.Canvas do
  begin
    Brush.color:=clBtnFace;
    Pen.color:=clBtnFace;
    FillRect(ClipRect);
  end;


  AniBmp1.Canvas.CopyRect(Rect(3, 0, Bitmap.Width, Bitmap.Height),
    Bitmap.Canvas, Rect(0, 0, Bitmap.Width, Bitmap.Height));
  Bitmap.Free;

  // No need to do something with AniBMP2. If you want to add a second
  // animation 'object', do it here....
end;

procedure TMainForm.ReloadBall;
var BitMap : TBitMap;
begin
  Bitmap := TBitmap.Create;
  Bitmap.Width := 48;
  Bitmap.Height := PaintBox1.Height;
  // Width->Reset...
  CreateCircleGradientBitmap(0, Bitmap);
  AniBmp1.Width := Bitmap.Width + 6;
  AniBmp1.Height := Bitmap.Height;
  // Clear...
  with AniBMP1.Canvas do
  begin
    Brush.color:=clBtnFace;
    Pen.color:=clBtnFace;
    FillRect(ClipRect);
  end;

  AniBmp1.Canvas.CopyRect(Rect(3, 0, Bitmap.Width, Bitmap.Height),
    Bitmap.Canvas, Rect(0, 0, Bitmap.Width, Bitmap.Height));
  Bitmap.Free;
  // No need to do something with AniBMP2. If you want to add a second
  // animation 'object', do it here....
end;

procedure TMainForm.DoNormalPath;
begin
  if (AnimationPosition > (PaintBox1.Width - AniBmp1.Width - 3)) and
    (AnimationToLeft = True) then
  begin
    AnimationPosition := PaintBox1.Width - 3;
    AnimationToLeft := False;
    with PaintBox1 do
    begin
      Canvas.Brush.Color := clBtnFace;
      Canvas.FillRect(Rect(0, 0, Width, Height));
    end;
  end;

  if (AnimationPosition < 0) and (AnimationToLeft = False) then
  begin
    AnimationPosition := -AniBmp1.Width + 3;
    AnimationToLeft := True;
    with PaintBox1 do begin
      Canvas.Brush.Color := clBtnFace;
      Canvas.FillRect(Rect(0, 0, Width, Height));
    end;
  end;
  if AnimationToLeft then
  begin
    Inc(AnimationPosition, 3);
    PaintBox1.Canvas.Draw(AnimationPosition, 0, AniBmp2);
  end
  else
  begin
    Dec(AnimationPosition, 3);
    PaintBox1.Canvas.Draw(AnimationPosition, 0, AniBmp1);
  end;
end;

procedure TMainForm.DoNoBumpPath;
begin
  if (AnimationPosition > (PaintBox1.Width - AniBMP1.Width div 2)) and
    (AnimationToLeft = True) then
  begin
    AnimationPosition := PaintBox1.Width;
    AnimationToLeft := False;
  end;

  if (AnimationPosition < ( 0 - AniBMP1.Width div 2)) and
    (AnimationToLeft = False) then
  begin
    AnimationPosition := -AniBMP1.Width;
    AnimationToLeft := True;
  end;
  if AnimationToLeft then
  begin
    with PaintBox1 do
    begin
      Canvas.Brush.Color := clBtnFace;
      Canvas.FillRect(Rect(0, 0, (animationposition - AniBMP1.Width) div 2,
        Height));
    end;
    Inc(AnimationPosition, 3);
    PaintBox1.Canvas.Draw(AnimationPosition,  - AniBMP1.height div 2
      + (PaintBox1.Height div 2), AniBmp1);
  end
  else
  begin
    with PaintBox1 do
    begin
      Canvas.Brush.Color := clBtnFace;
      Canvas.FillRect(Rect(AnimationPosition + AniBMP1.Width * 2, 0, Width , Height));
    end;

    Dec(AnimationPosition, 3);
    PaintBox1.Canvas.Draw(AnimationPosition, - AniBMP1.height div 2
      + (PaintBox1.Height div 2), AniBmp1);
  end;
end;


procedure TMainForm.DoAnimation(Mode : Integer);
begin
  case Mode of
  0 : begin
        // Default...
        DoNormalPath;
      end;
  1, 2, 3 : begin
        // Ball..., Lines and Math have the same path for now...
        DoNoBumpPath;
      end;
  end;
end;

procedure TMainForm.UpdateMainForm;
begin
  ListView1.Color := iLVBackGround;
  ListView2.Color := iLVBackGround;
  ListView2.Font.Color := iLVFontColour;
  ListView2.Font.Size := iLVFontSize;
  ListView2.Font.Name := sLVFontName;
  ListVIew2.Font.Style := fsLVFontStyle;
  RichEdit1.DefAttributes.BackColor := RichEdit1.Color;
  RichEdit1.DefAttributes.Color := RichEdit1.Font.Color;
  RichEdit1.DefAttributes.Name := RichEdit1.Font.Name;
  RichEdit1.DefAttributes.Size := RichEdit1.Font.Size;
  RichEdit1.DefAttributes.Style := RichEdit1.Font.Style;
  GradientBmp := TBitmap.Create;
  GradientBmp.Width := Image5.Width;
  GradientBmp.Height := Image5.Height;
  CreateGradientBitmap(60, lblStartColor, lblEndColor, GradientBmp.Canvas,
    Rect(0, 0, GradientBMP.Width, GradientBMP.Height));
  Image5.Picture.Bitmap.Assign(GradientBmp);
  Image1.Picture.Bitmap := Image5.Picture.Bitmap;
//  LabelFolderPanel.Font.Color := lblFontColor;
  Label1.Font.Color := lblFontColor;
  lblSubject.Font.Color := lblFontColor;
  GradientBmp.Free;
end;

procedure TMainForm.DoFormDecorations(sender : TObject);
begin
  if Screen.ActiveForm is TDFSGradientForm then
  begin
    if bPlainColours then
    begin
      (Screen.ActiveForm as TDFSGradientForm).PaintGradient := gfpNever;
      (Screen.ActiveForm as TDFSGradientForm).CaptionTextColor :=
        clCaptionText;
      (Screen.ActiveForm as TDFSGradientForm).InactiveCaptionTextColor :=
        clInActiveCaptionText;
    end
    else
    begin
      (Screen.ActiveForm as TDFSGradientForm).PaintGradient := gfpAlways;
      (Screen.ActiveForm as TDFSGradientForm).UseDithering := bDitheredCaption;
      (Screen.ActiveForm as TDFSGradientForm).GradientStartColor :=
        actStartColor;
      (Screen.ActiveForm as TDFSGradientForm).GradientStopColor := actEndColor;
      (Screen.ActiveForm as TDFSGradientForm).CaptionTextColor := actFontColor;

      (Screen.ActiveForm as TDFSGradientForm).GradientInactiveStartColor :=
        inActStartColor;
      (Screen.ActiveForm as TDFSGradientForm).GradientInactiveStopColor :=
        inActEndColor;
      (Screen.ActiveForm as TDFSGradientForm).InactiveCaptionTextColor :=
        inActFontColor;
    end;
  end;
end;
// AH16--------------------

procedure TMainForm.Treeview1WndCreate(Sender: TObject;
  var St: TMemoryStream; anode: TTreeNode);
var AccountData : PAccountData;
    FolderData : PFolderData;

  procedure ReadStringFromStream(L : TStream; var s : string);
  var i : integer;
  begin
    L.Read(i, SizeOf(Integer));
    SetString(S, PChar(nil), i);
    L.Read(Pointer(S)^, i);
  end;

begin
  case Anode.StateIndex of
    tnAccount :
    begin
      New(AccountData);
      ReadStringFromStream(ST, AccountData^.Path);
      ReadStringFromStream(St, AccountData^.Name);
      ReadStringFromStream(St, AccountData^.FromMail);
      ReadStringFromStream(St, AccountData^.FromDesc);
      ReadStringFromStream(St, AccountData^.ReplyMail);
      ReadStringFromStream(St, AccountData^.ReplyDesc);
      ReadStringFromStream(St, AccountData^.POPServer);
      ReadStringFromStream(St, AccountData^.POPPort);
      ReadStringFromStream(St, AccountData^.POPUser);
      ReadStringFromStream(St, AccountData^.POPPass);
      ReadStringFromStream(St, AccountData^.SMTPServer);
      ReadStringFromStream(St, AccountData^.SMTPPort);
      ReadStringFromStream(St, AccountData^.KeepFilter);
      ReadStringFromStream(St, AccountData^.DeleteFilter);

      ST.Read(AccountData^.SMTPAuthenticate, SizeOf(Boolean));

      ReadStringFromStream(St, AccountData^.SMTPUserName);
      ReadStringFromStream(St, AccountData^.SMTPPassword);
      readStringFromStream(St, AccountData^.Organization);
      ST.Read(AccountData^.DoSMTP, SizeOf(Byte));
      ST.Read(AccountData^.DoPOP, SizeOf(Byte));
      ST.Read(AccountData^.DoSMTPAfterPOP, SizeOf(Byte));
      ST.Read(AccountData^.StandardDownload, SizeOf(Byte));
      ST.Read(AccountData^.PromptPassword, SizeOf(Byte));
      ST.Read(AccountData^.ShowDownload, SizeOf(Byte)); //AHRK19
      Anode.Data := AccountData
    end;
    tnFolder :
    begin
      New(FolderData);
      ReadStringFromStream(St, Folderdata^.Path);
      ReadStringFromStream(St, Folderdata^.Name);
      ReadStringFromStream(St, Folderdata^.Filter);
      ST.Read(Folderdata^.Outbox, SizeOf(Boolean));
      ST.Read(FolderData^.Inbox, SizeOf(Boolean));
      ST.Read(FolderData^.Drafts, SizeOf(Boolean));
      Anode.Data := Folderdata;
    end;
  end;
end;

procedure TMainForm.Treeview1WndDestroy(Sender: TObject;
  var St: TMemoryStream; anode: TTreeNode);
  var B : boolean;
      Y : Byte;

  procedure SaveStringToStream(L : TStream; s : string);
  var i : integer;
  begin
    i := length(s);
    ST.Write(i, SizeOf(Integer));
    ST.Write(PChar(s)^, Length(s));
  end;
begin
  if Assigned(Anode) then
  begin
    case Anode.StateIndex of
      tnAccount :
      begin
        SaveStringToStream(ST, PAccountData(Anode.Data)^.Path);
        SaveStringToStream(St, PAccountData(Anode.Data)^.Name);
        SaveStringToStream(St, PAccountData(Anode.Data)^.FromMail);
        SaveStringToStream(St, PAccountData(Anode.Data)^.FromDesc);
        SaveStringToStream(St, PAccountData(Anode.Data)^.ReplyMail);
        SaveStringToStream(St, PAccountData(Anode.Data)^.ReplyDesc);
        SaveStringToStream(St, PAccountData(Anode.Data)^.POPServer);
        SaveStringToStream(St, PAccountData(Anode.Data)^.POPPort);
        SaveStringToStream(St, PAccountData(Anode.Data)^.POPUser);
        SaveStringToStream(St, PAccountData(Anode.Data)^.POPPass);
        SaveStringToStream(St, PAccountData(Anode.Data)^.SMTPServer);
        SaveStringToStream(St, PAccountData(Anode.Data)^.SMTPPort);
        SaveStringToStream(St, PAccountData(Anode.Data)^.KeepFilter);
        SaveStringToStream(St, PAccountData(Anode.Data)^.DeleteFilter);

        B := PAccountData(Anode.Data)^.SMTPAuthenticate;
        ST.Write(B, SizeOf(Boolean));

        SaveStringToStream(St, PAccountData(Anode.Data)^.SMTPUserName);
        SaveStringToStream(St, PAccountData(Anode.Data)^.SMTPPassword);
        SaveStringToStream(St, PAccountData(Anode.Data)^.Organization);
        Y := PAccountData(Anode.Data)^.DoSMTP;
        ST.Write(Y, SizeOf(Byte));
        Y := PAccountData(Anode.Data)^.DoPOP;
        ST.Write(Y, SizeOf(Byte));
        Y := PAccountData(Anode.Data)^.DoSMTPAfterPOP;
        ST.Write(Y, SizeOf(Byte));
        Y := PAccountData(Anode.Data)^.StandardDownload;
        ST.Write(Y, SizeOf(Byte));
        Y := PAccountData(Anode.Data)^.PromptPassword;
        ST.Write(Y, SizeOf(Byte));
        // AHRK19
        Y := PAccountData(Anode.Data)^.ShowDownload;
        ST.Write(Y, SizeOf(Byte));
      end;
      tnFolder :
      begin
        SaveStringToStream(St, PFolderdata(Anode.Data)^.Path);
        SaveStringToStream(St, PFolderdata(Anode.Data)^.Name);
        SaveStringToStream(St, PFolderdata(Anode.Data)^.Filter);
        B := PFolderdata(Anode.Data)^.Outbox;
        ST.Write(B, SizeOf(Boolean));
        B := PFolderData(Anode.Data)^.Inbox;
        ST.Write(B, SizeOf(Boolean));
        B := PFolderData(Anode.Data)^.Drafts;
        ST.Write(B, SizeOf(Boolean));
      end;
    end;
  end;
end;

procedure TMainForm.ListView1MeasureItem(Control: TWinControl;
  var AHeight: Cardinal);
begin
  // AHRJ05... This won't work with really big fonts, but then
  //           EnhListView already seems to have a hard time
  //           when setting the 'ItemHeight' (See source).
  AHeight := ((iLVFontSize * ListView2.Font.PixelsPerInch) div 72) + 8;
end;

procedure TMainForm.ListView1AfterDefaultDrawItem(Control: TWinControl;
  var ACanvas: TCanvas; Index: Integer; ARect: TRect;
  State: TOwnerDrawState);
var prect, Srect : TRect;
    p : integer;
begin
{  if odFocused in state then
  begin
    pRect := ListView1.SubItem_LabelRect[Index, 0];
    sRect := prect;
    sRect.Left := pRect.Right;
    p := ListView1.ActualColumn[ListView1.Columns.Count -1].Index;
    sRect.Right :=
      ListView1.SubItem_LabelRect[Index, p].right ;
    ACanvas.DrawFocusRect(SRect);
  end;}
end;

procedure TMainForm.actAccountPauseSchedulerUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled :=  False{bScheduleC1 or bScheduleC2 or bScheduleC3
    or bScheduleC4 or bScheduleC5; }
end;

// AHRK34 -- Synch results form, to be used for moving, renaming and
// deleting messages
procedure TMainForm.DoSynchSearch(old, new : string);
begin
  if SearchAdvanced <> nil then
    SearchAdvanced.DoRemoteMove(old, new);
  if menSearchForm <> nil then
    menSearchForm.DoRemoteMove(old, new);
end;
// AHRK34 -- Synch results form

procedure TMainForm.actEnhancedToolBarsExecute(Sender: TObject);
begin
  if not Assigned(CustomizeTB) then
  begin
    CustomizeTB := TCustomizeTB.Create(Self);
    if Assigned(LangHolder) then
    begin
      if LangHolder.Language <> '' then
        LangHolder.Translate([CustomizeTB]);
    end;
    CustomizeTB.ShowModal;
    CustomizeTB.ReColorToolBarButtons;
    CustomizeTB.Free; //AHRK109 -- Freebee. Yuck-Yuck.
  end;
end;

procedure TMainForm.DoAToolBar(aname : string; tsl : TStringList;
  var NumControls : Word);
var i, x, pm : integer;
    s : string;
    cmp : TComponent;
    foobar : TToolBar97;
    MyHomeMadeMenuItem : TMenuItem;

  procedure UseThatGrenadeLauncher;
  var l : integer;
      p : TPopUpMenu;
  begin
    for l := FooBar.ControlCount - 1 downto 0 do
    begin
      // FireInTheHole!
      if FooBar.Controls[l] is TToolBarButton97 then
      begin
        // Make sure that eventual attached menus are freed.
        p := TToolBarButton97(FooBar.Controls[l]).DropDownMenu;
        if Assigned(p) then
        begin
          p.Free;
          TToolBarButton97(FooBar.Controls[l]).DropDownMenu := nil;
        end;
      end;
      Foobar.Controls[l].Free;
    end;
  end;
  procedure WooahImHit(anAction : string);
  var cmp : TComponent;
      Buttocks : TToolBarButton97;
      m : TStringList;
      p : TPopUpMenu;
      mnu : TMenuItem;
      cnt : integer;
      action : TCustomAction;
  begin
    m := TStringList.Create;
    m.CommaText := anAction;
    Buttocks := nil;
    p := nil;
    for cnt := 0 to m.Count - 1 do
    begin
      cmp := MainForm.FindComponent(m.Strings[cnt]);
      if Assigned(cmp) then
      begin
        Action := TCustomAction(cmp);
        // There must be an ImageIndex associated with this action! (AHRK61)
        if Action.ImageIndex > -1 then
        begin
          if not Assigned(Buttocks) then
          begin
            Buttocks := TToolBarButton97.Create(MainForm);
            if Assigned(Buttocks) then
            begin
              Buttocks.Images := MainForm.imlToolBar;
              Buttocks.Action := Action;
              Buttocks.Flat := True;
              Buttocks.DisplayMode:= dmGlyphOnly;
              Buttocks.Visible := True;
              Buttocks.Enabled := True;
              Action.Enabled := True; //AHRK50
              if m.Count > 1 then
              begin
                Buttocks.DropdownArrow := True;
                Buttocks.DropdownCombo := True;
                // Create a menu...
                Buttocks.DropDownMenu := nil;
                p := TPopUpMenu.Create(MainForm);
                if Assigned(p) then
                begin
                  p.Images := imlToolBar;
                  Buttocks.DropdownMenu := p;
                end;
              end;
              Buttocks.Name := 'tbtn97_roundabout_'+ IntToStr(NumControls);
              Foobar.InsertControl(Buttocks);
            end
          end
          else
          begin
            // The PopUp has to exist of course...
            if Assigned(Buttocks.DropDownMenu) then
            begin
              mnu := TMenuItem.Create(MainForm);
              if Assigned(mnu) then
              begin
                mnu.Action := Action;
                mnu.Name := 'menu_roundabout_' + IntToStr(NumControls);
                mnu.Visible := True;
                p.Items.Add(mnu);
                Action.Enabled := True;
              end;
            end;
          end;
        end;
      end
      else
      begin
        // Again this must be a seperator...a menu item of course
        // AHRK129
        if m.Strings[cnt] = '__' then
        begin
          if Assigned(Buttocks.DropDownMenu) then
          begin
            mnu := TMenuItem.Create(MainForm);
            if Assigned(mnu) then
            begin
              mnu.Name := 'menu_seperator_' + IntToStr(NumControls);
              mnu.Caption := '-';
              mnu.Visible := True;
              Buttocks.DropDownMenu.Items.Add(mnu);
            end;
          end;
        end;
      end;
      inc(NumControls);
    end;
    m.Free;
  end;

  procedure WooahImStuck;
  var Pants : TToolBarSep97;
  begin
    Pants := TToolBarSep97.Create(MainForm);
    if Assigned(Pants) then
    begin
      Pants.Visible := True;
      Pants.Name := 'tbsep97_roundabout_' + IntToStr(NumControls);
      FooBar.InsertControl(Pants);
    end;
  end;
begin
  if (Assigned(tsl)) and (aname <> '') then
  begin
    // This is an existing toolbar, so first check if there are
    // a number of buttons defined...
    i := StrToIntDef(tsl.Values['TBNumCtrls'], 0);
    if i > 0 then
    begin
      x := 0;
      // Check if toolbar does exist:
      cmp := MainForm.FindComponent(aname);
      if Assigned(cmp) then
      begin
        FooBar := TToolBar97(cmp);
        UseThatGrenadeLauncher;
      end
      else
      begin
        FooBar := TToolBar97.Create(MainForm);
        FooBar.Name := aname;
        FooBar.Caption := tsl.Values['UserCaption'];
        if FooBar.Caption = '' then
          FooBar.Caption := generateName('tlbu');
        // We're going to add this to the menu list... hang on, hang on...
        MyHomeMadeMenuItem := TMenuItem.Create(Self);
        MyHomeMadeMenuItem.Caption := FooBar.Caption;
        MyHomeMadeMenuItem.Name := 'mnu_' + aname;
        MyHomeMadeMenuItem.Tag := LongInt(FooBar);
        MyHomeMadeMenuItem.OnClick := CustomMenuToolBarClick;
        MyHomeMadeMenuItem.Checked := True;

        // Insert the new MenuItem in the list of View Toolbars, before
        // the Seperator (N51)...
        for pm := 0 to ToolBars1.Count - 1 do
        begin
          if ToolBars1.Items[pm].Name = 'N51' then
          begin
            ToolBars1.Insert(pm, MyHomeMadeMenuItem);
            break;
          end;
        end;

        FooBar.ParentShowHint := True;
        FooBar.Parent := MainForm;
        FooBar.CloseButton := True;
        FooBar.OnClose := CustomMenuToolBarClick;
        FooBar.Visible := True;
      end;

      FooBar.BeginUpdate;
      // We clear things up here...
      s := tsl.Values['Control' + IntToStr(x)];
      while (s <> '') and (x < i) do // AHRK51
      begin
        if s = '__' then
        begin
          // Seperator.
          WooahImStuck;
        end
        else
        begin
          WooahImHit(s);
        end;
        inc(x);
        inc(NumControls);
        s := tsl.Values['Control' + IntToStr(x)];
      end;
      FooBar.EndUpdate;
    end;
  end;
end;


procedure TMainForm.DoLoadToolBars(aFile : TIniFile);
var msl, tsl : TStringList;
    x, p : integer;
    NumberOfControls : Word; // 65k + toolbar buttons should do the job <g>
    s : string;
begin
  // Loads and configures the buttons of a toolbar.
  // First do existing toolbars.
  if Assigned(aFile) then
  begin
    msl := TStringList.Create;
    tsl := TStringList.Create;

    AFile.ReadSections(msl);
    for x := 0 to msl.Count -1 do
    begin
      p := pos('Toolbars', msl.Strings[x]);
      if p = 1 then
      begin
        // Toolbar...
        // Does this toolbar actually exists: since the name starts
        // with toolbars, we do it the easy way <g>.
        tsl.Clear;
        s := Copy(msl.Strings[x], 9, Length(msl.Strings[x]));
        AFile.ReadSectionValues(msl.Strings[x], tsl);
        DoAToolBar(s, tsl, NumberOfControls);
      end;
    end;
    msl.Free;
    tsl.Free;
  end;
end;

procedure TMainForm.DoSaveToolBars(afile : TIniFile);
var x, i, l : integer;
    f : TToolBar97;
    p : TPopUpMenu;
    s : TStringList;
begin
  for x := 0 to MainForm.ComponentCount -1 do
  begin
    if MainForm.Components[x] is TToolbar97 then
    begin
      f := TToolBar97(MainForm.Components[x]);
      if f.Name <> 'tbClassic' then
      begin
        if pos('tlbu', f.Name) > 0 then
        begin
          afile.WriteString('Toolbars'+ f.name, 'UserCaption', f.Caption);
        end;
        afile.WriteInteger('Toolbars'+ f.Name, 'TBNumCtrls', f.ControlCount);
        for i := 0 to f.ControlCount -1 do
        begin
          if f.OrderedControls[i] is TToolBarSep97 then
          begin
            aFile.WriteString('Toolbars'+ f.Name, 'Control' + IntToStr(i),'__');
          end;
          if f.OrderedControls[i] is TToolBarButton97 then
          begin
            if Assigned(TToolBarButton97(f.OrderedControls[i]).Action) then
            begin
              p := TToolBarButton97(f.OrderedControls[i]).DropDownmenu;
              if Assigned(p) then
              begin
                s := TStringList.Create;
                // Add the first one...
                s.Add(TToolBarButton97(f.OrderedControls[i]).Action.Name);
                for l := 0 to p.Items.Count - 1 do
                begin
                  if Assigned(p.Items[l].Action) then
                  begin
                    s.Add(p.Items[l].Action.Name);
                  end
                  else
                  begin
                    // Must be a seperator then <g>.
                    s.Add('__');
                  end;
                end;
                afile.WriteString('ToolBars' + f.Name, 'Control' + intToStr(i),
                  s.CommaText);
                s.Free;
              end
              else
                afile.WriteString('Toolbars'+ f.Name, 'Control' + IntToStr(i),
                  TToolBarButton97(f.OrderedControls[i]).Action.Name);
            end;
          end;
        end;
      end;
    end;
  end;
end;

procedure TMainForm.CustomMenuToolBarClick(Sender : TObject);
var x : integer;
begin
  if Sender is TMenuItem then
  begin
    // Uncheck/Check
    (Sender as TMenuItem).Checked := not ((Sender as TMenuItem).Checked);
    // The address to the pointer of the object (or whatever) is stored.
    TToolBar97(Ptr((Sender as TMenuItem).Tag)).Visible := not
      TToolBar97(Ptr((Sender as TMenuItem).Tag)).Visible;
  end;
  if Sender is TToolBar97 then
  begin
    // Which menu item do we need?
    for x := 0 to ToolBars1.Count -1 do
    begin
      if (StripHotKey(ToolBars1.Items[x].Caption) =
        (Sender as TToolBar97).Caption) then
      begin
        ToolBars1.Items[x].Checked := False;
      end;
    end;
  end;
end;

// AHRK74---
procedure TMainForm.actMessageSendSelectedUpdate(Sender: TObject);
var bool : boolean;
begin
  bool := False;
  if Assigned(TreeView1.Selected) then
  begin
    if TreeView1.Selected.StateIndex = tnFolder then
    begin
      if PFolderData(TreeView1.Selected.Data)^.Outbox then
        if Listview1.SelCount > 0 then
        begin
          Bool := True;
        end;
    end;
  end;
  (Sender as TAction).enabled := bool and (not AreWeOnline); // AHRK115
end;

procedure TMainForm.actMessageSendSelectedExecute(Sender: TObject);
var op, nf : string;
    Item : TListItem;
begin
  if ListView1.SelCount > 0 then
  begin
    Item := ListView1.Selected;
    while Item <> nil do
    begin
      op := MakeValidDirName(ExtractFilePath(Item.SubItems[ciFileName]));
      if Item.ImageIndex <> 5 then
      begin
        nf := ChangeFileExt(ExtractFileName(Item.SubItems[ciFileName]), '')
          + '+';
        nf := nf + '.msg';

        if not FileExists(op + nf) then
        begin
          Item.ImageIndex := 5;
          RenameFile(Item.SubItems[ciFileName], op + nf);
          DoSynchSearch(Item.SubItems[ciFileName], op + nf);
          Item.SubItems[ciFileName] := op + nf;
        end;
      end;
      Item := ListView1.GetNextItem(Item, sdAll, [isSelected]);
    end;

    SetPXTreeNodeName(TreeView1.Selected);
    actUpdateStatusbarUpdate(Self);
    OnlineSession(otSendSelected);
  end;
end;

procedure TMainForm.menPopupMenu3Popup(Sender: TObject);
begin
{ if ListView1.Selected=nil then
   exit;


  if ListView1.Selected.ImageIndex=5 then
  begin
    Replay2.Enabled:=false;
    ReplytoAllRE1.Enabled:=false;
    Forward2.Enabled:=false
  end
  else
  begin
    Replay2.Enabled:=true;
    ReplytoAllRE1.Enabled:=true;
    Forward2.Enabled:=true;
  end;}


end;

// AHRK93 --
procedure TMainForm.actMessageAttPropertiesUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled :=
    (ListView1.SelCount = 1) and (ListView1.Selected <> nil) and
    (ListView2.SelCount = 1);
end;

procedure TMainForm.actMessageAttPropertiesExecute(Sender: TObject);
begin
  ShowProperties(Self.Handle, sTemporaryFolder + ListView2.Selected.Caption);
end;
// AHRK93 --

procedure TMainForm.SetPanelHeadersFields(Editable : Boolean);
var i : integer;
begin
  lblfrom.Caption:= CurrentEmail.From;
  lblsubject1.Caption:=CurrentEmail.Subject;
  if CurrentAddressField <> nil then
  begin
    lblto.Caption := StringListToCommataString(CurrentAddressField,
        False);
  end;


  if not Editable then
  begin
    fldFromHeader.Style := csDropDown;
    fldFromHeader.Text := CurrentEmail.From;

  end
  else
  begin
    fldFromHeader.Style := csDropDownList;
    i := fldFromHeader.Items.IndexOf(CurrentEmail.From);
    if i > -1 then
      fldFromHeader.ItemIndex := i
    else
    begin
      fldFromHeader.Items.Insert(0, CurrentEmail.From);
      fldFromHeader.ItemIndex := 0;
    end;
  end;

  SetFldAddresses;
  fldSubject.Text := CurrentEmail.Subject;

  EnableHeaderFields(Editable);
end;

procedure TMainForm.EnableHeaderFields(aboolean : boolean);
begin
  fldFromHeader.Enabled := True;
  fldAddresses.Enabled := True;
  fldSubject.Enabled := True;
  fldFromHeader.ReadOnly := not aboolean;
  fldAddresses.ReadOnly := not aboolean;
  fldSubject.ReadOnly := not aboolean;
end;

procedure TMainForm.SetFldAddresses;
begin
  if CurrentAddressField <> nil then
  begin
    fldAddresses.Text := StringListToCommataString(CurrentAddressField,
        False);
  end;
end;

procedure TMainForm.outSpeedButton1Click(Sender: TObject);
var ms : TStringList;
begin
  if HeaderChanged then
  begin
    // Make sure to store the last one
    ms := CurrentAddressField;
    if ms <> nil then
    begin
      ms.Clear;
      HeaderAddressToStringList(fldAddresses.Text, ms);
    end;
  end;

  Inc(AddressMode);
  if AddressMode > 2 then
    AddressMode := 0;
  Label3.Caption := GetMessageString(52 + AddressMode) + ':';
  SetFldAddresses;
end;

procedure TMainForm.SetFieldBorders(Editable : Boolean);
begin
  if Editable then
  begin
    fldFromHeader.BorderColor := RichEdit1.Font.Color;
    fldAddresses.BorderColor := RichEdit1.Font.Color;
    fldSubject.BorderColor := RichEdit1.Font.Color;
  end
  else
  begin
    fldFromHeader.BorderColor := RichEdit1.Color;
    fldAddresses.BorderColor := RichEdit1.Color;
    fldSubject.BorderColor := RichEdit1.Color;
  end;
end;

procedure TMainForm.fldFromHeaderEnter(Sender: TObject);
begin
  EnableHeaderButtons;
  if Sender is TPMComboBox then
  begin
   (Sender as TPMComboBox).BorderColor := RichEdit1.Font.Color;
  end;
end;

procedure TMainForm.fldFromHeaderExit(Sender: TObject);
var s : string;
begin
  if Sender is TPMComboBox then
  begin
    (Sender as TPMComboBox).BorderColor := RichEdit1.Color;
    if Sender = fldSubject then
    begin
      if not fldSubject.ReadOnly then
      begin
        s := fldSubject.Text;
        AddItemToHistoryStrings(s, fldSubject.Items,
           iSubjectItems, True);
        fldSubject.Text := s; // Removing this gives strange effects..
      end;
    end
  end;
end;

procedure TMainForm.fldFromHeaderChange(Sender: TObject);
var ms : TStringList;
begin
  SaveMessage := True;
  HeaderChanged := True;
  if Sender = fldFromHeader then
  begin
    ListView1.Selected.SubItems[ciFrom] := fldFromHeader.Text;
    CurrentEmail.From := fldFromHeader.Text;
    exit;
  end;
  if Sender = fldSubject then
  begin
    ListView1.Selected.SubItems[ciSubject] := fldSubject.Text;
    CurrentEmail.Subject := fldSubject.Text;
    exit;
  end;
  if Sender = fldAddresses then
  begin
    // This is the easiest way out, but at least it guarantees that the
    // right data is saved.
    ms := CurrentAddressField;
    if ms <> nil then
    begin
      ms.Clear;
      HeaderAddressToStringList(fldAddresses.Text, ms);
    end;
    ListView1.Selected.SubItems[ciTo] := GetCommataStringReceiver;
  end;
end;

procedure TMainForm.EnableHeaderButtons;
begin
  SpeedButton2.Enabled := (ActiveControl = fldFromHeader) or
    (ActiveControl = fldAddresses) or (actMessageAddToAddrbook.Enabled);
  SpeedButton5.Enabled := (ActiveControl = fldAddresses) and
    (not fldAddresses.Readonly);
  SpeedButton6.Enabled := (ActiveControl = fldFromHeader) or
    (ActiveControl = fldAddresses);
  OutSpeedButton1.Enabled := (ListView1.Selected <> nil);
end;

procedure TMainForm.CollectAccountsEmail(PStr : TStrings);
var s : string;
    p : TTreeNode;
begin
  PStr.Clear;
  if TreeView1.Items.Count<=0 then exit;
  p := TreeView1.Items[0].getFirstChild;

  while p <> nil do
  begin
    if Assigned(p.data) then
    begin
      // Not necessary, but I'm playing save here...
      if p.StateIndex = tnAccount then
      begin
        S := PAccountData(p.Data)^.FromDesc + ' <' +
          PAccountData(p.Data)^.FromMail + '>';
        if ExtractEMailAddress(S) <> '' then
          if PStr.IndexOf(S) = -1 then
            PStr.Add(S);
        S := PAccountData(p.Data)^.ReplyDesc + ' <' +
          PAccountData(p.Data)^.ReplyMail + '>';
        if ExtractEMailAddress(S) <> '' then
          if PStr.IndexOf(S) = -1 then
            PStr.Add(S);
      end;
    end;
    p := p.getNextSibling;
  end;
end;

function TMainForm.CurrentAddressField : TStringList;
begin
  result := nil;
  case AddressMode of
    0 : Result := CurrentEmail.ToReceiver;
    1 : Result := CurrentEmail.CC;
    2 : Result := CurrentEmail.BCC;
  end;
end;


procedure TMainForm.SpeedButton2Click(Sender: TObject);
var x : integer;
begin
  if ActiveControl = fldAddresses then
  begin
    if ListView1.Selected <> nil then
    begin
      if fldAddresses.SelText <> '' then
      begin
        AddressForm.SetAddressSilent(fldAddresses.SelText);
      end
      else
        for x := 0 to CurrentAddressField.Count - 1 do
          AddressForm.SetAddressSilent(CurrentAddressField.Strings[x]);
    end;
  end
  else
  begin
    actMessageAddToAddrbookExecute(Self);
  end;
end;

procedure TMainForm.SpeedButton5Click(Sender: TObject);
begin
  AddressForm.Close;
  if AddressForm.ShowModal = mrOK then
  begin
    if fldAddresses.Text <> '' then
    begin
      fldAddresses.Text := fldAddresses.Text + ','
         + AddressForm.GetSelAddresses;
    end
    else
    begin
      fldAddresses.Text := AddressForm.GetSelAddresses;
    end;
    fldFromHeaderChange(fldAddresses);
  end
end;

procedure TMainForm.SpeedButton6Click(Sender: TObject);
var SLh : TStringList;
begin
  if ActiveControl = fldAddresses then
  begin
    SLh := TStringList.Create;
    CommataStringTOStringList(fldAddresses.text, SLh);
    MailOptionsForm.AddStringsToHistory(SLh);
    SLh.Free;
  end
  else
  begin
    MailOptionsForm.AddItemToHistory(fldFromHeader.Text);
  end;
end;


procedure TMainForm.lbRecentMessageMouseLeave(Sender: TObject);
begin
  lbRecentMessage.SendToBack;
  lbRecentMessage.Visible := False;
end;

procedure TMainForm.lbRecentMessageClick(Sender: TObject);
begin
  lbRecentMessage.Visible := False;
  lbRecentMessage.SendToBack;
  if lbRecentMessage.Items.Count > 0 then
  begin
    if lbRecentMessage.ItemIndex > -1 then
    begin
      NavigateTo(lbRecentMessage.ItemIndex);
    end;
  end;
end;

procedure TMainForm.menMailHeadersClick(Sender: TObject);
begin
  PanelHeaders.Visible := not menMailHeaders.Checked;
  menMailHeaders.Checked := PanelHeaders.Visible;
end;

procedure TMainForm.lblSubjectClick(Sender: TObject);
begin
  lbRecentMessage.Top := PanelNewsTextCaption.Top
   + PanelNewsTextCaption.Height + 2;
  lbRecentMessage.Left := lblSubject.Left;
  lbRecentMessage.Width := lblSubject.Width;
  lbRecentMessage.Visible := not lbRecentMessage.Visible;
  if lbRecentMessage.Visible then
    lbRecentMessage.BringToFront
  else
    lbRecentMessage.SendToBack;

end;

procedure TMainForm.actNavigationUpExecute(Sender: TObject);
var i : TListItem;
begin
  if ListView1.Items.Count = 0 then exit;
  if ListView1.SelCount <> 1 then exit;
  i := ListView1.GetNextItem(ListView1.Selected, sdAbove, [isNone]);
  if Assigned(i) then
  begin
    ListView1.Selected.Selected := False;
    i.Selected := True;
    i.Focused := True;
    ListView1MouseUp(ListView1, mbLeft, [], 0,0);
  end
  else
    Beep;
end;

procedure TMainForm.actNavigationDownExecute(Sender: TObject);
var i: TListItem;
begin
  if ListView1.Items.Count = 0 then exit;
  if ListView1.SelCount <> 1 then exit;
  i := ListView1.GetNextItem(ListView1.Selected, sdBelow, [isNone]);
  if Assigned(i) then
  begin
    ListView1.Selected.Selected := False;
    i.Selected := True;
    i.Focused := True;
    ListView1MouseUp(ListView1, mbLeft, [], 0, 0);
  end
  else
    Beep;
end;

procedure TMainForm.actNavigationUpUpdate(Sender: TObject);
var abool : Boolean;
begin
  abool := (ListView1.Items.Count > 0) and (ListView1.SelCount = 1) and
    (ListView1.Selected.Index > 0);
  (Sender as TAction).Enabled := abool;
end;

procedure TMainForm.actNavigationDownUpdate(Sender: TObject);
var abool : Boolean;
begin
  abool := (ListView1.Items.Count > 0) and (ListView1.SelCount = 1) and
    (ListView1.Selected.Index < ListView1.Items.Count - 1);
  (Sender as TAction).Enabled := abool;
end;

procedure TMainForm.actNavigationBackUpdate(Sender: TObject);
var abool : Boolean;
begin
  abool := (lblSubject.Tag < (lbRecentMessage.Items.Count -1));
  (Sender as TAction).Enabled := abool;
end;

procedure TMainForm.actNavigationBackExecute(Sender: TObject);
begin
  lblSubject.Tag := lblSubject.Tag + 1;
  if (lblSubject.Tag >= lbRecentMessage.Items.Count - 1) then
  begin
    lblSubject.Tag := lbRecentMessage.Items.Count - 1;
  end;
  // Hyper jump...
  NavigateTo(lblSubject.Tag);
end;

procedure TMainForm.NavigateTo(AnIndex : Integer);
var Msg : TMessageHistoryItem;
    TNode : TTreeNode;
    LItem : TListItem;
begin
  // AHRK141...
  if (AnIndex < 0) or (AnIndex > lbRecentMessage.Items.Count - 1) then
    exit;
  Msg := TMessageHistoryItem(lbRecentMessage.Items.Objects[anIndex]);
  if Msg <> nil then
  begin
    // Which node...
    TNode := GetTreeByDirName(TreeView1.Items[0], Msg.Folder,
      [tnAccount, tnFolder, tnThrashbag, tnRepository]);
    if TNode <> nil then
    begin
       TreeView1.Selected := TNode;
       // AHRK141...
       if ListView1.Selected <> nil then
         ListView1.Selected.Selected := False;
       LItem := ListView1.Items[0];
       while LItem <> nil do
       begin
         if CompareText(LItem.Subitems[ciFileName],
           Msg.Folder + Msg.FileName) = 0 then
         begin
           LItem.MakeVisible(False);
           LItem.Selected := True;
           LItem.Focused := True;
           UpdateListView(False); //AHRK164 Heh.
           lblSubject.Tag := AnIndex;
           lbRecentMessage.ItemIndex := AnIndex;
           Break;
         end;
         Application.ProcessMessages;
         LItem := ListView1.GetNextItem(LItem, sdAll, []);
       end;
    end;
  end;
end;


procedure TMainForm.actNavigationForwardExecute(Sender: TObject);
begin
  lblSubject.Tag := lblSubject.Tag - 1;
  if (lblSubject.Tag < 0) then
  begin
    lblSubject.Tag := 0;
    exit;
  end;
  // Hyper jump...
  NavigateTo(lblSubject.Tag);
end;

procedure TMainForm.actNavigationForwardUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (lblSubject.Tag > 0);
end;

procedure TMainForm.timerTreeTimer(Sender: TObject);
var pnt : TPoint;
begin
  GetCursorPos(pnt);
  pnt := TreeView1.ScreenToClient(pnt);
  if (pnt.y < (ImageList1.Height * 1)) then
  begin
    TreeView1.Perform(wm_vscroll, SB_LINEUP, 0);
    TreeView1.Invalidate;
  end
  else
  begin
    if (pnt.y > (TreeView1.ClientHeight - ImageList1.Height* 1)) then
    begin
      TreeView1.Perform(wm_vscroll, SB_LINEDOWN, 0);
      TreeView1.Invalidate;
    end
    else
      if htOnLabel in TreeView1.GetHitTestInfoAt(pnt.x, pnt.y) then
      begin
        // Open up the leaves
        if TreeView1.DropTarget.HasChildren then
        begin
          TreeView1.DropTarget.Expand(False);
          TreeView1.Invalidate;
        end
        else
          timerTree.Enabled := False
      end
      else timerTree.Enabled := False;
  end;
end;

procedure TMainForm.PanelNewsTextResize(Sender: TObject);
begin
  ASpeedButton1.Left := PanelNewsTextCaption.ClientWidth
    - (ASpeedButton1.Width + 3);
  lblSubject.Width := (ASpeedButton1.Left - 5) - lblSubject.Left;
  fldFromHeader.Width := lblSubject.Width;
  fldAddresses.Width := lblSubject.Width;
  fldSubject.Width := lblSubject.Width;
  // AHRK161
  if fldFromHeader.Style = csDropDown then
    fldFromHeader.SelLength := 0;
  fldAddresses.SelLength := 0;
  fldSubject.SelLength := 0;
  SpeedButton2.Left := ASpeedButton1.Left;
  SpeedButton5.Left := ASpeedButton1.Left;
  SpeedButton6.Left := AspeedButton1.Left;
end;

procedure TMainForm.lbRecentMessageMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
var ps : TPoint;
begin
  // Has to be added to control. But until then, just do it this way.
  ps.x := x;
  ps.y := y;
  lbRecentMessage.ItemIndex := lbRecentMessage.ItemAtPos(ps, True);
end;

procedure TMainForm.actEnhSaveToolbarImagesExecute(Sender: TObject);
var s : string;
begin
  s := SaveDialog1.Filter;
  SaveDialog1.Filter := 'Bitmap file (*.bmp)|*.bmp';
  if SaveDialog1.Execute then
    SaveImageListToFile(SaveDialog1.Filename, imlToolBar);
  SaveDialog1.Filter := s;
end;

procedure TMainForm.actMessageShowHeadersExecute(Sender: TObject);
var
  SS:olevariant;
begin
  if actMessageShowHeaders.Checked then
  begin
    // We're switching back... so make sure that nothing gets saved.
    SaveMessage := False;
    SS:=sTempMessageFile;
    if FileExists(sTempMessageFile) then
    if CurrentEMail.MsgType = mtText then
        DHTMLEdit1.DOM.body.innerText:=ReadTxtFile(sTempMessageFile) else DHTMLEdit1.LoadDocument(SS);
//        RichEdit1.Lines.LoadFromFile(sTempMessageFile);
        actMessageShowHeaders.Checked := False;
  end
  else
  begin
    // Do this only for 'readonly messages'!!!
    if FileExists(CurrentEmail.FileName) then
    begin
      SS:=CurrentEmail.FileName;
  //    if CurrentEMail.MsgType = mtText then
        DHTMLEdit1.DOM.body.innerText:=ReadTxtFile(CurrentEmail.FileName);
  //    else DHTMLEdit1.LoadDocument(SS);
        actMessageShowHeaders.Checked := not actMessageShowHeaders.Checked;
    end;
  end;
end;


procedure TMainForm.UpdateCursorPos;
var
  CharPos: TPoint;
begin
  CharPos.Y := SendMessage(RichEdit1.Handle, EM_EXLINEFROMCHAR, 0,
    RichEdit1.SelStart);
  CharPos.X := (RichEdit1.SelStart -
    SendMessage(RichEdit1.Handle, EM_LINEINDEX, CharPos.Y, 0));
  Inc(CharPos.Y);
  Inc(CharPos.X);
  StatusBar1.Panels[0].Text := Format(sColRowInfo, [CharPos.Y, CharPos.X]);
end;



procedure TMainForm.actMessageShowHeadersUpdate(Sender: TObject);
begin
  (Sender as TAction).Enabled := (ListView1.SelCount = 1) and
    (RichEdit1.ReadOnly);
end;



function TMainForm.CurrText: TTextAttributes98;
begin
  if RichEdit1.SelLength > 0 then Result := RichEdit1.SelAttributes
  else Result := RichEdit1.DefAttributes;
end;




function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
  FontType: Integer; Data: Pointer): Integer; stdcall;
begin
  TStrings(Data).Add(LogFont.lfFaceName);
  Result := 1;
end;

procedure TMainForm.GetFontNames;
//var
//  DC: HDC;
begin
{  DC := GetDC(0);
  EnumFonts(DC, nil, @EnumFontsProc, Pointer(FontName.Items));
  ReleaseDC(0, DC);
  FontName.Sorted := True;}
end;

procedure TMainForm.DHTMLEdit1DocumentComplete(Sender: TObject);
begin
     DocComplete := True;
     DOMInterface := DHTMLEdit1.Dom as IHtmlDocument2;
     CommandTarget := DOMInterface as IOleCommandTarget;
end;

procedure TMainForm.ListView1Exit(Sender: TObject);
begin
  if (ListView1.Selected=nil) or (ListView1.SelCount>1) then
    SpeedButton1.Visible:=false;
end;

procedure TMainForm.Treeview1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
    ListView2.Visible:=false;
    DHTMLEdit1.NewDocument;

end;



function TMainForm.ReadTxtFile(FileName: string): string;
var

  S: string;
  SL:TStringList;
begin
    SL := TStringList.Create;
    AssignFile(F, FileName);
    Reset(F);
    while not EoF(F) do begin
      ReadLn(F, S);
      SL.Add(S);
    end;
    Result:=SL.Text;
    CloseFile(F);
    sl.Free;
end;

procedure TMainForm.ListView1DblClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin

  if ListView1.Selected=nil then exit;
  if ListView1.Selected.ImageIndex=2 then bEdit:=true else bEdit:=false;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.CreateViewMail;
var
  ViewMailFrm:TViewMailFrm;
begin
  CurrentIndex:=5;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.btnReplyClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageReply1.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;

end;

procedure TMainForm.btnReplyFClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageForward1.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.btnReplyToAllClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageReplyQuoted.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.BtnPrintClick(Sender: TObject);
var
  withui: OleVariant;
begin
  withui := true;
  DHTMLEdit1.PrintDocument(withui);
end;

procedure TMainForm.menSelectAllClick(Sender: TObject);
var i : integer;
begin
  if (ListView1.Focused) and (ListView1.Items.Count > 0) then
  begin
    for I := 0 to ListView1.Items.Count - 1 do
      ListView1.Items[I].Selected := True;
  end;

end;

procedure TMainForm.N87Click(Sender: TObject);
var
  Item: TListItem;
  I: Integer;
begin
//read
  ReadCounter := 0;
  for I := 0 to ListView1.Items.Count - 1 do
    if ListView1.Items[I].ImageIndex<>2 then
      if ListView1.Items[I].Selected then begin
        ListView1.Items[I].ImageIndex:=0;
        iPosition:=StrToInt(ListView1.Items[I].SubItems[6]);
        iPosition:=(iPosition-1)*Sizeof(TIndexData);
        AssignFile(IndexFile,sMailIndexFile);
        Reset(IndexFile);
        Seek(IndexFile,iPosition);
        BlockRead(IndexFile, IndexData, SizeOf(TIndexData));
        IndexData.Read:=true;
        Seek(IndexFile,iPosition);
        BlockWrite(IndexFile, IndexData, SizeOf(TIndexData));
      end;
  SetPXTreeNodeName(TreeView1.Selected);
  actUpdateStatusbarUpdate(Self);

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

end;

procedure TMainForm.N88Click(Sender: TObject);
var
  Item: TListItem;
  I: Integer;
begin
//unread
  ReadCounter := 0;
  for I := 0 to ListView1.Items.Count - 1 do
    if   ListView1.Items[I].ImageIndex<>2 then
     if ListView1.Items[I].Selected then
     begin
      ListView1.Items[I].ImageIndex:=1;
      iPosition:=StrToInt(ListView1.Items[I].SubItems[6]);
      iPosition:=(iPosition-1)*Sizeof(TIndexData);
      AssignFile(IndexFile,sMailIndexFile);
      Reset(IndexFile);
      Seek(IndexFile,iPosition);
      BlockRead(IndexFile, IndexData, SizeOf(TIndexData));
      IndexData.Read:=false;
      Seek(IndexFile,iPosition);
      BlockWrite(IndexFile, IndexData, SizeOf(TIndexData));

    end;
  SetPXTreeNodeName(TreeView1.Selected);
  actUpdateStatusbarUpdate(Self);
end;

procedure TMainForm.menDeleteClick(Sender: TObject);
begin
  if not ConfirmDelete(true) then Exit;
  EmptyTrash;
  RefreshListview;
end;

procedure TMainForm.myclick(Sender: TObject);
var
  sTemp:widestring;
  i:integer;
begin
  if TMenuItem(sender).Caption='保存附件' then
  begin
    ViewMailFrm.SaveAttach;
    exit;
  end;



     i:=PopupMenu9.Items.IndexOf(TMenuItem(sender));
      if not OpenFileWithDoubleExtension(sTemporaryFolder +
        ListView2.Items[I].Caption) then exit;
      FileMightBeInUse := True;
      if ShellExecute(Handle, 'open', PChar(sTemporaryFolder +
        ListView2.Items[I].Caption), '', PChar(sTemporaryFolder), SW_SHOWNORMAL)
        <= 32 then
      begin
        ShellExecute(Handle, 'open', PChar(sQuickViewer), PChar(sTemporaryFolder
          + ListView2.Items[I].Caption), PChar(sTemporaryFolder), SW_SHOWNORMAL);
      end;
end;

procedure TMainForm.ListView1Change(Sender: TObject; Item: TListItem;
  Change: TItemChange);
var
 i:TListItem;
begin
  btnReply.Enabled:=(ListView1.SelCount = 1) and
    (ListView1.Selected <> nil) and (not IsTypeOfFolder(TreeView1.Selected,
    setSysFolders));
  btnReplyToAll.Enabled:= btnReply.Enabled;
  btnReplyF.Enabled:= btnReplyToAll.Enabled;
  popReplay.Enabled:=btnReply.Enabled;
  popReplytoAllRE.Enabled:=btnReply.Enabled;
  popReplyF.Enabled:=btnReply.Enabled;
  menReplay.Enabled:=btnReply.Enabled;
  menReplyAll.Enabled:=btnReply.Enabled;
  menForward.Enabled:=btnReply.Enabled;



  if ListView1.Selected<> nil then
    begin
      if ListView1.Selected.Index= ListView1.Items.Count-1 then
        menNextMail.Enabled := false else menNextMail.Enabled :=true;
     if ListView1.Selected.Index=0 then menPre.Enabled:=false else menPre.Enabled:=true;
     BtnPrint.Enabled:=true;
     btnDelete.Enabled:=true;

   end
   else
   begin
     BtnPrint.Enabled:=false;
     btnDelete.Enabled:=false;
   end;
end;

procedure TMainForm.btnDeleteClick(Sender: TObject);
var
  Item: TListItem;
  S: string;
  I, E: Integer;
begin
  if ListView1.Selected = nil then Exit;
  if not ConfirmDelete((TreeView1.Selected.StateIndex = tnThrashBag)) then Exit;
  I := 0;
  E := ListView1.Items.Count - 1;
  while I <= E do begin
    if ListView1.Items[I].Selected then begin
      Item := ListView1.Items[I];
      S := Item.SubItems[ciFileName];
      SetFileAttr(S, False, True, False, False);
      if not (MakeValidDirName(ExtractFileDir(S)) = sTrashFolder) then
        CopyFile(PChar(S), PChar(sTrashFolder + ExtractFileName(S)), False);
      DeleteFile(S);
      DoSynchSearch(s, ''); // AHRK34
      Item.Delete;
      lblSubject.Caption := '';
      Dec(I);
      Dec(E);
    end;
    Inc(I);
  end;
  // DB01
  DHTMLEdit1.NewDocument;
  ListView1.Selected := ListView1.ItemFocused;
 // UpdateListView;

  // DB01
  SetPXTreeNodeName(TreeView1.Selected);
  ActualizeTrash;

end;

procedure TMainForm.ToolbarButton9731Click(Sender: TObject);
begin
  EnablePopUpMenu(false);
  if menSearchForm <> nil then menSearchForm.Close;
  if AddressForm.ShowModal = mrOK then
    NewMessage(True, True, '', AddressForm.GetSelAddresses, '', nil);
  EnablePopUpMenu(true);

end;

procedure TMainForm.ToolButton9Click(Sender: TObject);
begin
  if menSearchForm = nil then
  begin
    menSearchForm := TmenSearchForm.Create(Self);
    if Assigned(LangHolder) then
    begin
      if LangHolder.Language <> '' then
        LangHolder.Translate([menSearchForm]);
    end;
  end;
  with menSearchForm do begin
    SearchMode := smMessage;
    Caption := 'Find E-mail';
    Show;
  end;

end;

procedure TMainForm.myLetterclick(Sender: TObject);
var
  sCaption:string;
begin
  bNewPic:=true;
  sCaption:=copy(TMenuItem(sender).Caption,pos(' ',TMenuItem(sender).Caption)+1,length(TMenuItem(sender).Caption));
  sCaption:=sCaption+'.jpg';
  sBackGround:=sTemplateFolder+'\images\'+sCaption;
  actMessageNew.Execute;

end;

procedure TMainForm.ToolButton1MouseUp(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
//  DHTMLEdit1.BrowseMode:=false;
end;

procedure TMainForm.PopupMenu10Popup(Sender: TObject);
begin
//DHTMLEdit1.BrowseMode:=false;

end;

procedure TMainForm.myAccountclick(Sender: TObject);
var
  node:TTreeNode;
  sTemp:string;
  i:integer;
begin
  node:=AccountsNode.GetFirstChild;
  while node<>nil  do begin
    i:=pos('(',TMenuItem(sender).Caption);
    sTemp:=TMenuItem(sender).Caption;
    if i<>0 then sTemp:=copy(TMenuItem(sender).Caption,1,i-1);
    if node.Text=sTemp then
    begin
      node.Selected:=true;
      OnlineSession(otFetchSendOne);
      exit
    end;
    node:=AccountsNode.GetNextChild(node);
  end;

end;

procedure TMainForm.menSaveAttachClick(Sender: TObject);
begin
  ViewMailFrm.SaveAttach;
end;

procedure TMainForm.E1Click(Sender: TObject);
var
  Item: TListItem;
  I: Integer;
begin
//all read
  ReadCounter := 0;
  for I := 0 to ListView1.Items.Count - 1 do
  begin
      if   ListView1.Items[I].ImageIndex<>2 then
      begin
        Item := ListView1.Items[I];
        Item.ImageIndex := 0;
        iPosition:=StrToInt(ListView1.Items[I].SubItems[6]);
        iPosition:=(iPosition-1)*Sizeof(TIndexData);
        AssignFile(IndexFile,sMailIndexFile);
        Reset(IndexFile);
        Seek(IndexFile,iPosition);
        BlockRead(IndexFile, IndexData, SizeOf(TIndexData));
        IndexData.Read:=true;
        Seek(IndexFile,iPosition);
        BlockWrite(IndexFile, IndexData, SizeOf(TIndexData));
      end;
  end;
  SetPXTreeNodeName(TreeView1.Selected);
  actUpdateStatusbarUpdate(Self);
end;


procedure TMainForm.menFileHeadClick(Sender: TObject);
begin
  Panel3.Visible := not menFileHead.Checked;
  menFileHead.Checked := Panel3.Visible;
end;

procedure TMainForm.ToolButton2Click(Sender: TObject);
begin
  menOrdneruebersicht.Checked := false;
  pnlAccount.visible := false;
  Splitter2.Visible:=false;
  Splitter2.Align:=alnone;
  if not PnlAddress.Visible then PanelOrdneruebersicht.Visible:=false;
end;

procedure TMainForm.menReplayClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageReply1.Execute;
//  actMessageQueue.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;

end;

procedure TMainForm.popReplayClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageReply1.Execute;
//  actMessageQueue.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;

end;

procedure TMainForm.menReplyAllClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageReplyQuoted.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.menForwardClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageForward1.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.popForwardClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageForward1.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.popReplytoAllREClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageReplyQuoted.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.popReplyFClick(Sender: TObject);
var
  ViewMailFrm:TViewMailFrm;
begin
  bNewDoc:=true;
  actMessageForward1.Execute;
  ViewMailFrm:=TViewMailFrm.Create(self);
  ViewMailFrm.ShowModal;
end;

procedure TMainForm.RefreshListview;
var
    sTemp:string;
    Node:TtreeNode;
    Item:TListItem;
begin
  Listview1.Items.Clear;
  Node:=Treeview1.Selected;
  ActiveAccount := GetActiveAccount(Node);
  Dir := PAccountData(ActiveAccount.Data)^.Path;
  if TreeView1.Selected.Level>1 then
  begin
    if pos('(',TreeView1.Selected.Text)>0 then
      sTemp:=Copy(TreeView1.Selected.Text,1,pos('(',TreeView1.Selected.Text)-1) else sTemp:=TreeView1.Selected.Text;
    sMailIndexFile:=dir+trim(sTemp)+'.IND';
    sMailFile:=dir+trim(sTemp)+'.SML';


  AssignFile(IndexFile,sMailIndexFile);
  if FileExists(sMailIndexFile) then Reset(IndexFile) else Rewrite(IndexFile);
  Seek(IndexFile,0);
  while  not EOF(IndexFile) do begin
    BlockRead(IndexFile, IndexData,sizeof(TIndexData));
    if IndexData.Delete then Continue;
    Item := ListView1.Items.Add;
    if IndexData.Read then Item.ImageIndex:=0 else  Item.ImageIndex:=1;
    if IndexData.edit then Item.ImageIndex := 2;
      with Item.SubItems do begin
        Add(IndexData.Subject);
        Add(IndexData.Address);
        Add(IndexData.Priority);
        Add(DateToStr(IndexData.SDate) + ' ' +
          TimeToStr(IndexData.STime));
        Add(FormatByteText(IndexData.Size));
        Add(IntTostr(IndexData.Attach));
        Add(inttostr(IndexData.Index)); // invisible
      end;
  end;


  CloseFile(IndexFile);
  end;
  lblfrom.Caption:='';
  lblto.Caption:='';
  lblsubject1.Caption:='';
  DHTMLEdit1.NewDocument;

end;




procedure TMainForm.GetSubNotes(KNode: TTreeNode);
var
  I: Integer;
begin
  for I := 0 to KNode.Count - 1 do
  begin
    if assigned(Fnode) then exit;
    if PFolderData(KNode.Item[I].Data)^.Outbox then
    begin
      FNode := KNode.Item[I];
      exit;
    end;
    if KNode.Item[I].HasChildren then
      GetSubNotes(KNode.Item[I]);
  end;
end;

procedure TMainForm.GetSubNotesDrafts(KNode: TTreeNode);
  var
    I: Integer;
  begin
    for I := 0 to KNode.Count - 1 do
    begin
      if assigned(Fnode) then exit;
      if not ((KNode[i].StateIndex=tnRepository) or (KNode[i].StateIndex=tnThrashBag)) then
      begin
        if PFolderData(KNode.Item[I].Data)^.Drafts then
        begin
          FNode := KNode.Item[I];
          exit;
        end;
      end;
      if KNode.Item[I].HasChildren then
        GetSubNotesDrafts(KNode.Item[I]);
    end;
  end;

procedure TMainForm.Internet1Click(Sender: TObject);
var
  reg:TRegistry;
  s,t,sAccount:string;
  sTemp:TstringList;
  i,Found,iTask:integer;
  SearchRec: TSearchRec;
  Data: PAccountData;
  Node:TtreeNode;
  Folder: PFolderData;
begin
  reg:=TRegistry.Create;
  reg.RootKey:=HKEY_CURRENT_USER;
  sAccount:='\Software\Microsoft\Internet Account Manager\Accounts';
  if reg.OpenKey(sAccount,true) then
  begin
    sTemp:=TstringList.Create;
    reg.GetKeyNames(sTemp);
    for i:=0 to sTemp.Count-1 do
    begin
      if Pos('0000', sTemp.Strings[i])>0 then
      begin
        reg.OpenKey(sAccount+'\'+sTemp.Strings[i],false);
        s:=reg.ReadString('POP3 User Name');
        Found := FindFirst(sAccountRootFolder+s, faDirectory, SearchRec);
        if  Found <> 0 then begin
             ////////////////////////////////////////
            New(Data);
            Data^.POPPort := '110';
            Data^.SMTPPort := '25';
            Data^.DoSMTP := 1;
            Data^.DoPOP := 1;
            Data^.ShowDownload := 0;
            Data^.DoSMTPAfterPOP := 0;
            Data^.StandardDownload := 0;
            Data^.PromptPassword := 0;
            Data^.SMTPAuthenticate := false;


            Data^.Name:= s;
            Data^.Path := sAccountRootFolder +Data^.Name + '\';
            CreateFolder(sAccountRootFolder+s);
            Data^.FromMail := Reg.ReadString('SMTP Email Address');
            Data^.FromDesc := Reg.ReadString('Account Name');
            Data^.POPServer := Reg.ReadString('POP3 Server');
            Data^.POPUser := Reg.ReadString('POP3 User Name');
            Data^.POPPass := '';
            Data^.SMTPServer := Reg.ReadString('SMTP Server');
            Data^.SMTPAuthenticate := true;
            Data^.SMTPUserName := Reg.ReadString('POP3 User Name');
            Data^.SMTPPassword := '';
            Data^.DoPOP := Ord(true);
            Data^.DoSMTP := Ord(true);
            Data^.DoSMTPAfterPOP := Ord(true);
            SaveAccountDataToFile(Data);


              Node := TreeView1.Items.AddChild(AccountsNode, Data^.Name);
              Node.Data := Data;
              Node.StateIndex := tnAccount;
              Node.ImageIndex := 0;
              Node.SelectedIndex := 0;
              // Child folders

              New(Folder);
              Folder^.Name := GetMessageString(5);
              Folder^.Outbox := False;
              Folder^.Inbox := True;
              Folder^.Drafts := False;
              Folder^.Path := Data^.Path;
              SaveFolderDataToFile(Folder);
              FNode := TreeView1.Items.AddChild(Node, Folder^.Name);
              FNode.Data := Folder;
              FNode.StateIndex := tnFolder;
              FNode.ImageIndex := 15;
              FNode.SelectedIndex := 16;


              New(Folder);
              Folder^.Name := GetMessageString(4);
              Folder^.Outbox := True;
              Folder^.Inbox := False;
              Folder^.Drafts := False;
              Folder^.Path := Data^.Path;
              SaveFolderDataToFile(Folder);
              FNode := TreeView1.Items.AddChild(Node, Folder^.Name);
              FNode.Data := Folder;
              FNode.StateIndex := tnFolder;
              FNode.ImageIndex := 3;
              FNode.SelectedIndex := 4;


              //Repository
              FNode := TreeView1.Items.AddChild(Node, GetMessageString(2));
              FNode.StateIndex := tnRepository;
              FNode.ImageIndex := 8;
              FNode.SelectedIndex := 8;
              RepositoryNode := FNode;
              //Trash bag
              FNode := TreeView1.Items.AddChild(Node, GetMessageString(1));
              FNode.StateIndex := tnThrashBag;
              FNode.ImageIndex := 6;
              FNode.SelectedIndex := 6;
              TrashNode := FNode;


              New(Folder);
              Folder^.Name := GetMessageString(6);
              Folder^.Outbox := False;
              Folder^.Inbox := False;
              Folder^.Drafts := True;
              Folder^.Path := Data^.Path;
              SaveFolderDataToFile(Folder);
              FNode := TreeView1.Items.AddChild(Node, Folder^.Name);
              FNode.Data := Folder;
              FNode.StateIndex := tnFolder;
              FNode.ImageIndex := 17;
              FNode.SelectedIndex := 18;

              // AH15 Set account node icon when creating new account
              itask := GetServerStatus(Data^.DoSMTP, Data^.DoPop);
              SetServerStatus(Node, itask);

              TreeView1.Selected := Node;
              //TreeView1.AlphaSort;
              //CollectAccountsEmail(fldFromHeader.Items);
        end
        else
          showmessage('同样的帐号:'+s+'已经存在!');
        FindClose(SearchRec);
      end;
    end;
    reg.CloseKey;
  end;
  reg.Free;
  Treeview1.SaveToFile(sAccountRootFolder+'Fold.st');
end;

procedure TMainForm.ToolButton3Click(Sender: TObject);
begin
  menAddress.Checked:=false;
  PnlAddress.Visible:=false;
  Splitter2.Visible:=false;
  if not pnlAccount.visible then PanelOrdneruebersicht.Visible:=false;
  if pnlAccount.Visible then pnlAccount.Align:=alClient;
end;

procedure TMainForm.menAddressClick(Sender: TObject);
begin
  menAddress.Checked := not menAddress.Checked;
  PnlAddress.Visible:=menAddress.Checked;
  if PnlAddress.Visible then
  begin
      if pnlAccount.Visible then
      begin
        pnlAccount.Align:=altop;
        pnlAccount.Height:=PanelOrdneruebersicht.Height div 2;

        Splitter2.Visible:=true;
        Splitter2.Align:=altop;
        PnlAddress.Align:=alclient;
      end;
  end else
  begin
    if pnlAccount.Visible then
    begin
      pnlAccount.Align:=alclient;
      Splitter2.Visible:=false;
    end;  
  end;
  if pnlAccount.Visible or pnlAddress.Visible then PanelOrdneruebersicht.Visible:=true;
end;

procedure TMainForm.Timer3Timer(Sender: TObject);
var
//=====================================
  HMap: THandle;
  PMap: Pointer;
  RecHead: TMapRosterHead;
  count,i,j,Found: Integer;
  P: Pchar;
  tmpstr,tmpFileName,s: string;
  AddressNode:TTreeNode;
  SearchRec: TSearchRec;
//=====================================
begin
  //============================================================================
  TreeviewAsso.Items.Clear;
  HMap := OpenFileMapping(FILE_MAP_READ, true, MapFileName);
  if HMap = INVALID_HANDLE_VALUE then
    exit;
  PMap := MapViewOfFile(HMap, FILE_MAP_READ, 0, 0, 0);
  if PMap=nil then
  begin
    CloseHandle(HMap);
    HMap := INVALID_HANDLE_VALUE;
    exit;
  end;
  P := Pmap;
  Count := Pinteger(p)^;
  P := P+4;

  TreeviewAsso.Items.BeginUpdate;
  for i:= 0 to count -1 do
  begin
    RecHead :=  PMapRosterHead(P)^;
    P := P+sizeof(RecHead);
    j:=PByte(P)^;
    p := P+1;
    setlength(tmpstr, RecHead.wSize-1);
    move(p^, tmpstr[1], RecHead.wSize-1);
    tmpstr:=copy(tmpstr,Pos(#$D#$A,tmpstr)+2,length(tmpstr));


    AddressNode:=TreeviewAsso.Items.Add(nil,tmpstr);
    case j of
      0: AddressNode.ImageIndex:=0;
      1: AddressNode.ImageIndex:=1;
      2: AddressNode.ImageIndex:=2;
      3: AddressNode.ImageIndex:=3;
      4: AddressNode.ImageIndex:=4;
    else
      AddressNode.ImageIndex:=5;
    end;
    AddressNode.SelectedIndex:=AddressNode.ImageIndex;
    p := P+RecHead.wSize-1;
  end;
  UnmapViewOfFile(PMap);
  CloseHandle(HMap);
  //============================================================================
  Found := FindFirst(sAddressBookFolder + '*.ssf', faAnyFile, SearchRec);
  while Found = 0 do
  begin
    tmpFileName :=sAddressBookFolder+SearchRec.Name;
    AssignFile(F, tmpFileName);
    Reset(F);
    ReadLn(F, S);
    while not EoF(F) do begin
      ReadLn(F, S);
      if S <> '' then
      begin
        FromAddressFormat(S, AddressInfo);
        AddressNode:=TreeviewAsso.Items.Add(nil,AddressInfo[0]);
        AddressNode.ImageIndex:=5;
        AddressNode.SelectedIndex:=5;
      end;
    end;
    CloseFile(F);
    Found := FindNext(SearchRec);
  end;
  FindClose(SearchRec);
  TreeviewAsso.Items.EndUpdate;
end;

procedure TMainForm.Treeview1CustomDraw(Sender: TCustomTreeView;
  const ARect: TRect; var DefaultDraw: Boolean);
begin
{  if Treeview1.Height=1 then
  begin
    Splitter2.Beveled:=true;
    Splitter2.Height:=1;
  end
  else
  begin
    Splitter2.Beveled:=false;
    Splitter2.Height:=3;
  end;}
end;

procedure TMainForm.PopRenameClick(Sender: TObject);
var
  FrmRename:TFrmRename;
begin
  FrmRename:=TFrmRename.Create(self);
  if FrmRename.ShowModal= mrok then
    treeview1.Selected.Text:=FrmRename.Edit1.Text;
end;

procedure TMainForm.Treeview1Edited(Sender: TObject; Node: TTreeNode;
  var S: String);
begin
  Treeview1.ReadOnly:=true;
end;

procedure TMainForm.PopFindClick(Sender: TObject);
begin
  if FrmSearchMail = nil then
  begin
    FrmSearchMail := TFrmSearchMail.Create(Self);
  end;
  FrmSearchMail.Show;

end;


procedure TMainForm.SendReceipt(AFrom,ATo,ASubject, ADetail:string);
var
  ms : TStringList;
begin
    ms := CurrentEmail.ToReceiver;
    ms.Clear;
    HeaderAddressToStringList(AFrom, ms);
    CurrentEmail.From := ATo;
    CurrentEmail.Subject := ASubject;
    CurrentEmail.Priority:='normal';
    CurrentEmail.Priority[1]:=UpCase(CurrentEmail.Priority[1]);

  AssignFile(F, sTempMessageFile);
  Rewrite(F);
  WriteLn(F, ADetail);
  CloseFile(F);


  ActualMailFile := MakeValidDirName(PAccountData(treeview1.Selected.Data)^.Path) + GetUniqueMailName + '.msg';
  isReceipt:=true;
  CurrentEMail.CompileMsgFileOnDisk(ActualMailFile);
  FileCopy(nil,ActualMailFile,sTemplateFolder+'Temp.SML');
  DeleteFile(ActualMailFile);
  OnlineSession(otSendSelected);


end;

initialization
   PMRegistry.AddCustomClass(TmainForm, 'TMainForm');
  NilVariant  := null;

end.
